-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
263 lines (223 loc) · 6.72 KB
/
background.js
File metadata and controls
263 lines (223 loc) · 6.72 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
let activeTabId = null;
let activeUrl = null;
let activeHostname = null;
let startTime = null;
let trackingInterval = null;
// Track active tab changes
chrome.tabs.onActivated.addListener(async (activeInfo) => {
await handleTabChange(activeInfo.tabId);
});
// Track URL changes within tabs
chrome.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => {
if (tabId === activeTabId && changeInfo.url) {
await updateTimeSpent();
setActiveTab(tabId, tab.url);
}
});
// Track when Chrome becomes active/inactive
chrome.windows.onFocusChanged.addListener(async (windowId) => {
if (windowId === chrome.windows.WINDOW_ID_NONE) {
// Chrome lost focus
await updateTimeSpent();
resetActiveTab();
stopTrackingInterval();
} else {
// Chrome gained focus
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
if (tabs.length > 0) {
await handleTabChange(tabs[0].id);
}
}
});
// Set up persistent tracking using intervals
function startTrackingInterval() {
if (trackingInterval) {
clearInterval(trackingInterval);
}
// Update time spent every 5 seconds to ensure accuracy
trackingInterval = setInterval(async () => {
await updateTimeSpent();
// Reset start time to current time without changing the active site
if (activeHostname) {
startTime = Date.now();
}
}, 5000);
}
function stopTrackingInterval() {
if (trackingInterval) {
clearInterval(trackingInterval);
trackingInterval = null;
}
}
// Set up daily reset alarm at midnight
chrome.alarms.create("dailyReset", {
periodInMinutes: 1440, // 24 hours
when: getNextMidnight()
});
// Listen for the alarm
chrome.alarms.onAlarm.addListener((alarm) => {
if (alarm.name === "dailyReset") {
handleDailyReset();
}
});
// Get the timestamp for the next midnight
function getNextMidnight() {
const now = new Date();
const midnight = new Date(now);
midnight.setHours(24, 0, 0, 0);
return midnight.getTime();
}
// Reset daily stats and update weekly/monthly as needed
async function handleDailyReset() {
// First update any active session
await updateTimeSpent();
const today = new Date();
const data = await getStoredData();
// Store yesterday's data in history
const yesterday = new Date(today);
yesterday.setDate(yesterday.getDate() - 1);
const dateStr = formatDate(yesterday);
if (!data.history) data.history = {};
data.history[dateStr] = { ...data.daily };
// Reset daily stats
data.daily = {};
// Check if we need to reset weekly stats (on Mondays)
if (today.getDay() === 1) { // Monday
data.weekly = {};
} else {
// Update weekly from daily data
await updateAggregateStats(data.daily, data.weekly);
}
// Check if we need to reset monthly stats (on the 1st)
if (today.getDate() === 1) {
data.monthly = {};
} else {
// Update monthly from daily data
await updateAggregateStats(data.daily, data.monthly);
}
await chrome.storage.local.set({ data });
}
// Update aggregate (weekly/monthly) stats
async function updateAggregateStats(sourceData, targetData) {
Object.keys(sourceData).forEach(hostname => {
if (!targetData[hostname]) {
targetData[hostname] = sourceData[hostname];
} else {
targetData[hostname] += sourceData[hostname];
}
});
}
// Format date as YYYY-MM-DD
function formatDate(date) {
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
}
// Handle tab change
async function handleTabChange(tabId) {
await updateTimeSpent();
try {
const tab = await chrome.tabs.get(tabId);
if (tab.active) {
setActiveTab(tabId, tab.url);
startTrackingInterval(); // Start tracking interval when tab changes
}
} catch (error) {
console.error("Error getting tab info:", error);
resetActiveTab();
stopTrackingInterval();
}
}
// Set active tab information
function setActiveTab(tabId, url) {
try {
activeTabId = tabId;
activeUrl = url;
// Extract hostname
if (url && url.startsWith('http')) {
const urlObj = new URL(url);
activeHostname = urlObj.hostname;
} else {
activeHostname = "chrome://";
}
startTime = Date.now();
} catch (error) {
console.error("Error setting active tab:", error);
resetActiveTab();
}
}
// Reset active tab tracking
function resetActiveTab() {
activeTabId = null;
activeUrl = null;
activeHostname = null;
startTime = null;
}
// Update time spent on current site
async function updateTimeSpent() {
if (activeHostname && startTime) {
const timeSpent = Date.now() - startTime;
// Only log if more than 1 second was spent
if (timeSpent > 1000) {
const data = await getStoredData();
// Update daily stats
if (!data.daily[activeHostname]) {
data.daily[activeHostname] = 0;
}
data.daily[activeHostname] += timeSpent;
// Update weekly stats
if (!data.weekly[activeHostname]) {
data.weekly[activeHostname] = 0;
}
data.weekly[activeHostname] += timeSpent;
// Update monthly stats
if (!data.monthly[activeHostname]) {
data.monthly[activeHostname] = 0;
}
data.monthly[activeHostname] += timeSpent;
await chrome.storage.local.set({ data });
// For debugging - log to console
console.log(`Updated ${activeHostname}: +${formatTime(timeSpent)} (total: ${formatTime(data.daily[activeHostname])})`);
}
}
}
// Format milliseconds into human-readable time for logging
function formatTime(milliseconds) {
const seconds = Math.floor(milliseconds / 1000);
if (seconds < 60) {
return `${seconds}s`;
}
const minutes = Math.floor(seconds / 60);
const remainingSeconds = seconds % 60;
if (minutes < 60) {
return `${minutes}m ${remainingSeconds}s`;
}
const hours = Math.floor(minutes / 60);
const remainingMinutes = minutes % 60;
return `${hours}h ${remainingMinutes}m ${remainingSeconds}s`;
}
// Get stored time data
async function getStoredData() {
const result = await chrome.storage.local.get('data');
if (!result.data) {
return {
daily: {},
weekly: {},
monthly: {},
history: {}
};
}
return result.data;
}
// Initialize tracking when extension starts
chrome.runtime.onStartup.addListener(async () => {
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
if (tabs.length > 0) {
await handleTabChange(tabs[0].id);
}
});
// Start tracking when extension is installed or updated
chrome.runtime.onInstalled.addListener(async () => {
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
if (tabs.length > 0) {
await handleTabChange(tabs[0].id);
}
});