From 4eec69cac22c041eca0b65ef48782bd20f0b9ce9 Mon Sep 17 00:00:00 2001 From: Femi Oladeji Date: Wed, 4 Oct 2023 23:42:02 +0200 Subject: [PATCH 1/2] fix issues related to new manifest and service worker --- manifest.json | 3 +- src/assets/js/background.js | 149 ++++++++++++++++-------------------- src/assets/js/storage.js | 18 ++++- src/assets/js/utils.js | 22 ++---- yarn.lock | 7 +- 5 files changed, 93 insertions(+), 106 deletions(-) diff --git a/manifest.json b/manifest.json index b96f5d7..28fea42 100644 --- a/manifest.json +++ b/manifest.json @@ -15,7 +15,8 @@ "permissions": [ "storage", "notifications", - "tabs" + "tabs", + "alarms" ], "content_security_policy": { "extension_pages": "script-src 'self'; object-src 'self'" diff --git a/src/assets/js/background.js b/src/assets/js/background.js index c53c6b4..7804196 100644 --- a/src/assets/js/background.js +++ b/src/assets/js/background.js @@ -1,18 +1,11 @@ import utils, { CONFIGKEY, DATAKEY } from './utils'; +import storage from './storage'; -const cacheStorage = { - active: {}, - configuration: {}, - data: {} -}; - -let delayHandler; - -const setDelayedAction = async (name, tabId) => { - const { configuration } = cacheStorage; +const setDelayedAction = async (name) => { + const configuration = await utils.getData(CONFIGKEY); if (configuration[name] && configuration[name].control) { const currentDate = utils.getCurrentDate(); - const { data } = cacheStorage; + const data = await utils.getData(DATAKEY); let timeSpent = 0; if (data[currentDate] && data[currentDate][name]) { timeSpent = data[currentDate][name]; @@ -23,10 +16,9 @@ const setDelayedAction = async (name, tabId) => { if (secondsToNextBlock && secondsToNextBlock < secondsToLimit) { secondsLeft = secondsToNextBlock; } - delayHandler = setTimeout(() => { - chrome.tabs.remove(tabId); - utils.notify(`You can no longer be on ${name}`); - }, secondsLeft * 1000); + await chrome.alarms.create(name, { + delayInMinutes: secondsLeft / 60, + }); } }; @@ -35,95 +27,84 @@ const setActive = async () => { if (activeTab) { const { url, id } = activeTab; const name = utils.getName(url); - if (utils.isTabAMatch(name, cacheStorage.configuration)) { - if (utils.isTimeExceeded(cacheStorage, name)) { + const cacheStorage = await storage.getCacheStorage(); + const data = await utils.getData(DATAKEY); + const configuration = await utils.getData(CONFIGKEY); + if (utils.isTabAMatch(name, configuration)) { + if (utils.isTimeExceeded(data, configuration, name)) { // eslint-disable-next-line chrome.tabs.remove(id); - } else if (utils.isTimeframeBlocked(cacheStorage, name)) { + } else if (utils.isTimeframeBlocked(configuration, name)) { // eslint-disable-next-line chrome.tabs.remove(id); } else if (cacheStorage.active.name !== name) { // if a different site is active then end the existing site's session - utils.end(cacheStorage); - cacheStorage.active = { + let updatedCacheStorage = await utils.end(); + updatedCacheStorage.active = { name, timeStamp: Date.now() }; - clearTimeout(delayHandler); + await storage.save('cache', updatedCacheStorage); + await chrome.alarms.clearAll(); setDelayedAction(name, id); } } } }; -const synchronize = async (fetchData = false) => { - const promises = [utils.getData(CONFIGKEY)]; - let currentDate; - if (fetchData) { - currentDate = utils.getCurrentDate(); - promises.push(utils.getData(DATAKEY)); - } - const details = await Promise.all(promises); - [cacheStorage.configuration] = details; - if (fetchData) { - if (!cacheStorage.data[currentDate]) { - cacheStorage.data = {}; - cacheStorage.data[currentDate] = details[1][currentDate]; - } +// eslint-disable-next-line +chrome.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => { + const { url } = tab; + const name = utils.getName(url); + const cacheStorage = await storage.getCacheStorage(); + if (cacheStorage.active.name !== name) { + setActive(); } -}; +}); // eslint-disable-next-line -(function () { - synchronize(true); - - // eslint-disable-next-line - chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => { - const { url } = tab; - const name = utils.getName(url); - if (cacheStorage.active.name !== name) { - setActive(); - } - }); - - // eslint-disable-next-line - chrome.tabs.onActivated.addListener(() => { - clearTimeout(delayHandler); - if (cacheStorage.active.name) { - utils.end(cacheStorage); - } - setActive(); - }); +chrome.tabs.onActivated.addListener(async () => { + await chrome.alarms.clearAll(); + const cacheStorage = await storage.getCacheStorage(); + if (cacheStorage.active.name) { + const updatedCacheStorage = await utils.end(); + await storage.save('cache', updatedCacheStorage); + } + await setActive(); +}); - // eslint-disable-next-line - chrome.windows.onFocusChanged.addListener((window) => { - clearTimeout(delayHandler); - if (window === -1) { - utils.end(cacheStorage); - } else { - setActive(); - } - }); +// eslint-disable-next-line +chrome.windows.onFocusChanged.addListener(async (window) => { + await chrome.alarms.clearAll(); + if (window === -1) { + const updatedCacheStorage = await utils.end(); + await storage.save('cache', updatedCacheStorage); + } else { + await setActive(); + } +}); - // eslint-disable-next-line - chrome.notifications.onButtonClicked.addListener((notificationId, buttonIndex) => { - if (buttonIndex === 0) { - // close the tab +// eslint-disable-next-line +chrome.notifications.onButtonClicked.addListener((notificationId, buttonIndex) => { + if (buttonIndex === 0) { + // close the tab + // eslint-disable-next-line + chrome.tabs.query({ + active: true, + currentWindow: true + }, (activeTab) => { // eslint-disable-next-line - chrome.tabs.query({ - active: true, - currentWindow: true - }, (activeTab) => { - // eslint-disable-next-line - chrome.tabs.remove(activeTab[0].id); - }); - } - }); + chrome.tabs.remove(activeTab[0].id); + }); + } +}); - // eslint-disable-next-line - chrome.storage.onChanged.addListener((changes, area) => { - if (changes.sites && area === 'local') { - synchronize(); - } +chrome.alarms.onAlarm.addListener(({ name }) => { + chrome.tabs.query({ + active: true, + currentWindow: true + }, (activeTab) => { + utils.notify(`You can no longer be on ${name}`); + chrome.tabs.remove(activeTab[0].id); }); -}()); +}); diff --git a/src/assets/js/storage.js b/src/assets/js/storage.js index b4a22ff..f1ccad8 100644 --- a/src/assets/js/storage.js +++ b/src/assets/js/storage.js @@ -3,17 +3,19 @@ import devStorage from './dev_storage'; // eslint-disable-next-line const STORAGE = process.env.NODE_ENV === 'development' ? devStorage : chrome.storage.local; const DATAKEY = 'timer'; +const DEFAULT_CACHE = { + active: {}, +}; export default { async update(host, seconds) { const currentDate = this.getCurrentDate(); let data = await this.getData(DATAKEY); data = data[currentDate] || {}; - if (data[host]) { - data[host] += seconds; - } else { - data[host] = seconds; + if (!data[host]) { + data[host] = 0; } + data[host] += seconds; this.save(DATAKEY, { [currentDate]: data }); }, @@ -52,5 +54,13 @@ export default { getCurrentDate() { return new Date().toISOString().substr(0, 10); + }, + + async getCacheStorage() { + const cache = await this.getData('cache'); + return { + ...DEFAULT_CACHE, + ...cache, + } } }; diff --git a/src/assets/js/utils.js b/src/assets/js/utils.js index 9b1aadc..e77e92c 100644 --- a/src/assets/js/utils.js +++ b/src/assets/js/utils.js @@ -96,10 +96,9 @@ export default { /** * @description close out all currently active sites being tracked - * @param {Array} all array of sites currently being tracked (this should - * typically be an array of length 1) */ - end(cacheStorage) { + async end() { + const cacheStorage = await storage.getCacheStorage(); const moment = Date.now(); const { active } = cacheStorage; if (active.name) { @@ -107,16 +106,11 @@ export default { const startOfDayTimestamp = new Date(`${currentDate}T00:00:00`).getTime(); const start = Math.max(startOfDayTimestamp, active.timeStamp); const seconds = parseInt((moment - start) / 1000, 10); - if (!cacheStorage.data[currentDate]) { - cacheStorage.data = {}; - cacheStorage.data[currentDate] = {}; - } - // intentionally manipulating cache storage to keep it updated real time - const currentlyUsedTime = cacheStorage.data[currentDate][active.name] || 0; - cacheStorage.data[currentDate][active.name] = currentlyUsedTime + seconds; cacheStorage.active = {}; storage.update(active.name, seconds); + return cacheStorage; } + return cacheStorage; }, /** @@ -164,11 +158,11 @@ export default { * @param {string} name the site name * @returns {boolean} if the site should be blocked */ - isTimeExceeded({ configuration, data }, name) { + isTimeExceeded(data, configuration, name) { // check if the control is on and time spent on the site is greater than allotted time - const current = data[this.getCurrentDate()]; + const current = data[this.getCurrentDate()] || {}; if (configuration[name] && configuration[name].control - && current && current[name] >= configuration[name].time * 60) { + && (current[name] || 0) >= configuration[name].time * 60) { this.notify(`Time limit exceeded for ${name}`); return true; } @@ -179,7 +173,7 @@ export default { return `${text.charAt(0).toUpperCase()}${text.slice(1)}`; }, - isTimeframeBlocked({ configuration }, name) { + isTimeframeBlocked(configuration, name) { const currentDate = new Date(); const day = days[currentDate.getDay()]; // load the days data if there's any diff --git a/yarn.lock b/yarn.lock index 04fa8fb..0a24faf 100644 --- a/yarn.lock +++ b/yarn.lock @@ -8606,9 +8606,9 @@ postcss@^7.0.0, postcss@^7.0.1, postcss@^7.0.14, postcss@^7.0.27, postcss@^7.0.3 source-map "^0.6.1" postcss@^8.4.14: - version "8.4.30" - resolved "https://registry.yarnpkg.com/postcss/-/postcss-8.4.30.tgz#0e0648d551a606ef2192a26da4cabafcc09c1aa7" - integrity sha512-7ZEao1g4kd68l97aWG/etQKPKq07us0ieSZ2TnFDk11i0ZfDW2AwKHYU8qv4MZKqN2fdBfg+7q0ES06UA73C1g== + version "8.4.31" + resolved "https://registry.yarnpkg.com/postcss/-/postcss-8.4.31.tgz#92b451050a9f914da6755af352bdc0192508656d" + integrity sha512-PS08Iboia9mts/2ygV3eLpY5ghnUcfLV/EXTOW1E2qYxJKGGBUtNjN76FYHnMs36RmARn41bC0AZmn+rR0OVpQ== dependencies: nanoid "^3.3.6" picocolors "^1.0.0" @@ -10676,6 +10676,7 @@ vue-jest@^3.0.4: vue-template-es2015-compiler "^1.6.0" "vue-loader-v16@npm:vue-loader@^16.1.0": + name vue-loader version "16.8.3" resolved "https://registry.yarnpkg.com/vue-loader/-/vue-loader-16.8.3.tgz#d43e675def5ba9345d6c7f05914c13d861997087" integrity sha512-7vKN45IxsKxe5GcVCbc2qFU5aWzyiLrYJyUuMz4BQLKctCj/fmCa0w6fGiiQ2cLFetNcek1ppGJQDCup0c1hpA== From c8f11174efc7d23e854e24a401c2ded0d7b96fc6 Mon Sep 17 00:00:00 2001 From: Femi Oladeji Date: Wed, 4 Oct 2023 23:43:53 +0200 Subject: [PATCH 2/2] update version --- manifest.json | 2 +- package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/manifest.json b/manifest.json index 28fea42..f476f59 100644 --- a/manifest.json +++ b/manifest.json @@ -3,7 +3,7 @@ "name": "Screentime", "description": "To keep track and manage your time on sites that reduce productivity. You can set the number of minutes you want and time frames", "short_name": "screentime", - "version": "5.0.6", + "version": "5.0.7", "icons": { "16": "images/icon_16.png", "48": "images/icon_48.png", diff --git a/package.json b/package.json index 7dfe0a3..84f366d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "screentime", - "version": "5.0.6", + "version": "5.0.7", "private": true, "scripts": { "serve": "vue-cli-service serve",