-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
1346 lines (1201 loc) · 41.1 KB
/
background.js
File metadata and controls
1346 lines (1201 loc) · 41.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { buildPrompt, normalizeCard } from "./src/prompts.js";
import {
clearHistory,
getHistory,
removeHistoryEntry,
saveHistoryEntry
} from "./src/storage.js";
import {
formatTimecode,
mergeAdjacentSegments,
dedupeNumericList,
buildTranscriptPayload
} from "./src/subtitle-utils.js";
if (chrome.sidePanel?.setPanelBehavior) {
chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true }).catch(() => {});
}
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message?.type === "ANALYZE_CURRENT_PAGE") {
handleAnalyzeCurrentPage()
.then((card) => sendResponse({ ok: true, card }))
.catch((error) => sendResponse({ ok: false, error: formatError(error) }));
return true;
}
if (message?.type === "ANALYZE_URL") {
handleAnalyzeUrl(message.url)
.then((card) => sendResponse({ ok: true, card }))
.catch((error) => sendResponse({ ok: false, error: formatError(error) }));
return true;
}
if (message?.type === "GET_SETTINGS") {
getSettings().then((settings) => sendResponse({ ok: true, settings }));
return true;
}
if (message?.type === "GET_HISTORY") {
getHistory().then((history) => sendResponse({ ok: true, history }));
return true;
}
if (message?.type === "SAVE_CARD") {
saveCard(message.card)
.then((history) => sendResponse({ ok: true, history }))
.catch((error) => sendResponse({ ok: false, error: formatError(error) }));
return true;
}
if (message?.type === "DELETE_HISTORY") {
removeHistoryEntry(message.id)
.then((history) => sendResponse({ ok: true, history }))
.catch((error) => sendResponse({ ok: false, error: formatError(error) }));
return true;
}
if (message?.type === "CLEAR_HISTORY") {
clearHistory()
.then((history) => sendResponse({ ok: true, history }))
.catch((error) => sendResponse({ ok: false, error: formatError(error) }));
return true;
}
if (message?.type === "DOWNLOAD_CARD") {
downloadCardAsset(message)
.then(() => sendResponse({ ok: true }))
.catch((error) => sendResponse({ ok: false, error: formatError(error) }));
return true;
}
return false;
});
async function handleAnalyzeCurrentPage() {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
if (!tab?.id || !tab.url) {
throw new Error("没有找到当前标签页。");
}
const page = await extractFromTab(tab.id);
return buildCard(page);
}
async function handleAnalyzeUrl(url) {
const safeUrl = ensureUrl(url);
const hostname = new URL(safeUrl).hostname;
if (hostname.includes("youtube.com") || hostname === "youtu.be") {
throw new Error("YouTube 暂不支持“分析这个链接”。请先打开视频页面,再用“读取当前页面”。");
}
const tab = await chrome.tabs.create({ url: safeUrl, active: false });
try {
await waitForTabComplete(tab.id);
const page = await extractFromTab(tab.id);
return buildCard(page);
} finally {
if (tab.id) {
chrome.tabs.remove(tab.id).catch(() => {});
}
}
}
async function extractFromTab(tabId) {
await pingTab(tabId);
const response = await chrome.tabs.sendMessage(tabId, { type: "EXTRACT_PAGE" });
if (!response?.ok) {
throw new Error(response?.error || "页面内容提取失败。");
}
return {
...response.payload,
tabId
};
}
async function pingTab(tabId) {
try {
await chrome.tabs.sendMessage(tabId, { type: "PING" });
} catch (error) {
await chrome.scripting.executeScript({
target: { tabId },
files: ["content-script.js"]
});
}
}
async function buildCard(page) {
page = await enrichVideoPage(page);
const settings = await getSettings();
validateSettings(settings);
validatePageForAnalysis(page);
const prompt = buildPrompt(page);
const response = await requestCompletion({
providerFormat: settings.providerFormat,
endpoint: settings.baseUrl,
apiKey: settings.apiKey,
model: settings.model,
prompt
});
const content = await extractResponseText(response, settings.providerFormat);
if (!content) {
throw new Error("模型没有返回可解析的内容。");
}
const parsed = tryParseJson(content);
const card = normalizeCard(parsed, {
sourceType: page.pageType,
sourceUrl: page.url,
sourceTitle: page.title,
provider: settings.providerFormat,
model: settings.model
});
await saveCard(card);
return card;
}
async function getSettings() {
const defaults = {
providerFormat: "openai",
baseUrl: "https://api.openai.com/v1",
model: "gpt-4.1-mini",
apiKey: ""
};
return chrome.storage.sync.get(defaults);
}
function validateSettings(settings) {
if (!settings.apiKey?.trim()) {
throw new Error("请先在设置页填写 API Key。");
}
if (!settings.baseUrl?.trim()) {
throw new Error("请先填写 API Base URL。");
}
if (!settings.model?.trim()) {
throw new Error("请先填写模型名。");
}
}
function validatePageForAnalysis(page) {
if (page.pageType !== "video") {
return;
}
if (!["youtube", "bilibili", "douyin"].includes(page.videoPlatform || "")) {
throw new Error("当前仅支持 B站、YouTube、抖音 的视频分析。");
}
const transcriptText = page.video?.transcript?.text?.trim();
const hasChapters = Array.isArray(page.video?.chapters) && page.video.chapters.length > 0;
if (!transcriptText && !hasChapters) {
throw new Error(page.videoError || "当前视频没有可用字幕或章节信息,暂时无法分析。");
}
}
async function enrichVideoPage(page) {
if (page.pageType !== "video") {
return page;
}
// 如果已有字幕,直接使用
if (page.video?.transcript?.text?.trim()) {
return page;
}
// 如果没有字幕但视频已有章节信息,使用章节作为时间轴
if (page.video?.chapters?.length) {
return {
...page,
timestamps: page.video.chapters.map((chapter) => ({
time: chapter.time,
context: chapter.title
})),
videoError: ""
};
}
// 尝试获取字幕
try {
if (page.videoPlatform === "bilibili") {
const transcript = await fetchBilibiliTranscript(page.video);
return {
...page,
video: {
...page.video,
transcript
},
timestamps: transcript.segments.map((item) => ({
time: item.timecode,
context: item.text
})),
videoError: ""
};
}
if (page.videoPlatform === "douyin") {
const enrichedVideo = await fetchDouyinVideoData(page.video);
return {
...page,
video: enrichedVideo,
timestamps: enrichedVideo.transcript.segments.map((item) => ({
time: item.timecode,
context: item.text
})),
videoError: ""
};
}
if (page.videoPlatform === "youtube" && page.tabId) {
const enrichedVideo = await fetchYoutubeVideoDataFromTab(page.tabId, page.video);
return {
...page,
video: enrichedVideo,
timestamps: enrichedVideo.transcript.segments.map((item) => ({
time: item.timecode,
context: item.text
})),
videoError: ""
};
}
} catch (error) {
// 字幕获取失败,检查是否有章节信息可以降级使用
if (page.video?.chapters?.length) {
return {
...page,
timestamps: page.video.chapters.map((chapter) => ({
time: chapter.time,
context: chapter.title
})),
videoError: ""
};
}
return {
...page,
videoError: formatError(error)
};
}
return page;
}
function waitForTabComplete(tabId) {
return new Promise((resolve, reject) => {
let settled = false;
const timeoutId = setTimeout(() => {
if (settled) {
return;
}
settled = true;
chrome.tabs.onUpdated.removeListener(listener);
reject(new Error("页面加载超时,请重试。"));
}, 20000);
function listener(updatedTabId, info, tab) {
if (settled) {
return;
}
if (updatedTabId === tabId && info.status === "complete" && !tab.pendingUrl) {
settled = true;
clearTimeout(timeoutId);
chrome.tabs.onUpdated.removeListener(listener);
resolve();
}
}
chrome.tabs.onUpdated.addListener(listener);
chrome.tabs
.get(tabId)
.then((tab) => {
if (settled) {
return;
}
if (tab.status === "complete" && !tab.pendingUrl) {
settled = true;
clearTimeout(timeoutId);
chrome.tabs.onUpdated.removeListener(listener);
resolve();
}
})
.catch(() => {});
});
}
function ensureUrl(raw) {
const value = String(raw || "").trim();
if (!value) {
throw new Error("请输入要分析的链接。");
}
try {
return new URL(value).toString();
} catch (error) {
return new URL(`https://${value}`).toString();
}
}
function trimTrailingSlash(value) {
return value.replace(/\/+$/, "");
}
function tryParseJson(content) {
try {
return JSON.parse(content);
} catch (error) {
const match = content.match(/\{[\s\S]*\}/);
if (!match) {
throw new Error("模型返回的不是合法 JSON。");
}
return JSON.parse(match[0]);
}
}
async function safeReadText(response) {
try {
return (await response.text()).slice(0, 400);
} catch (error) {
return "";
}
}
function formatError(error) {
return error instanceof Error ? error.message : String(error);
}
async function requestCompletion({ providerFormat, endpoint, apiKey, model, prompt }) {
if (providerFormat === "anthropic") {
return requestAnthropic({ endpoint, apiKey, model, prompt });
}
return requestOpenAICompatible({ endpoint, apiKey, model, prompt });
}
async function fetchBilibiliTranscript(video) {
const bvid = video?.identifiers?.bvid;
const cid = video?.identifiers?.cid;
const cidCandidates = Array.isArray(video?.identifiers?.cidCandidates)
? video.identifiers.cidCandidates
: [];
const aid = video?.identifiers?.aid;
const durationSeconds = video?.durationSeconds || null;
const candidateList = dedupeNumericList([cid, ...cidCandidates]);
if (!bvid || !candidateList.length) {
throw new Error("无法识别当前 B站 视频信息,暂时无法分析。");
}
let lastError = "这个 B站 视频没有可用字幕,暂时无法分析。";
const attempts = [];
for (const currentCid of candidateList) {
try {
const transcript = await fetchSingleBilibiliTranscript({
bvid,
aid,
cid: currentCid,
durationSeconds
});
return transcript;
} catch (error) {
lastError = formatError(error);
attempts.push(`cid=${currentCid}: ${lastError}`);
}
}
throw new Error(`${lastError}${attempts.length ? `;尝试记录:${attempts.slice(0, 6).join(" | ")}` : ""}`);
}
async function fetchDouyinVideoData(video) {
const captions = Array.isArray(video?.subtitleMeta?.captions) ? video.subtitleMeta.captions : [];
if (!captions.length) {
throw new Error("这个抖音视频没有可用字幕,暂时无法分析。");
}
const selectedCaption = selectDouyinCaption(captions);
if (!selectedCaption?.url) {
throw new Error("这个抖音视频没有可用字幕,暂时无法分析。");
}
const response = await fetch(selectedCaption.url);
if (!response.ok) {
throw new Error(`抖音字幕请求失败 (${response.status})`);
}
const data = await response.json();
const transcript = buildTranscriptPayload(normalizeDouyinSubtitleBody(data), video?.durationSeconds || null);
if (!transcript.text.trim()) {
throw new Error("这个抖音视频没有可解析字幕,暂时无法分析。");
}
return {
...video,
subtitleMeta: {
languageCode: selectedCaption.lang || "",
trackName: selectedCaption.lang || "",
isAutoGenerated: false
},
transcript
};
}
async function fetchSingleBilibiliTranscript({ bvid, aid, cid, durationSeconds }) {
const apiUrl = new URL("https://api.bilibili.com/x/player/v2");
apiUrl.searchParams.set("cid", String(cid));
apiUrl.searchParams.set("bvid", String(bvid));
if (aid) {
apiUrl.searchParams.set("aid", String(aid));
}
const response = await fetch(apiUrl.toString());
if (!response.ok) {
throw new Error(`B站字幕接口请求失败 (${response.status})`);
}
const data = await response.json();
const subtitle = data?.data?.subtitle;
const subtitles = subtitle?.subtitles || [];
if (!subtitles.length) {
if (subtitle?.need_login_subtitle) {
throw new Error("这个 B站 视频字幕需要登录后才能获取,当前无法分析。");
}
throw new Error(`cid=${cid} 没有可用字幕`);
}
const selectedSubtitle = selectBilibiliSubtitle(subtitles);
const subtitleUrl = selectedSubtitle.subtitle_url?.startsWith("//")
? `https:${selectedSubtitle.subtitle_url}`
: selectedSubtitle.subtitle_url;
if (!subtitleUrl) {
throw new Error(`cid=${cid} 没有可用字幕地址`);
}
const subtitleResponse = await fetch(subtitleUrl);
if (!subtitleResponse.ok) {
throw new Error(`B站字幕文件请求失败 (${subtitleResponse.status})`);
}
const subtitleJson = await subtitleResponse.json();
const segments = (subtitleJson?.body || [])
.map((item) => ({
startSeconds: Number(item.from || 0),
endSeconds: Number(item.to || 0),
text: String(item.content || "").trim()
}))
.filter((item) => item.text)
.filter((item) => !durationSeconds || item.startSeconds <= durationSeconds + 0.5);
if (!segments.length) {
throw new Error(`cid=${cid} 字幕内容为空`);
}
return buildTranscriptPayload(segments, durationSeconds);
}
async function fetchYoutubeVideoDataFromTab(tabId, fallbackVideo) {
let result;
try {
result = await executeYoutubeScriptWithRetry(tabId);
} catch (error) {
const message = formatError(error);
if (isMissingTabError(message)) {
throw new Error("目标 YouTube 页面已关闭或刚刚刷新,请停稳后重试。");
}
throw error;
}
if (!result?.ok) {
throw new Error(result?.error || "当前 YouTube 视频无法读取字幕。");
}
return {
...fallbackVideo,
...result.video
};
}
async function executeYoutubeScriptWithRetry(tabId) {
await waitForTabReady(tabId);
try {
const [{ result }] = await chrome.scripting.executeScript({
target: { tabId },
world: "MAIN",
func: async () => {
function sanitizeText(value) {
return String(value || "").replace(/\s+/g, " ").trim();
}
/**
* 选择最优的 YouTube 字幕轨道
* 评分规则:
* - 人工字幕优先(+10 分)
* - 中文字幕优先(+6 分)
* - 英文字幕次之(+4 分)
*/
function scoreTrack(track) {
const language = String(track?.languageCode || "");
let score = 0;
// 人工字幕优先(asr = auto-generated,非 asr 是人工字幕)
if (track?.kind !== "asr") {
score += 10;
}
// 中文字幕优先
if (language.startsWith("zh")) {
score += 6;
}
// 英文字幕次之
if (language.startsWith("en")) {
score += 4;
}
return score;
}
function selectTrack(tracks) {
return [...tracks].sort((left, right) => scoreTrack(right) - scoreTrack(left))[0];
}
function decodeHtml(text) {
const textarea = document.createElement("textarea");
textarea.innerHTML = text;
return textarea.value;
}
function parseXmlTranscript(xmlText) {
const xml = new DOMParser().parseFromString(xmlText, "text/xml");
return Array.from(xml.querySelectorAll("text"))
.map((node) => {
const text = sanitizeText(decodeHtml(node.textContent || ""));
if (!text) {
return null;
}
const startSeconds = parseFloat(node.getAttribute("start") || "0");
const duration = parseFloat(node.getAttribute("dur") || "0");
return {
startSeconds,
endSeconds: startSeconds + duration,
text
};
})
.filter(Boolean);
}
function withQuery(url, params) {
const parsed = new URL(url);
Object.entries(params).forEach(([key, value]) => parsed.searchParams.set(key, value));
return parsed.toString();
}
function mergeSegments(segments) {
const merged = [];
for (const segment of segments) {
const text = sanitizeText(segment.text || "");
if (!text) continue;
const current = {
startSeconds: Number(segment.startSeconds || 0),
endSeconds: Number(segment.endSeconds || segment.startSeconds || 0),
text
};
const previous = merged[merged.length - 1];
if (previous && current.startSeconds - previous.endSeconds <= 0.35 && previous.text.length < 120) {
previous.endSeconds = Math.max(previous.endSeconds, current.endSeconds);
previous.text = `${previous.text} ${current.text}`.trim();
} else {
merged.push(current);
}
}
return merged;
}
function formatTimecode(totalSeconds) {
const rounded = Math.max(0, Math.floor(Number(totalSeconds) || 0));
const hours = Math.floor(rounded / 3600);
const minutes = Math.floor((rounded % 3600) / 60);
const seconds = rounded % 60;
if (hours > 0) {
return [hours, minutes, seconds].map((value) => String(value).padStart(2, "0")).join(":");
}
return [minutes, seconds].map((value) => String(value).padStart(2, "0")).join(":");
}
function buildTranscriptPayload(segments, durationSeconds) {
const cleaned = mergeSegments(segments)
.map((item) => ({
startSeconds: item.startSeconds,
endSeconds: item.endSeconds,
timecode: formatTimecode(item.startSeconds),
text: item.text
}))
.filter((item) => item.text)
.filter((item) => !durationSeconds || item.startSeconds <= durationSeconds + 0.5)
.slice(0, 400);
return {
durationSeconds,
text: cleaned.map((item) => `${item.timecode} ${item.text}`).join("\n"),
segments: cleaned
};
}
function parseVisibleTranscriptFromDom() {
const segmentNodes = document.querySelectorAll(
'ytd-transcript-segment-renderer, [target-id^="transcript-segment-"]'
);
const segments = Array.from(segmentNodes)
.map((node) => {
const timeText =
node.querySelector('.segment-timestamp')?.textContent ||
node.querySelector('[class*="timestamp"]')?.textContent ||
"";
const bodyText =
node.querySelector('.segment-text')?.textContent ||
node.querySelector('[class*="segment-text"]')?.textContent ||
node.textContent ||
"";
const timecode = String(timeText || "").trim();
const text = sanitizeText(bodyText.replace(timecode, ""));
if (!timecode || !text) {
return null;
}
const startSeconds = parseTimecode(timecode);
if (startSeconds == null) {
return null;
}
return {
startSeconds,
endSeconds: startSeconds,
text
};
})
.filter(Boolean);
return segments;
}
function parseTimecode(value) {
const parts = String(value || "")
.trim()
.split(":")
.map((part) => Number(part));
if (!parts.length || parts.some((part) => Number.isNaN(part))) {
return null;
}
if (parts.length === 3) {
return parts[0] * 3600 + parts[1] * 60 + parts[2];
}
if (parts.length === 2) {
return parts[0] * 60 + parts[1];
}
return null;
}
const playerResponse = window.ytInitialPlayerResponse || window.ytplayer?.config?.args?.player_response && JSON.parse(window.ytplayer.config.args.player_response);
const details = playerResponse?.videoDetails || {};
const trackList = playerResponse?.captions?.playerCaptionsTracklistRenderer?.captionTracks || [];
if (!trackList.length) {
const domSegments = parseVisibleTranscriptFromDom();
if (domSegments.length) {
const durationSeconds = parseInt(details.lengthSeconds || "0", 10) || null;
return {
ok: true,
video: {
platform: "youtube",
channelName: details.author || "",
description: String(details.shortDescription || "").trim(),
durationSeconds,
subtitleMeta: {
languageCode: "",
trackName: "visible-transcript-panel",
isAutoGenerated: false
},
transcript: buildTranscriptPayload(domSegments, durationSeconds)
}
};
}
return { ok: false, error: "这个 YouTube 视频没有可用字幕,暂时无法分析。" };
}
const selectedTrack = selectTrack(trackList);
if (!selectedTrack?.baseUrl) {
return { ok: false, error: "这个 YouTube 视频没有可用字幕地址,暂时无法分析。" };
}
let segments = [];
const xmlResponse = await fetch(selectedTrack.baseUrl, { credentials: "include" });
if (xmlResponse.ok) {
const xmlText = await xmlResponse.text();
segments = parseXmlTranscript(xmlText);
}
if (!segments.length) {
const jsonResponse = await fetch(withQuery(selectedTrack.baseUrl, { fmt: "json3" }), { credentials: "include" });
if (jsonResponse.ok) {
const text = await jsonResponse.text();
if (text.trim()) {
try {
const json = JSON.parse(text);
segments = (json?.events || [])
.map((event) => {
const segmentText = sanitizeText((event?.segs || []).map((seg) => seg?.utf8 || "").join(""));
if (!segmentText) {
return null;
}
return {
startSeconds: (event.tStartMs || 0) / 1000,
endSeconds: ((event.tStartMs || 0) + (event.dDurationMs || 0)) / 1000,
text: segmentText
};
})
.filter(Boolean);
} catch (error) {}
}
}
}
if (!segments.length) {
const domSegments = parseVisibleTranscriptFromDom();
if (domSegments.length) {
return {
ok: true,
video: {
platform: "youtube",
channelName: details.author || "",
description: String(details.shortDescription || "").trim(),
durationSeconds: parseInt(details.lengthSeconds || "0", 10) || null,
subtitleMeta: {
languageCode: selectedTrack.languageCode || "",
trackName: "visible-transcript-panel",
isAutoGenerated: selectedTrack.kind === "asr"
},
transcript: buildTranscriptPayload(domSegments, parseInt(details.lengthSeconds || "0", 10) || null)
}
};
}
return { ok: false, error: "这个 YouTube 视频字幕内容为空,暂时无法分析。" };
}
const durationSeconds = parseInt(details.lengthSeconds || "0", 10) || null;
return {
ok: true,
video: {
platform: "youtube",
channelName: details.author || "",
description: String(details.shortDescription || "").trim(),
durationSeconds,
subtitleMeta: {
languageCode: selectedTrack.languageCode || "",
trackName: selectedTrack.name?.simpleText || selectedTrack.vssId || "",
isAutoGenerated: selectedTrack.kind === "asr"
},
transcript: buildTranscriptPayload(segments, durationSeconds)
}
};
}
});
return result;
} catch (error) {
const message = formatError(error);
if (!shouldRetryMainWorldInjection(message)) {
throw error;
}
await waitForTabReady(tabId);
const [{ result }] = await chrome.scripting.executeScript({
target: { tabId },
world: "MAIN",
func: async () => {
function sanitizeText(value) {
return String(value || "").replace(/\s+/g, " ").trim();
}
function scoreTrack(track) {
const language = String(track?.languageCode || "");
let score = 0;
if (track?.kind !== "asr") {
score += 10;
}
if (language.startsWith("zh")) {
score += 6;
}
if (language.startsWith("en")) {
score += 4;
}
return score;
}
function selectTrack(tracks) {
return [...tracks].sort((left, right) => scoreTrack(right) - scoreTrack(left))[0];
}
function decodeHtml(text) {
const textarea = document.createElement("textarea");
textarea.innerHTML = text;
return textarea.value;
}
function parseXmlTranscript(xmlText) {
const xml = new DOMParser().parseFromString(xmlText, "text/xml");
return Array.from(xml.querySelectorAll("text"))
.map((node) => {
const text = sanitizeText(decodeHtml(node.textContent || ""));
if (!text) {
return null;
}
const startSeconds = parseFloat(node.getAttribute("start") || "0");
const duration = parseFloat(node.getAttribute("dur") || "0");
return {
startSeconds,
endSeconds: startSeconds + duration,
text
};
})
.filter(Boolean);
}
function withQuery(url, params) {
const parsed = new URL(url);
Object.entries(params).forEach(([key, value]) => parsed.searchParams.set(key, value));
return parsed.toString();
}
function mergeSegments(segments) {
const merged = [];
for (const segment of segments) {
const text = sanitizeText(segment.text || "");
if (!text) continue;
const current = {
startSeconds: Number(segment.startSeconds || 0),
endSeconds: Number(segment.endSeconds || segment.startSeconds || 0),
text
};
const previous = merged[merged.length - 1];
if (previous && current.startSeconds - previous.endSeconds <= 0.35 && previous.text.length < 120) {
previous.endSeconds = Math.max(previous.endSeconds, current.endSeconds);
previous.text = `${previous.text} ${current.text}`.trim();
} else {
merged.push(current);
}
}
return merged;
}
function formatTimecode(totalSeconds) {
const rounded = Math.max(0, Math.floor(Number(totalSeconds) || 0));
const hours = Math.floor(rounded / 3600);
const minutes = Math.floor((rounded % 3600) / 60);
const seconds = rounded % 60;
if (hours > 0) {
return [hours, minutes, seconds].map((value) => String(value).padStart(2, "0")).join(":");
}
return [minutes, seconds].map((value) => String(value).padStart(2, "0")).join(":");
}
function buildTranscriptPayload(segments, durationSeconds) {
const cleaned = mergeSegments(segments)
.map((item) => ({
startSeconds: item.startSeconds,
endSeconds: item.endSeconds,
timecode: formatTimecode(item.startSeconds),
text: item.text
}))
.filter((item) => item.text)
.filter((item) => !durationSeconds || item.startSeconds <= durationSeconds + 0.5)
.slice(0, 400);
return {
durationSeconds,
text: cleaned.map((item) => `${item.timecode} ${item.text}`).join("\n"),
segments: cleaned
};
}
function parseVisibleTranscriptFromDom() {
const segmentNodes = document.querySelectorAll(
'ytd-transcript-segment-renderer, [target-id^="transcript-segment-"]'
);
const segments = Array.from(segmentNodes)
.map((node) => {
const timeText =
node.querySelector('.segment-timestamp')?.textContent ||
node.querySelector('[class*="timestamp"]')?.textContent ||
"";
const bodyText =
node.querySelector('.segment-text')?.textContent ||
node.querySelector('[class*="segment-text"]')?.textContent ||
node.textContent ||
"";
const timecode = String(timeText || "").trim();
const text = sanitizeText(bodyText.replace(timecode, ""));
if (!timecode || !text) {
return null;
}
const startSeconds = parseTimecode(timecode);
if (startSeconds == null) {
return null;
}
return {
startSeconds,
endSeconds: startSeconds,
text
};
})
.filter(Boolean);
return segments;
}
function parseTimecode(value) {
const parts = String(value || "")
.trim()
.split(":")
.map((part) => Number(part));
if (!parts.length || parts.some((part) => Number.isNaN(part))) {
return null;
}
if (parts.length === 3) {
return parts[0] * 3600 + parts[1] * 60 + parts[2];
}
if (parts.length === 2) {
return parts[0] * 60 + parts[1];
}
return null;
}
const playerResponse = window.ytInitialPlayerResponse || window.ytplayer?.config?.args?.player_response && JSON.parse(window.ytplayer.config.args.player_response);
const details = playerResponse?.videoDetails || {};
const trackList = playerResponse?.captions?.playerCaptionsTracklistRenderer?.captionTracks || [];
if (!trackList.length) {
const domSegments = parseVisibleTranscriptFromDom();
if (domSegments.length) {
const durationSeconds = parseInt(details.lengthSeconds || "0", 10) || null;
return {
ok: true,
video: {
platform: "youtube",
channelName: details.author || "",
description: String(details.shortDescription || "").trim(),
durationSeconds,
subtitleMeta: {
languageCode: "",
trackName: "visible-transcript-panel",
isAutoGenerated: false
},
transcript: buildTranscriptPayload(domSegments, durationSeconds)
}
};
}
return { ok: false, error: "这个 YouTube 视频没有可用字幕,暂时无法分析。" };
}