-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground-script.js
323 lines (274 loc) · 10.8 KB
/
background-script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
const storageArea = browser.storage.local;
/**
* Logs a message to the console with a specified type and color.
*
* @param {string} type - The type of the log message (e.g., "INFO", "ERROR").
* @param {string} msg - The message to log.
* @param {string} [color="LawnGreen"] - The color of the log message. Defaults to "LawnGreen".
*/
function log(type, msg, color = "LawnGreen") {
console.log(`%c[${type}]: `, `color: ${color};font-weight:bold;`, msg);
}
/**
* Returns the current date formatted as MM/DD/YYYY.
*
* @returns {string} The formatted date string.
*/
function getToday() {
return new Date().toLocaleDateString('en-US', {
month: '2-digit',
day: '2-digit',
year: 'numeric'
});
}
/**
* Formats a Date object into a string of the format MM/DD/YYYY.
*
* @param {Date} date - The date to format.
* @returns {string} The formatted date string.
*/
function formatDate(date) {
return date.toLocaleDateString('en-US', {
month: '2-digit',
day: '2-digit',
year: 'numeric'
});
}
/**
* Function to check if url is valid and not in ignore-list
*
* @param {String} url - URL to check
* @param {Array<String>} ignore_list - List of URLs to ignore
* @returns {Boolean} Returns true if URL is valid
*/
function checkUrl(url, ignore_list = []) {
const patterns = [/^https:\/\/.*\/.*/, /^http:\/\/.*\/.*/];
// Check url whether is valid or not
const isValid = patterns.some((pattern) => pattern.test(url));
if (!isValid) { return false };
// Check url whether is beeing in ignore-list or not
const hostname = getHostname(url);
return !ignore_list.includes(hostname);
}
/**
* Function to get hostname part from URL
*
* @param {String} url - URL to get hostname from
* @returns {String} Hostname of URL
*/
function getHostname(url) {
const url_obj = new URL(url);
return url_obj.hostname
}
/**
* Adds a URL entry to the storage for the current day.
* If no URL is provided, it attempts to retrieve the current URL from storage.
* If the URL entry for the current day already exists, no new entry is created.
*
* @param {string|null} [url=null] - The URL to add. If null, the current URL from storage is used.
* @returns {Promise<void>} - A promise that resolves when the operation is complete.
*/
async function addUrlEntry(url = null) {
log("FUNC", "Called addUrlEntry", "DodgerBlue");
let today = getToday();
if (!url) {
const storage = await storageArea.get("c_url");
url = storage?.c_url;
}
if (!url) {
log("WARN", "Can't create new entry! No URL provided and Current url (c_url) is undefined!", "orange");
return;
}
const { [today]: dayStorage } = await storageArea.get(today);
if (dayStorage?.[url]) {
log("INFO", `Entry for ${url} on ${today} already exists! No new entry was created.`);
return;
}
let obj = { [today]: { ...dayStorage, [url]: 0 } };
await storageArea.set(obj);
log("INFO", `New entry created for ${url} on ${today}`);
}
/**
* Adds the specified time to the given URL for the current or specified day.
*
* @param {string} url - The URL to which the time should be added.
* @param {number} time - The amount of time to add.
* @param {string} [day=null] - The day for which the time should be added. Defaults to the current day if not provided.
* @returns {Promise<void>} A promise that resolves when the time has been successfully added.
*/
async function addTime(url, time, day = null) {
day = day || getToday();
let item = await storageArea.get(day);
let obj = item[day] || {};
obj[url] = (obj[url] ?? 0) + time;
await storageArea.set({ [day]: obj });
log("INFO", `Time successfully added! \nUrl: ${url} | Date: ${day} | Time-added: ${time}`);
return;
}
/**
* Updates the time for the current URL based on the time elapsed since the URL was last set.
* The time is split into days and added to the corresponding days. The timestamp of the current
* URL will updated accordingly.
*
* @returns {Promise<void>} A promise that resolves when the time has been successfully updated.
*/
async function updateTime() {
log("FUNC", "Called updateTime", "DodgerBlue")
const item = await storageArea.get("c_url");
if (!item?.c_url) {
log("WARN", "Can't update time! Current url (c_url) is undefined!", "orange");
return;
}
const [url, startTime] = item.c_url;
const startDate = new Date(startTime * 1000);
const now = new Date();
let elapsedTime = (now - startDate) / 1000 | 0;
// Split the elapsed time into appropriate days
while (elapsedTime > 0) {
const startOfDay = new Date(startDate);
startOfDay.setHours(0, 0, 0, 0);
const endOfDay = new Date(startOfDay);
endOfDay.setDate(endOfDay.getDate() + 1);
const timeUntilEndOfDay = (endOfDay - startDate) / 1000 | 0;
if (elapsedTime <= timeUntilEndOfDay) {
// All remaining time fits in the current day
await addTime(url, elapsedTime, formatDate(startDate));
elapsedTime = 0;
} else {
// Add time until the end of the current day
await addTime(url, timeUntilEndOfDay, formatDate(startDate));
elapsedTime -= timeUntilEndOfDay;
startDate.setDate(startDate.getDate() + 1);
startDate.setHours(0, 0, 0, 0);
}
}
await storageArea.set({ "c_url": [url, now / 1000 | 0] });
log("INFO", `Updated time for ${url}`);
}
/**
* Deletes the time entry for a given URL on a specified day from the storage.
*
* @param {string} url - The URL for which the time entry should be deleted.
* @param {string} [day=null] - The day for which the time entry should be deleted. Defaults to the current day if not provided.
* @returns {Promise<void>} A promise that resolves when the time entry has been deleted.
*/
async function deleteTime(url, day = null) {
log("FUNC", "Called deleteTime", "DodgerBlue");
day = day || getToday();
const { [day]: dayStorage } = await storageArea.get(day);
if (dayStorage?.[url]) {
delete dayStorage[url];
await storageArea.set({ [day]: dayStorage });
log("INFO", `Time successfully deleted for ${day}! Url: ${url}`);
} else {
log("WARN", `No entry found for ${url} on ${day}`);
}
}
/**
* Adds a URL to the ignore list and deletes its entry from today's records.
*
* @param {string} url - The URL to be ignored.
* @returns {Promise<void>} A promise that resolves when the URL has been added to the ignore list and its entry has been deleted from today's records.
*/
async function addIgnore(url) {
log("FUNC", "Called addIgnore", "DodgerBlue");
// First delete entry from today's records
// TODO: delete entry from all days -> currently it will only be deleted from the current day
await deleteTime(url);
// Add it to ignore list in local-storage
const { ignored: ignore_list = [] } = await storageArea.get("ignored");
ignore_list.push(url);
await storageArea.set({ "ignored": ignore_list });
log("INFO", `Url to ignore was added: ${url}`);
}
/**
* This function updates the time for the previous URL, retrieves the new active tab, checks if the URL is valid
* and not in the ignore list and updates the current URL based on the result.
*
* @returns {Promise<void>} A promise that resolves when the function completes.
*/
async function updateActive() {
log("EVENT", "Tab changed or updated!", "rgb(255, 153, 0)");
await updateTime();
// Get current active tab of active window
const [tab] = await browser.tabs.query({ active: true, currentWindow: true });
const url = tab?.url;
if (!url) {
log("WARN", "No URL found for the active tab.");
await storageArea.remove("c_url");
return;
}
// Get current ignore-list and validate url
const { ignored: ignore_list = [] } = await storageArea.get("ignored");
const valid = checkUrl(url, ignore_list);
if (!valid) {
await storageArea.remove("c_url");
return;
}
// Update current url in storage
await storageArea.set({
"c_url": [getHostname(url), Date.now() / 1000 | 0]
});
log("INFO", `Current url (c_url) updated to: ${url}`);
// Create new entry for new url (will be created only if not exists)
await addUrlEntry(getHostname(url));
}
// Event listener for when the extension is installed or updated
browser.runtime.onInstalled.addListener(async (details) => {
switch (details.reason) {
case "install":
log("EVENT", "Extension installed!", "rgb(255, 153, 0)");
// Set default values for the storage
await storageArea.set({
"c_url": null,
"ignored": [],
"settings": {
"focusDetection": true,
"absentDetection": true,
"inactivityTimeout": 120
}
});
break;
case "update":
log("EVENT", "Extension updated!", "rgb(255, 153, 0)");
break;
}
});
// Event listeners for tab changes
browser.tabs.onActivated.addListener(updateActive);
browser.tabs.onUpdated.addListener(updateActive);
// Wait for messages from popup.js and main.js
browser.runtime.onMessage.addListener((data, _sender, sendResponse) => {
// See the following link for more information on message handling in the background script,
// including the use of sendResponse in combination with async functionality:
// https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/onMessage#sending_an_asynchronous_response_using_sendresponse
log("MESSAGE", `${data.cmd}-Request received.`, "orchid");
switch (data.cmd) {
case 'update_time':
updateTime().then(() => sendResponse({ state: "updated" }));
return true;
case 'update_active':
updateActive().then(() => sendResponse({ state: "updated" }));
return true;
case 'stop':
try {
updateTime().then(async () => {
await storageArea.remove("c_url");
sendResponse({ state: "stopped" });
});
} catch (err) {
log("ERROR", `Error occurred when deleting c_url from storage after Stop-Request. Error: \n${err}`);
sendResponse({ state: "error" });
}
return true;
case 'delete_entry':
deleteTime(data.url).then(() => sendResponse({ state: "successful" }));
return true;
case 'ignore_entry':
addIgnore(data.url).then(() => sendResponse({ state: "successful" }));
return true;
default:
log("WARN", `Unknown command received: ${data.cmd}`);
break;
}
});