-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
361 lines (332 loc) · 12.4 KB
/
background.js
File metadata and controls
361 lines (332 loc) · 12.4 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
// background.js (MV3 service worker)
import {
openDb, txGet, txGetAll, txPut, txClear,
getHtmlSnapByVisit, getImgSnapByVisit
} from './db.js';
const uuid = () => crypto.randomUUID();
const state = {
recording: true,
dwellMs: 10000, // default 10s
allowIncognitoSnaps: false, // default off
preNavByTab: new Map(), // tabId -> { visitId, url, tsStart }
headByTab: new Map(), // tabId -> visitId
};
initSettings();
async function initSettings() {
await openDb();
const s = await new Promise(res => chrome.storage.local.get(
['recording', 'dwellMs', 'allowIncognitoSnaps'], obj => res(obj)
));
state.recording = typeof s.recording === 'boolean' ? s.recording : true;
state.dwellMs = Number.isFinite(s.dwellMs) ? s.dwellMs : 10000;
state.allowIncognitoSnaps = !!s.allowIncognitoSnaps;
}
// ——— DB helpers ———
async function putVisit(v) { await txPut('visits', v); }
async function getVisit(id) { return await txGet('visits', id); }
async function visitsAll() { return await txGetAll('visits'); }
async function putEdge(e) { await txPut('edges', e); }
async function edgesAll() { return await txGetAll('edges'); }
async function putHtmlSnap(s) { await txPut('snapshots_html', s); }
async function putImgSnap(s) { await txPut('snapshots_img', s); }
// ——— Dwell / auto-snapshot scheduling ———
function scheduleDwellAlarm(tabId) {
// per-tab dwell alarm
chrome.alarms.create(`uvcs-dwell-${tabId}`, { when: Date.now() + state.dwellMs });
}
function clearDwellAlarm(tabId) {
chrome.alarms.clear(`uvcs-dwell-${tabId}`);
}
chrome.alarms.onAlarm.addListener(async (alarm) => {
if (!alarm.name.startsWith('uvcs-dwell-')) return;
const tabId = Number(alarm.name.slice('uvcs-dwell-'.length));
if (!state.recording) return;
const headId = state.headByTab.get(tabId);
if (!headId) return;
const v = await getVisit(headId);
if (!v) return;
// Only snapshot if dwell threshold elapsed on this node and not already captured
const base = v.tsLoaded || v.tsCommitted || v.tsStart || Date.now();
const elapsed = Date.now() - base;
if (elapsed < state.dwellMs) {
// reschedule lightly if user still on same page
scheduleDwellAlarm(tabId);
return;
}
if (v.incognito && !state.allowIncognitoSnaps) return;
// Attempt textual (always) + visual (only if tab is active & visible)
try {
// textual
if (!v.snapshotHtmlId) {
const html = await chrome.tabs.sendMessage(tabId, { type: 'uvcs.snapshot.request' }).catch(() => '');
if (html) {
const sid = uuid();
await putHtmlSnap({ id: sid, visitId: v.id, mime: 'text/html', htmlText: html });
v.snapshotHtmlId = sid;
await putVisit(v);
}
}
} catch {}
try {
if (!v.snapshotImgId) {
const tab = await chrome.tabs.get(tabId).catch(() => null);
if (tab && tab.active && typeof tab.windowId === 'number') {
const dataUrl = await chrome.tabs.captureVisibleTab(tab.windowId, { format: 'jpeg', quality: 80 }).catch(() => null);
if (dataUrl) {
const sid = uuid();
await putImgSnap({ id: sid, visitId: v.id, mime: 'image/jpeg', dataUrl });
v.snapshotImgId = sid;
await putVisit(v);
}
}
}
} catch {}
// No further auto-capture; user can recapture manually if needed
});
// ——— Navigation tracking ———
// (1) Before navigate → create tentative node (so we don’t miss root hop)
chrome.webNavigation.onBeforeNavigate.addListener(async (d) => {
if (!state.recording || d.frameId !== 0) return;
try {
const tab = await chrome.tabs.get(d.tabId);
const visit = {
id: uuid(),
url: d.url,
title: null,
tsStart: Date.now(),
tsCommitted: null,
tsLoaded: null,
durationMs: 0,
httpStatus: null,
kind: 'request',
tabId: d.tabId,
windowId: tab.windowId,
incognito: !!tab.incognito,
snapshotHtmlId: null,
snapshotImgId: null
};
await putVisit(visit);
state.preNavByTab.set(d.tabId, { visitId: visit.id, url: d.url, tsStart: visit.tsStart });
state.headByTab.set(d.tabId, visit.id);
clearDwellAlarm(d.tabId);
scheduleDwellAlarm(d.tabId);
} catch {}
});
// (2) SPA route changes → new node with type 'spa'
chrome.webNavigation.onHistoryStateUpdated.addListener(async (d) => {
if (!state.recording || d.frameId !== 0) return;
try {
const tab = await chrome.tabs.get(d.tabId);
const prevId = state.headByTab.get(d.tabId);
const visit = {
id: uuid(),
url: d.url,
title: tab.title || null,
tsStart: Date.now(),
tsCommitted: Date.now(),
tsLoaded: null,
durationMs: 0,
httpStatus: null,
kind: 'spa',
tabId: d.tabId,
windowId: tab.windowId,
incognito: !!tab.incognito,
snapshotHtmlId: null,
snapshotImgId: null
};
await putVisit(visit);
if (prevId) await putEdge({ id: uuid(), fromVisitId: prevId, toVisitId: visit.id, type: 'spa' });
state.headByTab.set(d.tabId, visit.id);
clearDwellAlarm(d.tabId);
scheduleDwellAlarm(d.tabId);
} catch {}
});
// (3) Committed → normal vs redirect
chrome.webNavigation.onCommitted.addListener(async (d) => {
if (!state.recording || d.frameId !== 0) return;
const tab = await chrome.tabs.get(d.tabId).catch(() => null);
if (!tab) return;
const pre = state.preNavByTab.get(d.tabId);
const isRedirect =
(d.transitionQualifiers && (d.transitionQualifiers.includes('server_redirect') || d.transitionQualifiers.includes('client_redirect'))) ||
(pre && pre.url !== d.url);
if (pre && !isRedirect) {
const v = await getVisit(pre.visitId);
if (v) {
v.kind = 'navigation';
v.tsCommitted = Date.now();
v.title = tab.title || v.title;
await putVisit(v);
state.headByTab.set(d.tabId, v.id);
clearDwellAlarm(d.tabId);
scheduleDwellAlarm(d.tabId);
}
state.preNavByTab.delete(d.tabId);
return;
}
// Redirect case (or missing pre)
const prevId = pre ? pre.visitId : state.headByTab.get(d.tabId);
const finalVisit = {
id: uuid(),
url: d.url,
title: tab.title || null,
tsStart: Date.now(),
tsCommitted: Date.now(),
tsLoaded: null,
durationMs: 0,
httpStatus: null,
kind: 'navigation',
tabId: d.tabId,
windowId: tab.windowId,
incognito: !!tab.incognito,
snapshotHtmlId: null,
snapshotImgId: null
};
await putVisit(finalVisit);
if (prevId) await putEdge({ id: uuid(), fromVisitId: prevId, toVisitId: finalVisit.id, type: 'redirect' });
state.headByTab.set(d.tabId, finalVisit.id);
clearDwellAlarm(d.tabId);
scheduleDwellAlarm(d.tabId);
if (pre) state.preNavByTab.delete(d.tabId);
});
// (4) Loaded → mark tsLoaded
chrome.webNavigation.onCompleted.addListener(async (d) => {
if (!state.recording || d.frameId !== 0) return;
const headId = state.headByTab.get(d.tabId);
if (!headId) return;
const v = await getVisit(headId);
if (v && !v.tsLoaded) {
v.tsLoaded = Date.now();
await putVisit(v);
}
});
// (5) HTTP status for “head” visit
chrome.webRequest.onHeadersReceived.addListener(async (info) => {
if (!state.recording || info.tabId < 0) return;
const headId = state.headByTab.get(info.tabId);
if (!headId) return;
const v = await getVisit(headId);
if (!v) return;
const st = info.statusCode || null;
if (st && st !== v.httpStatus) {
v.httpStatus = st;
await putVisit(v);
}
}, { urls: ['<all_urls>'] });
// ——— Messaging (popup/content) ———
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
(async () => {
if (msg?.type === 'uvcs.toggle') {
state.recording = !!msg.enabled;
await chrome.storage.local.set({ recording: state.recording });
sendResponse({ ok: true, enabled: state.recording });
return;
}
if (msg?.type === 'uvcs.settings.set') {
const { dwellMs, allowIncognitoSnaps } = msg;
if (Number.isFinite(dwellMs)) { state.dwellMs = dwellMs; await chrome.storage.local.set({ dwellMs }); }
if (typeof allowIncognitoSnaps === 'boolean') { state.allowIncognitoSnaps = allowIncognitoSnaps; await chrome.storage.local.set({ allowIncognitoSnaps }); }
sendResponse({ ok: true, dwellMs: state.dwellMs, allowIncognitoSnaps: state.allowIncognitoSnaps });
return;
}
if (msg?.type === 'uvcs.query') {
const vs = (await visitsAll()).sort((a,b) => b.tsStart - a.tsStart);
const es = await edgesAll();
sendResponse({ visits: vs, edges: es, recording: state.recording, dwellMs: state.dwellMs, allowIncognitoSnaps: state.allowIncognitoSnaps });
return;
}
if (msg?.type === 'uvcs.clear') {
await txClear('visits'); await txClear('edges'); await txClear('snapshots_html'); await txClear('snapshots_img');
state.preNavByTab.clear(); state.headByTab.clear();
sendResponse({ ok: true }); return;
}
// Manual snapshot (capture both if possible)
if (msg?.type === 'uvcs.snapshot.capture') {
const { tabId, visitId } = msg;
const v = await getVisit(visitId);
if (!v) { sendResponse({ ok: false, error: 'visit_not_found' }); return; }
if (v.incognito && !state.allowIncognitoSnaps) { sendResponse({ ok: false, error: 'incognito_blocked' }); return; }
// textual
let htmlOK = false, imgOK = false;
try {
const html = await chrome.tabs.sendMessage(tabId, { type: 'uvcs.snapshot.request' });
if (html) {
const sid = uuid();
await putHtmlSnap({ id: sid, visitId, mime: 'text/html', htmlText: html });
v.snapshotHtmlId = sid;
await putVisit(v);
htmlOK = true;
}
} catch {}
// visual (only if active)
try {
const tab = await chrome.tabs.get(tabId).catch(()=>null);
if (tab && tab.active && typeof tab.windowId === 'number') {
const dataUrl = await chrome.tabs.captureVisibleTab(tab.windowId, { format: 'jpeg', quality: 80 }).catch(()=>null);
if (dataUrl) {
const sid2 = uuid();
await putImgSnap({ id: sid2, visitId, mime: 'image/jpeg', dataUrl });
v.snapshotImgId = sid2;
await putVisit(v);
imgOK = true;
}
}
} catch {}
sendResponse({ ok: htmlOK || imgOK, html: htmlOK, img: imgOK });
return;
}
// Get snapshot (format: 'html' | 'img')
if (msg?.type === 'uvcs.snapshot.get') {
const { visitId, format } = msg;
if (format === 'html') {
const s = await getHtmlSnapByVisit(visitId);
if (!s) { sendResponse({ ok: false, error: 'not_found' }); return; }
sendResponse({ ok: true, mime: s.mime, htmlText: s.htmlText, id: s.id });
return;
} else if (format === 'img') {
const s = await getImgSnapByVisit(visitId);
if (!s) { sendResponse({ ok: false, error: 'not_found' }); return; }
sendResponse({ ok: true, mime: s.mime, dataUrl: s.dataUrl, id: s.id });
return;
} else {
sendResponse({ ok: false, error: 'bad_format' }); return;
}
}
// Export (JSON)
if (msg?.type === 'uvcs.export.json') {
const vs = await txGetAll('visits');
const es = await txGetAll('edges');
sendResponse({ ok: true, payload: { app: 'uvcs', version: 1, exportedAt: new Date().toISOString(), visits: vs, edges: es } });
return;
}
// Import (JSON of visits+edges)
if (msg?.type === 'uvcs.import.json') {
const { payload } = msg;
if (!payload || !Array.isArray(payload.visits) || !Array.isArray(payload.edges)) {
sendResponse({ ok: false, error: 'invalid_payload' }); return;
}
// remap visit IDs to avoid collisions
const idMap = new Map();
for (const v of payload.visits) {
const newId = uuid();
idMap.set(v.id, newId);
const nv = { ...v, id: newId };
// snapshots not imported in JSON mode
delete nv.snapshotHtmlId; delete nv.snapshotImgId;
await putVisit(nv);
}
for (const e of payload.edges) {
const ne = {
id: uuid(),
fromVisitId: idMap.get(e.fromVisitId) || e.fromVisitId,
toVisitId: idMap.get(e.toVisitId) || e.toVisitId,
type: e.type || 'navigation'
};
await putEdge(ne);
}
sendResponse({ ok: true, importedVisits: payload.visits.length, importedEdges: payload.edges.length });
return;
}
})();
return true;
});