Skip to content

Commit

Permalink
Merge pull request #49 from femioladeji/fix-timer-bug
Browse files Browse the repository at this point in the history
fix issues related to new manifest and service worker
  • Loading branch information
femioladeji authored Oct 4, 2023
2 parents b7525cf + c8f1117 commit c087500
Show file tree
Hide file tree
Showing 6 changed files with 95 additions and 108 deletions.
5 changes: 3 additions & 2 deletions manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -15,7 +15,8 @@
"permissions": [
"storage",
"notifications",
"tabs"
"tabs",
"alarms"
],
"content_security_policy": {
"extension_pages": "script-src 'self'; object-src 'self'"
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "screentime",
"version": "5.0.6",
"version": "5.0.7",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
Expand Down
149 changes: 65 additions & 84 deletions src/assets/js/background.js
Original file line number Diff line number Diff line change
@@ -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];
Expand All @@ -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,
});
}
};

Expand All @@ -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);
});
}());
});
18 changes: 14 additions & 4 deletions src/assets/js/storage.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
},

Expand Down Expand Up @@ -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,
}
}
};
22 changes: 8 additions & 14 deletions src/assets/js/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,27 +96,21 @@ export default {

/**
* @description close out all currently active sites being tracked
* @param {Array<string>} 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) {
const currentDate = this.getCurrentDate();
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;
},

/**
Expand Down Expand Up @@ -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;
}
Expand All @@ -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
Expand Down
7 changes: 4 additions & 3 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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==
Expand Down

0 comments on commit c087500

Please sign in to comment.