Skip to content
This repository has been archived by the owner on Sep 22, 2020. It is now read-only.

Commit

Permalink
1.0.0-beta.5 (#5)
Browse files Browse the repository at this point in the history
The release of 1.0.0-beta.5 version.
  • Loading branch information
Amaimersion authored Mar 10, 2018
1 parent 05dc49c commit 264fc16
Show file tree
Hide file tree
Showing 15 changed files with 194 additions and 37 deletions.
33 changes: 33 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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)

## Расширение
Expand Down
42 changes: 42 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
- [Возможности](#Возможности)
- [Системные требования](#Системные-требования)
- [Установка](#Установка)
- [Использование](#Использование)
- [Лицензия](#Лицензия)

## Возможности
Expand All @@ -36,6 +37,47 @@
5. Нажмите на "Загрузить распакованное расширение...".
6. Выберите папку "extension".

## Использование

### Скриншот

- Работает на страницах `*://2ch.hk/*/res/*`.
- При создании скриншота существует ограничение на размер изображения и на использование оперативной памяти.

**Скриншот постов**

1. Зайдите в тред.
2. Выберите посты, используя флажок (чекбокс).
3. Нажмите на иконку расширения.
4. Нажмите на кнопку "Скриншот постов".

**Скриншот треда**

1. Зайдите в тред.
2. Нажмите на иконку расширения.
3. Нажмите на кнопку "Скриншот треда".

<hr>

### Загрузка

- Работает на страницах `*://2ch.hk/*/res/*`.
- Медиаконтент = видео + изображения.
- Тред скачивается в формате MHTML.

**Загрузка**

1. Зайдите в тред.
2. Нажмите на иконку расширения.
3. Выберите необходимую функцию: `Скачать *`

<hr>

### Статистика

- Работает на страницах `*://2ch.hk/*`.
- Проведенное время учитывается на основе активных окон.

## Лицензия

Исходный код находится под [лицензией MIT](https://github.com/Amaimersion/2ch-helper/blob/master/LICENSE "Лицензия").
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ BackgroundEvents.DOMContentLoaded = function() {
* @static
*/
BackgroundEvents.firstInstall = function() {
UserProfile.createProfile();
UserProfile.createProfile(this.DOMContentLoaded);
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,8 @@ BackgroundScreenshot.createImagesOfData = function() {
return rej();
});
}
}, () => {
return rej();
});
});
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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<void | Error>}
* 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;
Expand Down Expand Up @@ -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;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}


Expand All @@ -56,7 +57,7 @@ UserProfile.createProfile = function() {
* @memberof UserProfile
* @static
*/
UserProfile.deleteProfile = function() {
UserProfile.deleteProfile = function(callback) {
chrome.storage.sync.clear();
}

Expand Down
4 changes: 4 additions & 0 deletions extension/interaction/js/scripts/content/content-downloads.js
Original file line number Diff line number Diff line change
Expand Up @@ -132,5 +132,9 @@ ContentDownloads.processDownload = function(selector, command, condition, callba

ContentAPI.sendMessageToBackground(message, (response) => {
callback(response);

if (!response.status) {
alert('Ошибка: не удалось выполнить загрузку.');
}
});
}
19 changes: 19 additions & 0 deletions extension/interaction/js/scripts/content/content-screenshot.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,17 +96,27 @@ 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;
}

ContentAPI.sendMessageToBackground({
type: 'command',
command: 'createPostsImage'
}, (response) => {
if (!response.status) {
alert('Ошибка: не удалось создать полное изображение.');
}
});

this.restorePageOptions(thread);

if (ContentAPI.userSettings.settings_screenshot.turnOffPostsYes) {
Expand Down Expand Up @@ -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;
}
Expand All @@ -311,6 +326,10 @@ ContentScreenshot.createScreenshotOfThread = async function() {
ContentAPI.sendMessageToBackground({
type: 'command',
command: 'createThreadImage'
}, (response) => {
if (!response.status) {
alert('Ошибка: не удалось создать полное изображение.');
}
});
}

Expand Down
84 changes: 67 additions & 17 deletions extension/interaction/js/scripts/content/content-statistics.js
Original file line number Diff line number Diff line change
@@ -1,69 +1,119 @@
/**
* The module that handles statistics requests.
* A module for work with statistics.
*
* @module ContentStatistics
*/
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);
Loading

0 comments on commit 264fc16

Please sign in to comment.