-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
512 lines (434 loc) · 15.5 KB
/
background.js
File metadata and controls
512 lines (434 loc) · 15.5 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
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
const IDLE_TIMEOUT = 60;
const ONE_YEAR_MS = 365 * 24 * 60 * 60 * 1000;
const BADGE_UPDATE_INTERVAL = 1000;
const EMAIL_HOUR = 23;
let currentTab = null;
let startTime = null;
let isIdle = false;
let badgeInterval = null;
function extractDomain(url) {
try {
const urlObj = new URL(url);
return urlObj.hostname;
} catch {
return null;
}
}
function getDateKey(date = new Date()) {
return date.toISOString().split('T')[0];
}
function formatBadgeTime(ms) {
if (!ms || ms < 0) return '';
const totalSeconds = Math.floor(ms / 1000);
const minutes = Math.floor(totalSeconds / 60);
const hours = Math.floor(minutes / 60);
if (hours > 0) {
const remainingMins = minutes % 60;
if (remainingMins > 0) {
return `${hours}h${remainingMins}`;
}
return `${hours}h`;
}
if (minutes > 0) {
return `${minutes}m`;
}
return `${totalSeconds}s`;
}
function formatEmailTime(ms) {
if (!ms || ms < 0) return '0m';
const totalSeconds = Math.floor(ms / 1000);
const minutes = Math.floor(totalSeconds / 60);
const hours = Math.floor(minutes / 60);
const remainingMins = minutes % 60;
if (hours > 0) {
return remainingMins > 0 ? `${hours}h ${remainingMins}m` : `${hours}h`;
}
return `${minutes}m`;
}
async function updateBadge() {
if (!currentTab || !currentTab.domain || isIdle) {
await chrome.action.setBadgeText({ text: '' });
return;
}
try {
const dateKey = getDateKey();
const { activityData = {} } = await chrome.storage.local.get('activityData');
let domainTime = 0;
if (activityData[dateKey] && activityData[dateKey][currentTab.domain]) {
domainTime = activityData[dateKey][currentTab.domain].totalTime || 0;
}
if (startTime) {
domainTime += Date.now() - startTime;
}
const badgeText = formatBadgeTime(domainTime);
await chrome.action.setBadgeText({ text: badgeText });
await chrome.action.setBadgeBackgroundColor({ color: '#22d3ee' });
await chrome.action.setBadgeTextColor({ color: '#0a0a0b' });
} catch (error) {
console.error('Failed to update badge:', error);
}
}
function startBadgeUpdates() {
if (badgeInterval) {
clearInterval(badgeInterval);
}
badgeInterval = setInterval(updateBadge, BADGE_UPDATE_INTERVAL);
updateBadge();
}
chrome.runtime.onInstalled.addListener(() => {
console.log('Activity Tracker installed');
initializeTracking();
});
chrome.runtime.onStartup.addListener(() => {
console.log('Activity Tracker started');
initializeTracking();
});
async function initializeTracking() {
chrome.idle.setDetectionInterval(IDLE_TIMEOUT);
chrome.alarms.create('cleanup', { periodInMinutes: 60 * 24 });
chrome.alarms.create('save', { periodInMinutes: 1 });
chrome.alarms.create('emailCheck', { periodInMinutes: 5 });
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
if (tab && tab.url) {
startTracking(tab);
}
await cleanOldData();
startBadgeUpdates();
}
function startTracking(tab) {
if (!tab || !tab.url || tab.url.startsWith('chrome://') || tab.url.startsWith('chrome-extension://')) {
currentTab = null;
startTime = null;
updateBadge();
return;
}
currentTab = {
id: tab.id,
url: tab.url,
title: tab.title || 'Untitled',
domain: extractDomain(tab.url)
};
startTime = Date.now();
updateBadge();
}
async function saveCurrentSession() {
if (!currentTab || !startTime || isIdle) {
return;
}
const timeSpent = Date.now() - startTime;
if (timeSpent < 1000) return;
const dateKey = getDateKey();
const { activityData = {} } = await chrome.storage.local.get('activityData');
if (!activityData[dateKey]) {
activityData[dateKey] = {};
}
const domain = currentTab.domain;
if (!domain) return;
if (!activityData[dateKey][domain]) {
activityData[dateKey][domain] = {
totalTime: 0,
pages: {}
};
}
activityData[dateKey][domain].totalTime += timeSpent;
const pageKey = currentTab.url;
if (!activityData[dateKey][domain].pages[pageKey]) {
activityData[dateKey][domain].pages[pageKey] = {
url: currentTab.url,
title: currentTab.title,
time: 0,
visits: 0
};
}
activityData[dateKey][domain].pages[pageKey].title = currentTab.title;
activityData[dateKey][domain].pages[pageKey].time += timeSpent;
activityData[dateKey][domain].pages[pageKey].visits += 1;
activityData[dateKey][domain].pages[pageKey].lastVisit = Date.now();
await chrome.storage.local.set({ activityData });
startTime = Date.now();
}
async function cleanOldData() {
const { activityData = {} } = await chrome.storage.local.get('activityData');
const cutoffDate = new Date(Date.now() - ONE_YEAR_MS);
const cutoffKey = getDateKey(cutoffDate);
let cleaned = false;
for (const dateKey of Object.keys(activityData)) {
if (dateKey < cutoffKey) {
delete activityData[dateKey];
cleaned = true;
}
}
if (cleaned) {
await chrome.storage.local.set({ activityData });
console.log('Cleaned old activity data');
}
}
// Email functionality
async function getEmailSettings() {
const { emailSettings = {} } = await chrome.storage.sync.get('emailSettings');
return emailSettings;
}
async function checkAndSendDailyEmail() {
const now = new Date();
const currentHour = now.getHours();
const dateKey = getDateKey();
if (currentHour !== EMAIL_HOUR) {
return;
}
const { lastEmailSent = '' } = await chrome.storage.local.get('lastEmailSent');
if (lastEmailSent === dateKey) {
return;
}
const emailSettings = await getEmailSettings();
if (!emailSettings.enabled || !emailSettings.apiKey || !emailSettings.userEmail) {
return;
}
const { activityData = {} } = await chrome.storage.local.get('activityData');
const todayData = activityData[dateKey];
if (!todayData || Object.keys(todayData).length === 0) {
return;
}
try {
await sendDailySummaryEmail(todayData, dateKey, emailSettings);
await chrome.storage.local.set({ lastEmailSent: dateKey });
console.log('Daily summary email sent successfully');
} catch (error) {
console.error('Failed to send daily summary email:', error);
}
}
function generateEmailHTML(todayData, dateKey) {
const domains = Object.entries(todayData)
.map(([domain, data]) => ({
domain,
totalTime: data.totalTime,
pagesCount: Object.keys(data.pages).length
}))
.sort((a, b) => b.totalTime - a.totalTime);
const totalTime = domains.reduce((sum, d) => sum + d.totalTime, 0);
const totalSites = domains.length;
const totalPages = domains.reduce((sum, d) => sum + d.pagesCount, 0);
const displayDate = new Date(dateKey).toLocaleDateString('en-US', {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric'
});
const domainRows = domains.slice(0, 15).map((d, index) => `
<tr style="background-color: ${index % 2 === 0 ? '#1a1a1d' : '#141416'};">
<td style="padding: 12px 16px; border-bottom: 1px solid #2a2a2e; color: #fafafa; font-size: 14px;">
<img src="https://www.google.com/s2/favicons?domain=${d.domain}&sz=16"
alt="" style="width: 16px; height: 16px; margin-right: 8px; vertical-align: middle; border-radius: 2px;">
${d.domain}
</td>
<td style="padding: 12px 16px; border-bottom: 1px solid #2a2a2e; color: #22d3ee; font-family: monospace; font-size: 14px; text-align: right;">
${formatEmailTime(d.totalTime)}
</td>
<td style="padding: 12px 16px; border-bottom: 1px solid #2a2a2e; color: #71717a; font-size: 13px; text-align: right;">
${d.pagesCount} ${d.pagesCount === 1 ? 'page' : 'pages'}
</td>
</tr>
`).join('');
const moreDomainsNote = domains.length > 15
? `<p style="color: #71717a; font-size: 12px; margin-top: 8px; text-align: center;">... and ${domains.length - 15} more sites</p>`
: '';
return `
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Daily Activity Summary</title>
</head>
<body style="margin: 0; padding: 0; background-color: #0a0a0b; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">
<div style="max-width: 600px; margin: 0 auto; padding: 40px 20px;">
<div style="text-align: center; margin-bottom: 32px;">
<h1 style="color: #fafafa; font-size: 24px; margin: 0 0 8px 0; font-weight: 600;">📊 Daily Activity Summary</h1>
<p style="color: #71717a; font-size: 14px; margin: 0;">${displayDate}</p>
</div>
<div style="display: flex; gap: 12px; margin-bottom: 32px;">
<div style="flex: 1; background-color: #111113; border: 1px solid #27272a; border-radius: 12px; padding: 20px; text-align: center;">
<div style="color: #22d3ee; font-size: 24px; font-weight: 600; font-family: monospace;">${formatEmailTime(totalTime)}</div>
<div style="color: #71717a; font-size: 11px; text-transform: uppercase; letter-spacing: 0.05em; margin-top: 4px;">Total Time</div>
</div>
<div style="flex: 1; background-color: #111113; border: 1px solid #27272a; border-radius: 12px; padding: 20px; text-align: center;">
<div style="color: #22d3ee; font-size: 24px; font-weight: 600; font-family: monospace;">${totalSites}</div>
<div style="color: #71717a; font-size: 11px; text-transform: uppercase; letter-spacing: 0.05em; margin-top: 4px;">Sites</div>
</div>
<div style="flex: 1; background-color: #111113; border: 1px solid #27272a; border-radius: 12px; padding: 20px; text-align: center;">
<div style="color: #22d3ee; font-size: 24px; font-weight: 600; font-family: monospace;">${totalPages}</div>
<div style="color: #71717a; font-size: 11px; text-transform: uppercase; letter-spacing: 0.05em; margin-top: 4px;">Pages</div>
</div>
</div>
<div style="background-color: #111113; border: 1px solid #27272a; border-radius: 12px; overflow: hidden;">
<div style="padding: 16px 16px 12px 16px; border-bottom: 1px solid #27272a;">
<h2 style="color: #fafafa; font-size: 14px; font-weight: 600; margin: 0;">Top Sites</h2>
</div>
<table style="width: 100%; border-collapse: collapse;">
<thead>
<tr style="background-color: #18181b;">
<th style="padding: 10px 16px; text-align: left; color: #71717a; font-size: 11px; font-weight: 500; text-transform: uppercase;">Site</th>
<th style="padding: 10px 16px; text-align: right; color: #71717a; font-size: 11px; font-weight: 500; text-transform: uppercase;">Time</th>
<th style="padding: 10px 16px; text-align: right; color: #71717a; font-size: 11px; font-weight: 500; text-transform: uppercase;">Pages</th>
</tr>
</thead>
<tbody>
${domainRows}
</tbody>
</table>
${moreDomainsNote}
</div>
<div style="text-align: center; margin-top: 32px; padding-top: 24px; border-top: 1px solid #27272a;">
<p style="color: #52525b; font-size: 12px; margin: 0;">
Sent by Activity Tracker browser extension
</p>
</div>
</div>
</body>
</html>
`;
}
async function sendDailySummaryEmail(todayData, dateKey, emailSettings) {
const htmlContent = generateEmailHTML(todayData, dateKey);
const displayDate = new Date(dateKey).toLocaleDateString('en-US', {
month: 'short',
day: 'numeric',
year: 'numeric'
});
const senderEmail = emailSettings.senderEmail || 'Activity Tracker <onboarding@resend.dev>';
const response = await fetch('https://api.resend.com/emails', {
method: 'POST',
headers: {
'Authorization': `Bearer ${emailSettings.apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
from: senderEmail,
to: emailSettings.userEmail,
subject: `📊 Activity Summary - ${displayDate}`,
html: htmlContent
})
});
if (!response.ok) {
const errorData = await response.text();
throw new Error(`Resend API error: ${response.status} - ${errorData}`);
}
return await response.json();
}
// Event listeners
chrome.tabs.onActivated.addListener(async (activeInfo) => {
await saveCurrentSession();
try {
const tab = await chrome.tabs.get(activeInfo.tabId);
startTracking(tab);
} catch {
currentTab = null;
startTime = null;
updateBadge();
}
});
chrome.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => {
if (!currentTab || tabId !== currentTab.id) return;
if (changeInfo.url) {
await saveCurrentSession();
startTracking(tab);
} else if (changeInfo.title && currentTab) {
currentTab.title = changeInfo.title;
}
});
chrome.windows.onFocusChanged.addListener(async (windowId) => {
if (windowId === chrome.windows.WINDOW_ID_NONE) {
await saveCurrentSession();
currentTab = null;
startTime = null;
updateBadge();
return;
}
const [tab] = await chrome.tabs.query({ active: true, windowId });
if (tab) {
await saveCurrentSession();
startTracking(tab);
}
});
chrome.idle.onStateChanged.addListener(async (state) => {
if (state === 'idle' || state === 'locked') {
await saveCurrentSession();
isIdle = true;
updateBadge();
} else if (state === 'active') {
isIdle = false;
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
if (tab) {
startTracking(tab);
}
}
});
chrome.alarms.onAlarm.addListener(async (alarm) => {
if (alarm.name === 'cleanup') {
await cleanOldData();
} else if (alarm.name === 'save') {
await saveCurrentSession();
} else if (alarm.name === 'emailCheck') {
await checkAndSendDailyEmail();
}
});
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === 'getActivityData') {
chrome.storage.local.get('activityData').then(({ activityData = {} }) => {
sendResponse({ activityData });
});
return true;
}
if (message.type === 'clearData') {
chrome.storage.local.set({ activityData: {} }).then(() => {
updateBadge();
sendResponse({ success: true });
});
return true;
}
if (message.type === 'getCurrentTracking') {
sendResponse({
currentTab,
startTime,
isIdle
});
return true;
}
if (message.type === 'getEmailSettings') {
getEmailSettings().then(settings => {
sendResponse({ settings });
});
return true;
}
if (message.type === 'saveEmailSettings') {
chrome.storage.sync.set({ emailSettings: message.settings }).then(() => {
sendResponse({ success: true });
});
return true;
}
if (message.type === 'sendTestEmail') {
(async () => {
try {
const emailSettings = await getEmailSettings();
if (!emailSettings.apiKey || !emailSettings.userEmail) {
sendResponse({ success: false, error: 'Please configure email settings first' });
return;
}
const dateKey = getDateKey();
const { activityData = {} } = await chrome.storage.local.get('activityData');
const todayData = activityData[dateKey];
if (!todayData || Object.keys(todayData).length === 0) {
sendResponse({ success: false, error: 'No activity data for today' });
return;
}
await sendDailySummaryEmail(todayData, dateKey, emailSettings);
sendResponse({ success: true });
} catch (error) {
sendResponse({ success: false, error: error.message });
}
})();
return true;
}
});
self.addEventListener('beforeunload', async () => {
await saveCurrentSession();
});