From 264fc16dc45727204168495228387a2420acb36c Mon Sep 17 00:00:00 2001 From: Sergey Kuznetsov Date: Sat, 10 Mar 2018 12:24:27 +0300 Subject: [PATCH] 1.0.0-beta.5 (#5) The release of 1.0.0-beta.5 version. --- CHANGELOG.md | 33 ++++++++ README.md | 42 ++++++++++ .../js/scripts/background/background-API.js | 2 +- .../scripts/background/background-events.js | 2 +- .../background/background-screenshot.js | 2 + .../background/background-statistics.js | 23 ++--- .../background/background-user-profile.js | 7 +- .../js/scripts/content/content-downloads.js | 4 + .../js/scripts/content/content-screenshot.js | 19 +++++ .../js/scripts/content/content-statistics.js | 84 +++++++++++++++---- extension/interface/html/popup.html | 2 +- extension/interface/html/settings.html | 2 +- extension/interface/html/statistics.html | 2 +- extension/interface/js/scripts/statistics.js | 5 +- extension/manifest.json | 2 +- 15 files changed, 194 insertions(+), 37 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 289f769..11d9687 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,36 @@ +# 1.0.0-beta.5 (10 мая, 2018) + +## Расширение + +### Исправлено + +* Исправлен баг, при котором проведенное время не сохранялось. +* Исправлен баг, при котором после установки профиль пользователя не был загружен. + +### Добавлено + +* Добавлены уведомления об ошибках. + +### Изменено + +* Теперь проведенное время учитывается только на основе активных окон. + +## Проект + +### Удалено + +* Удален лишний console.log из модулей: background-statistics.js, statistics.js. + +### Добавлено + +* Добавлен модуль "Использование" в README. + +### Изменено + +* Небольшие изменения в документации модулей. +* content-statistics.js полностью переписан. +* Изменен метод округления времени в модуле statistics.js. + # 1.0.0-beta.4 (3 мая, 2018) ## Расширение diff --git a/README.md b/README.md index 3777bc6..3f6b30b 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ - [Возможности](#Возможности) - [Системные требования](#Системные-требования) - [Установка](#Установка) +- [Использование](#Использование) - [Лицензия](#Лицензия) ## Возможности @@ -36,6 +37,47 @@ 5. Нажмите на "Загрузить распакованное расширение...". 6. Выберите папку "extension". +## Использование + +### Скриншот + +- Работает на страницах `*://2ch.hk/*/res/*`. +- При создании скриншота существует ограничение на размер изображения и на использование оперативной памяти. + +**Скриншот постов** + +1. Зайдите в тред. +2. Выберите посты, используя флажок (чекбокс). +3. Нажмите на иконку расширения. +4. Нажмите на кнопку "Скриншот постов". + +**Скриншот треда** + +1. Зайдите в тред. +2. Нажмите на иконку расширения. +3. Нажмите на кнопку "Скриншот треда". + +
+ +### Загрузка + +- Работает на страницах `*://2ch.hk/*/res/*`. +- Медиаконтент = видео + изображения. +- Тред скачивается в формате MHTML. + +**Загрузка** + +1. Зайдите в тред. +2. Нажмите на иконку расширения. +3. Выберите необходимую функцию: `Скачать *` + +
+ +### Статистика + +- Работает на страницах `*://2ch.hk/*`. +- Проведенное время учитывается на основе активных окон. + ## Лицензия Исходный код находится под [лицензией MIT](https://github.com/Amaimersion/2ch-helper/blob/master/LICENSE "Лицензия"). \ No newline at end of file diff --git a/extension/interaction/js/scripts/background/background-API.js b/extension/interaction/js/scripts/background/background-API.js index 097ab2b..fdfc3bb 100644 --- a/extension/interaction/js/scripts/background/background-API.js +++ b/extension/interaction/js/scripts/background/background-API.js @@ -80,7 +80,7 @@ BackgroundAPI.saveUserSettings = function(field, callback) { callback = callback || function() {}; if (field) { - chrome.storage.sync.set(this.userSettings[field], callback); + chrome.storage.sync.set({[field]: this.userSettings[field]}, callback); } else { chrome.storage.sync.set(this.userSettings, callback); } diff --git a/extension/interaction/js/scripts/background/background-events.js b/extension/interaction/js/scripts/background/background-events.js index d3ae234..5f57219 100644 --- a/extension/interaction/js/scripts/background/background-events.js +++ b/extension/interaction/js/scripts/background/background-events.js @@ -25,7 +25,7 @@ BackgroundEvents.DOMContentLoaded = function() { * @static */ BackgroundEvents.firstInstall = function() { - UserProfile.createProfile(); + UserProfile.createProfile(this.DOMContentLoaded); } diff --git a/extension/interaction/js/scripts/background/background-screenshot.js b/extension/interaction/js/scripts/background/background-screenshot.js index a26e12d..74cb913 100644 --- a/extension/interaction/js/scripts/background/background-screenshot.js +++ b/extension/interaction/js/scripts/background/background-screenshot.js @@ -271,6 +271,8 @@ BackgroundScreenshot.createImagesOfData = function() { return rej(); }); } + }, () => { + return rej(); }); }); }); diff --git a/extension/interaction/js/scripts/background/background-statistics.js b/extension/interaction/js/scripts/background/background-statistics.js index 3042b2f..133fe3f 100644 --- a/extension/interaction/js/scripts/background/background-statistics.js +++ b/extension/interaction/js/scripts/background/background-statistics.js @@ -41,8 +41,8 @@ BackgroundStatistics.updateStatistics = function(field, data) { if (field === 'totalSecondsSpent') { try { await this.updateTotalSecondsSpent( - data.loadedDate, - data.closedDate + data.focusOnTime, + data.focusOffTime ); } catch (error) { return reject(error); @@ -66,22 +66,26 @@ BackgroundStatistics.updateStatistics = function(field, data) { * @static * @async * - * @param {Number} loadedMs - * A time of opening the page in milliseconds. + * @param {Number} focusOnMs + * A time when the page got focus. + * A number is represented in milliseconds elapsed between + * 1 January 1970 00:00:00 UTC and the current date. * - * @param {Number} closedMs - * A time of closing the page in milliseconds. + * @param {Number} focusOffMs + * A time when the page lost focus. + * A number is represented in milliseconds elapsed between + * 1 January 1970 00:00:00 UTC and the current date. * * @returns {Promise} * A promise for the update that will resolve when the update will end. * Resolve will contain nothing if success, otherwise reject will contain an error. */ -BackgroundStatistics.updateTotalSecondsSpent = function(loadedMs, closedMs) { +BackgroundStatistics.updateTotalSecondsSpent = function(focusOnMs, focusOffMs) { return new Promise(async (resolve, reject) => { let seconds = 0; - seconds = closedMs - loadedMs; - seconds /= 1000; + seconds = focusOffMs - focusOnMs; + seconds /= 1000; // from ms to seconds. seconds = Math.round(seconds); const mainField = this.fields.main; @@ -121,7 +125,6 @@ BackgroundStatistics.updateStatisticsField = function(field, value) { return new Promise((resolve, reject) => { const mainField = this.fields.main; const errorOccurrence = this.createErrorOccurrence(reject); - console.log(errorOccurrence); BackgroundAPI.userSettings[mainField][field] = value; diff --git a/extension/interaction/js/scripts/background/background-user-profile.js b/extension/interaction/js/scripts/background/background-user-profile.js index ee1451f..e18ebf4 100644 --- a/extension/interaction/js/scripts/background/background-user-profile.js +++ b/extension/interaction/js/scripts/background/background-user-profile.js @@ -45,8 +45,9 @@ UserProfile.defaultProfile = { * @memberof UserProfile * @static */ -UserProfile.createProfile = function() { - chrome.storage.sync.set(this.defaultProfile); +UserProfile.createProfile = function(callback) { + callback = callback || function() {}; + chrome.storage.sync.set(this.defaultProfile, callback); } @@ -56,7 +57,7 @@ UserProfile.createProfile = function() { * @memberof UserProfile * @static */ -UserProfile.deleteProfile = function() { +UserProfile.deleteProfile = function(callback) { chrome.storage.sync.clear(); } diff --git a/extension/interaction/js/scripts/content/content-downloads.js b/extension/interaction/js/scripts/content/content-downloads.js index 1353110..46e1d5d 100644 --- a/extension/interaction/js/scripts/content/content-downloads.js +++ b/extension/interaction/js/scripts/content/content-downloads.js @@ -132,5 +132,9 @@ ContentDownloads.processDownload = function(selector, command, condition, callba ContentAPI.sendMessageToBackground(message, (response) => { callback(response); + + if (!response.status) { + alert('Ошибка: не удалось выполнить загрузку.'); + } }); } diff --git a/extension/interaction/js/scripts/content/content-screenshot.js b/extension/interaction/js/scripts/content/content-screenshot.js index 3016d7b..6ad49c6 100644 --- a/extension/interaction/js/scripts/content/content-screenshot.js +++ b/extension/interaction/js/scripts/content/content-screenshot.js @@ -96,9 +96,14 @@ ContentScreenshot.createScreenshotOfPosts = async function() { const coordinates = this.getScrenshotCoordinates(thread); + if (!coordinates.length) { + alert('Не выбраны посты.'); + } + try { await this.handleScreenshotCoordinates(coordinates); } catch (error) { + alert('Ошибка: не удалось обработать координаты.'); this.restorePageOptions(thread); throw error; } @@ -106,7 +111,12 @@ ContentScreenshot.createScreenshotOfPosts = async function() { ContentAPI.sendMessageToBackground({ type: 'command', command: 'createPostsImage' + }, (response) => { + if (!response.status) { + alert('Ошибка: не удалось создать полное изображение.'); + } }); + this.restorePageOptions(thread); if (ContentAPI.userSettings.settings_screenshot.turnOffPostsYes) { @@ -300,9 +310,14 @@ ContentScreenshot.createScreenshotOfThread = async function() { const coordinates = this.getThreadCoordinates(thread); + if (!coordinates.length) { + alert('Ошибка: не удалось получить координаты треда.'); + } + try { await this.handleThreadCoordinates(coordinates); } catch (error) { + alert('Ошибка: не удалось обработать координаты.'); this.restorePageOptions(thread); throw error; } @@ -311,6 +326,10 @@ ContentScreenshot.createScreenshotOfThread = async function() { ContentAPI.sendMessageToBackground({ type: 'command', command: 'createThreadImage' + }, (response) => { + if (!response.status) { + alert('Ошибка: не удалось создать полное изображение.'); + } }); } diff --git a/extension/interaction/js/scripts/content/content-statistics.js b/extension/interaction/js/scripts/content/content-statistics.js index 1b12494..afc6053 100644 --- a/extension/interaction/js/scripts/content/content-statistics.js +++ b/extension/interaction/js/scripts/content/content-statistics.js @@ -1,5 +1,5 @@ /** - * The module that handles statistics requests. + * A module for work with statistics. * * @module ContentStatistics */ @@ -7,63 +7,113 @@ function ContentStatistics() {} /** - * A date of the opening page in milliseconds + * A time when the page got focus. + * A number is represented in milliseconds elapsed between + * 1 January 1970 00:00:00 UTC and the current date. * * @memberof ContentStatistics * @static * @type {Number} */ -ContentStatistics.loadedDate = 0; +ContentStatistics.focusOnTime = 0; /** - * A date of the closing page in milliseconds + * A time when the page lost focus. + * A number is represented in milliseconds elapsed between + * 1 January 1970 00:00:00 UTC and the current date. * * @memberof ContentStatistics * @static * @type {Number} */ -ContentStatistics.closedDate = 0; +ContentStatistics.focusOffTime = 0; /** - * The event for 'DOMContentLoaded'. + * An event when the page was opened. * * @memberof ContentStatistics * @static */ -ContentStatistics.pageLoaded = function() { - ContentStatistics.loadedDate = new Date().getTime(); +ContentStatistics.pageOpened = function() { + if (document.hasFocus()) { + ContentStatistics.pageGotFocus(); + } + + ContentStatistics.bindEvents(); } /** - * The event for 'beforeunload'. + * An event when the page was closed. * * @memberof ContentStatistics * @static */ ContentStatistics.pageClosed = function() { - ContentStatistics.closedDate = new Date().getTime(); + if (ContentStatistics.focusOnTime) { + ContentStatistics.pageLostFocus(); + } +} + + +/** + * An event when the page got focus. + * + * @memberof ContentStatistics + * @static + */ +ContentStatistics.pageGotFocus = function() { + ContentStatistics.focusOnTime = new Date().getTime(); +} + + +/** + * An event when the page lost focus. + * + * @memberof ContentStatistics + * @static + */ +ContentStatistics.pageLostFocus = function() { + ContentStatistics.focusOffTime = new Date().getTime(); + ContentAPI.sendMessageToBackground({ type: 'command', command: 'updateStatistics', field: 'totalSecondsSpent', data: { - loadedDate: ContentStatistics.loadedDate, - closedDate: ContentStatistics.closedDate + focusOnTime: ContentStatistics.focusOnTime, + focusOffTime: ContentStatistics.focusOffTime } }); + + // if focusOnTime not equal to zero, + // then when the page will be closed + // pageLostFocus event will be called. + ContentStatistics.focusOnTime = 0; + ContentStatistics.focusOffTime = 0; +} + + +/** + * Binds an events to the page. + * + * @memberof ContentStatistics + * @static + */ +ContentStatistics.bindEvents = function() { + window.addEventListener('beforeunload', this.pageClosed); + window.addEventListener('focus', this.pageGotFocus); + window.addEventListener('blur', this.pageLostFocus); } /** - * Adds events listeners to the page. + * Adds events listener to the page. */ if (document.readyState === 'loading') { - document.addEventListener('DOMContentLoaded', ContentStatistics.pageLoaded); + document.addEventListener('DOMContentLoaded', ContentStatistics.pageOpened); } else { - ContentStatistics.pageLoaded(); + ContentStatistics.pageOpened(); } - -window.addEventListener('beforeunload', ContentStatistics.pageClosed); diff --git a/extension/interface/html/popup.html b/extension/interface/html/popup.html index 69b71c3..2923525 100644 --- a/extension/interface/html/popup.html +++ b/extension/interface/html/popup.html @@ -74,7 +74,7 @@

diff --git a/extension/interface/html/settings.html b/extension/interface/html/settings.html index 95f3a3f..52ede1e 100644 --- a/extension/interface/html/settings.html +++ b/extension/interface/html/settings.html @@ -58,7 +58,7 @@

- 1.0.0-beta.4 + 1.0.0-beta.5

diff --git a/extension/interface/html/statistics.html b/extension/interface/html/statistics.html index b716ca4..db8594b 100644 --- a/extension/interface/html/statistics.html +++ b/extension/interface/html/statistics.html @@ -51,7 +51,7 @@

- 1.0.0-beta.4 + 1.0.0-beta.5

diff --git a/extension/interface/js/scripts/statistics.js b/extension/interface/js/scripts/statistics.js index 2f605a5..e53a221 100644 --- a/extension/interface/js/scripts/statistics.js +++ b/extension/interface/js/scripts/statistics.js @@ -27,8 +27,11 @@ Statistics.main = async function() { */ Statistics.bindTime = function() { const element = document.getElementById('statistics-time'); + + // from seconds to hours. let time = SettingsIframe.userSettings.statistics.totalSecondsSpent / 3600; - time = Math.round(time); + time = Math.floor(time); + element.textContent = time; } diff --git a/extension/manifest.json b/extension/manifest.json index 4107908..d6d9eb2 100644 --- a/extension/manifest.json +++ b/extension/manifest.json @@ -4,7 +4,7 @@ "name": "2ch-helper", "short_name": "2ch-helper", "version": "1.0.0", - "version_name": "1.0.0-beta.4", + "version_name": "1.0.0-beta.5", "description": "Облегчение взаимодействия с имиджбордой 2ch.hk.", "author": "Sergey Kuznetsov",