-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
296 lines (258 loc) · 7.99 KB
/
Copy pathbackground.js
File metadata and controls
296 lines (258 loc) · 7.99 KB
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
import {
defaultValues,
loadStatus,
storageKeys,
messageType,
} from "./js/utils.js";
// URL Filter /////////////
const urlParser = (url) => {
const parsedUrl = new URL(url);
const domain = parsedUrl.hostname;
return domain;
};
//If URL found in the pattern, return true. Else, return false.
const urlFilter = (currentWebsite) => {
if (!currentWebsite.url) {
return false;
}
let url = currentWebsite.url;
let pattern = /^chrome:\/\//;
if (pattern.test(url)) {
return true;
}
return false;
};
//////////////////////////////
// CurrentWebsiteData Operations
const getCurrentWebsiteFromStore = async () => {
const currentWebsiteData = await new Promise((resolve, reject) => {
chrome.storage.local.get(storageKeys.CURRENTWEBSITE, (result) => {
if (chrome.runtime.lastError) {
reject(chrome.runtime.lastError);
} else {
let currentWebsite =
result.currentWebsite || defaultValues.currentWebsite;
if (
currentWebsite.lastAccessedDate !== new Date().toLocaleDateString()
) {
currentWebsite = defaultValues.currentWebsite;
currentWebsite.lastAccessedDate = new Date().toLocaleDateString();
resetData(currentWebsite);
}
resolve(currentWebsite);
}
});
});
return currentWebsiteData;
};
const setCurrentWebsiteToStore = async (data) => {
chrome.storage.local.set({ currentWebsite: data }, () => {
if (chrome.runtime.lastError) {
console.error("Error ", chrome.runtime.lastError);
}
});
};
const setCurrentWebsite = ({ currentWebsite, id, url, status, startTime }) => {
const propertiesToUpdate = { id, url, status, startTime };
for (const [key, value] of Object.entries(propertiesToUpdate)) {
if (value !== undefined) {
if (value === null) {
currentWebsite[key] = null;
} else {
currentWebsite[key] = value;
}
}
}
// if (startTime) {
// console.log("time started at ", currentWebsite.url);
// }
setCurrentWebsiteToStore(currentWebsite);
};
/////////////////////////////
// Timer Operations /////////
const stopTimer = (currentWebsite) => {
if (
!currentWebsite.url ||
urlFilter(currentWebsite) ||
!currentWebsite.startTime
) {
return;
}
let endTime = Date.now();
let timeSpent = (endTime - currentWebsite.startTime) / 60000;
// console.log("time stopped at ", currentWebsite.url, timeSpent);
saveDataToStore(currentWebsite.url, timeSpent);
};
//////////////////////////////
// Get/Set Data (sitesInfo, sitesData) From Store and Custom Operations to Aid this functionality //
const getDataFromStore = async () => {
try {
const sitesData = await new Promise((resolve, reject) => {
chrome.storage.local.get(storageKeys.SITESDATA, (result) => {
if (chrome.runtime.lastError) {
reject(chrome.runtime.lastError);
} else {
resolve(result.sitesData || defaultValues.sitesData);
}
});
});
const sitesInfo = await new Promise((resolve, reject) => {
chrome.storage.local.get(storageKeys.SITESINFO, (result) => {
if (chrome.runtime.lastError) {
reject(chrome.runtime.lastError);
} else {
resolve(result.sitesInfo || defaultValues.sitesInfo);
}
});
});
return { sitesData, sitesInfo };
} catch (error) {
console.error("Error fetching data from storage:", error);
return {
sitesData: defaultValues.sitesData,
sitesInfo: defaultValues.sitesInfo,
};
}
};
/*
Functionality:-
If a certain url is in array, find the index in the arr and append time
if it is not there, create a new object of url and time and append to the arr
*/
const customArrOperation = (arr, url, time) => {
let idx = arr.urlArr.findIndex((item) => item.url === url);
if (idx !== -1) {
arr.urlArr[idx].timeSpent += time;
} else {
let data = { url: url, timeSpent: time };
arr.urlArr.push(data);
}
arr.time += time;
return arr;
};
const saveDataSetOperation = (data) => {
chrome.storage.local.set({ sitesInfo: data }, () => {
if (chrome.runtime.lastError) {
console.error("Error ", chrome.runtime.lastError);
}
});
};
const saveDataToStore = async (url, timeSpent) => {
const { sitesData, sitesInfo } = await getDataFromStore();
const parsedUrl = urlParser(url);
const { domain, webPage } = sitesData;
let idx = webPage.findIndex((item) => item.url === url);
// check if the current URL is listed in the webpage prod list
if (idx !== -1) {
sitesInfo.prod = customArrOperation(sitesInfo.prod, url, timeSpent);
}
// else check if the current URL is listed in the domain prod list
else {
let idxd = domain.findIndex((item) => item.url === parsedUrl);
if (idxd !== -1) {
sitesInfo.prod = customArrOperation(sitesInfo.prod, parsedUrl, timeSpent);
}
// it means it is not a productive site, add it to unproductive list
else {
sitesInfo.nonProd = customArrOperation(
sitesInfo.nonProd,
parsedUrl,
timeSpent
);
}
}
saveDataSetOperation(sitesInfo);
};
///////////////////////////////////////////
// Main Logic /////////////////////////////
chrome.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => {
const currentWebsite = await getCurrentWebsiteFromStore();
// NEW WEBSITE, UPDATE WEBSITE, RELOAD WEBSITE
if (
currentWebsite?.id &&
tabId == currentWebsite.id &&
tab.url &&
tab.status === "complete"
) {
// in case of new tab, setting a url
if (currentWebsite.status === loadStatus.INITIAL) {
setCurrentWebsite({
currentWebsite,
url: tab.url,
status: loadStatus.LOADED,
startTime: Date.now(),
});
} else if (
currentWebsite.status === loadStatus.LOADED &&
currentWebsite.url !== tab.url
) {
stopTimer(currentWebsite);
setCurrentWebsite({
currentWebsite,
url: tab.url,
status: loadStatus.LOADED,
startTime: Date.now(),
});
}
}
});
chrome.tabs.onActivated.addListener((activeInfo) => {
// CHANGE TAB
chrome.tabs.get(activeInfo.tabId, async (tab) => {
const currentWebsite = await getCurrentWebsiteFromStore();
stopTimer(currentWebsite);
setCurrentWebsite({
currentWebsite,
id: tab.id,
url: tab.url ?? null,
status: tab.url ? loadStatus.LOADED : loadStatus.INITIAL,
startTime: Date.now(),
});
});
});
////////////////////////////////////////////////////
// Out of focus/ Window change ////
chrome.windows.onFocusChanged.addListener(async (windowId) => {
let currentWebsite = await getCurrentWebsiteFromStore();
if (windowId === chrome.windows.WINDOW_ID_NONE) {
stopTimer(currentWebsite);
setCurrentWebsite({
currentWebsite,
startTime: null,
status: loadStatus.LOST_FOCUS,
});
} else {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
const activeTab = tabs[0];
setCurrentWebsite({
currentWebsite,
id: activeTab.id,
url: activeTab.url,
status: loadStatus.LOADED,
startTime: Date.now(),
});
});
}
});
////////////////////////////////////////////////////
// Update the data when the extension is opened ////
chrome.runtime.onMessage.addListener(async (message) => {
if (message.action === messageType.ONSTART) {
let currentWebsite = await getCurrentWebsiteFromStore();
stopTimer(currentWebsite);
setCurrentWebsite({ currentWebsite, startTime: Date.now() });
}
});
////////////////////////////////////////////////////
// Reset Data (Everyday reset data) ////////////////
const resetData = (currentWebsite) => {
chrome.storage.local.get(storageKeys.SITESINFO, (result) => {
result = result.sitesInfo || defaultValues.sitesInfo;
chrome.storage.local.set({ previousSitesInfo: result });
});
chrome.storage.local.set({ currentWebsite: currentWebsite });
chrome.storage.local.set({
sitesInfo: defaultValues.sitesInfo,
});
};
////////////////////////////////////////////////////