forked from xifangczy/cat-catch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
popup.js
953 lines (931 loc) · 33.7 KB
/
popup.js
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
// 解析参数
const params = new URL(location.href).searchParams;
const _tabId = parseInt(params.get("tabId"));
window.isPopup = _tabId ? true : false;
// 当前页面
const $mediaList = $('#mediaList');
const $current = $("<div></div>");
const $currentCount = $("#currentTab #quantity");
let currentCount = 0;
// 其他页面
const $allMediaList = $('#allMediaList');
const $all = $("<div></div>");
const $allCount = $("#allTab #quantity");
let allCount = 0;
// 疑似密钥
const $maybeKey = $("<div></div>");
// 提示 操作按钮 DOM
const $tips = $("#Tips");
const $down = $("#down");
const $mergeDown = $("#mergeDown");
// 储存所有资源数据
const allData = new Map([
[true, new Map()], // 当前页面
[false, new Map()] // 其他页面
]);
// 筛选
const $filter_ext = $("#filter #ext");
// 储存所有扩展名,保存是否筛选状态 来判断新加入的资源 立刻判断是否需要隐藏
const filterExt = new Map();
// 当前所在页面
let activeTab = true;
// 储存下载id
const downData = [];
// 图标地址
const favicon = new Map();
// 当前页面DOM
let pageDOM = undefined;
// HeartBeat
chrome.runtime.sendMessage(chrome.runtime.id, { Message: "HeartBeat" });
// 清理冗余数据
chrome.runtime.sendMessage(chrome.runtime.id, { Message: "clearRedundant" });
// 监听下载 出现服务器拒绝错误 调用下载器
chrome.downloads.onChanged.addListener(function (item) {
if (G.catDownload) { delete downData[item.id]; return; }
const errorList = ["SERVER_BAD_CONTENT", "SERVER_UNAUTHORIZED", "SERVER_FORBIDDEN", "SERVER_UNREACHABLE", "SERVER_CROSS_ORIGIN_REDIRECT", "SERVER_FAILED"];
if (item.error && errorList.includes(item.error.current) && downData[item.id]) {
catDownload(downData[item.id]);
delete downData[item.id];
}
});
// 复选框状态 点击返回或者全选后 影响新加入的资源 复选框勾选状态
let checkboxState = true;
// 生成资源DOM
function AddMedia(data, currentTab = true) {
data._title = data.title;
data.title = stringModify(data.title);
// 不存在扩展使用类型
if (data.ext === undefined && data.type !== undefined) {
data.ext = data.type.split("/")[1];
}
// 正则匹配的备注扩展
if (data.extraExt) {
data.ext = data.extraExt;
}
//文件名
data.name = isEmpty(data.name) ? data.title + '.' + data.ext : decodeURIComponent(stringModify(data.name));
//截取文件名长度
let trimName = data.name;
if (data.name.length >= 50 && !isPopup) {
trimName = trimName.substr(0, 20) + '...' + trimName.substr(-30);
}
//添加下载文件名
Object.defineProperty(data, "pageDOM", {
get() { return pageDOM; }
});
data.downFileName = G.TitleName ? templates(G.downFileName, data) : data.name;
// 文件大小单位转换
data._size = data.size;
if (data.size) {
data.size = byteToSize(data.size);
}
// 是否需要解析
data.parsing = false;
if (isM3U8(data)) {
data.parsing = "m3u8";
} else if (isMPD(data)) {
data.parsing = "mpd";
} else if (isJSON(data)) {
data.parsing = "json";
}
// 网站图标
if (data.favIconUrl && !favicon.has(data.webUrl)) {
favicon.set(data.webUrl, data.favIconUrl);
}
data.isPlay = isPlay(data);
if (allData.get(currentTab).has(data.requestId)) {
data.requestId = data.requestId + "_" + Date.now().toString();
}
//添加html
data.html = $(`
<div class="panel">
<div class="panel-heading">
<input type="checkbox" class="DownCheck"/>
${G.ShowWebIco ? `<img class="favicon ${!data.favIconUrl ? "faviconFlag" : ""}" requestId="${data.requestId}" src="${data.favIconUrl}"/>` : ""}
<img src="img/regex.png" class="favicon regex ${data.isRegex ? "" : "hide"}" title="${i18n.regexTitle}"/>
<span class="name ${data.parsing || data.isRegex || data.tabId == -1 ? "bold" : ""}">${trimName}</span>
<span class="size ${data.size ? "" : "hide"}">${data.size}</span>
<img src="img/copy.png" class="icon copy" id="copy" title="${i18n.copy}"/>
<img src="img/parsing.png" class="icon parsing ${data.parsing ? "" : "hide"}" id="parsing" data-type="${data.parsing}" title="${i18n.parser}"/>
<img src="img/play.png" class="icon play ${data.isPlay ? "" : "hide"}" id="play" title="${i18n.preview}"/>
<img src="img/download.png" class="icon download" id="download" title="${i18n.download}"/>
<img src="img/aria2.png" class="icon aria2 ${G.enableAria2Rpc ? "" : "hide"}"" id="aria2" title="Aria2"/>
<img src="img/invoke.svg" class="icon invoke ${G.invoke ? "" : "hide"}"" id="invoke" title="${i18n.invoke}"/>
</div>
<div class="url hide">
<div id="mediaInfo" data-state="false">
${data.title ? `<b>标题:</b> ${data.title}` : ""}
${data.type ? `<br><b>MIME:</b> ${data.type}` : ""}
</div>
<div class="moreButton">
<div id="qrcode"><img src="img/qrcode.png" class="icon qrcode" title="QR Code"/></div>
<div id="catDown"><img src="img/cat-down.png" class="icon cat-down" title="${i18n.downloadWithRequestHeader}"/></div>
<div><img src="img/invoke.svg" class="icon invoke" title="${i18n.invoke}"/></div>
</div>
<a href="${data.url}" target="_blank" download="${data.downFileName}">${data.url}</a>
<br>
<img id="screenshots" class="hide"/>
<video id="preview" class="hide" controls></video>
</div>
</div>`);
////////////////////////绑定事件////////////////////////
//展开网址
data.urlPanel = data.html.find(".url");
data.urlPanelShow = false;
data.panelHeading = data.html.find(".panel-heading");
data.panelHeading.click(function (event) {
data.urlPanelShow = !data.urlPanelShow;
const mediaInfo = data.html.find("#mediaInfo");
const preview = data.html.find("#preview");
if (!data.urlPanelShow) {
if (event.target.id == "play") {
preview.show().trigger("play");
return false;
}
data.urlPanel.hide();
!preview[0].paused && preview.trigger("pause");
return false;
}
data.urlPanel.show();
if (!mediaInfo.data("state")) {
mediaInfo.data("state", true);
if (isM3U8(data)) {
const hls = new Hls({ enableWorker: false });
setRequestHeaders(data.requestHeaders, function () {
hls.loadSource(data.url);
hls.attachMedia(preview[0]);
});
hls.on(Hls.Events.BUFFER_CREATED, function (event, data) {
if (data.tracks && !data.tracks.audiovideo) {
!data.tracks.audio && mediaInfo.append(`<br><b>${i18n.noAudio}</b>`);
!data.tracks.video && mediaInfo.append(`<br><b>${i18n.noVideo}</b>`);
}
});
hls.on(Hls.Events.ERROR, function (event, data) {
if (data.error.message == "Unsupported HEVC in M2TS found") {
hls.stopLoad();
mediaInfo.append(`<br><b>${i18n.hevcPreviewTip}</b>`);
}
});
hls.on(Hls.Events.MANIFEST_PARSED, function (event, data) {
if (data.levels.length > 1 && !mediaInfo.text().includes(i18n.m3u8Playlist)) {
mediaInfo.append(`<br><b>${i18n.m3u8Playlist}</b>`);
}
});
} else if (data.isPlay) {
setRequestHeaders(data.requestHeaders, function () {
preview.attr("src", data.url);
});
} else if (isPicture(data)) {
setRequestHeaders(data.requestHeaders, function () {
data.html.find("#screenshots").show().attr("src", data.url);
});
return false;
} else {
return false;
}
preview.on("loadedmetadata", function () {
preview.show();
if (this.duration && this.duration != Infinity) {
data.duration = this.duration;
mediaInfo.append(`<br><b>${i18n.duration}:</b> ` + secToTime(this.duration));
}
if (this.videoHeight && this.videoWidth) {
mediaInfo.append(`<br><b>${i18n.resolution}:</b> ` + this.videoWidth + "x" + this.videoHeight);
data.videoWidth = this.videoWidth;
data.videoHeight = this.videoHeight;
}
});
}
if (event.target.id == "play") {
preview.show().trigger("play");
}
return false;
});
// 二维码
data.html.find("#qrcode").click(function () {
const size = data.url.length >= 300 ? 400 : 256;
$(this).html("").qrcode({ width: size, height: size, text: data.url }).off("click");
});
// 猫抓下载器 下载
data.html.find("#catDown").click(function () {
catDownload(data);
});
//点击复制网址
data.html.find('#copy').click(function () {
const text = copyLink(data);
navigator.clipboard.writeText(text);
Tips(i18n.copiedToClipboard);
return false;
});
// 发送到Aria2
data.html.find('#aria2').click(function () {
aria2AddUri(data, function (data) {
Tips(i18n.hasSent + JSON.stringify(data), 2000);
}, function (errMsg) {
Tips(i18n.sendFailed, 2000);
console.log(errMsg);
});
return false;
});
// 下载
data.html.find('#download').click(function () {
if (G.m3u8dl && (isM3U8(data) || isMPD(data))) {
if (!data.url.startsWith("blob:")) {
const m3u8dlArg = templates(G.m3u8dlArg, data);
const url = 'm3u8dl://' + Base64.encode(m3u8dlArg);
if (url.length >= 2046) {
navigator.clipboard.writeText(m3u8dlArg);
Tips(i18n.M3U8DLparameterLong, 2000);
return false;
}
if (G.isFirefox) {
window.location.href = url;
return false;
}
chrome.tabs.update({ url: url });
return false;
}
Tips(i18n.blobM3u8DLError, 1500);
}
if (G.m3u8AutoDown && data.parsing == "m3u8") {
openParser(data, { autoDown: true, autoClose: true });
return false;
}
chrome.downloads.download({
url: data.url,
filename: stringModify(data.downFileName),
saveAs: G.saveAs
}, function (id) { downData[id] = data; });
return false;
});
// 调用
data.html.find('.invoke').click(function () {
const url = templates(G.invokeText, data);
if (G.isFirefox) {
window.location.href = url;
} else {
chrome.tabs.update({ url: url });
}
return false;
});
//播放
data.html.find('#play').click(function () {
if (isEmpty(G.Player)) { return true; }
if (G.Player == "$shareApi$" || G.Player == "${shareApi}") {
navigator.share({ url: data.url });
return false;
}
let url = templates(G.Player, data);
if (G.isFirefox) {
window.location.href = url;
return false;
}
chrome.tabs.update({ url: url });
return false;
});
//解析
data.html.find('#parsing').click(function (e) {
openParser(data);
return false;
});
// 多选框 创建checked属性 值和checked状态绑定
data._checked = checkboxState;
data.html.find(".DownCheck").prop("checked", data._checked);
data.html.find('input').click(function (event) {
data._checked = this.checked;
mergeDownButton();
event.originalEvent.cancelBubble = true;
});
Object.defineProperty(data, "checked", {
get() {
return data._checked;
},
set(newValue) {
data._checked = newValue;
data.html.find('input').prop("checked", newValue);
}
});
// 使用Map 储存数据
allData.get(currentTab).set(data.requestId, data);
// 筛选
if (!filterExt.has(data.ext)) {
filterExt.set(data.ext, true);
const html = $(`<label class="flexFilter" id="${data.ext}"><input type="checkbox" checked>${data.ext}</label>`);
html.click(function () {
filterExt.set(this.id, html.find("input").prop("checked"));
getAllData().forEach(function (value) {
if (filterExt.get(value.ext)) {
value.html.find("input").prop("checked", true);
value.html.show();
} else {
value.html.find("input").prop("checked", false);
value.html.hide();
}
});
});
$filter_ext.append(html);
}
// 如果被筛选出去 直接隐藏
if (!filterExt.get(data.ext)) {
data.html.hide();
data.html.find("input").prop("checked", false);
}
return data.html;
}
function AddKey(key) {
const data = {};
data.html = $(`
<div class="panel">
<div class="panel-heading">
<span class="name bold">${key}</span>
<img src="img/copy.png" class="icon copy" id="copy" title="${i18n.copy}"/>
</div>
<div class="url hide">
Hex: ${base64ToHex(key)}
</div>
</div>`);
data.html.find('.panel-heading').click(function () {
data.html.find(".url").toggle();
});
data.html.find('.copy').click(function () {
navigator.clipboard.writeText(key);
Tips(i18n.copiedToClipboard);
return false;
});
return data.html;
}
/********************绑定事件********************/
//标签切换
$(".Tabs .TabButton").click(function () {
activeTab = this.id == "currentTab";
const index = $(this).index();
$(".Tabs .TabButton").removeClass('Active');
$(this).addClass("Active");
$(".container").removeClass("TabShow").eq(index).addClass("TabShow");
UItoggle();
$("#filter, #unfold").hide();
});
// 其他页面
$('#allTab').click(function () {
!allCount && chrome.runtime.sendMessage(chrome.runtime.id, { Message: "getAllData" }, function (data) {
if (!data) { return; }
for (let key in data) {
if (key == G.tabId) { continue; }
allCount += data[key].length;
for (let i = 0; i < data[key].length; i++) {
$all.append(AddMedia(data[key][i], false));
}
}
allCount && $allMediaList.append($all);
UItoggle();
});
});
// 下载选中文件
$('#DownFile').click(function () {
const [checkedData, maxSize] = getCheckedData();
if (checkedData.length >= 10 && !confirm(i18n("confirmDownload", [checkedData.length]))) {
return;
}
if (G.enableAria2Rpc) {
Tips(i18n.hasSent, 2000);
checkedData.forEach(function (data) {
aria2AddUri(data);
});
return;
}
checkedData.forEach(function (data) {
setTimeout(function () {
chrome.downloads.download({
url: data.url,
filename: stringModify(data.downFileName)
}, function (id) { downData[id] = data; });
}, 233);
});
});
// 合并下载
$mergeDown.click(function () {
const [checkedData, maxSize] = getCheckedData();
chrome.runtime.sendMessage({
Message: "catCatchFFmpeg",
action: "openFFmpeg",
extra: i18n.waitingForMedia
});
const taskId = Date.parse(new Date());
// 都是m3u8 自动合并并发送到ffmpeg
if (checkedData.every(data => isM3U8(data))) {
checkedData.forEach(function (data) {
openParser(data, { ffmpeg: "merge", quantity: checkedData.length, taskId: taskId, autoDown: true, autoClose: true });
});
return true;
}
checkedData.forEach(function (data) {
catDownload(data, {
ffmpeg: "merge",
quantity: checkedData.length,
title: data._title,
taskId: taskId,
});
});
});
// 复制选中文件
$('#AllCopy').click(function () {
const url = [];
getData().forEach(function (data) {
if (data.checked) {
url.push(data.parsing ? copyLink(data) : data.url);
}
});
navigator.clipboard.writeText(url.join("\n"));
Tips(i18n.copiedToClipboard);
});
// 全选 反选
$('#AllSelect, #invertSelection').click(function () {
checkboxState = !checkboxState;
const checked = this.id == "AllSelect";
getData().forEach(function (data) {
data.checked = checked ? checked : !data.checked;
});
mergeDownButton();
});
// unfoldAll展开全部 unfoldPlay展开可播放 unfoldFilter展开选中的 fold关闭展开
$('#unfoldAll, #unfoldPlay, #unfoldFilter, #fold').click(function () {
$("#features").hide();
if (this.id == "unfoldAll") {
getData().forEach(function (data) {
if (data.html.is(":hidden")) { return true; }
!data.urlPanelShow && data.panelHeading.click();
});
} else if (this.id == "unfoldPlay") {
getData().forEach(function (data) {
if (data.html.is(":hidden")) { return true; }
data.isPlay && !data.urlPanelShow && data.panelHeading.click();
});
} else if (this.id == "unfoldFilter") {
getData().forEach(function (data) {
if (data.html.is(":hidden")) { return true; }
data.checked && !data.urlPanelShow && data.panelHeading.click();
});
} else if (this.id == "fold") {
getData().forEach(function (data) {
if (data.html.is(":hidden")) { return true; }
data.urlPanelShow && data.panelHeading.click();
});
}
});
// 捕捉/录制 展开按钮 筛选按钮 按钮
// $('#Catch, #openUnfold, #openFilter, #more').click(function () {
$('#openFilter, #more').click(function () {
// const _height = parseInt($(".container").css("margin-bottom"));
// $(".container").css("margin-bottom", ($down[0].offsetHeight + 26) + "px");
const $panel = $(`#${this.getAttribute("panel")}`);
$panel.css("bottom", $down[0].offsetHeight + "px");
$(".more").not($panel).hide();
if ($panel.is(":hidden")) {
$panel.css("display", "flex");
return;
}
// $(".container").css("margin-bottom", _height);
$panel.hide();
});
// 正则筛选
$("#regular input").bind('keypress', function (event) {
if (event.keyCode == "13") {
const regex = new RegExp($(this).val());
getData().forEach(function (data) {
if (!regex.test(data.url)) {
data.checked = false;
data.html.hide();
}
});
$("#filter").hide();
}
});
// 清空数据
$('#Clear').click(function () {
chrome.runtime.sendMessage({ Message: "clearData", tabId: G.tabId, type: activeTab });
chrome.runtime.sendMessage({ Message: "ClearIcon", type: activeTab, tabId: G.tabId });
if (activeTab) {
currentCount = 0;
$current.empty();
} else {
allCount = 0;
$all.empty();
}
allData.get(activeTab).clear();
UItoggle();
});
// 模拟手机端
$("#MobileUserAgent").click(function () {
chrome.runtime.sendMessage({ Message: "mobileUserAgent", tabId: G.tabId }, function () {
G.refreshClear && $('#Clear').click();
updateButton();
});
});
// 自动下载
$("#AutoDown").click(function () {
chrome.runtime.sendMessage({ Message: "autoDown", tabId: G.tabId }, function () {
updateButton();
});
});
// 深度搜索 缓存捕捉 注入脚本
$("[type='script']").click(function () {
chrome.runtime.sendMessage({ Message: "script", tabId: G.tabId, script: this.id + ".js" }, function () {
G.refreshClear && $('#Clear').click();
updateButton();
});
});
// 102以上开启 捕获按钮/注入脚本
if (G.version >= 102) {
$("[type='script']").show();
}
// Firefox 关闭画中画 全屏 修复右边滚动条遮挡
if (G.isFirefox) {
$("body").addClass("fixFirefoxRight");
$(".firefoxHide").each(function () { $(this).hide(); });
}
// 跳转页面
$("[go]").click(function () {
let url = this.getAttribute("go");
if (url == "ffmpegURL") {
chrome.tabs.create({ url: G.ffmpegConfig.url })
return;
}
// isPopup ? chrome.tabs.update({ url: url }) : chrome.tabs.create({ url: url });
chrome.tabs.create({ url: url });
});
// 暂停 启用
$("#enable").click(function () {
chrome.runtime.sendMessage({ Message: "enable" }, function (state) {
$("#enable").html(state ? i18n.pause : i18n.enable);
});
});
// 弹出窗口
$("#popup").click(function () {
chrome.tabs.query({ currentWindow: false, windowType: "popup", url: chrome.runtime.getURL("popup.html?tabId=") + "*" }, function (tabs) {
if (tabs.length) {
chrome.tabs.update(tabs[0].id, { url: `popup.html?tabId=${G.tabId}` });
chrome.windows.update(tabs[0].windowId, { focused: true });
} else {
chrome.windows.create({
url: `popup.html?tabId=${G.tabId}`,
type: "popup",
height: G.popupHeight ?? 1080,
width: G.popupWidth ?? 1920,
top: G.popupTop ?? 0,
left: G.popupLeft ?? 0,
});
}
window.close();
});
});
// 一些需要等待G变量加载完整的操作
const interval = setInterval(function () {
if (!G.initSyncComplete || !G.initLocalComplete || !G.tabId) { return; }
clearInterval(interval);
// 弹出模式 修改G.tabID为参数设定 设置css
if (isPopup) {
G.tabId = _tabId;
$("body").css("width", "100%"); // body 宽度100%
$("#popup").hide(); // 隐藏弹出按钮
$("#more").hide(); // 隐藏更多功能按钮
$("#down").append($("#features button")).css("justify-content", "center"); // 把更多功能内按钮移动到底部
$("#down button").css("margin-left", "5px"); // 按钮间隔
} else if (G.popup) {
$("#popup").click(); // 默认弹出模式
}
// 获取页面DOM
chrome.tabs.sendMessage(G.tabId, { Message: "getPage" }, { frameId: 0 }, function (result) {
if (chrome.runtime.lastError) { return; }
pageDOM = new DOMParser().parseFromString(result, 'text/html');
});
// 填充数据
chrome.runtime.sendMessage(chrome.runtime.id, { Message: "getData", tabId: G.tabId }, function (data) {
if (!data || data === "OK") {
$tips.html(i18n.noData);
$tips.attr("data-i18n", "noData");
return;
}
currentCount = data.length;
if (currentCount >= 500 && confirm(i18n("confirmLoading", [currentCount]))) {
$mediaList.append($current);
UItoggle();
return;
}
for (let key = 0; key < currentCount; key++) {
$current.append(AddMedia(data[key]));
}
$mediaList.append($current);
UItoggle();
});
// 监听资源数据
chrome.runtime.onMessage.addListener(function (MediaData, sender, sendResponse) {
if (MediaData.Message) { return; }
const html = AddMedia(MediaData, MediaData.tabId == G.tabId);
if (MediaData.tabId == G.tabId) {
!currentCount && $mediaList.append($current);
currentCount++;
$current.append(html);
UItoggle();
} else if (allCount) {
allCount++;
$all.append(html);
UItoggle();
}
sendResponse("OK");
});
// 获取模拟手机 自动下载 捕获 状态
updateButton();
// 上一次设定的倍数
$("#playbackRate").val(G.playbackRate);
$(`<style>${G.css}</style>`).appendTo("head");
updateDownHeight();
const observer = new MutationObserver(updateDownHeight);
observer.observe($down[0], { childList: true, subtree: true, attributes: true });
// 记忆弹出窗口的大小
(isPopup && !G.isFirefox) && chrome.windows.onBoundsChanged.addListener(function (window) {
chrome.storage.sync.set({
popupHeight: window.height,
popupWidth: window.width,
popupTop: window.top,
popupLeft: window.left,
});
updateDownHeight();
});
// 疑似密钥
chrome.webNavigation.getAllFrames({ tabId: G.tabId }, function (frames) {
if (!frames) { return; }
for (let frame of frames) {
chrome.tabs.sendMessage(G.tabId, { Message: "getKey" }, { frameId: frame.frameId }, function (result) {
if (chrome.runtime.lastError || !result || result.length == 0) { return; }
$("#maybeKeyTab").show();
for (let key of result) {
$maybeKey.append(AddKey(key));
}
$("#maybeKey").append($maybeKey);
UItoggle();
});
}
});
// 监听密钥
chrome.runtime.onMessage.addListener(function (data, sender, sendResponse) {
if (!data.Message || !data.data || data.Message != "popupAddKey") { return; }
$("#maybeKeyTab").show();
chrome.tabs.query({}, function (tabs) {
let tabId = -1;
for (let item of tabs) {
if (item.url == data.url) {
tabId = item.id;
break;
}
}
if (tabId == -1 || tabId == G.tabId) {
$maybeKey.append(AddKey(data.data));
}
!$("#maybeKey .panel").length && $("#maybeKey").append($maybeKey);
});
});
}, 0);
/********************绑定事件END********************/
// 按钮状态更新
function updateButton() {
chrome.runtime.sendMessage({ Message: "getButtonState", tabId: G.tabId }, function (state) {
for (let key in state) {
const $DOM = $(`#${key}`);
if (key == "MobileUserAgent") {
$DOM.html(state.MobileUserAgent ? i18n.closeSimulation : i18n.simulateMobile);
continue;
}
if (key == "AutoDown") {
$DOM.html(state.AutoDown ? i18n.closeDownload : i18n.autoDownload);
continue;
}
if (key == "enable") {
$DOM.html(state.enable ? i18n.pause : i18n.enable);
continue;
}
const script = G.scriptList.get(key + ".js");
$DOM.html(state[key] ? script.off : script.name);
}
});
}
/* 格式判断 */
const isMediaExt = (ext) => ['ogg', 'ogv', 'mp4', 'webm', 'mp3', 'wav', 'm4a', '3gp', 'mpeg', 'mov', 'm4s', 'aac'].includes(ext);
function isPlay(data) {
if (G.Player && !isJSON(data) && !isPicture(data)) { return true; }
const typeArray = ['video/ogg', 'video/mp4', 'video/webm', 'audio/ogg', 'audio/mp3', 'audio/wav', 'audio/m4a', 'video/3gp', 'video/mpeg', 'video/mov'];
return isMediaExt(data.ext) || typeArray.includes(data.type) || isM3U8(data);
}
function isM3U8(data) {
return (data.ext == "m3u8" ||
data.ext == "m3u" ||
data.type == "application/vnd.apple.mpegurl" ||
data.type == "application/x-mpegurl" ||
data.type == "application/mpegurl" ||
data.type == "application/octet-stream-m3u8"
)
}
function isMPD(data) {
return (data.ext == "mpd" ||
data.type == "application/dash+xml"
)
}
function isJSON(data) {
return (data.ext == "json" ||
data.type == "application/json" ||
data.type == "text/json"
)
}
function isPicture(data) {
if (data.type && data.type.split("/")[0] == "image") {
return true;
}
return (data.ext == "jpg" ||
data.ext == "png" ||
data.ext == "jpeg" ||
data.ext == "bmp" ||
data.ext == "gif" ||
data.ext == "webp"
)
}
// 复制选项
function copyLink(data) {
let text = data.url;
if (data.parsing == "m3u8") {
text = G.copyM3U8;
} else if (data.parsing == "mpd") {
text = G.copyMPD;
} else {
text = G.copyOther;
}
return templates(text, data);
}
// 携带referer 下载
function catDownload(obj, extra = {}) {
let active = !G.downActive;
if (extra) { active = false; }
chrome.tabs.get(G.tabId, function (tab) {
const arg = {
url: `/download.html?${new URLSearchParams({
url: obj.url,
requestHeaders: JSON.stringify(obj.requestHeaders),
filename: obj.downFileName,
initiator: obj.initiator,
...extra
})}`,
index: tab.index + 1,
active: active
};
chrome.tabs.create(arg);
});
}
// 提示
function Tips(text, delay = 200) {
$('#TipsFixed').html(text).fadeIn(500).delay(delay).fadeOut(500);
}
/*
* 有资源 隐藏无资源提示
* 更新数量显示
* 如果标签是其他设置 隐藏底部按钮
*/
function UItoggle() {
getData().size > 0 ? $tips.hide() : $tips.show().html(i18n.noData);
$currentCount.text(currentCount ? `[${currentCount}]` : "");
$allCount.text(allCount ? `[${allCount}]` : "");
const id = $('.TabShow').attr("id");
if (id == "otherOptions" || id == "maybeKey") {
$tips.hide();
$down.hide();
} else if ($down.is(":hidden")) {
$down.show();
}
// 更新图标
$(".faviconFlag").each(function () {
const data = getData(this.getAttribute("requestId"));
if (data && data.webUrl && favicon.has(data.webUrl)) {
this.setAttribute("src", favicon.get(data.webUrl));
this.classList.remove("faviconFlag");
}
});
if (getData().size >= 2) { mergeDownButton(); }
}
// 检查是否符合条件 更改 合并下载 按钮状态
function mergeDownButtonCheck(data) {
if (!data.type) {
return isMediaExt(data.ext);
}
return data.type.startsWith("video") || data.type.startsWith("audio") || data.type.endsWith("octet-stream");
}
function mergeDownButton() {
const [checkedData, maxSize] = getCheckedData();
if (checkedData.length != 2 || maxSize > 2147483648) {
$mergeDown.hide();
return;
}
if (checkedData.every(mergeDownButtonCheck) || checkedData.every(data => isM3U8(data))) {
$mergeDown.show();
}
}
// 获取当前标签 所有选择的文件
function getCheckedData() {
const checkedData = [];
let maxSize = 0;
getData().forEach(function (data) {
if (data.checked) {
const size = data._size ?? 0;
maxSize = size > maxSize ? size : maxSize;
checkedData.push(data);
}
});
return [checkedData, maxSize];
}
// 获取当前标签的资源列表 存在requestId返回该资源
function getData(requestId = false) {
if (requestId) {
return allData.get(activeTab).get(requestId);
}
return allData.get(activeTab);
}
// 获取所有资源列表
function getAllData() {
const data = [];
data.push(...allData.get(true).values());
data.push(...allData.get(false).values());
return data;
}
/**
* ari2a RPC发送一套资源
* @param {object} data 资源对象
* @param {Function} success 成功运行函数
* @param {Function} error 失败运行函数
*/
function aria2AddUri(data, success, error) {
const json = {
"jsonrpc": "2.0",
"id": "cat-catch-" + data.requestId,
"method": "aria2.addUri",
"params": []
};
if (G.aria2RpcToken) {
json.params.push(`token:${G.aria2RpcToken}`);
}
const params = { out: data.downFileName };
if (G.enableAria2RpcReferer) {
if (data.requestHeaders?.referer) {
params.referer = data.requestHeaders.referer;
}
if (data.cookie) {
params.cookie = data.cookie;
}
}
json.params.push([data.url], params);
$.ajax({
type: "POST",
url: G.aria2Rpc,
data: JSON.stringify(json),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
success && success(data);
},
error: function (errMsg) {
error && error(errMsg);
}
});
}
/**
* 打开解析器
* @param {Object} data 资源对象
* @param {Object} options 选项
*/
function openParser(data, options = {}) {
chrome.tabs.get(G.tabId, function (tab) {
const url = `/${data.parsing}.html?${new URLSearchParams({
url: data.url,
title: data.title,
filename: data.downFileName,
tabid: data.tabId == -1 ? G.tabId : data.tabId,
initiator: data.initiator,
tabid: tab.id,
requestHeaders: data.requestHeaders ? JSON.stringify(data.requestHeaders) : undefined,
...Object.fromEntries(Object.entries(options).map(([key, value]) => [key, typeof value === 'boolean' ? 1 : value])),
})}`
chrome.tabs.create({ url: url, index: tab.index + 1, active: !options.autoDown });
});
}
// 更新底部按钮高度
function updateDownHeight() {
$(".container").css("margin-bottom", ($down[0].offsetHeight + 2) + "px");
}
function base64ToHex(base64) {
const binaryString = atob(base64);
let hexString = '';
for (let i = 0; i < binaryString.length; i++) {
let hex = binaryString.charCodeAt(i).toString(16);
if (hex.length === 1) {
hex = '0' + hex;
}
hexString += hex;
}
return hexString;
}