Repository navigation
Expand file tree
/
Copy pathbackground.js
More file actions
1522 lines (1301 loc) · 40.9 KB
/
Copy pathbackground.js
File metadata and controls
1522 lines (1301 loc) · 40.9 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
const DEFAULT_OPTIONS = {
minWidth: 480,
minHeight: 480,
folder: "jjal-collector",
includeBackgrounds: true,
includeSrcset: true,
hideDownloadUi: true,
saveByDate: true,
logEnabled: true
};
const MIN_IMAGE_DIMENSION = 480;
const MIN_DELAY_MS = 100;
const MAX_DELAY_MS = 1500;
const ICON_SIZES = [16, 32, 48, 128];
const CONSECUTIVE_FAILURE_LIMIT = 3;
const HOST_PAUSE_MS = 10 * 60 * 1000;
const UPDATE_REPOSITORY = "killkimno/jjalCollector";
const UPDATE_RELEASE_API_URL = `https://api.github.com/repos/${UPDATE_REPOSITORY}/releases/latest`;
const UPDATE_RELEASES_URL = `https://github.com/${UPDATE_REPOSITORY}/releases`;
const UPDATE_CHECK_INTERVAL_MS = 6 * 60 * 60 * 1000;
const UPDATE_ALARM_NAME = "checkLatestRelease";
const OPEN_FOLDER_MARKER_CLEANUP_MS = 30000;
const DEFAULT_RUNTIME = {
collectorActive: false
};
const DAILY_STATS_KEY = "dailyStats";
const DAILY_DOWNLOADS_KEY = "dailyDownloads";
const LOG_KEY = "collectorLogs";
const UPDATE_STATUS_KEY = "updateStatus";
const MAX_LOG_ENTRIES = 200;
const tabStates = new Map();
const pausedHosts = new Map();
let collectorDownloadUiHideDepth = 0;
let lastActiveWebTabId = null;
let dailyStatsWriteQueue = Promise.resolve();
let dailyDownloadsWriteQueue = Promise.resolve();
let logWriteQueue = Promise.resolve();
chrome.runtime.onInstalled.addListener(async () => {
const existing = await chrome.storage.sync.get(Object.keys(DEFAULT_OPTIONS));
const next = {};
for (const [key, value] of Object.entries(DEFAULT_OPTIONS)) {
if (existing[key] === undefined) {
next[key] = value;
}
}
if (Object.keys(next).length > 0) {
await chrome.storage.sync.set(next);
}
await chrome.storage.sync.remove(["minBytes", "maxBytes"]);
const runtime = await chrome.storage.local.get(DEFAULT_RUNTIME);
if (runtime.collectorActive === undefined) {
await chrome.storage.local.set(DEFAULT_RUNTIME);
}
await syncActionIcon();
await setChromeDownloadUiVisible(true);
scheduleUpdateCheck();
checkForUpdate({ force: true }).catch((error) => {
console.warn("Jjal Collector could not check updates:", error);
});
});
chrome.tabs.onRemoved.addListener((tabId) => {
tabStates.delete(tabId);
});
chrome.tabs.onActivated.addListener(async (activeInfo) => {
const tab = await getTabById(activeInfo.tabId);
await syncActiveTabCollection(tab?.id || null, {
preserveLastWebTab: isOwnExtensionUrl(tab?.url)
});
});
chrome.tabs.onUpdated.addListener((_tabId, changeInfo, tab) => {
if (changeInfo.status === "complete" && tab.active) {
syncActiveTabCollection();
}
});
chrome.windows.onFocusChanged.addListener((windowId) => {
if (windowId !== chrome.windows.WINDOW_ID_NONE) {
syncActiveTabCollection();
}
});
chrome.runtime.onStartup.addListener(() => {
syncActionIcon();
setChromeDownloadUiVisible(true).catch((error) => {
console.warn("Jjal Collector could not restore download UI:", error);
});
syncActiveTabCollection();
scheduleUpdateCheck();
checkForUpdate({ force: false }).catch((error) => {
console.warn("Jjal Collector could not check updates:", error);
});
});
chrome.alarms.onAlarm.addListener((alarm) => {
if (alarm.name !== UPDATE_ALARM_NAME) {
return;
}
checkForUpdate({ force: false }).catch((error) => {
console.warn("Jjal Collector could not check updates:", error);
});
});
chrome.storage.onChanged.addListener((changes, areaName) => {
if (areaName === "sync") {
if (changes.includeBackgrounds || changes.includeSrcset) {
syncActiveTabCollection();
}
}
if (areaName === "local") {
if (changes.collectorActive || changes[UPDATE_STATUS_KEY]) {
syncActionIcon();
}
}
});
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message?.type === "SCAN_SUMMARY") {
addLog("info", "페이지 스캔 완료", {
pageUrl: sender.tab?.url || "",
images: toNonNegativeNumber(message.images),
srcset: toNonNegativeNumber(message.srcset),
backgrounds: toNonNegativeNumber(message.backgrounds)
});
sendResponse({ ok: true });
return false;
}
if (message?.type === "IMAGE_CANDIDATES") {
const tabId = sender.tab?.id;
handleImageCandidates(tabId, message.candidates || [], sender.tab?.url || "")
.then(() => sendResponse({ ok: true }))
.catch((error) => sendResponse({ ok: false, error: error.message }));
return true;
}
if (message?.type === "CONTENT_READY") {
const tabId = sender.tab?.id;
handleContentReady(tabId, sender.tab?.url)
.then((response) => sendResponse(response))
.catch(() => sendResponse({ active: false }));
return true;
}
if (message?.type === "GET_TAB_STATUS") {
getPublicState(message.tabId)
.then((state) => sendResponse(state))
.catch(() => sendResponse(null));
return true;
}
if (message?.type === "SET_TAB_ACTIVE") {
setCollectorActive(message.tabId, Boolean(message.active))
.then((state) => sendResponse({ ok: true, state }))
.catch((error) => sendResponse({ ok: false, error: error.message }));
return true;
}
if (message?.type === "RESET_TAB_STATS") {
resetDailyStats(message.tabId)
.then(() => getPublicState(message.tabId))
.then((state) => sendResponse(state))
.catch(() => sendResponse(null));
return true;
}
if (message?.type === "CLEAR_LOGS") {
clearLogs()
.then(() => sendResponse({ ok: true }))
.catch((error) => sendResponse({ ok: false, error: error.message }));
return true;
}
if (message?.type === "OPEN_DOWNLOAD_FOLDER") {
openDownloadFolder()
.then((result) => sendResponse({ ok: true, ...result }))
.catch((error) => sendResponse({ ok: false, error: error.message }));
return true;
}
if (message?.type === "CLEANUP_OPEN_FOLDER_MARKER") {
cleanupOpenFolderMarker(message.downloadId)
.then(() => sendResponse({ ok: true }))
.catch((error) => sendResponse({ ok: false, error: error.message }));
return true;
}
if (message?.type === "CLEAR_DAILY_DOWNLOADS") {
clearDailyDownloads()
.then(() => sendResponse({ ok: true }))
.catch((error) => sendResponse({ ok: false, error: error.message }));
return true;
}
if (message?.type === "GET_UPDATE_STATUS") {
checkForUpdate({ force: Boolean(message.force) })
.then((status) => sendResponse(status))
.catch((error) => sendResponse(createUpdateStatus({
error: error?.message || String(error)
})));
return true;
}
return false;
});
function getState(tabId) {
if (!tabStates.has(tabId)) {
tabStates.set(tabId, {
active: false,
pageUrl: "",
queued: 0,
processing: false,
failureHost: "",
failureStreak: 0,
stopReason: "",
seen: new Set(),
queue: []
});
}
return tabStates.get(tabId);
}
async function getPublicState(tabId) {
const state = getState(tabId);
const stats = await getDailyStats();
const collectorActive = await isCollectorActive();
return {
active: collectorActive,
collecting: state.active,
downloaded: stats.downloaded,
skipped: stats.skipped,
errors: stats.errors,
queued: state.queue.length,
seen: stats.seen,
stopReason: state.stopReason
};
}
async function setCollectorActive(sourceTabId, active) {
await chrome.storage.local.set({ collectorActive: active });
addLog("info", active ? "수집 켜짐" : "수집 꺼짐", { tabId: sourceTabId });
if (active) {
getState(sourceTabId).stopReason = "";
await syncActiveTabCollection(sourceTabId);
return getPublicState(sourceTabId);
}
const tabs = await chrome.tabs.query({});
await Promise.all(tabs.map(async (tab) => {
if (!tab.id) {
return;
}
const state = getState(tab.id);
state.active = false;
state.queue = [];
state.queued = 0;
state.stopReason = "";
resetFailureState(state);
await sendCollectorStateToTab(tab, false, null);
await updateBadge(tab.id);
}));
return getPublicState(sourceTabId);
}
function resetTabStats(tabId) {
const state = getState(tabId);
state.queued = 0;
state.queue = [];
state.seen = new Set();
state.stopReason = "";
resetFailureState(state);
}
async function resetDailyStats(tabId) {
dailyStatsWriteQueue = dailyStatsWriteQueue.then(() => saveDailyStats(createEmptyDailyStats()));
dailyDownloadsWriteQueue = dailyDownloadsWriteQueue.then(async () => {
const downloads = createEmptyDailyDownloads();
await saveDailyDownloads(downloads);
});
await dailyStatsWriteQueue;
await dailyDownloadsWriteQueue;
resetTabStats(tabId);
}
async function getDailyStats() {
await dailyStatsWriteQueue.catch(() => {});
return getDailyStatsRaw();
}
async function getDailyStatsRaw() {
const today = getTodayKey();
const stored = await chrome.storage.local.get(DAILY_STATS_KEY);
const stats = stored[DAILY_STATS_KEY];
if (!stats || stats.date !== today) {
const next = createEmptyDailyStats();
await saveDailyStats(next);
return next;
}
return {
...createEmptyDailyStats(),
...stats,
date: today
};
}
function addDailyStat(field, amount = 1) {
dailyStatsWriteQueue = dailyStatsWriteQueue
.then(async () => {
const stats = await getDailyStatsRaw();
stats[field] = toNonNegativeNumber(stats[field]) + amount;
await saveDailyStats(stats);
})
.catch((error) => {
console.warn("Jjal Collector could not update daily stats:", error);
});
return dailyStatsWriteQueue;
}
async function saveDailyStats(stats) {
await chrome.storage.local.set({
[DAILY_STATS_KEY]: stats
});
}
function createEmptyDailyStats() {
return {
date: getTodayKey(),
downloaded: 0,
skipped: 0,
errors: 0,
seen: 0
};
}
async function getDailyDownloads() {
await dailyDownloadsWriteQueue.catch(() => {});
return getDailyDownloadsRaw();
}
async function getDailyDownloadsRaw() {
const today = getTodayKey();
const stored = await chrome.storage.local.get(DAILY_DOWNLOADS_KEY);
const downloads = stored[DAILY_DOWNLOADS_KEY];
if (!downloads || downloads.date !== today) {
const next = createEmptyDailyDownloads();
await saveDailyDownloads(next);
return next;
}
return {
...createEmptyDailyDownloads(),
...downloads,
date: today,
filenames: downloads.filenames || {},
urls: downloads.urls || {},
items: Array.isArray(downloads.items) ? downloads.items : []
};
}
async function hasDownloadedToday(imageUrl) {
const downloads = await getDailyDownloads();
return Boolean(downloads.urls[imageUrl]);
}
function addDailyDownload(originalName, savedName, siteUrl, imageUrl, options) {
dailyDownloadsWriteQueue = dailyDownloadsWriteQueue
.then(async () => {
const downloads = await getDailyDownloadsRaw();
if (downloads.urls[imageUrl]) {
return;
}
downloads.filenames[originalName] = true;
downloads.urls[imageUrl] = true;
downloads.items.push({
filename: originalName,
savedName,
siteUrl,
imageUrl,
savedAt: new Date().toISOString()
});
await saveDailyDownloads(downloads);
})
.catch((error) => {
console.warn("Jjal Collector could not update daily download list:", error);
});
return dailyDownloadsWriteQueue;
}
async function saveDailyDownloads(downloads) {
await chrome.storage.local.set({
[DAILY_DOWNLOADS_KEY]: downloads
});
}
async function clearDailyDownloads() {
dailyDownloadsWriteQueue = dailyDownloadsWriteQueue.then(async () => {
await saveDailyDownloads(createEmptyDailyDownloads());
});
await dailyDownloadsWriteQueue;
addLog("info", "다운로드 목록 초기화");
}
function addLog(level, message, details = {}) {
const entry = {
id: `${Date.now()}-${Math.random().toString(16).slice(2)}`,
time: new Date().toISOString(),
level,
message,
details
};
logWriteQueue = logWriteQueue
.then(async () => {
if (!(await isLogEnabled())) {
return;
}
const stored = await chrome.storage.local.get({ [LOG_KEY]: [] });
const logs = Array.isArray(stored[LOG_KEY]) ? stored[LOG_KEY] : [];
logs.push(entry);
await chrome.storage.local.set({
[LOG_KEY]: logs.slice(-MAX_LOG_ENTRIES)
});
})
.catch((error) => {
console.warn("Jjal Collector could not write log:", error);
});
return logWriteQueue;
}
async function clearLogs() {
logWriteQueue = logWriteQueue.then(() => chrome.storage.local.set({ [LOG_KEY]: [] }));
return logWriteQueue;
}
async function isLogEnabled() {
const stored = await chrome.storage.sync.get({ logEnabled: DEFAULT_OPTIONS.logEnabled });
return stored.logEnabled !== false;
}
function scheduleUpdateCheck() {
chrome.alarms.create(UPDATE_ALARM_NAME, {
periodInMinutes: UPDATE_CHECK_INTERVAL_MS / 60000
});
}
async function checkForUpdate({ force = false } = {}) {
const stored = await getStoredUpdateStatus();
const now = Date.now();
const currentVersion = chrome.runtime.getManifest().version;
if (
!force &&
stored.checkedAt &&
stored.currentVersion === currentVersion &&
now - stored.checkedAt < UPDATE_CHECK_INTERVAL_MS
) {
return stored;
}
try {
const response = await fetch(UPDATE_RELEASE_API_URL, {
headers: {
Accept: "application/vnd.github+json"
}
});
if (!response.ok) {
throw new Error(`GitHub release check failed: ${response.status}`);
}
const release = await response.json();
const tagVersion = normalizeVersion(release.tag_name || release.name || "");
const latestVersion = tagVersion || "";
const available = latestVersion ? compareVersions(latestVersion, currentVersion) > 0 : false;
const status = createUpdateStatus({
checkedAt: now,
currentVersion,
latestVersion,
available,
releaseUrl: release.html_url || UPDATE_RELEASES_URL,
releaseName: release.name || release.tag_name || "",
publishedAt: release.published_at || "",
error: ""
});
await chrome.storage.local.set({ [UPDATE_STATUS_KEY]: status });
return status;
} catch (error) {
const latestVersion = stored.latestVersion || "";
const status = createUpdateStatus({
...stored,
checkedAt: now,
currentVersion,
available: latestVersion ? compareVersions(latestVersion, currentVersion) > 0 : false,
error: error?.message || String(error)
});
await chrome.storage.local.set({ [UPDATE_STATUS_KEY]: status });
return status;
}
}
async function getStoredUpdateStatus() {
const currentVersion = chrome.runtime.getManifest().version;
const stored = await chrome.storage.local.get({
[UPDATE_STATUS_KEY]: createUpdateStatus({ currentVersion })
});
return createUpdateStatus({
...stored[UPDATE_STATUS_KEY],
currentVersion: stored[UPDATE_STATUS_KEY]?.currentVersion || currentVersion
});
}
function createUpdateStatus(status = {}) {
return {
checkedAt: toNonNegativeNumber(status.checkedAt),
currentVersion: status.currentVersion || chrome.runtime.getManifest().version,
latestVersion: status.latestVersion || "",
available: status.available === true,
releaseUrl: status.releaseUrl || "",
releaseName: status.releaseName || "",
publishedAt: status.publishedAt || "",
error: status.error || ""
};
}
function normalizeVersion(value) {
const match = String(value).trim().match(/^v?(\d+(?:\.\d+){0,3})(?:[-+].*)?$/i);
return match ? match[1] : "";
}
function compareVersions(left, right) {
const leftParts = normalizeVersion(left).split(".").map((part) => Number(part));
const rightParts = normalizeVersion(right).split(".").map((part) => Number(part));
const length = Math.max(leftParts.length, rightParts.length);
for (let index = 0; index < length; index += 1) {
const leftPart = Number.isFinite(leftParts[index]) ? leftParts[index] : 0;
const rightPart = Number.isFinite(rightParts[index]) ? rightParts[index] : 0;
if (leftPart > rightPart) {
return 1;
}
if (leftPart < rightPart) {
return -1;
}
}
return 0;
}
function countCandidateSources(candidates) {
return candidates.reduce((counts, candidate) => {
const source = candidate?.source || "unknown";
counts[source] = (counts[source] || 0) + 1;
return counts;
}, {});
}
function createEmptyDailyDownloads() {
return {
date: getTodayKey(),
filenames: {},
urls: {},
items: []
};
}
function getTodayKey() {
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, "0");
const day = String(now.getDate()).padStart(2, "0");
return `${year}-${month}-${day}`;
}
async function pauseHostForFailure(tabId, host, reason) {
const state = getState(tabId);
pausedHosts.set(host, {
expiresAt: Date.now() + HOST_PAUSE_MS,
reason
});
state.active = false;
state.queue = state.queue.filter((candidate) => getCandidateHost(candidate) !== host);
state.queued = state.queue.length;
state.stopReason = reason;
resetFailureState(state);
await syncActiveTabCollection();
state.stopReason = reason;
await updateBadge(tabId);
}
async function handleContentReady(tabId, pageUrl) {
const collectorActive = await isCollectorActive();
if (tabId === undefined) {
addLog("warn", "콘텐츠 준비 메시지에 탭 ID가 없습니다.", { pageUrl });
return { active: false };
}
const state = getState(tabId);
if (state.pageUrl !== pageUrl) {
resetTabStats(tabId);
state.pageUrl = pageUrl || "";
}
const pausedReason = getPausedHostReason(getUrlHost(pageUrl));
state.active = collectorActive && isWebUrl(pageUrl) && !pausedReason && await isFocusedActiveTab(tabId);
state.stopReason = pausedReason;
await updateBadge(tabId);
addLog("info", "콘텐츠 준비", {
pageUrl,
active: state.active,
stopReason: state.stopReason || ""
});
return {
active: state.active,
scanOptions: state.active ? getContentScanOptions(await getOptions()) : null
};
}
async function handleImageCandidates(tabId, candidates, pageUrl) {
if (tabId === undefined || !(await isCollectorActive()) || !(await isFocusedActiveTab(tabId))) {
addLog("info", "후보 무시", {
pageUrl,
count: candidates.length,
reason: tabId === undefined ? "탭 ID 없음" : "수집 꺼짐 또는 비활성 탭"
});
if (tabId !== undefined) {
const state = getState(tabId);
state.active = false;
state.queue = [];
state.queued = 0;
await updateBadge(tabId);
}
return;
}
const tab = await chrome.tabs.get(tabId);
const pausedReason = getPausedHostReason(getUrlHost(tab.url));
if (pausedReason) {
const state = getState(tabId);
state.active = false;
state.queue = [];
state.queued = 0;
state.stopReason = pausedReason;
await updateBadge(tabId);
addLog("warn", "일시 중단된 호스트라 후보를 무시했습니다.", {
pageUrl,
count: candidates.length,
reason: pausedReason
});
return;
}
addLog("info", "이미지 후보 수신", {
pageUrl,
count: candidates.length,
sources: countCandidateSources(candidates)
});
await enqueueCandidates(tabId, candidates, pageUrl);
}
async function enqueueCandidates(tabId, candidates, pageUrl) {
const state = getState(tabId);
if (!state.active) {
return;
}
const dailyDownloads = await getDailyDownloads();
let seenAdded = 0;
const skipped = {
invalid: 0,
duplicateInPage: 0,
undersized: 0,
pausedHost: 0,
downloadedToday: 0
};
for (const candidate of candidates) {
const normalized = normalizeCandidate(candidate, pageUrl);
const key = normalized ? getCandidateKey(normalized) : "";
if (!normalized) {
skipped.invalid += 1;
continue;
}
if (state.seen.has(key)) {
skipped.duplicateInPage += 1;
continue;
}
if (isUndersizedCandidate(normalized)) {
skipped.undersized += 1;
continue;
}
if (isHostPaused(getCandidateHost(normalized))) {
skipped.pausedHost += 1;
continue;
}
if (dailyDownloads.urls[normalized.url]) {
skipped.downloadedToday += 1;
continue;
}
state.seen.add(key);
seenAdded += 1;
state.queue.push(normalized);
}
if (seenAdded > 0) {
await addDailyStat("seen", seenAdded);
}
addLog(seenAdded > 0 ? "info" : "warn", "후보 큐 반영", {
pageUrl,
received: candidates.length,
queued: seenAdded,
queueTotal: state.queue.length,
skipped
});
runQueue(tabId);
}
async function runQueue(tabId) {
const state = getState(tabId);
if (state.processing) {
return;
}
state.processing = true;
try {
while (state.active && state.queue.length > 0) {
if (!(await isCollectorActive())) {
state.active = false;
state.queue = [];
state.queued = 0;
break;
}
if (!(await isFocusedActiveTab(tabId))) {
state.active = false;
state.queue = [];
state.queued = 0;
break;
}
const candidate = state.queue.shift();
state.queued = state.queue.length;
const pausedReason = getPausedHostReason(getCandidateHost(candidate));
if (pausedReason) {
state.stopReason = pausedReason;
state.queue = state.queue.filter((queuedCandidate) => getCandidateHost(queuedCandidate) !== getCandidateHost(candidate));
state.queued = state.queue.length;
continue;
}
try {
const options = await getOptions();
const result = await collectCandidate(candidate, options);
if (result === "downloaded") {
await addDailyStat("downloaded");
state.stopReason = "";
resetFailureState(state);
} else {
await addDailyStat("skipped");
addLog("info", "이미지 스킵", {
url: candidate.url,
reason: result
});
}
} catch (error) {
console.warn("Jjal Collector failed:", candidate.url, error);
addLog("error", "이미지 처리 실패", {
url: candidate.url,
error: error?.message || String(error)
});
await addDailyStat("errors");
if (await shouldStopAfterFailure(tabId, candidate, error)) {
break;
}
}
await updateBadge(tabId);
}
} finally {
state.processing = false;
state.queued = state.queue.length;
await updateBadge(tabId);
}
}
async function shouldStopAfterFailure(tabId, candidate, error) {
const state = getState(tabId);
const host = getCandidateHost(candidate);
if (!host) {
return false;
}
if (state.failureHost === host) {
state.failureStreak += 1;
} else {
state.failureHost = host;
state.failureStreak = 1;
}
if (state.failureStreak < CONSECUTIVE_FAILURE_LIMIT) {
return false;
}
const reason = `${host} 다운로드 실패가 ${state.failureStreak}회 연속 발생해 10분 동안 이 사이트 수집을 중단합니다.`;
console.warn("Jjal Collector paused host:", reason, error);
await pauseHostForFailure(tabId, host, reason);
return true;
}
function resetFailureState(state) {
state.failureHost = "";
state.failureStreak = 0;
}
async function getOptions() {
const stored = await chrome.storage.sync.get(DEFAULT_OPTIONS);
return {
minWidth: toMinimumDimension(stored.minWidth),
minHeight: toMinimumDimension(stored.minHeight),
folder: sanitizeFolder(stored.folder || DEFAULT_OPTIONS.folder),
includeBackgrounds: stored.includeBackgrounds !== false,
includeSrcset: stored.includeSrcset !== false,
hideDownloadUi: stored.hideDownloadUi !== false,
saveByDate: stored.saveByDate !== false,
logEnabled: stored.logEnabled !== false
};
}
async function syncActiveTabCollection(preferredActiveTabId = null, options = {}) {
const collectorActive = await isCollectorActive();
let activeTab = collectorActive ? await getFocusedActiveTab(preferredActiveTabId) : null;
if (
collectorActive &&
(!activeTab || isOwnExtensionUrl(activeTab.url) || (options.preserveLastWebTab && !isWebUrl(activeTab.url)))
) {
activeTab = await getTabById(lastActiveWebTabId);
}
if (collectorActive && activeTab?.id && isWebUrl(activeTab.url)) {
lastActiveWebTabId = activeTab.id;
}
const activeTabId = activeTab?.id;
const scanOptions = collectorActive ? getContentScanOptions(await getOptions()) : null;
const tabs = await chrome.tabs.query({});
if (collectorActive) {
addLog(activeTabId ? "info" : "warn", "활성 탭 동기화", {
preferredActiveTabId,
preserveLastWebTab: Boolean(options.preserveLastWebTab),
activeTabId: activeTabId || null,
activeTabUrl: activeTab?.url || ""
});
}
await Promise.all(tabs.map(async (tab) => {
if (!tab.id) {
return;
}
const pausedReason = getPausedHostReason(getUrlHost(tab.url));
const shouldRun = collectorActive && tab.id === activeTabId && isWebUrl(tab.url) && !pausedReason;
const state = getState(tab.id);
state.active = shouldRun;
state.stopReason = pausedReason;
if (!shouldRun) {
if (pausedReason) {
const pausedHost = getUrlHost(tab.url);
state.queue = state.queue.filter((candidate) => getCandidateHost(candidate) !== pausedHost);
state.queued = state.queue.length;
} else {
state.queue = [];
state.queued = 0;
}
}
await sendCollectorStateToTab(tab, shouldRun, shouldRun ? scanOptions : null);
await updateBadge(tab.id);
}));
}
async function sendCollectorStateToTab(tab, active, scanOptions) {
if (!tab.id) {
return;
}
try {
await chrome.tabs.sendMessage(tab.id, {
type: "COLLECTOR_ACTIVE_CHANGED",
active,
scanOptions
});
return;
} catch (error) {
if (!active || !isWebUrl(tab.url) || !isMissingContentScriptError(error)) {
return;
}
}
try {
await chrome.scripting.executeScript({
target: { tabId: tab.id },
files: ["content.js"]
});
} catch (error) {
console.warn("Jjal Collector could not inject content script:", tab.url, error);
}
}
async function collectCandidate(candidate, options) {
if (candidate.source === "background" && !options.includeBackgrounds) {
return "background-disabled";
}
if (candidate.source === "srcset" && !options.includeSrcset) {
return "srcset-disabled";
}
if (candidate.width < options.minWidth) {
return "min-width";
}
if (candidate.height < options.minHeight) {
return "min-height";
}
const originalName = getOriginalFilename(candidate.url);
if (await hasDownloadedToday(candidate.url)) {
return "downloaded-today";
}
const filename = buildFilename(options.folder, originalName, options.saveByDate);
addLog("info", "다운로드 시작", {
url: candidate.url,
filename,
width: candidate.width,
height: candidate.height,
source: candidate.source
});
await downloadCollectorFile({
url: candidate.url,
filename,
conflictAction: "uniquify",
saveAs: false
}, options);
await addDailyDownload(originalName, filename, candidate.pageUrl || candidate.url, candidate.url, options);
addLog("info", "다운로드 완료", {
url: candidate.url,
filename
});
await sleep(randomDelayMs());
return "downloaded";
}
async function downloadCollectorFile(downloadOptions, options) {