-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
1186 lines (1078 loc) · 34.8 KB
/
Copy pathbackground.js
File metadata and controls
1186 lines (1078 loc) · 34.8 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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
DEFAULT_SETTINGS,
SETTINGS_KEY,
mergeSettings,
normalizeSettings,
settingsForContent
} from "./shared/settings.js";
import { lookupWordWithLlm, generateQuizWithLlm, gradeBlankAnswersWithLlm } from "./shared/llm.js";
import {
loadArenaMisses,
removeArenaMissesStorage,
upsertArenaMissesStorage
} from "./shared/arena-misses.js";
import {
deleteCapture as dbDeleteCapture,
deleteQuiz as dbDeleteQuiz,
deleteWord as dbDeleteWord,
getAllCaptures as dbGetAllCaptures,
getAllFavicons as dbGetAllFavicons,
getAllQuizzes as dbGetAllQuizzes,
getAllScreenshots as dbGetAllScreenshots,
getAllWords as dbGetAllWords,
getCapture as dbGetCapture,
getFavicon as dbGetFavicon,
getQuiz as dbGetQuiz,
getScreenshot as dbGetScreenshot,
getWord as dbGetWord,
findWordByNormalized as dbFindWordByNormalized,
importAllData as dbImportAllData,
migrateFromStorage,
putFavicon as dbPutFavicon,
putScreenshot as dbPutScreenshot,
saveCapture as dbSaveCapture,
saveQuiz as dbSaveQuiz,
saveScreenshotCapture as dbSaveScreenshotCapture,
saveWord as dbSaveWord,
updateCapture as dbUpdateCapture,
updateQuiz as dbUpdateQuiz,
updateWord as dbUpdateWord
} from "./shared/db.js";
const faviconMem = new Map();
let migratePromise = null;
function ensureMigrated() {
if (!migratePromise) {
migratePromise = migrateFromStorage().then((res) => {
if (res && res.migrated && (res.captures || res.favicons)) {
console.log("[RecordU] migrated to IndexedDB", res);
}
return res;
});
}
return migratePromise;
}
/** Keep the MV3 service worker alive during long LLM fetches. */
function withLlmKeepAlive(promise) {
const id = setInterval(() => {}, 20000);
return Promise.resolve(promise).finally(() => clearInterval(id));
}
function llmFailResponse(e, extra = {}) {
const code = (e && e.code) || "error";
let error = String(e && e.message ? e.message : e);
if (code === "timeout") {
error = "请求超时,请减少题量或稍后重试";
} else if (code === "aborted") {
error = "已取消";
}
return { ok: false, error, code, ...extra };
}
function hostFromUrl(url) {
try {
let h = new URL(url).hostname;
if (h.startsWith("www.")) h = h.slice(4);
return h || null;
} catch (e) {
return null;
}
}
async function broadcastToContentTabs(message) {
try {
const tabs = await chrome.tabs.query({});
await Promise.all(
tabs.map(async (tab) => {
if (!tab.id || !tab.url) return;
if (!/^https?:/i.test(tab.url) && !/\.pdf(\?|#|$)/i.test(tab.url)) return;
try {
await chrome.tabs.sendMessage(tab.id, message);
} catch (e) {
// tab without content script
}
})
);
} catch (e) {}
}
async function notifyCapturesChanged(pageUrl) {
await broadcastToContentTabs({
type: "rc-captures-changed",
pageUrl: pageUrl || null
});
}
async function notifyWordsChanged() {
await broadcastToContentTabs({ type: "rc-words-changed" });
}
async function notifySettingsChanged(settings) {
await broadcastToContentTabs({
type: "rc-settings-changed",
settings: settingsForContent(settings)
});
}
// ---------- toolbar icon: word-scan progress ring ----------
const DEFAULT_ACTION_ICON = {
16: "icons/icon16.png",
48: "icons/icon48.png",
128: "icons/icon128.png"
};
const ICON_PROGRESS_SIZES = [16, 32];
const ICON_DONE_HOLD_MS = 520;
/** Merge back-to-back word scans (idle + delayed reconcile) into one ring. */
const ICON_DONE_SETTLE_MS = 750;
/** @type {ImageBitmap | null} */
let actionIconBitmap = null;
/** @type {Map<number, any>} */
const tabIconProgress = new Map();
async function loadActionIconBitmap() {
if (actionIconBitmap) return actionIconBitmap;
const res = await fetch(chrome.runtime.getURL("icons/icon128.png"));
const blob = await res.blob();
actionIconBitmap = await createImageBitmap(blob);
return actionIconBitmap;
}
function drawActionProgressIcon(bitmap, size, ratio, done) {
const canvas = new OffscreenCanvas(size, size);
const ctx = canvas.getContext("2d");
const lw = Math.max(1.5, size * 0.14);
const inset = Math.ceil(lw + 0.5);
ctx.clearRect(0, 0, size, size);
ctx.drawImage(bitmap, inset, inset, size - inset * 2, size - inset * 2);
const t = Math.max(0, Math.min(1, ratio));
if (t <= 0.001 && !done) {
return ctx.getImageData(0, 0, size, size);
}
const cx = size / 2;
const cy = size / 2;
const r = size / 2 - lw / 2;
const start = -Math.PI / 2;
const sweep = Math.PI * 2 * (done ? 1 : t);
ctx.lineWidth = lw;
ctx.lineCap = "butt";
ctx.strokeStyle = done ? "#2e7d32" : "#0000ff";
ctx.beginPath();
ctx.arc(cx, cy, r, start, start + sweep);
ctx.stroke();
return ctx.getImageData(0, 0, size, size);
}
function clearTabIconState(tabId) {
const st = tabIconProgress.get(tabId);
if (st) {
if (st.doneTimer) clearTimeout(st.doneTimer);
if (st.settleTimer) clearTimeout(st.settleTimer);
if (st.animTimer) clearInterval(st.animTimer);
}
tabIconProgress.delete(tabId);
}
async function restoreDefaultActionIcon(tabId) {
clearTabIconState(tabId);
try {
await chrome.action.setIcon({ tabId, path: DEFAULT_ACTION_ICON });
} catch (e) {}
}
async function paintTabActionProgress(tabId, ratio, done) {
const bitmap = await loadActionIconBitmap();
const imageData = {};
for (const size of ICON_PROGRESS_SIZES) {
imageData[size] = drawActionProgressIcon(bitmap, size, ratio, done);
}
try {
await chrome.action.setIcon({ tabId, imageData });
} catch (e) {}
}
function ensureTabIconAnim(tabId) {
let st = tabIconProgress.get(tabId);
if (!st || st.animTimer) return;
st.animTimer = setInterval(() => {
st = tabIconProgress.get(tabId);
if (!st) return;
const target = Math.max(0, Math.min(1, st.targetRatio || 0));
const step = target >= 0.999 ? 0.08 : 0.028;
if (st.displayRatio + 0.002 >= target) {
st.displayRatio = target;
clearInterval(st.animTimer);
st.animTimer = null;
const finishing = !!st.pendingDone && target >= 0.999;
paintTabActionProgress(tabId, st.displayRatio, finishing).catch(() => {});
if (finishing) {
st.pendingDone = false;
st.sessionActive = false;
if (st.doneTimer) clearTimeout(st.doneTimer);
st.doneTimer = setTimeout(() => {
restoreDefaultActionIcon(tabId);
}, ICON_DONE_HOLD_MS);
}
return;
}
st.displayRatio = Math.min(target, st.displayRatio + step);
paintTabActionProgress(tabId, st.displayRatio, false).catch(() => {});
}, 45);
}
function cancelIconDonePipeline(st) {
if (st.doneTimer) {
clearTimeout(st.doneTimer);
st.doneTimer = null;
}
if (st.settleTimer) {
clearTimeout(st.settleTimer);
st.settleTimer = null;
}
st.pendingDone = false;
}
async function handleWordScanProgress(tabId, msg) {
if (!tabId) return;
const phase = msg && msg.phase;
const gen = Number(msg && msg.gen) || 0;
let st = tabIconProgress.get(tabId);
if (!st) {
st = {
lastSentAt: 0,
lastRatio: 0,
displayRatio: 0,
targetRatio: 0,
sessionBase: 0,
sessionActive: false,
doneTimer: null,
settleTimer: null,
animTimer: null,
pendingDone: false,
gen: 0
};
tabIconProgress.set(tabId, st);
}
if (phase === "clear") {
await restoreDefaultActionIcon(tabId);
return;
}
if (phase === "start") {
cancelIconDonePipeline(st);
st.gen = gen;
const continueSession =
st.sessionActive || st.displayRatio > 0.02 || st.targetRatio > 0.02;
if (continueSession) {
// Page often runs wordFull more than once; keep the ring growing.
st.sessionBase = Math.max(st.sessionBase, st.displayRatio);
st.sessionActive = true;
return;
}
if (st.animTimer) {
clearInterval(st.animTimer);
st.animTimer = null;
}
st.sessionActive = true;
st.sessionBase = 0;
st.displayRatio = 0;
st.targetRatio = 0;
st.lastRatio = 0;
st.lastSentAt = Date.now();
await paintTabActionProgress(tabId, 0, false);
return;
}
if (phase === "done") {
st.gen = gen;
// Wait: another word pass may start immediately (idle / delayed reconcile).
if (st.settleTimer) clearTimeout(st.settleTimer);
st.settleTimer = setTimeout(() => {
st.settleTimer = null;
st.pendingDone = true;
st.targetRatio = 1;
st.lastRatio = 1;
ensureTabIconAnim(tabId);
}, ICON_DONE_SETTLE_MS);
return;
}
cancelIconDonePipeline(st);
st.gen = gen;
st.sessionActive = true;
const raw = Math.max(0, Math.min(1, Number(msg.ratio) || 0));
const base = Math.max(0, Math.min(1, st.sessionBase || 0));
const mapped = base + (1 - base) * raw;
if (mapped + 0.0005 < st.targetRatio) return;
st.targetRatio = mapped;
st.lastRatio = mapped;
st.lastSentAt = Date.now();
ensureTabIconAnim(tabId);
}
chrome.tabs.onRemoved.addListener((tabId) => {
clearTabIconState(tabId);
});
chrome.tabs.onUpdated.addListener((tabId, changeInfo) => {
if (changeInfo.status === "loading" && changeInfo.url) {
restoreDefaultActionIcon(tabId);
}
});
async function getSettings() {
const data = await chrome.storage.local.get(SETTINGS_KEY);
return normalizeSettings(data[SETTINGS_KEY]);
}
async function saveSettings(patch) {
const current = await getSettings();
const next = mergeSettings(current, patch);
await chrome.storage.local.set({ [SETTINGS_KEY]: next });
await notifySettingsChanged(next);
return next;
}
async function resetSettings() {
const next = { ...DEFAULT_SETTINGS };
await chrome.storage.local.set({ [SETTINGS_KEY]: next });
await notifySettingsChanged(next);
return next;
}
async function lookupWord(word) {
const settings = await getSettings();
return lookupWordWithLlm(word, settings);
}
async function saveWord(payload) {
await ensureMigrated();
const record = await dbSaveWord(payload);
await notifyWordsChanged();
return record;
}
async function updateWord(id, patch) {
await ensureMigrated();
const next = await dbUpdateWord(id, patch);
if (next) await notifyWordsChanged();
return next;
}
async function deleteWord(id) {
await ensureMigrated();
await dbDeleteWord(id);
await notifyWordsChanged();
}
async function saveCapture(capture) {
await ensureMigrated();
const record = await dbSaveCapture(capture);
const host = hostFromUrl(record.pageUrl);
if (host) fetchFaviconDataUrl(host);
await notifyCapturesChanged(record.pageUrl);
return record;
}
async function updateCapture(id, patch) {
await ensureMigrated();
const next = await dbUpdateCapture(id, patch);
if (next) await notifyCapturesChanged(next.pageUrl);
return next;
}
async function deleteCapture(id) {
await ensureMigrated();
const existing = await dbGetCapture(id);
await dbDeleteCapture(id);
await notifyCapturesChanged(existing && existing.pageUrl);
}
function mimeToExt(mime) {
const m = String(mime || "").toLowerCase();
if (m.includes("png")) return "png";
if (m.includes("webp")) return "webp";
if (m.includes("gif")) return "gif";
if (m.includes("svg")) return "svg";
if (m.includes("x-icon") || m.includes("vnd.microsoft.icon") || m.includes("icon")) return "ico";
return "jpg";
}
function mimeFromDataUrl(dataUrl) {
if (typeof dataUrl !== "string") return "";
const m = /^data:([^;,]+)/i.exec(dataUrl);
return (m && m[1]) || "";
}
function sanitizeHostForFile(host) {
return String(host || "unknown")
.trim()
.toLowerCase()
.replace(/[^a-z0-9._-]+/g, "_")
.replace(/^_+|_+$/g, "")
.slice(0, 120) || "unknown";
}
async function exportBackupMeta() {
await ensureMigrated();
const [captures, words, favicons, screenshots, settings, quizzes] = await Promise.all([
dbGetAllCaptures(),
dbGetAllWords(),
dbGetAllFavicons(),
dbGetAllScreenshots(),
getSettings(),
dbGetAllQuizzes()
]);
const shotIndex = (screenshots || [])
.filter((s) => s && s.captureId)
.map((s) => {
const mime = s.mime || (s.blob && s.blob.type) || "image/jpeg";
const ext = mimeToExt(mime);
return {
captureId: s.captureId,
mime,
w: typeof s.w === "number" ? s.w : 0,
h: typeof s.h === "number" ? s.h : 0,
file: `screenshots/${s.captureId}.${ext}`
};
});
const usedFavNames = new Set();
const favIndex = (favicons || [])
.filter((f) => f && f.host && f.dataUrl)
.map((f) => {
const mime = mimeFromDataUrl(f.dataUrl) || "image/png";
const ext = mimeToExt(mime);
let base = sanitizeHostForFile(f.host);
let file = `favicons/${base}.${ext}`;
let n = 2;
while (usedFavNames.has(file)) {
file = `favicons/${base}_${n}.${ext}`;
n++;
}
usedFavNames.add(file);
return {
host: f.host,
mime,
updatedAt: f.updatedAt || 0,
file
};
});
return {
format: "recordu-backup",
version: 1,
exportedAt: Date.now(),
settings,
captures: captures || [],
words: words || [],
quizzes: quizzes || [],
favicons: favIndex,
screenshots: shotIndex
};
}
async function getScreenshotBuffer(captureId) {
await ensureMigrated();
const row = await dbGetScreenshot(captureId);
if (!row || !row.blob) return null;
// Prefer base64 over ArrayBuffer — some Chromium forks drop binary in messages.
const dataUrl = await blobToDataUrl(row.blob);
const comma = dataUrl.indexOf(",");
const base64 = comma >= 0 ? dataUrl.slice(comma + 1) : "";
return {
captureId: row.captureId,
mime: row.mime || row.blob.type || "image/jpeg",
w: typeof row.w === "number" ? row.w : 0,
h: typeof row.h === "number" ? row.h : 0,
base64
};
}
async function getFaviconBuffer(host) {
await ensureMigrated();
if (!host) return null;
const dataUrl = await dbGetFavicon(host);
if (!dataUrl || typeof dataUrl !== "string" || !dataUrl.startsWith("data:")) return null;
const comma = dataUrl.indexOf(",");
if (comma < 0) return null;
const meta = dataUrl.slice(0, comma);
const base64 = dataUrl.slice(comma + 1);
if (!base64) return null;
const mimeMatch = /^data:([^;,]+)/i.exec(meta);
return {
host,
mime: (mimeMatch && mimeMatch[1]) || "image/png",
base64
};
}
async function importBackupBegin(payload) {
await ensureMigrated();
if (!payload || payload.format !== "recordu-backup") {
throw new Error("invalid backup format");
}
const settings = normalizeSettings(payload.settings);
await chrome.storage.local.set({ [SETTINGS_KEY]: settings });
// Legacy backups embed favicon dataUrl in JSON; file-based favicons are imported later.
const legacyFavs = (Array.isArray(payload.favicons) ? payload.favicons : []).filter(
(f) => f && f.host && typeof f.dataUrl === "string" && f.dataUrl.startsWith("data:")
);
const counts = await dbImportAllData({
captures: payload.captures,
words: payload.words,
quizzes: payload.quizzes,
favicons: legacyFavs,
screenshots: []
});
faviconMem.clear();
await notifySettingsChanged(settings);
await notifyCapturesChanged(null);
await notifyWordsChanged();
return { ...counts, settings };
}
async function importScreenshotRow(msg) {
await ensureMigrated();
const captureId = msg.captureId;
if (!captureId) throw new Error("captureId required");
let blob = null;
const mime = typeof msg.mime === "string" && msg.mime ? msg.mime : "image/jpeg";
// Prefer base64 — ArrayBuffer is dropped by some Chromium forks (e.g. Quark).
if (typeof msg.base64 === "string" && msg.base64.length > 0) {
blob = base64ToBlob(msg.base64, mime);
} else if (msg.buffer && typeof msg.buffer.byteLength === "number" && msg.buffer.byteLength > 0) {
blob = new Blob([msg.buffer], { type: mime });
} else if (typeof msg.dataUrl === "string" && msg.dataUrl.startsWith("data:image/")) {
blob = dataUrlToBlob(msg.dataUrl);
} else {
throw new Error("missing screenshot payload");
}
if (!blob || blob.size < 32) {
throw new Error("empty screenshot payload");
}
await dbPutScreenshot({
captureId,
blob,
mime: blob.type || mime,
w: typeof msg.w === "number" ? msg.w : 0,
h: typeof msg.h === "number" ? msg.h : 0
});
return { captureId };
}
async function importFaviconRow(msg) {
await ensureMigrated();
const host = typeof msg.host === "string" ? msg.host.trim() : "";
if (!host) throw new Error("host required");
let dataUrl = null;
if (typeof msg.dataUrl === "string" && msg.dataUrl.startsWith("data:")) {
dataUrl = msg.dataUrl;
} else if (typeof msg.base64 === "string" && msg.base64.length > 0) {
const mime = typeof msg.mime === "string" && msg.mime ? msg.mime : "image/png";
dataUrl = `data:${mime};base64,${msg.base64}`;
} else {
throw new Error("missing favicon payload");
}
await dbPutFavicon(host, dataUrl);
faviconMem.set(host, dataUrl);
return { host };
}
async function blobToDataUrl(blob) {
const buf = await blob.arrayBuffer();
const bytes = new Uint8Array(buf);
const chunk = 0x8000;
let binary = "";
for (let i = 0; i < bytes.length; i += chunk) {
binary += String.fromCharCode.apply(null, bytes.subarray(i, i + chunk));
}
const mime = blob.type || "image/jpeg";
return `data:${mime};base64,${btoa(binary)}`;
}
function base64ToBlob(base64, mime) {
const binary = atob(base64);
const len = binary.length;
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) bytes[i] = binary.charCodeAt(i);
return new Blob([bytes], { type: mime || "image/jpeg" });
}
/** SW cannot reliably fetch(data:) URLs; parse base64 manually. */
function dataUrlToBlob(dataUrl) {
const comma = dataUrl.indexOf(",");
if (comma < 0) throw new Error("invalid dataUrl");
const meta = dataUrl.slice(0, comma);
const payload = dataUrl.slice(comma + 1);
const mimeMatch = /^data:([^;,]+)/i.exec(meta);
const mime = (mimeMatch && mimeMatch[1]) || "image/jpeg";
if (!/;base64/i.test(meta)) {
throw new Error("expected base64 dataUrl");
}
return base64ToBlob(payload, mime);
}
async function saveScreenshotCapture(msg) {
await ensureMigrated();
let blob = null;
let mime = typeof msg.mime === "string" && msg.mime ? msg.mime : "image/jpeg";
// Prefer base64 string — ArrayBuffer is dropped by some Chromium forks (e.g. Quark).
if (typeof msg.base64 === "string" && msg.base64.length > 0) {
blob = base64ToBlob(msg.base64, mime);
} else if (msg.buffer && typeof msg.buffer.byteLength === "number" && msg.buffer.byteLength > 0) {
blob = new Blob([msg.buffer], { type: mime });
} else if (typeof msg.dataUrl === "string" && msg.dataUrl.startsWith("data:image/")) {
blob = dataUrlToBlob(msg.dataUrl);
mime = blob.type || mime;
} else {
throw new Error("missing screenshot payload");
}
if (!blob || blob.size < 32) {
throw new Error("empty screenshot blob");
}
const record = await dbSaveScreenshotCapture(
{
text: msg.text,
pageTitle: msg.pageTitle,
pageUrl: msg.pageUrl,
createdAt: msg.createdAt
},
{
blob,
mime,
w: typeof msg.w === "number" ? msg.w : 0,
h: typeof msg.h === "number" ? msg.h : 0
}
);
const host = hostFromUrl(record.pageUrl);
if (host) fetchFaviconDataUrl(host);
try {
await notifyCapturesChanged(record.pageUrl);
} catch (e) {}
return record;
}
async function startRegionCaptureOnTab(tabId) {
if (!tabId) return { ok: false, error: "no-tab" };
try {
await chrome.tabs.sendMessage(tabId, { type: "rc-start-region-capture" });
return { ok: true };
} catch (e) {
try {
await chrome.scripting.executeScript({
target: { tabId },
files: ["shared/capture-theme.js", "content.js"]
});
await chrome.tabs.sendMessage(tabId, { type: "rc-start-region-capture" });
return { ok: true };
} catch (e2) {
return { ok: false, error: "inject-failed" };
}
}
}
async function startRegionCaptureActive() {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
if (!tab || !tab.id) return { ok: false, error: "no-tab" };
if (tab.url && /^(chrome|edge|about|chrome-extension):/i.test(tab.url)) {
return { ok: false, error: "restricted-url" };
}
return startRegionCaptureOnTab(tab.id);
}
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create({
id: "rc-capture-selection",
title: "记下感触",
contexts: ["selection"]
});
ensureMigrated();
});
ensureMigrated();
chrome.contextMenus.onClicked.addListener(async (info, tab) => {
if (info.menuItemId !== "rc-capture-selection") return;
if (!tab || !tab.id) return;
try {
await chrome.tabs.sendMessage(tab.id, {
type: "rc-show-capture",
exact: info.selectionText || ""
});
} catch (e) {
chrome.action.openPopup();
}
});
chrome.commands.onCommand.addListener(async (command) => {
if (command === "capture") {
chrome.action.openPopup();
return;
}
if (command === "capture-screenshot") {
await startRegionCaptureActive();
}
});
async function bufferToDataUrl(buf, mime) {
const bytes = new Uint8Array(buf);
const chunk = 0x8000;
let binary = "";
for (let i = 0; i < bytes.length; i += chunk) {
binary += String.fromCharCode.apply(null, bytes.subarray(i, i + chunk));
}
return `data:${mime || "image/x-icon"};base64,${btoa(binary)}`;
}
async function fetchWithTimeout(url, ms) {
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), ms);
try {
return await fetch(url, {
method: "GET",
redirect: "follow",
cache: "force-cache",
signal: ctrl.signal,
credentials: "omit"
});
} finally {
clearTimeout(timer);
}
}
async function fetchFaviconDataUrl(host) {
if (!host || host === "__none__") return null;
if (faviconMem.has(host)) return faviconMem.get(host);
await ensureMigrated();
const cached = await dbGetFavicon(host);
if (cached) {
faviconMem.set(host, cached);
return cached;
}
const urls = [
`https://icons.duckduckgo.com/ip3/${host}.ico`,
`https://www.google.com/s2/favicons?sz=64&domain_url=${encodeURIComponent("https://" + host)}`,
`https://favicon.yandex.net/favicon/${host}`,
`https://icon.horse/icon/${host}`,
`https://${host}/favicon.ico`,
`https://${host}/apple-touch-icon.png`
];
for (const url of urls) {
try {
const res = await fetchWithTimeout(url, 5000);
if (!res || !res.ok) continue;
const buf = await res.arrayBuffer();
if (!buf || buf.byteLength < 32) continue;
const head = String.fromCharCode.apply(null, new Uint8Array(buf.slice(0, 64))).toLowerCase();
if (head.includes("<!doctype") || head.includes("<html")) continue;
const mime = (res.headers.get("content-type") || "").split(";")[0].trim();
if (mime.startsWith("text/")) continue;
const dataUrl = await bufferToDataUrl(buf, mime.startsWith("image/") ? mime : "image/x-icon");
faviconMem.set(host, dataUrl);
await dbPutFavicon(host, dataUrl);
return dataUrl;
} catch (e) {
// try next
}
}
faviconMem.set(host, null);
return null;
}
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (!msg || !msg.type) return;
if (msg.type === "rc-word-scan-progress") {
const tabId = sender.tab && sender.tab.id;
handleWordScanProgress(tabId, msg).catch(() => {});
return;
}
if (msg.type === "rc-save") {
saveCapture({
text: msg.text,
anchor: msg.anchor,
pageTitle: msg.pageTitle,
pageUrl: msg.pageUrl,
type: msg.captureType === "screenshot" ? "screenshot" : "text"
})
.then((record) => sendResponse({ ok: true, id: record.id }))
.catch((e) => sendResponse({ ok: false, error: String(e) }));
return true;
}
if (msg.type === "rc-save-screenshot") {
saveScreenshotCapture(msg)
.then((record) => sendResponse({ ok: true, id: record.id }))
.catch((e) => sendResponse({ ok: false, error: String(e) }));
return true;
}
if (msg.type === "rc-update") {
updateCapture(msg.id, msg.patch)
.then(() => sendResponse({ ok: true }))
.catch((e) => sendResponse({ ok: false, error: String(e) }));
return true;
}
if (msg.type === "rc-delete") {
deleteCapture(msg.id)
.then(() => sendResponse({ ok: true }))
.catch((e) => sendResponse({ ok: false, error: String(e) }));
return true;
}
if (msg.type === "rc-get-all") {
ensureMigrated()
.then(() => dbGetAllCaptures())
.then((all) => sendResponse({ ok: true, captures: all }))
.catch((e) => sendResponse({ ok: false, captures: [], error: String(e) }));
return true;
}
if (msg.type === "rc-get-page") {
ensureMigrated()
.then(() => dbGetAllCaptures())
.then((all) => sendResponse({ ok: true, captures: all || [] }))
.catch((e) => sendResponse({ ok: false, captures: [], error: String(e) }));
return true;
}
if (msg.type === "rc-get-one") {
ensureMigrated()
.then(() => dbGetCapture(msg.id))
.then((capture) => sendResponse({ ok: true, capture }))
.catch((e) => sendResponse({ ok: false, capture: null, error: String(e) }));
return true;
}
if (msg.type === "rc-save-word") {
saveWord({
word: msg.word,
note: msg.note,
phonetic: msg.phonetic,
translation: msg.translation,
matchMode: msg.matchMode,
pageTitle: msg.pageTitle,
pageUrl: msg.pageUrl
})
.then((record) => sendResponse({ ok: true, id: record.id, word: record }))
.catch((e) => sendResponse({ ok: false, error: String(e) }));
return true;
}
if (msg.type === "rc-update-word") {
updateWord(msg.id, msg.patch)
.then((word) => sendResponse({ ok: true, word }))
.catch((e) => sendResponse({ ok: false, error: String(e) }));
return true;
}
if (msg.type === "rc-delete-word") {
deleteWord(msg.id)
.then(() => sendResponse({ ok: true }))
.catch((e) => sendResponse({ ok: false, error: String(e) }));
return true;
}
if (msg.type === "rc-get-all-words") {
ensureMigrated()
.then(() => dbGetAllWords())
.then((all) => sendResponse({ ok: true, words: all || [] }))
.catch((e) => sendResponse({ ok: false, words: [], error: String(e) }));
return true;
}
if (msg.type === "rc-get-word") {
ensureMigrated()
.then(() => dbGetWord(msg.id))
.then((word) => sendResponse({ ok: true, word }))
.catch((e) => sendResponse({ ok: false, word: null, error: String(e) }));
return true;
}
if (msg.type === "rc-find-word") {
ensureMigrated()
.then(() => dbFindWordByNormalized(msg.word))
.then((word) => sendResponse({ ok: true, word: word || null }))
.catch((e) => sendResponse({ ok: false, word: null, error: String(e) }));
return true;
}
if (msg.type === "rc-get-settings") {
getSettings()
.then((settings) => {
const keepKey = msg.forContent === false || msg.source === "review";
sendResponse({
ok: true,
settings: keepKey ? settings : settingsForContent(settings)
});
})
.catch((e) =>
sendResponse({
ok: false,
settings: settingsForContent(DEFAULT_SETTINGS),
error: String(e)
})
);
return true;
}
if (msg.type === "rc-lookup-word") {
withLlmKeepAlive(lookupWord(msg.word))
.then((result) =>
sendResponse({
ok: true,
phonetic: result.phonetic,
translation: result.translation
})
)
.catch((e) => sendResponse(llmFailResponse(e)));
return true;
}
if (msg.type === "rc-generate-quiz") {
const words = msg.words || [];
const t0 = Date.now();
console.log("[RecordU quiz] bg generate start", {
words: words.length,
promptLang: msg.promptLang,
difficulty: msg.difficulty
});
withLlmKeepAlive(
ensureMigrated()
.then(() => getSettings())
.then((settings) =>
generateQuizWithLlm(words, msg.promptLang === "zh" ? "zh" : "en", settings, {
difficulty: msg.difficulty
})
)
)
.then((items) => {
console.log("[RecordU quiz] bg generate ok", {
items: (items || []).length,
ms: Date.now() - t0
});
sendResponse({ ok: true, items });
})
.catch((e) => {
console.warn("[RecordU quiz] bg generate fail", {
code: e && e.code,
error: e && e.message ? e.message : e,
ms: Date.now() - t0
});
sendResponse(llmFailResponse(e));
});
return true;
}
if (msg.type === "rc-grade-quiz-blanks") {
const blanks = msg.blanks || [];
const t0 = Date.now();
console.log("[RecordU quiz] bg grade start", { blanks: blanks.length });
withLlmKeepAlive(
ensureMigrated()
.then(() => getSettings())
.then((settings) =>
gradeBlankAnswersWithLlm(blanks, msg.promptLang === "zh" ? "zh" : "en", settings)
)
)
.then((grades) => {
console.log("[RecordU quiz] bg grade ok", {
grades: Object.keys(grades || {}).length,
ms: Date.now() - t0
});
sendResponse({ ok: true, grades: grades || {} });
})
.catch((e) => {