Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
4067 lines (3493 loc) · 140 KB
/
Copy pathscript.js
File metadata and controls
4067 lines (3493 loc) · 140 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
document.addEventListener('DOMContentLoaded', function () {
console.log('DOM加载完成,初始化脚本...');
const getPageUrlBtn = document.getElementById('getPageUrlBtn');
const getCurrentUrlBtn = document.getElementById('getCurrentUrlBtn');
const urlInput = document.getElementById('urlInput');
const generateUrlBtn = document.getElementById('generateUrlBtn');
const getFavoriteBtn = document.getElementById('getFavoriteBtn');
const importChargePopupBtn = document.getElementById('importChargePopupBtn');
// 自定义下拉框元素
const urlTypeTrigger = document.getElementById('urlTypeTrigger');
const urlTypeDropdown = document.getElementById('urlTypeDropdown');
const urlTypeOptions = document.querySelectorAll('.custom-select-option');
const urlTypeSelectedText = document.querySelector('.custom-select-selected-text');
const userVideoLimitRow = document.getElementById('userVideoLimitRow');
const userVideoLimitInput = document.getElementById('userVideoLimitInput');
const userVideoDateRangeRow = document.getElementById('userVideoDateRangeRow');
const userVideoDateStartInput = document.getElementById('userVideoDateStartInput');
const userVideoDateEndInput = document.getElementById('userVideoDateEndInput');
let currentUrlType = 'video'; // 默认选择视频地址
const bilibiliCookieInput = document.getElementById('bilibiliCookie');
const cookieClearBtn = document.querySelector('.cookie-clear-btn');
const errorToast = document.getElementById('errorToast');
const successToast = document.getElementById('successToast');
const previewBtn = document.getElementById('previewBtn');
const copyBtn = document.getElementById('copyBtn');
const sponsorBtn = document.getElementById('sponsorBtn');
const followBtn = document.getElementById('followBtn');
// 表格相关元素
const videoTableBody = document.getElementById('videoTableBody');
const exportTableBtn = document.getElementById('exportTableBtn');
const exportNoSubtitleBtn = document.getElementById('exportNoSubtitleBtn');
const openNoSubtitleBtn = document.getElementById('openNoSubtitleBtn');
const importReferenceDedupeBtn = document.getElementById('importReferenceDedupeBtn');
const referenceDedupeFileInput = document.getElementById('referenceDedupeFileInput');
const dedupeTableBtn = document.getElementById('dedupeTableBtn');
const clearTableBtn = document.getElementById('clearTableBtn');
const batchGetSubtitleBtn = document.getElementById('batchGetSubtitleBtn');
// 进度条相关元素
const progressContainer = document.getElementById('progressContainer');
const progressCircleValue = document.getElementById('progressCircleValue');
const progressText = document.getElementById('progressText');
const progressSubText = document.getElementById('progressSubText');
// 显示和更新进度条函数
function showProgress(show = true) {
if (show) {
progressContainer.classList.add('show');
} else {
progressContainer.classList.remove('show');
}
}
function updateProgress(percent, text = '获取字幕中...') {
// 确保百分比为整数和限制范围在0-100
percent = Math.max(0, Math.min(100, Math.floor(percent)));
// 更新进度文字
progressText.textContent = `${percent}%`;
progressSubText.textContent = text;
// 获取进度圆环SVG元素
const circle = document.getElementById('progressCircleValue');
// 计算圆周长
const radius = circle.getAttribute('r');
const circumference = 2 * Math.PI * radius;
// 根据百分比计算stroke-dashoffset
const offset = circumference - (percent / 100) * circumference;
// 设置stroke-dashoffset
circle.style.strokeDashoffset = offset;
// 根据进度情况设置颜色
if (percent === 100) {
// 完成时显示绿色
circle.style.stroke = '#52C41A';
progressText.style.color = '#52C41A';
// 如果有成功文本显示,添加绿色背景
if (text.includes('完成') || text.includes('成功')) {
progressSubText.style.color = '#52C41A';
}
} else if (text.includes('失败') || text.includes('错误')) {
// 失败时显示黄色警告
circle.style.stroke = '#FAAD14';
progressText.style.color = '#FAAD14';
progressSubText.style.color = '#FAAD14';
} else {
// 处理中显示紫色(保持原有颜色)
circle.style.stroke = '#52C41A';
progressText.style.color = '#333';
progressSubText.style.color = '#666';
}
}
// 检查批量获取字幕按钮是否存在
if (batchGetSubtitleBtn) {
console.log('批量获取字幕按钮已找到,绑定事件');
} else {
console.error('找不到批量获取字幕按钮元素');
}
// 获取表头和表体容器,用于同步滚动
const tableHeaderContainer = document.getElementById('tableHeaderContainer');
const tableBodyContainer = document.getElementById('tableBodyContainer');
// 设置表格同步滚动
if (tableBodyContainer && tableHeaderContainer) {
tableBodyContainer.addEventListener('scroll', function () {
// 当表体水平滚动时,同步表头的水平滚动位置
tableHeaderContainer.scrollLeft = tableBodyContainer.scrollLeft;
});
} else {
console.error('找不到表格容器元素,无法设置同步滚动');
}
let generatedUrl = '';
let currentVideoInfo = null;
let currentSubtitleData = null;
// 视频列表数组,用于存储添加到表格的视频
let videoList = [];
let isBatchFetchingSubtitles = false;
let shouldStopBatchSubtitles = false;
const referenceDedupeItems = [];
function updateUserVideoLimitVisibility() {
if (!userVideoLimitRow) return;
const displayValue = currentUrlType === 'user' ? 'flex' : 'none';
userVideoLimitRow.style.display = displayValue;
if (userVideoDateRangeRow) {
userVideoDateRangeRow.style.display = displayValue;
}
}
function getUserVideoLimit() {
const defaultLimit = 100;
if (!userVideoLimitInput) return defaultLimit;
const rawValue = userVideoLimitInput.value.trim();
if (!rawValue) return defaultLimit;
const parsedValue = Number.parseInt(rawValue, 10);
if (!Number.isFinite(parsedValue) || parsedValue < 1) {
userVideoLimitInput.value = String(defaultLimit);
return defaultLimit;
}
return parsedValue;
}
function parseDateInputToTimestamp(input, endOfDay = false) {
if (!input || !input.value) return null;
const [year, month, day] = input.value.split('-').map((value) => Number.parseInt(value, 10));
if (!year || !month || !day) return null;
const date = endOfDay
? new Date(year, month - 1, day, 23, 59, 59, 999)
: new Date(year, month - 1, day, 0, 0, 0, 0);
return Math.floor(date.getTime() / 1000);
}
function getUserVideoDateRange() {
const startTimestamp = parseDateInputToTimestamp(userVideoDateStartInput);
const endTimestamp = parseDateInputToTimestamp(userVideoDateEndInput, true);
if (startTimestamp && endTimestamp && startTimestamp > endTimestamp) {
throw new Error('开始日期不能晚于结束日期');
}
return {
startTimestamp,
endTimestamp,
enabled: Boolean(startTimestamp || endTimestamp),
};
}
function getVideoPublishTimestamp(video) {
const rawTimestamp = video?.created || video?.pubdate || video?.pubtime || video?.ctime || 0;
const timestamp = Number(rawTimestamp);
return Number.isFinite(timestamp) && timestamp > 0 ? timestamp : 0;
}
function isVideoInDateRange(video, dateRange) {
if (!dateRange.enabled) return true;
const timestamp = getVideoPublishTimestamp(video);
if (!timestamp) return true;
if (dateRange.startTimestamp && timestamp < dateRange.startTimestamp) return false;
if (dateRange.endTimestamp && timestamp > dateRange.endTimestamp) return false;
return true;
}
function shouldStopUserVideoPagingByDate(medias, dateRange) {
if (!dateRange.startTimestamp || !medias.length) return false;
return medias.every((video) => {
const timestamp = getVideoPublishTimestamp(video);
return timestamp > 0 && timestamp < dateRange.startTimestamp;
});
}
let errorToastTimer = null;
let successToastTimer = null;
// 显示错误提示
function showError(message) {
const messageElement = errorToast.querySelector('.error-toast-message');
const closeButton = errorToast.querySelector('.error-toast-close');
const iconElement = errorToast.querySelector('.error-toast-icon');
if (successToastTimer) {
clearTimeout(successToastTimer);
successToastTimer = null;
}
if (errorToastTimer) {
clearTimeout(errorToastTimer);
errorToastTimer = null;
}
successToast.classList.remove('show');
// 修改图标为黄色感叹号
iconElement.innerHTML = `
<svg viewBox="0 0 24 24" fill="#FAAD14">
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 15h2v-2h-2v2zm0-4h2V7h-2v6z" />
</svg>
`;
messageElement.textContent = message;
errorToast.classList.add('show');
// 修改为黄色背景样式
errorToast.style.backgroundColor = '#FFF9E6';
errorToast.style.borderLeft = '4px solid #FAAD14';
errorToast.querySelector('.error-toast-icon').style.color = '#FAAD14';
// 点击关闭按钮关闭提示
const closeToast = () => {
errorToast.classList.remove('show');
if (errorToastTimer) {
clearTimeout(errorToastTimer);
errorToastTimer = null;
}
};
closeButton.onclick = closeToast;
// 3秒后自动关闭
errorToastTimer = setTimeout(closeToast, 5000);
}
// 显示成功提示
function showSuccess(message) {
const messageElement = successToast.querySelector('.success-toast-message');
const closeButton = successToast.querySelector('.success-toast-close');
const iconElement = successToast.querySelector('.success-toast-icon');
if (errorToastTimer) {
clearTimeout(errorToastTimer);
errorToastTimer = null;
}
if (successToastTimer) {
clearTimeout(successToastTimer);
successToastTimer = null;
}
errorToast.classList.remove('show');
// 修改图标为绿色勾勾
iconElement.innerHTML = `
<svg viewBox="0 0 24 24" fill="#52C41A">
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z" />
</svg>
`;
messageElement.textContent = message;
successToast.classList.add('show');
// 修改为绿色背景样式
successToast.style.backgroundColor = '#F6FFED';
successToast.style.borderLeft = '4px solid #52C41A';
successToast.querySelector('.success-toast-icon').style.color = '#52C41A';
// 点击关闭按钮关闭提示
const closeToast = () => {
successToast.classList.remove('show');
if (successToastTimer) {
clearTimeout(successToastTimer);
successToastTimer = null;
}
};
closeButton.onclick = closeToast;
// 3秒后自动关闭
successToastTimer = setTimeout(closeToast, 3000);
}
// 从URL中提取视频ID
function extractBilibiliVideoId(url) {
// 匹配常规格式 https://www.bilibili.com/video/BV1xx411c7mD/
const bvRegex = /bilibili\.com\/video\/(BV\w+)/i;
const bvMatch = url.match(bvRegex);
if (bvMatch) return bvMatch[1];
// 匹配短链接 https://b23.tv/OurLgw6
const shortRegex = /b23\.tv\/(\w+)/i;
const shortMatch = url.match(shortRegex);
if (shortMatch) return shortMatch[1];
// 匹配旧版av号 https://www.bilibili.com/video/av788057797/
const avRegex = /bilibili\.com\/video\/av(\d+)/i;
const avMatch = url.match(avRegex);
if (avMatch) return `av${avMatch[1]}`;
return null;
}
// 从URL中提取合集信息 (mid和season_id)
function parseCollectionUrl(url) {
// 匹配格式: https://space.bilibili.com/521041866/lists/4337438?type=season
const regex = /space\.bilibili\.com\/(\d+)\/lists\/(\d+)/;
const match = url.match(regex);
if (match && match.length >= 3) {
return {
mid: match[1],
season_id: match[2],
};
}
return null;
}
// 判断是否为B站URL
function isBilibiliUrl(url) {
return url.includes('bilibili.com/video') || url.includes('b23.tv') || /bilibili\.com\/video\/av\d+/i.test(url);
}
// 格式化数字(添加千位分隔符)
function formatNumber(num) {
return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
// 重置视频信息显示
function resetVideoInfo() {
currentVideoInfo = null;
currentSubtitleData = null;
}
// 显示视频信息
function displayVideoInfo(videoInfo) {
if (!videoInfo || !videoInfo.success) {
resetVideoInfo();
return;
}
}
// 获取B站视频信息
async function fetchBilibiliVideoInfo(url) {
try {
console.log('正在获取视频信息...');
const videoId = extractBilibiliVideoId(url);
if (!videoId) {
showError('无法识别的B站视频地址');
return null;
}
// 通过chrome.runtime.sendMessage调用background脚本获取视频信息,避免CORS限制
const response = await chrome.runtime.sendMessage({
action: 'fetchBilibiliInfo',
videoId: videoId,
});
if (response && response.success) {
// 确保保存了完整的视频信息,特别是cid和bvid
currentVideoInfo = response;
console.log('获取到视频信息:', currentVideoInfo);
// 检查是否有cid
if (!currentVideoInfo.cid) {
console.warn('视频信息中缺少cid参数,可能无法获取字幕');
} else {
console.log('成功获取cid:', currentVideoInfo.cid);
}
displayVideoInfo(response);
showSuccess('成功获取视频信息');
return {
...response,
mid: response?.full_data?.owner?.mid || 0,
};
} else {
showError('获取视频信息失败');
return null;
}
} catch (error) {
console.error('获取B站视频信息错误:', error);
showError('获取视频信息出错,请稍后再试');
return null;
}
}
// 获取B站视频字幕
async function fetchBilibiliSubtitle(isBatchMode = false) {
try {
// 只有在非批量模式下才操作UI
if (!isBatchMode) {
// 隐藏无字幕选项
// noSubtitleOptions.style.display = 'none';
}
// 检查currentVideoInfo是否包含必要的信息
if (!currentVideoInfo) {
if (!isBatchMode) showError('请先获取视频信息');
console.error('fetchBilibiliSubtitle: currentVideoInfo 为空');
return { success: false, message: '请先获取视频信息' };
}
// 打印调试信息
console.log('当前视频信息:', currentVideoInfo);
if (!currentVideoInfo.cid) {
if (!isBatchMode) {
// subtitleContainer.style.display = 'block';
// subtitleStatusElement.textContent = '(无法获取)';
// subtitleContentElement.textContent = '无法获取字幕:视频信息中缺少cid参数';
showError('视频信息中没有cid,无法获取字幕');
// 显示无字幕选项
// noSubtitleOptions.style.display = 'block';
}
console.error('fetchBilibiliSubtitle: 视频信息中没有cid');
return { success: false, message: '视频信息中没有cid,无法获取字幕' };
}
if (!currentVideoInfo.bvid) {
if (!isBatchMode) {
// subtitleContainer.style.display = 'block';
// subtitleStatusElement.textContent = '(无法获取)';
// subtitleContentElement.textContent = '无法获取字幕:视频信息中缺少bvid参数';
showError('视频信息中没有bvid,无法获取字幕');
// 显示无字幕选项
// noSubtitleOptions.style.display = 'block';
}
console.error('fetchBilibiliSubtitle: 视频信息中没有bvid');
return { success: false, message: '视频信息中没有bvid,无法获取字幕' };
}
if (!isBatchMode) {
// subtitleStatusElement.textContent = '获取中...';
// subtitleContentElement.textContent = '正在获取字幕数据...';
// subtitleContainer.style.display = 'block';
console.log('正在获取字幕数据...');
}
// 增加详细日志
console.log(
`正在请求字幕数据,cid: ${currentVideoInfo.cid}, bvid: ${currentVideoInfo.bvid}, aid: ${
currentVideoInfo.aid || '未知'
}`,
);
const response = await chrome.runtime.sendMessage({
action: 'fetchBilibiliSubtitle',
cid: currentVideoInfo.cid,
bvid: currentVideoInfo.bvid,
aid: currentVideoInfo.aid, // 添加aid参数,帮助后台更好地获取字幕
});
console.log('获取字幕响应:', response);
if (response && response.success) {
if (!isBatchMode) {
currentSubtitleData = response;
}
if (response.subtitleText && response.subtitleText.trim() !== '') {
if (!isBatchMode) {
// subtitleContentElement.textContent = response.subtitleText;
// subtitleStatusElement.textContent = response.metadata?.lan_doc ? `(${response.metadata.lan_doc})` : '';
showSuccess('成功获取字幕');
// 增加解析次数统计
checkAndIncrementExtractCount(1);
// 添加测试WBI接口按钮
addTestApiButton();
}
return response;
} else {
if (!isBatchMode) {
// subtitleContentElement.textContent = '获取到的字幕内容为空';
// subtitleStatusElement.textContent = '(内容为空)';
showError('获取到的字幕内容为空');
// 显示无字幕选项
// noSubtitleOptions.style.display = 'block';
}
console.warn('fetchBilibiliSubtitle: 获取到的字幕内容为空');
return { ...response, success: false, message: '获取到的字幕内容为空' };
}
} else {
// 字幕获取失败,显示错误信息
const errorMessage = response?.message || '未知错误';
console.error('字幕获取失败原因:', errorMessage);
if (!isBatchMode) {
// subtitleContentElement.textContent = '获取字幕失败: ' + errorMessage;
// subtitleStatusElement.textContent = '(获取失败)';
showError('获取字幕失败: ' + errorMessage);
// 如果是因为视频没有字幕,则显示无字幕选项
if (
response &&
response.message &&
(response.message.includes('没有字幕') ||
response.message.includes('字幕数据为空') ||
response.message.includes('没有可用字幕') ||
response.message.includes('解析字幕内容失败'))
) {
// noSubtitleOptions.style.display = 'block';
}
}
return { success: false, message: errorMessage };
}
} catch (error) {
console.error('获取字幕错误:', error);
if (!isBatchMode) {
// 即使出错也显示错误信息
// subtitleContainer.style.display = 'block';
// subtitleContentElement.textContent = `获取字幕出错: ${error.message || '未知错误'}`;
// subtitleStatusElement.textContent = '(获取出错)';
showError('获取字幕出错,请稍后再试');
// 显示无字幕选项
// noSubtitleOptions.style.display = 'block';
}
return { success: false, message: error.message || '未知错误' };
}
}
// 修复SRT格式时间戳函数
function isNoSubtitleMessage(message) {
const text = String(message || '');
return (
text.includes('没有字幕') ||
text.includes('没有可用字幕') ||
text.includes('字幕数据为空') ||
text.includes('字幕内容为空') ||
text.includes('no subtitle') ||
text.includes('no subtitles')
);
}
function formatTimeForSRT(seconds) {
const pad = (num) => (num < 10 ? '0' + num : num);
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
const secs = Math.floor(seconds % 60);
const ms = Math.floor((seconds % 1) * 1000);
// 注意这里使用逗号而不是点号
return `${pad(hours)}:${pad(minutes)}:${pad(secs)},${ms.toString().padStart(3, '0')}`;
}
// 导出字幕为TXT文件
async function exportSubtitleToTxt() {
console.log('导出字幕数据:', currentSubtitleData);
// 首先检查是否有字幕文本内容
if (!currentSubtitleData || !currentSubtitleData.subtitleText) {
showError('没有可导出的字幕文本数据');
return;
}
try {
let subtitleText = currentSubtitleData.subtitleText;
// 如果有字幕URL,尝试获取最新内容
if (currentSubtitleData.metadata && currentSubtitleData.metadata.subtitle_url) {
try {
const subtitleUrl = currentSubtitleData.metadata.subtitle_url;
// 显示请求进度反馈
showSuccess('正在请求最新字幕内容...');
console.log('请求字幕内容URL:', subtitleUrl);
// 获取字幕内容
const subtitleHeaders = {
Referer: 'https://www.bilibili.com/video/' + (currentVideoInfo?.bvid || ''),
'User-Agent':
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
Accept: 'application/json, text/plain, */*',
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
Origin: 'https://www.bilibili.com',
};
const response = await fetch(subtitleUrl, {
headers: subtitleHeaders,
credentials: 'include', // 确保发送Cookie
});
if (response.ok) {
const subtitleData = await response.json();
console.log('成功获取最新字幕内容:', subtitleData);
// 处理字幕内容格式
if (subtitleData && subtitleData.body && subtitleData.body.length > 0) {
subtitleText = subtitleData.body
.map((item) => {
const startTime = formatTimeForSRT(item.from);
const endTime = formatTimeForSRT(item.to);
return `${startTime} --> ${endTime}\n${item.content}\n`;
})
.join('\n');
console.log('成功格式化最新字幕内容');
}
}
} catch (fetchError) {
console.error('获取最新字幕内容失败,将使用缓存的字幕数据:', fetchError);
// 出错时继续使用缓存的字幕数据
}
}
// 创建Blob对象
const finalText = prependVideoInfo ? prependVideoInfoText(subtitleText, currentVideoInfo?.title, currentVideoInfo?.bvid) : subtitleText;
const blob = new Blob([finalText], { type: 'text/plain;charset=utf-8' });
// 创建下载链接
const url = URL.createObjectURL(blob);
// 创建一个临时的<a>元素用于下载
const downloadLink = document.createElement('a');
downloadLink.href = url;
const safeTitle = (currentVideoInfo?.title || 'subtitle').replace(/[\\/:*?"<>|]/g, '_');
const safeAuthor = (currentVideoInfo?.author || 'unknown').replace(/[\\/:*?"<>|]/g, '_');
// 格式化发布日期
let formattedDate = '';
if (currentVideoInfo?.publishDate) {
const d = formatDate(currentVideoInfo.publishDate);
if (d && d !== '-') {
formattedDate = d;
}
}
downloadLink.download = buildFileName(safeAuthor, safeTitle, formattedDate, 'txt');
// 将链接添加到文档中并点击
document.body.appendChild(downloadLink);
downloadLink.click();
// 清理
document.body.removeChild(downloadLink);
URL.revokeObjectURL(url);
showSuccess('字幕导出成功');
} catch (error) {
console.error('导出字幕错误:', error);
showError('导出字幕失败: ' + (error.message || '未知错误'));
}
}
// 生成URL
function generateUrl() {
const url = urlInput.value.trim();
if (!url) {
showError('请先填写地址!');
return '';
}
return url;
}
// 复制文本到剪贴板
async function copyToClipboard(text) {
try {
await navigator.clipboard.writeText(text);
showSuccess('已复制到剪贴板');
copyBtn.innerHTML = `
<svg viewBox="0 0 24 24">
<path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/>
</svg>
已复制
`;
setTimeout(() => {
copyBtn.innerHTML = `
<svg viewBox="0 0 24 24">
<path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"/>
</svg>
复制地址
`;
}, 2000);
} catch (err) {
console.error('复制失败:', err);
showError('复制失败,请重试');
}
}
// 事件监听器
// 清空地址输入框
document.querySelector('#urlInput + .clear-btn').addEventListener('click', () => {
urlInput.value = '';
resetVideoInfo();
// 清空后自动聚焦输入框
urlInput.focus();
});
// 自定义下拉框点击显示/隐藏下拉列表
urlTypeTrigger.addEventListener('click', function (e) {
e.stopPropagation();
this.classList.toggle('active');
urlTypeDropdown.classList.toggle('active');
});
// 支持触摸事件
urlTypeTrigger.addEventListener('touchend', function (e) {
e.stopPropagation();
e.preventDefault();
this.classList.toggle('active');
urlTypeDropdown.classList.toggle('active');
});
// 点击页面其他部分关闭下拉框
document.addEventListener('click', function () {
urlTypeTrigger.classList.remove('active');
urlTypeDropdown.classList.remove('active');
});
document.addEventListener('touchend', function () {
urlTypeTrigger.classList.remove('active');
urlTypeDropdown.classList.remove('active');
});
// 下拉选项点击事件
urlTypeOptions.forEach(function (option) {
option.addEventListener('click', function (e) {
e.stopPropagation();
// 更新当前选中值
currentUrlType = this.getAttribute('data-value');
// 获取选项中的SVG图标
const iconSvg = this.querySelector('.option-icon').cloneNode(true);
// 更新选中文本和图标
urlTypeSelectedText.textContent = this.textContent.trim();
// 替换触发器中的图标
const triggerIcon = urlTypeTrigger.querySelector('.option-icon');
triggerIcon.innerHTML = iconSvg.innerHTML;
// 更新选中状态
urlTypeOptions.forEach((opt) => opt.classList.remove('selected'));
this.classList.add('selected');
// 根据类型显示不同按钮
if (currentUrlType === 'video') {
generateUrlBtn.style.display = 'inline-flex';
getFavoriteBtn.style.display = 'none';
urlInput.placeholder = '请输入B站单个视频地址';
} else if (currentUrlType === 'favorite') {
generateUrlBtn.style.display = 'none';
getFavoriteBtn.style.display = 'inline-flex';
urlInput.placeholder = '请输入B站收藏夹地址';
} else if (currentUrlType === 'collection') {
generateUrlBtn.style.display = 'none';
getFavoriteBtn.style.display = 'inline-flex';
urlInput.placeholder = '请输入B站合集地址';
} else if (currentUrlType === 'user') {
generateUrlBtn.style.display = 'none';
getFavoriteBtn.style.display = 'inline-flex';
urlInput.placeholder = '请输入B站个人主页地址';
} else if (currentUrlType === 'selection') {
generateUrlBtn.style.display = 'none';
getFavoriteBtn.style.display = 'inline-flex';
urlInput.placeholder = '请输入B站视频选集地址 (含分P)';
}
updateUserVideoLimitVisibility();
// 关闭下拉框
urlTypeTrigger.classList.remove('active');
urlTypeDropdown.classList.remove('active');
});
// 同样更新触摸事件处理
option.addEventListener('touchend', function (e) {
e.stopPropagation();
e.preventDefault();
// 更新当前选中值
currentUrlType = this.getAttribute('data-value');
// 获取选项中的SVG图标
const iconSvg = this.querySelector('.option-icon').cloneNode(true);
// 更新选中文本和图标
urlTypeSelectedText.textContent = this.textContent.trim();
// 替换触发器中的图标
const triggerIcon = urlTypeTrigger.querySelector('.option-icon');
triggerIcon.innerHTML = iconSvg.innerHTML;
// 更新选中状态
urlTypeOptions.forEach((opt) => opt.classList.remove('selected'));
this.classList.add('selected');
// 根据类型显示不同按钮
if (currentUrlType === 'video') {
generateUrlBtn.style.display = 'inline-flex';
getFavoriteBtn.style.display = 'none';
urlInput.placeholder = '请输入B站视频地址';
} else if (currentUrlType === 'favorite') {
generateUrlBtn.style.display = 'none';
getFavoriteBtn.style.display = 'inline-flex';
urlInput.placeholder = '请输入B站收藏夹地址';
} else if (currentUrlType === 'collection') {
generateUrlBtn.style.display = 'none';
getFavoriteBtn.style.display = 'inline-flex';
urlInput.placeholder = '请输入B站合集地址';
} else if (currentUrlType === 'user') {
generateUrlBtn.style.display = 'none';
getFavoriteBtn.style.display = 'inline-flex';
urlInput.placeholder = '请输入B站个人主页地址';
} else if (currentUrlType === 'selection') {
generateUrlBtn.style.display = 'none';
getFavoriteBtn.style.display = 'inline-flex';
urlInput.placeholder = '请输入B站视频地址 (含分P)';
}
updateUserVideoLimitVisibility();
// 关闭下拉框
urlTypeTrigger.classList.remove('active');
urlTypeDropdown.classList.remove('active');
});
});
updateUserVideoLimitVisibility();
async function fillCurrentPageUrl() {
try {
const response = await chrome.runtime.sendMessage({ action: 'getTabUrl' });
if (response?.url) {
urlInput.value = response.url;
resetVideoInfo();
showSuccess('已获取当前页面地址');
} else {
showError(response?.message || '未找到当前页面地址,请先打开B站页面');
}
} catch (error) {
console.error('获取URL失败:', error);
showError('获取地址失败,请重试');
}
}
// 获取当前页面地址按钮
if (getPageUrlBtn) {
getPageUrlBtn.addEventListener('click', fillCurrentPageUrl);
}
if (getCurrentUrlBtn) {
getCurrentUrlBtn.addEventListener('click', fillCurrentPageUrl);
}
// Cookie 处理函数
function setCookie() {
const cookie = bilibiliCookieInput.value.trim();
console.log('设置Cookie (部分显示):', cookie ? cookie.substring(0, 20) + '...' : '空');
// 即使Cookie为空也发送设置请求,这样可以清除Cookie
chrome.runtime.sendMessage(
{
action: 'setCookie',
cookie: cookie,
},
(response) => {
if (response && response.success) {
console.log('Cookie设置成功');
} else {
showError('Cookie设置失败');
console.error('Cookie设置失败:', response?.message || '未知错误');
}
},
);
}
// 清除Cookie按钮事件
cookieClearBtn.addEventListener('click', () => {
bilibiliCookieInput.value = '';
setCookie(); // 清除后发送空Cookie
bilibiliCookieInput.focus();
});
// 为Cookie输入框添加input事件监听器,当用户输入内容时自动保存
bilibiliCookieInput.addEventListener('input', setCookie);
// 为Cookie输入框添加blur事件,当用户输入完成离开输入框时设置Cookie
bilibiliCookieInput.addEventListener('blur', setCookie);
// 为Cookie输入框添加键盘事件,当用户按下回车键时设置Cookie
bilibiliCookieInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
setCookie();
}
});
// 添加获取Cookie按钮的事件监听
const getCookieBtn = document.getElementById('getCookieBtn');
if (getCookieBtn) {
getCookieBtn.addEventListener('click', async () => {
try {
// 显示处理中状态
getCookieBtn.disabled = true;
getCookieBtn.innerHTML = `
<svg viewBox="0 0 24 24" style="animation: spin 1.5s linear infinite;">
<path d="M12 6v3l4-4-4-4v3c-4.42 0-8 3.58-8 8 0 1.57.46 3.03 1.24 4.26L6.7 14.8c-.45-.83-.7-1.79-.7-2.8 0-3.31 2.69-6 6-6zm6.76 1.74L17.3 9.2c.44.84.7 1.79.7 2.8 0 3.31-2.69 6-6 6v-3l-4 4 4 4v-3c4.42 0 8-3.58 8-8 0-1.57-.46-3.03-1.24-4.26z"/>
</svg>
获取中...
`;
// 先检查当前是否在B站页面
const tabResponse = await chrome.runtime.sendMessage({ action: 'getTabUrl' });
const currentUrl = tabResponse?.url || '';
if (!currentUrl.includes('bilibili.com')) {
// 如果不在B站页面,提示用户并尝试打开B站页面
showError('请先前往B站页面,正在为您跳转...');
// 尝试在新标签页打开B站
chrome.tabs.create({ url: 'https://www.bilibili.com/' }, (tab) => {
showSuccess('请在B站页面登录后再次点击获取Cookie按钮');
});
// 恢复按钮状态
getCookieBtn.disabled = false;
getCookieBtn.innerHTML = `
<svg viewBox="0 0 24 24">
<path d="M9 16.2L4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4L9 16.2z" />
</svg>
获取Cookie
`;
return;
}
// 在B站页面,尝试获取Cookie
console.log('正在获取Cookie,请稍候...');
showSuccess('正在获取Cookie,请稍候...');
const response = await chrome.runtime.sendMessage({ action: 'getCookie' });
console.log('获取Cookie响应:', response);
// 恢复按钮状态
getCookieBtn.disabled = false;
getCookieBtn.innerHTML = `
<svg viewBox="0 0 24 24">
<path d="M9 16.2L4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4L9 16.2z" />
</svg>
获取Cookie
`;
if (response && response.success && response.cookie) {
bilibiliCookieInput.value = response.cookie;
setCookie();
// 显示自定义消息或默认成功消息
if (response.message) {
showSuccess(response.message);
} else {
showSuccess('已成功获取B站Cookie');
}
} else {
// 处理错误情况,确保即使response没有message属性也不会报错
const errorMsg = response && response.message ? response.message : '获取Cookie失败,请确保已登录B站';
showError(errorMsg);
}
} catch (error) {
console.error('获取Cookie出错:', error);
showError('获取Cookie失败: ' + (error?.message || '未知错误'));
// 确保按钮状态恢复
getCookieBtn.disabled = false;
getCookieBtn.innerHTML = `
<svg viewBox="0 0 24 24">
<path d="M9 16.2L4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4L9 16.2z" />
</svg>
获取Cookie
`;
}
});
}
// 修改获取视频信息按钮的事件监听
generateUrlBtn.addEventListener('click', async () => {
// Cookie已通过input事件自动设置,无需在此处再调用setCookie