-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
1443 lines (1226 loc) · 69.4 KB
/
background.js
File metadata and controls
1443 lines (1226 loc) · 69.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
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
importScripts('dexie.min.js', 'db.js', 'common.js');
let lastRightClickedTitle = "";
let downloadTitlesMap = {}; // 다운로드 ID와 폴더명(책 제목) 매핑
let urlToTitleMap = {};
let gofileAuthLock = null;
async function getGofileCredentials(forceRefresh = false) {
let now = Date.now();
let stored = await chrome.storage.local.get(['gfToken', 'gfWt', 'gfTime']);
if (!forceRefresh && stored.gfToken && stored.gfWt && stored.gfTime && (now - stored.gfTime < 1000 * 60 * 60 * 1)) {
return { token: stored.gfToken, wt: stored.gfWt };
}
if (gofileAuthLock && !forceRefresh) {
return await gofileAuthLock;
}
let task = (async () => {
let token = "";
let wt = "4fd6sg89d7s6";
try {
let accRes = await fetch('https://api.gofile.io/accounts', { method: 'POST' });
let accData = await accRes.json();
if (accData.status === 'ok') token = accData.data.token;
let htmlRes = await fetch('https://gofile.io/');
let html = await htmlRes.text();
let jsPaths = [...html.matchAll(/src=["'](\/dist\/js\/[^"']+\.js)["']/g)].map(m => m[1]);
for (let path of jsPaths) {
let jsRes = await fetch("https://gofile.io" + path);
if (jsRes.ok) {
let jsText = await jsRes.text();
let wtMatch = jsText.match(/wt\s*[:=]\s*["']([a-zA-Z0-9]{10,64})["']/i) || jsText.match(/["']wt["']\s*[:=]\s*["']([a-zA-Z0-9]{10,64})["']/i);
if (wtMatch) {
wt = wtMatch[1];
break;
}
}
}
if (token) {
await chrome.storage.local.set({ gfToken: token, gfWt: wt, gfTime: Date.now() });
}
return { token, wt };
} catch (e) {
console.log("Gofile 인증 실패:", e);
if (stored.gfToken) return { token: stored.gfToken, wt: stored.gfWt || wt };
throw e;
}
})();
if (!forceRefresh) gofileAuthLock = task;
try {
let result = await task;
return result;
} finally {
if (!forceRefresh) gofileAuthLock = null;
}
}
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === "RIGHT_CLICK_TITLE") {
lastRightClickedTitle = message.title;
}
else if (message.action === "CLOSE_ME") {
if (sender.tab && sender.tab.id) {
chrome.tabs.remove(sender.tab.id).catch(() => {});
}
return true;
}
else if (message.action === "INJECT_BYPASS_SCRIPT") {
if (sender.tab && sender.tab.id) {
chrome.scripting.executeScript({
target: { tabId: sender.tab.id },
world: "MAIN",
func: (keywords) => {
if (window._bmBypassInjected) return;
window._bmBypassInjected = true;
const _originalConfirm = window.confirm;
window.confirm = function(msg) {
if (msg && keywords.every(kw => msg.includes(kw))) {
return true;
}
return _originalConfirm(msg);
};
},
args: [message.keywords]
}).catch(err => console.log("Bypass injection failed:", err));
}
return true;
}
else if (message.action === "OPEN_DOWNLOAD_FOLDER") {
chrome.downloads.show(message.downloadId);
return true;
}
else if (message.action === "QUICK_ACTION") {
const tabId = sender.tab ? sender.tab.id : null;
if (message.type === "search") {
chrome.tabs.create({ url: "https://www.google.com/search?q=" + encodeURIComponent(message.cleanTitle) }).catch(() => {});
return true;
}
if (message.type === "everything_search") {
executeEverythingSearch(message.cleanTitle, tabId);
return true;
}
console.log(message.type);
if (message.type === "ridi_preview") {
performRidiSearch(message.cleanTitle);
return true;
}
if (message.type === "delete") {
chrome.storage.local.get({ bookList: [] }, (data) => {
let list = Array.isArray(data.bookList) ? data.bookList : [];
let targetTitleStr = message.cleanTitle.replace(/[^a-zA-Z0-9가-힣ㄱ-ㅎㅏ-ㅣ\sぁ-んァ-ヶー一-龥]/g, '').toLowerCase().trim().replace(/\s+/g, '');
// 삭제 처리 최적화를 위해 뒤에서부터 빠르게 탐색
let existingIndex = -1;
for (let i = list.length - 1; i >= 0; i--) {
if ((list[i].title || "").replace(/[^a-zA-Z0-9가-힣ㄱ-ㅎㅏ-ㅣ\sぁ-んァ-ヶー一-龥]/g, '').toLowerCase().trim().replace(/\s+/g, '') === targetTitleStr) {
existingIndex = i;
break;
}
}
if (existingIndex > -1) {
let deletedBook = list.splice(existingIndex, 1)[0];
bgListMapCache = null; // [추가] 삭제 시 백그라운드 캐시 무효화
chrome.storage.local.set({ bookList: list }, () => {
if (tabId) chrome.tabs.sendMessage(tabId, { action: "SHOW_TOAST", book: deletedBook, isDelete: true }).catch(() => {});
});
} else {
if (tabId) chrome.tabs.sendMessage(tabId, { action: "SHOW_INFO_TOAST", msg: "❌ 등록된 데이터가 없어 삭제할 수 없습니다.", isError: true }).catch(() => {});
}
});
return true;
}
pendingTasks.push({
cleanTitle: message.cleanTitle,
resolution: message.resolution,
lastVol: message.lastVol,
type: message.type,
dateString: new Date().toISOString(),
tabId: tabId
});
if (saveTimer) clearTimeout(saveTimer);
saveTimer = setTimeout(processSaveQueue, 10);
return true;
}
else if (message.action === "DOWNLOAD_GIGAFILE") {
(async () => {
try {
let url = message.url;
let pw = message.password || "";
let res = await fetch(url);
let finalUrl = res.url;
let hostMatch = finalUrl.match(/https?:\/\/([^\/]+)/);
let host = hostMatch ? hostMatch[1] : "94.gigafile.nu";
let fileIdMatch = finalUrl.match(/[?&]file=([0-9]{4}-[0-9a-zA-Z]+)/) || finalUrl.match(/\/([0-9]{4}-[0-9a-zA-Z]+)(?:[?&\/]|$)/);
let fileId = fileIdMatch ? fileIdMatch[1] : null;
if (!fileId) {
chrome.tabs.sendMessage(sender.tab.id, { action: "SHOW_INFO_TOAST", msg: "❌ 파일 ID를 찾을 수 없습니다.", isError: true }).catch(() => {});
return;
}
let pwQuery = pw ? "&dlkey=" + encodeURIComponent(pw) : "";
let zipUrl = "https://" + host + "/dl_zip.php?file=" + fileId + pwQuery;
let singleUrl = "https://" + host + "/download.php?file=" + fileId + pwQuery;
let targetDlUrl = null;
for (let testUrl of [zipUrl, singleUrl]) {
try {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 5000);
const fetchRes = await fetch(testUrl, { method: 'GET', signal: controller.signal });
clearTimeout(timeoutId);
const ct = (fetchRes.headers.get('content-type') || '').toLowerCase();
const cd = (fetchRes.headers.get('content-disposition') || '').toLowerCase();
controller.abort();
if (fetchRes.ok && (!ct.includes('text/html') || cd.includes('attachment'))) {
targetDlUrl = testUrl;
break;
}
} catch (e) {
}
}
if (!targetDlUrl) {
chrome.tabs.sendMessage(sender.tab.id, { action: "SHOW_INFO_TOAST", msg: "❌ 다운로드 링크를 찾지 못했거나 기간이 만료되었습니다.", isError: true }).catch(() => {});
return;
}
// 콜백에서 다운로드 ID와 폴더명(title) 연결
chrome.downloads.download({ url: targetDlUrl, conflictAction: "uniquify" }, (downloadId) => {
if (downloadId && message.title) {
downloadTitlesMap[downloadId] = message.title;
}
if (chrome.runtime.lastError) {
chrome.tabs.sendMessage(sender.tab.id, { action: "SHOW_INFO_TOAST", msg: "❌ 다운로드 시작 실패: " + chrome.runtime.lastError.message, isError: true }).catch(() => {});
} else {
chrome.tabs.sendMessage(sender.tab.id, { action: "SHOW_INFO_TOAST", msg: "✅ Gigafile 백그라운드 다운로드가 시작되었습니다!" }).catch(() => {});
}
});
} catch (error) {
chrome.tabs.sendMessage(sender.tab.id, { action: "SHOW_INFO_TOAST", msg: "❌ 주소 해석 중 에러가 발생했습니다.", isError: true }).catch(() => {});
}
})();
return true;
}
else if (message.action === "DOWNLOAD_GOFILE") {
let url = message.url;
let pw = message.password || "";
chrome.tabs.sendMessage(sender.tab.id, { action: "SHOW_INFO_TOAST", msg: "🚀 Gofile 보안 회피를 위해 새 탭에서 자동 다운로드를 진행합니다." }).catch(()=>{});
chrome.tabs.create({ url: url, active: true }, function(tab) {
let listener = function(tabId, changeInfo) {
if (tabId === tab.id && changeInfo.status === 'complete') {
chrome.tabs.onUpdated.removeListener(listener);
chrome.scripting.executeScript({
target: { tabId: tab.id },
func: (password) => {
if (!document.getElementById('bm-macro-overlay')) {
const overlay = document.createElement('div');
overlay.id = 'bm-macro-overlay';
overlay.style.cssText = `
position: fixed; top: 0; left: 0; width: 100vw; height: 100vh;
background: rgba(0, 0, 0, 0.85); z-index: 2147483647;
display: flex; flex-direction: column; align-items: center; justify-content: center;
color: white; font-family: 'Malgun Gothic', sans-serif; pointer-events: all;
`;
overlay.innerHTML = `
<style>@keyframes bm-spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }</style>
<div style="width: 60px; height: 60px; border: 6px solid rgba(255,255,255,0.2); border-top: 6px solid #20c997; border-radius: 50%; animation: bm-spin 1s linear infinite; margin-bottom: 25px;"></div>
<h2 style="margin: 0 0 15px 0; color: #fff; font-size: 26px; font-weight: bold; letter-spacing: -1px;">🚀 자동 다운로드 진행 중...</h2>
<p style="margin: 0; color: #ced4da; font-size: 16px;">매크로가 안전하게 동작 중입니다. 마우스를 클릭하지 말고 잠시만 기다려주세요.</p>
<p id="bm-macro-status" style="margin: 15px 0 0 0; color: #ffc107; font-size: 15px; font-weight: bold;">(Gofile 서버가 준비될 때까지 대기 중...)</p>
`;
document.body.appendChild(overlay);
}
let attempts = 0;
let stage = 'INIT';
let lastBtnCount = 0;
let stableCount = 0;
let totalBtnsToDownload = 0;
let clickedCount = 0;
const setNativeValue = (element, value) => {
const valueSetter = Object.getOwnPropertyDescriptor(element, 'value').set;
const prototype = Object.getPrototypeOf(element);
const prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value').set;
if (valueSetter && valueSetter !== prototypeValueSetter) {
prototypeValueSetter.call(element, value);
} else {
valueSetter.call(element, value);
}
element.dispatchEvent(new Event('input', { bubbles: true }));
};
const getVisiblePwInput = () => {
return Array.from(document.querySelectorAll('input[type="password"]')).find(el => {
if (el.disabled) return false;
const rect = el.getBoundingClientRect();
return rect.width > 0 && rect.height > 0 && window.getComputedStyle(el).visibility !== 'hidden' && window.getComputedStyle(el).display !== 'none';
});
};
const getDlBtns = () => {
return Array.from(document.querySelectorAll('button, a, div[role="button"]')).filter(el => {
if (el.offsetParent === null || el.disabled) return false;
let t = (el.textContent || '').trim().toLowerCase();
if (t.includes('premium') || t.includes('app') || t.includes('vpn') || t.includes('download all') || t.includes('zip') || t.includes('play')) return false;
return t === 'download' || el.querySelector('.fa-download, [data-icon="download"], i[class*="download"]');
});
};
const autoMacro = () => {
if (stage === 'DONE') return;
let pwInput = getVisiblePwInput();
if (pwInput && stage === 'INIT') {
if (!password) {
let ov = document.getElementById('bm-macro-overlay');
if (ov) {
ov.innerHTML = `<h2 style="color:#ffc107;">🔒 비밀번호 필요</h2><p>본문에서 추출된 비밀번호가 없습니다. 수동으로 입력해주세요.</p>`;
setTimeout(() => ov.remove(), 3000);
}
stage = 'DONE';
return;
}
setNativeValue(pwInput, password);
let submitBtn = document.querySelector('#passwordSubmit') ||
Array.from(document.querySelectorAll('button')).find(b => (b.textContent||'').toLowerCase().includes('enter') || (b.textContent||'').toLowerCase().includes('submit'));
if (submitBtn) submitBtn.click();
else pwInput.dispatchEvent(new KeyboardEvent('keydown', {key: 'Enter', keyCode: 13, which: 13, bubbles: true}));
stage = 'WAIT_FOR_LIST';
setTimeout(autoMacro, 2000);
return;
}
if (stage === 'INIT' && !pwInput) {
stage = 'WAIT_FOR_LIST';
}
if (stage === 'WAIT_FOR_LIST') {
let currentValidBtns = getDlBtns();
let statusText = document.getElementById('bm-macro-status');
if (currentValidBtns.length > 0) {
if (currentValidBtns.length === lastBtnCount) {
stableCount++;
if (statusText) statusText.innerText = `⏳ 파일 렌더링 완료 대기 중... (${stableCount}/2)`;
} else {
lastBtnCount = currentValidBtns.length;
stableCount = 0;
if (statusText) statusText.innerText = `⏳ 파일 목록 불러오는 중... (${lastBtnCount}개 발견)`;
}
if (stableCount >= 2) {
stage = 'DL_CLICKED';
totalBtnsToDownload = currentValidBtns.length;
if (statusText) statusText.innerText = `✅ 총 ${totalBtnsToDownload}개 파일 확인됨. 다운로드 시작!`;
setTimeout(() => {
let clickInterval = setInterval(() => {
let freshBtns = getDlBtns();
if (clickedCount < freshBtns.length) {
let targetBtn = freshBtns[clickedCount];
try {
targetBtn.scrollIntoView({block: 'center', behavior: 'smooth'});
targetBtn.click();
clickedCount++;
let statusText2 = document.getElementById('bm-macro-status');
if (statusText2) statusText2.innerText = `⏳ 파일 순차 다운로드 중... (${clickedCount} / ${totalBtnsToDownload})`;
} catch(e){}
} else {
clearInterval(clickInterval);
let statusText3 = document.getElementById('bm-macro-status');
if (statusText3) statusText3.innerText = `✅ 총 ${clickedCount}개 다운로드 요청 완료! (곧 창이 닫힙니다)`;
stage = 'DONE';
setTimeout(() => {
chrome.runtime.sendMessage({ action: "CLOSE_ME" });
}, 5000);
}
}, 2500);
}, 1000);
return;
}
} else {
attempts++;
if (attempts > 30) {
let ov = document.getElementById('bm-macro-overlay');
if (ov) {
ov.innerHTML = `<h2 style="color:#dc3545;">⚠️ 자동 다운로드 지연됨</h2><p>화면을 클릭하여 수동으로 진행해 주세요.</p>`;
setTimeout(() => ov.remove(), 3000);
}
stage = 'DONE';
}
}
if (stage === 'WAIT_FOR_LIST') {
setTimeout(autoMacro, 800);
}
}
};
setTimeout(autoMacro, 1000);
},
args: [pw]
}).catch(err => console.log(err));
}
};
chrome.tabs.onUpdated.addListener(listener);
});
return true;
}
else if (message.action === "DOWNLOAD_HELLKDIS") {
(async () => {
try {
let url = message.url;
let pw = message.password || "";
let urlObj = new URL(url);
let host = urlObj.origin;
let tokenMatch = url.match(/\/s\/([a-zA-Z0-9]+)/);
if (!tokenMatch) throw new Error("토큰을 찾을 수 없습니다.");
let token = tokenMatch[1];
let res = await fetch(url);
let currentUrl = res.url;
let html = await res.text();
let isPasswordProtected = html.includes('name="password"') || html.includes('password-input-form');
let authHtml = html;
if (isPasswordProtected) {
if (!pw) throw new Error("비밀번호가 필요합니다.");
let rtMatch = html.match(/data-requesttoken="([^"]+)"/);
if (!rtMatch) throw new Error("CSRF 토큰을 추출할 수 없습니다.");
let requestToken = rtMatch[1];
let params = new URLSearchParams();
params.append('password', pw);
params.append('requesttoken', requestToken);
let stMatch = html.match(/name="sharingToken" value="([^"]+)"/);
if(stMatch) params.append('sharingToken', stMatch[1]);
params.append('sharingType', '3');
let authRes = await fetch(currentUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'requesttoken': requestToken
},
body: params.toString()
});
authHtml = await authRes.text();
if (authHtml.includes('name="password"') || authHtml.includes('Wrong password') || authHtml.includes('비밀번호가 잘못되었습니다')) {
throw new Error("비밀번호가 틀렸습니다.");
}
}
let dlMatch = authHtml.match(/href="([^"]+dav\/files[^"]+)"/);
let dlUrl = "";
if (dlMatch) {
dlUrl = dlMatch[1].replace(/&/g, '&');
if (dlUrl.startsWith('/')) dlUrl = host + dlUrl;
} else {
dlUrl = `${host}/s/${token}/download`;
}
// 콜백에서 다운로드 ID와 폴더명(title) 연결
chrome.downloads.download({ url: dlUrl, conflictAction: "uniquify" }, (downloadId) => {
if (downloadId && message.title) {
downloadTitlesMap[downloadId] = message.title;
}
if (chrome.runtime.lastError) {
chrome.tabs.sendMessage(sender.tab.id, { action: "SHOW_INFO_TOAST", msg: "❌ 다운로드 시작 실패: " + chrome.runtime.lastError.message, isError: true }).catch(() => {});
} else {
chrome.tabs.sendMessage(sender.tab.id, { action: "SHOW_INFO_TOAST", msg: "✅ Hellkdis 백그라운드 다운로드가 시작되었습니다!" }).catch(() => {});
}
});
} catch (error) {
chrome.tabs.sendMessage(sender.tab.id, { action: "SHOW_INFO_TOAST", msg: "⚠️ 백그라운드 통신 실패. 새 탭을 열어 다운로드를 진행합니다.", isError: true }).catch(() => {});
chrome.runtime.sendMessage({ action: "OPEN_HELLKDIS_WITH_PW", url: message.url, password: message.password }).catch(() => {});
}
})();
return true;
}
else if (message.action === "OPEN_HELLKDIS_WITH_PW") {
let url = message.url;
let pw = message.password;
chrome.tabs.create({ url: url, active: true }, function(tab) {
let listener = function(tabId, changeInfo, updatedTab) {
if (tabId === tab.id && changeInfo.status === 'complete') {
chrome.tabs.onUpdated.removeListener(listener);
chrome.scripting.executeScript({
target: { tabId: tab.id },
func: (password) => {
if (!document.getElementById('bm-macro-overlay')) {
const overlay = document.createElement('div');
overlay.id = 'bm-macro-overlay';
overlay.style.cssText = `
position: fixed; top: 0; left: 0; width: 100vw; height: 100vh;
background: rgba(0, 0, 0, 0.85); z-index: 2147483647;
display: flex; flex-direction: column; align-items: center; justify-content: center;
color: white; font-family: 'Malgun Gothic', sans-serif; pointer-events: all;
`;
overlay.innerHTML = `
<style>@keyframes bm-spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }</style>
<div style="width: 60px; height: 60px; border: 6px solid rgba(255,255,255,0.2); border-top: 6px solid #6f42c1; border-radius: 50%; animation: bm-spin 1s linear infinite; margin-bottom: 25px;"></div>
<h2 style="margin: 0 0 15px 0; color: #fff; font-size: 26px; font-weight: bold; letter-spacing: -1px;">🚀 자동 다운로드 진행 중...</h2>
<p style="margin: 0; color: #ced4da; font-size: 16px;">매크로가 안전하게 동작 중입니다. 마우스를 클릭하지 말고 잠시만 기다려주세요.</p>
<p id="bm-macro-status" style="margin: 15px 0 0 0; color: #ffc107; font-size: 15px; font-weight: bold;">(다운로드가 서버에서 시작되면 창이 자동으로 닫힙니다)</p>
`;
document.body.appendChild(overlay);
}
const setNativeValue = (element, value) => {
const valueSetter = Object.getOwnPropertyDescriptor(element, 'value').set;
const prototype = Object.getPrototypeOf(element);
const prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value').set;
if (valueSetter && valueSetter !== prototypeValueSetter) {
prototypeValueSetter.call(element, value);
} else {
valueSetter.call(element, value);
}
element.dispatchEvent(new Event('input', { bubbles: true }));
};
const getVisiblePwInput = () => {
return Array.from(document.querySelectorAll('input[type="password"]')).find(el => {
if (el.disabled) return false;
const rect = el.getBoundingClientRect();
return rect.width > 0 && rect.height > 0 && window.getComputedStyle(el).visibility !== 'hidden' && window.getComputedStyle(el).display !== 'none';
});
};
let attempts = 0;
let stage = 'INIT';
const autoMacro = () => {
if (stage === 'DONE') return;
attempts++;
let pwInput = getVisiblePwInput();
let dlBtn = document.querySelector('#public-page-menu--primary, a[href*="/dav/files/"]');
if (!dlBtn) {
dlBtn = Array.from(document.querySelectorAll('a[role="button"], button')).find(el => (el.textContent||'').includes('다운로드'));
}
if (pwInput && password && stage === 'INIT') {
setNativeValue(pwInput, password);
let submitBtn = document.querySelector('button.icon-confirm, button[type="submit"], input[type="submit"], .button-vue--primary, button.primary');
if (submitBtn) {
submitBtn.click();
} else {
let form = pwInput.closest('form');
if(form) form.submit();
else pwInput.dispatchEvent(new KeyboardEvent('keydown', {key: 'Enter', keyCode: 13, which: 13, bubbles: true}));
}
stage = 'PW_ENTERED';
setTimeout(autoMacro, 1500);
return;
} else if (dlBtn && stage !== 'DL_CLICKED') {
stage = 'DL_CLICKED';
setTimeout(() => {
dlBtn.click();
let statusText = document.getElementById('bm-macro-status');
if (statusText) statusText.innerText = "✅ 다운로드 요청 완료! 곧 창이 닫힙니다...";
setTimeout(() => { chrome.runtime.sendMessage({ action: "CLOSE_ME" }); }, 6000);
}, 1000);
} else if (attempts < 40 && stage !== 'DL_CLICKED') {
setTimeout(autoMacro, 500);
} else if (attempts >= 40 && stage !== 'DL_CLICKED') {
let ov = document.getElementById('bm-macro-overlay');
if (ov) {
ov.innerHTML = `<h2 style="color:#dc3545;">⚠️ 자동 다운로드 지연됨</h2><p>화면을 클릭하여 수동으로 다운로드를 진행해 주세요.</p>`;
setTimeout(() => ov.remove(), 2500);
}
}
};
setTimeout(autoMacro, 1000);
},
args: [pw || ""]
}).catch(err => console.log(err));
}
};
chrome.tabs.onUpdated.addListener(listener);
});
return true;
}
else if (message.action === "DOWNLOAD_TRANSFERIT") {
(async () => {
try {
const transferUrl = message.url;
chrome.tabs.sendMessage(sender.tab.id, {
action: "SHOW_INFO_TOAST",
msg: "🚀 Transfer.it 백그라운드 다운로드를 준비합니다..."
}).catch(() => {});
// 1. 화면 포커스를 뺏지 않고(active: false) 뒤쪽에 조용히 탭 열기
chrome.tabs.create({ url: transferUrl, active: false }, (tab) => {
const macroTabId = tab.id;
// 2. 탭 로드 대기
const tabListener = (updatedTabId, changeInfo) => {
if (updatedTabId === macroTabId && changeInfo.status === 'complete') {
chrome.tabs.onUpdated.removeListener(tabListener);
// 3. 강력한 버튼 추적 매크로 주입
chrome.scripting.executeScript({
target: { tabId: macroTabId },
func: () => {
// 디버깅 및 사용자 안내용 오버레이 (클릭을 방해하지 않도록 pointer-events: none 처리)
if (!document.getElementById('bm-macro-overlay')) {
const overlay = document.createElement('div');
overlay.id = 'bm-macro-overlay';
overlay.style.cssText = `
position: fixed; top: 0; left: 0; width: 100vw; height: 100vh;
background: rgba(0, 0, 0, 0.85); z-index: 2147483647;
display: flex; flex-direction: column; align-items: center; justify-content: center;
color: white; font-family: 'Malgun Gothic', sans-serif; pointer-events: none;
`;
overlay.innerHTML = `
<div style="width: 50px; height: 50px; border: 5px solid rgba(255,255,255,0.2); border-top: 5px solid #dc3545; border-radius: 50%; animation: spin 1s linear infinite; margin-bottom: 20px;"></div>
<h2 style="margin: 0 0 15px 0; color: #fff; font-size: 26px;">🚀 Transfer.it 자동 다운로드 중...</h2>
<p style="margin: 0; color: #ced4da; font-size: 16px;">파일을 준비하고 있습니다. 다운로드가 시작되면 이 탭은 자동으로 닫힙니다.</p>
<p id="bm-macro-status" style="margin: 15px 0 0 0; color: #ffc107; font-size: 15px; font-weight: bold;">(다운로드 버튼 추적 중...)</p>
<style>@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }</style>
`;
document.body.appendChild(overlay);
}
let attempts = 0;
const clickDownload = () => {
attempts++;
// 🚨 [핵심 수정] 버튼을 찾는 조건을 극단적으로 넓혔습니다. (div, span 태그 모두 포함)
let dlBtn = document.querySelector('.js-standard-download, .js-zip-download, .download-btn');
if (!dlBtn) {
const elements = Array.from(document.querySelectorAll('button, a, div, span'));
dlBtn = elements.find(el => {
if (el.offsetParent === null) return false; // 화면에 안 보이는 요소 제외
if (el.children.length > 2) return false; // 너무 큰 컨테이너 영역 제외
const text = (el.innerText || el.textContent || '').trim().toLowerCase();
return text === 'download' ||
text === '다운로드' ||
text === 'download as zip' ||
text === 'zip으로 다운로드' ||
text === '모두 다운로드' ||
text === '일반 다운로드' ||
text === 'download all';
});
}
const statusEl = document.getElementById('bm-macro-status');
if (dlBtn) {
if (statusEl) statusEl.innerText = "✅ 버튼 클릭 완료! 서버 응답 대기 중...";
dlBtn.click();
} else if (attempts < 60) {
// SPA 사이트는 렌더링이 늦으므로 최대 60초까지 끈질기게 추적합니다.
setTimeout(clickDownload, 1000);
} else {
if (statusEl) {
statusEl.innerText = "⚠️ 버튼을 찾을 수 없습니다. 화면을 클릭하여 수동으로 다운로드 해주세요.";
statusEl.style.color = "#dc3545";
}
}
};
setTimeout(clickDownload, 2000);
}
}).catch(err => console.log("스크립트 주입 에러:", err));
}
};
chrome.tabs.onUpdated.addListener(tabListener);
// 4. 다운로드 감지 및 숨김 탭 자동 종료 로직
let myDownloadId = null;
const onCreatedListener = (item) => {
// 🚨 [핵심 수정] ZIP 파일의 직접 다운로드 주소(userstorage.mega.co.nz) 완벽 대응
const isTransferItDownload =
item.url.includes('.userstorage.mega.co.nz') ||
item.url.includes('transfer.it') ||
(item.referrer && item.referrer.includes('transfer.it'));
if (isTransferItDownload) {
myDownloadId = item.id;
if (message.title) downloadTitlesMap[item.id] = message.title;
chrome.tabs.sendMessage(sender.tab.id, {
action: "SHOW_INFO_TOAST", msg: "✅ Transfer.it 다운로드가 시작되었습니다! (탭 자동 종료)"
}).catch(() => {});
chrome.downloads.onCreated.removeListener(onCreatedListener);
// Blob 다운로드(개별 파일 암호 해독)가 아닌, 일반 HTTPS 주소(ZIP 파일)면 탭을 바로 닫아도 안전함
if (!item.url.startsWith('blob:')) {
setTimeout(() => { chrome.tabs.remove(macroTabId).catch(() => {}); }, 2000);
}
}
};
chrome.downloads.onCreated.addListener(onCreatedListener);
// Blob 다운로드일 경우 다운로드가 '완료'되어야 탭을 닫음 (도중에 닫으면 끊김)
const onChangedListener = (delta) => {
if (delta.id === myDownloadId && delta.state) {
if (delta.state.current === 'complete' || delta.state.current === 'interrupted') {
chrome.tabs.remove(macroTabId).catch(() => {});
chrome.downloads.onChanged.removeListener(onChangedListener);
}
}
};
chrome.downloads.onChanged.addListener(onChangedListener);
// 무한 대기 방지 10분 타이머
setTimeout(() => {
chrome.tabs.remove(macroTabId).catch(() => {});
chrome.downloads.onCreated.removeListener(onCreatedListener);
chrome.downloads.onChanged.removeListener(onChangedListener);
}, 1000 * 60 * 10);
});
} catch (error) {
console.error("[Transfer.it] 에러:", error);
chrome.tabs.sendMessage(sender.tab.id, {
action: "SHOW_INFO_TOAST", msg: `❌ Transfer.it 오류: ${error.message}`, isError: true
}).catch(() => {});
}
})();
return true;
}
});
async function performRidiSearch(cleanTitle) {
// 1. 책 제목 앞뒤에 쌍따옴표를 붙여 구글 정확도 검색(Exact match)을 유도합니다.
const query = `site:https://ridibooks.com/books "${cleanTitle}"`;
const googleUrl = "https://www.google.com/search?q=" + encodeURIComponent(query);
console.log('googleUrl:', googleUrl);
// 매칭 실패 시 사용할 일반 구글 검색 주소
const fallbackGoogleUrl = "https://www.google.com/search?q=" + encodeURIComponent(cleanTitle);
try {
// 2. 화면 이동 없이 백그라운드에서 구글 검색 결과를 가져옵니다.
const res = await fetch(googleUrl);
const html = await res.text();
// 3. 정규식을 사용하여 a 태그 내부의 href 링크와 텍스트(제목)를 추출합니다.
const aTagRegex = /<a\s+[^>]*href=["']([^"']+)["'][^>]*>(.*?)<\/a>/gi;
let matches = [];
let m;
while ((m = aTagRegex.exec(html)) !== null) {
let href = m[1];
let innerHtml = m[2];
// 구글 리다이렉트 주소 형태 (/url?q=...) 처리
if (href.startsWith('/url?q=')) {
href = decodeURIComponent(href.split('&')[0].replace('/url?q=', ''));
}
// 리디북스 책 상세페이지 링크인 경우만 수집
if (href.includes('ridibooks.com/books/')) {
// 태그 제거 및 띄어쓰기 정제
let text = innerHtml.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim();
matches.push({ url: href, title: text });
}
}
// [버그 수정] 구글 대체 검색 및 오탈자 방어를 위한 고도화된 교차 검증 로직
// 레벤슈타인 거리 알고리즘 (오탈자 및 띄어쓰기 뭉개짐 계산용)
const getSimilarity = (a, b) => {
if (!a) return b ? 0 : 1;
if (!b) return 0;
const matrix = [];
for (let i = 0; i <= b.length; i++) matrix[i] = [i];
for (let j = 0; j <= a.length; j++) matrix[0][j] = j;
for (let i = 1; i <= b.length; i++) {
for (let j = 1; j <= a.length; j++) {
if (b.charAt(i - 1) === a.charAt(j - 1)) matrix[i][j] = matrix[i - 1][j - 1];
else matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, Math.min(matrix[i][j - 1] + 1, matrix[i - 1][j] + 1));
}
}
let maxLen = Math.max(a.length, b.length);
return maxLen === 0 ? 1 : (maxLen - matrix[b.length][a.length]) / maxLen;
};
// 원본 검색어에서도 혹시 모를 대괄호와 공백을 제거하여 비교 기준을 잡습니다.
let targetBase = cleanTitle.replace(/^(\s*\[.*?\])+\s*/g, '').replace(/\s+/g, '');
let validMatches = matches.filter(match => {
let rTitle = match.title;
let hasBracket = /^(\s*\[.*?\])+/.test(rTitle);
let cleanRTitle = rTitle.replace(/^(\s*\[.*?\])+\s*/g, '').replace(/\s+/g, '');
let limit = hasBracket ? 13 : 30;
let t1 = targetBase.substring(0, limit);
let t2 = cleanRTitle.substring(0, limit);
let similarity = getSimilarity(t1, t2);
let isIncluded = (t1.length > 1 && t2.length > 1) && (t1.includes(t2) || t2.includes(t1));
return similarity >= 0.70 || isIncluded;
});
let finalRidiUrl = null;
if (validMatches.length > 0) {
let p1 = validMatches.find(m => m.title.includes('1권 미리보기'));
let p2 = validMatches.find(m => m.title.includes('- 만화 e북'));
let p3 = validMatches.find(m => m.title.includes('- 만화 연재'));
let p4 = validMatches.find(m => m.title.includes('바닐라'));
let p5 = validMatches.find(m => m.title.includes('코믹'));
if (p1) finalRidiUrl = p1.url;
else if (p2) finalRidiUrl = p2.url;
else if (p3) finalRidiUrl = p3.url;
else if (p4) finalRidiUrl = p4.url;
else if (p5) finalRidiUrl = p5.url;
else finalRidiUrl = validMatches[0].url;
}
if (finalRidiUrl) {
chrome.tabs.create({ url: finalRidiUrl }).catch(() => {});
} else {
chrome.tabs.create({ url: fallbackGoogleUrl }).catch(() => {});
}
} catch (err) {
chrome.tabs.create({ url: googleUrl }).catch(() => {});
}
}
function createIndependentMenus() {
chrome.contextMenus.removeAll(() => {
chrome.contextMenus.create({ id: "addExclude", title: "1. 제외 추가", contexts: ["link", "selection"] });
chrome.contextMenus.create({ id: "addIncomplete", title: "2. 미완 추가", contexts: ["link", "selection"] });
chrome.contextMenus.create({ id: "addComplete", title: "3. 완결 추가", contexts: ["link", "selection"] });
chrome.contextMenus.create({ id: "deleteBook", title: "4. 삭제 처리", contexts: ["link", "selection"] });
chrome.contextMenus.create({ id: "searchBook", title: "5. 검색", contexts: ["link", "selection"] });
chrome.contextMenus.create({ id: "searchRidi", title: "6. 리디검색", contexts: ["link", "selection"] });
chrome.contextMenus.create({ id: "searchEverything", title: "7. 애브리띵검색", contexts: ["link", "selection"] });
chrome.contextMenus.create({ id: "separator", type: "separator", contexts: ["all"] });
chrome.contextMenus.create({ id: "registerDetailSelector", title: "🎯 이 요소를 상세페이지 제목으로 등록 (버튼 표시)", contexts: ["all"] });
});
}
function initSidePanelBehavior() {
chrome.storage.local.get({ openSlidePanel: false }, (data) => {
if (chrome.action) {
chrome.action.setPopup({ popup: data.openSlidePanel ? "" : "options.html" });
}
if (chrome.sidePanel && chrome.sidePanel.setPanelBehavior) {
chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: data.openSlidePanel }).catch(console.error);
}
});
}
// ==============================================================================
// 일일 로컬 스냅샷 (타임머신) 생성 로직 (최대 7일 보관)
// ==============================================================================
async function createDailySnapshot() {
try {
const now = new Date();
const dateStr = now.toLocaleDateString('ko-KR');
// 오늘 날짜의 스냅샷이 이미 있다면 패스
const existing = await db.snapshots.where('dateStr').equals(dateStr).first();
if (existing) return;
chrome.storage.local.get({ bookList: [], allowedSites: [], filterWords: [] }, async (data) => {
const snapshotData = { timestamp: now.getTime(), dateStr: dateStr, data: data };
await db.snapshots.add(snapshotData); // 스냅샷 저장
// 7개를 초과하면 가장 오래된 것 삭제
const count = await db.snapshots.count();
if (count > 7) {
const oldest = await db.snapshots.orderBy('timestamp').limit(count - 7).toArray();
const oldestIds = oldest.map(s => s.id);
await db.snapshots.bulkDelete(oldestIds);
}
});
} catch (e) { console.error("Snapshot creation failed:", e); }
}
function checkUpdateInBackground() {
const GITHUB_RAW_URL = "https://raw.githubusercontent.com/dongkkase/Chrome_Library_Management/main/version.json";
const currentVersion = chrome.runtime.getManifest().version;
const now = Date.now();
chrome.storage.local.get(['lastVersionCheckTime', 'latestVersionInfo'], async (data) => {
const updateInterval = 12 * 60 * 60 * 1000; // 12시간 주기
let shouldFetch = !data.lastVersionCheckTime || (now - data.lastVersionCheckTime > updateInterval);
if (shouldFetch) {
try {
const response = await fetch(GITHUB_RAW_URL + "?t=" + now);
if (response.ok) {
const latestData = await response.json();
chrome.storage.local.set({ lastVersionCheckTime: now, latestVersionInfo: latestData });
if (latestData && latestData.latest_version && latestData.latest_version !== currentVersion) {
chrome.action.setBadgeText({ text: "NEW" });
chrome.action.setBadgeBackgroundColor({ color: "#dc3545" });
} else {
chrome.action.setBadgeText({ text: "" });
}
}
} catch (e) {}
} else if (data.latestVersionInfo && data.latestVersionInfo.latest_version && data.latestVersionInfo.latest_version !== currentVersion) {
chrome.action.setBadgeText({ text: "NEW" });
chrome.action.setBadgeBackgroundColor({ color: "#dc3545" });
}
});
}
// 스토리지 변경 감지 리스너 추가 (옵션 설정 실시간 반영 및 레이스 컨디션 해결)
chrome.storage.onChanged.addListener((changes, areaName) => {
if (areaName === 'local' && changes.openSlidePanel) {
const isSlide = changes.openSlidePanel.newValue;
if (chrome.action) {
chrome.action.setPopup({ popup: isSlide ? "" : "options.html" });
}
if (chrome.sidePanel && chrome.sidePanel.setPanelBehavior) {
chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: isSlide }).catch(console.error);
}
}
});
chrome.runtime.onInstalled.addListener(() => {
createIndependentMenus();
initSidePanelBehavior();
checkUpdateInBackground();
createDailySnapshot();
chrome.alarms.create("updateCheckAlarm", { periodInMinutes: 720 });
});
chrome.runtime.onStartup.addListener(() => {
createIndependentMenus();
initSidePanelBehavior();
checkUpdateInBackground();
createDailySnapshot();
});
chrome.alarms.onAlarm.addListener((alarm) => {
if (alarm.name === "updateCheckAlarm") {
checkUpdateInBackground();
createDailySnapshot();
}
});
let pendingTasks = [];
let isSaving = false;
let saveTimer = null;
let bgListMapCache = null; // [신규] 백그라운드 해시맵 캐시
let bgListLength = -1;
chrome.contextMenus.onClicked.addListener((info, tab) => {
const menuId = info.menuItemId;
if (menuId === "registerDetailSelector") {
if (tab && tab.id) {
chrome.tabs.sendMessage(tab.id, { action: "GET_AND_REGISTER_SELECTOR" }).catch(() => {});
}
return;
}
let rawTitle = (info.selectionText || lastRightClickedTitle || info.linkText || "").trim();
if (!rawTitle) return;
let cleanTitle = cleanSiteTitle(rawTitle);
if (!cleanTitle) {
if (tab && tab.id) {
chrome.tabs.sendMessage(tab.id, { action: "SHOW_INFO_TOAST", msg: "❌ 제목을 식별할 수 없어 취소되었습니다.", isError: true }).catch(() => {});
}
return;
}
if (menuId === "searchBook") {
chrome.tabs.create({ url: "https://www.google.com/search?q=" + encodeURIComponent(cleanTitle) }).catch(() => {});
return;
}
if (menuId === "searchRidi") {