-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathbackground.js
More file actions
1213 lines (1073 loc) · 40.4 KB
/
Copy pathbackground.js
File metadata and controls
1213 lines (1073 loc) · 40.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('shared.js')
const Shared = globalThis.MediaSnifferShared
const DEFAULT_USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36'
const STREAM_CACHE_TTL_MS = 5 * 60 * 1000
const STREAM_CACHE_LIMIT = 120
const REQUEST_CONTEXT_TTL_MS = 2 * 60 * 1000
const REQUEST_CONTEXT_LIMIT = 2000
const STATUS_RANK = {
failed: -1,
discovered: 0,
analyzed: 1,
exported: 2,
downloaded: 3,
}
const mediaByTab = new Map()
const requestContextById = new Map()
const streamContextCache = new Map()
let captureSettings = { ...Shared.DEFAULT_CAPTURE_SETTINGS }
let sessionSaveTimer = null
chrome.storage.local.get(['captureSettings'], (data) => {
captureSettings = Shared.normalizeSettings(data.captureSettings)
})
function scheduleSessionSave() {
if (sessionSaveTimer) clearTimeout(sessionSaveTimer)
sessionSaveTimer = setTimeout(() => {
const data = {}
for (const [tabId, state] of mediaByTab.entries()) {
const records = Array.from(state.recordsByKey.values())
if (records.length) data[tabId] = records
}
chrome.storage.session?.set({ mediaByTab: data }).catch(() => {})
}, 2000)
}
function restoreSession() {
if (!chrome.storage.session) return
chrome.storage.session.get(['mediaByTab'], (result) => {
if (chrome.runtime.lastError || !result?.mediaByTab) return
for (const [tabIdStr, records] of Object.entries(result.mediaByTab)) {
const tabId = Number(tabIdStr)
if (!Number.isFinite(tabId) || tabId < 0) continue
const state = getTabState(tabId)
for (const record of records) {
const key = record.key || Shared.buildMediaKey(record.url, record.referer || '', record.frameId)
state.recordsByKey.set(key, record)
}
updateBadge(tabId)
}
})
}
function getTabState(tabId) {
if (!mediaByTab.has(tabId)) {
mediaByTab.set(tabId, { recordsByKey: new Map() })
}
return mediaByTab.get(tabId)
}
function listTabMedia(tabId, fallbackReferer) {
const records = Array.from(mediaByTab.get(tabId)?.recordsByKey.values() || [])
return records.map((item) => ({
...item,
referer: item.referer || fallbackReferer || '',
refererOrigin: item.refererOrigin || Shared.getOrigin(item.referer || fallbackReferer || '', item.url || ''),
}))
}
function categoryScore(category) {
return category === 'other' ? 0 : 1
}
function statusRank(status) {
return Object.prototype.hasOwnProperty.call(STATUS_RANK, status) ? STATUS_RANK[status] : 0
}
function selectProgressStatus(currentStatus, nextStatus) {
const current = currentStatus || 'discovered'
const next = nextStatus || current
if (next === 'failed') {
return current === 'downloaded' ? current : next
}
if (current === 'failed') return next
return statusRank(next) >= statusRank(current) ? next : current
}
function uniqueStringList(values) {
return Array.from(new Set((values || []).map((value) => String(value || '').trim()).filter(Boolean)))
}
function normalizeHeaderMap(raw) {
const result = {}
const entries = Array.isArray(raw)
? raw.map((item) => [item?.name, item?.value])
: Object.entries(raw || {})
for (const [name, value] of entries) {
const key = String(name || '').trim().toLowerCase()
if (!key) continue
const sensitive = key === 'cookie' || key === 'authorization' || key === 'proxy-authorization'
result[key] = sensitive ? '[redacted]' : String(value || '')
}
return result
}
function decorateMediaRecord(record) {
const category = Shared.normalizeCategory(record)
const requestHeaders = normalizeHeaderMap(record.requestHeaders)
const responseHeaders = normalizeHeaderMap(record.responseHeaders)
const sourceList = uniqueStringList([...(record.sourceList || []), record.source])
const referer = record.referer || ''
const key = record.key || Shared.buildMediaKey(record.url, referer, record.frameId)
return {
...record,
key,
category,
finalUrl: record.finalUrl || record.url || '',
filename: Shared.sanitizeFilename(record.filename || Shared.extractFilename(record.url)),
requestHeaders,
responseHeaders,
referer,
refererOrigin: record.refererOrigin || Shared.getOrigin(referer, record.url || ''),
source: record.source || sourceList[0] || 'unknown',
sourceList,
method: record.method || '',
initiator: record.initiator || '',
fromCache: !!record.fromCache,
status: record.status || 'discovered',
hasCookieHeader:
typeof record.hasCookieHeader === 'boolean'
? record.hasCookieHeader
: Object.prototype.hasOwnProperty.call(requestHeaders, 'cookie'),
hasAuthorizationHeader:
typeof record.hasAuthorizationHeader === 'boolean'
? record.hasAuthorizationHeader
: Object.prototype.hasOwnProperty.call(requestHeaders, 'authorization') ||
Object.prototype.hasOwnProperty.call(requestHeaders, 'proxy-authorization'),
lastError: record.lastError || '',
biliMeta: record.biliMeta || '',
downloadMode: Shared.getDownloadMode({ ...record, category }),
downloadNotice: Shared.getDownloadNotice({ ...record, category }),
}
}
function mergeMediaRecord(oldItem, newItem) {
const oldCategory = oldItem.category || 'other'
const newCategory = newItem.category || 'other'
const preferNewCategory = categoryScore(newCategory) > categoryScore(oldCategory)
const mergedRequestHeaders = { ...(oldItem.requestHeaders || {}), ...(newItem.requestHeaders || {}) }
const mergedResponseHeaders = { ...(oldItem.responseHeaders || {}), ...(newItem.responseHeaders || {}) }
return decorateMediaRecord({
...oldItem,
...newItem,
id: oldItem.id || newItem.id,
key: oldItem.key || newItem.key,
category: preferNewCategory ? newCategory : oldCategory,
categoryHint: newItem.categoryHint || oldItem.categoryHint || '',
contentType: newItem.contentType || oldItem.contentType || '',
size: newItem.size || oldItem.size || '',
sizeBytes: newItem.sizeBytes || oldItem.sizeBytes || 0,
referer: newItem.referer || oldItem.referer || '',
refererOrigin: newItem.refererOrigin || oldItem.refererOrigin || '',
finalUrl: newItem.finalUrl || oldItem.finalUrl || newItem.url || oldItem.url || '',
filename: newItem.filename || oldItem.filename || 'media',
frameId: Number.isInteger(newItem.frameId) ? newItem.frameId : oldItem.frameId,
platform: newItem.platform || oldItem.platform || 'generic',
source: newItem.source || oldItem.source || 'unknown',
sourceList: uniqueStringList([...(oldItem.sourceList || []), ...(newItem.sourceList || []), oldItem.source, newItem.source]),
method: newItem.method || oldItem.method || '',
initiator: newItem.initiator || oldItem.initiator || '',
fromCache: newItem.fromCache || oldItem.fromCache || false,
requestHeaders: mergedRequestHeaders,
responseHeaders: mergedResponseHeaders,
hasCookieHeader: typeof newItem.hasCookieHeader === 'boolean' ? newItem.hasCookieHeader : !!oldItem.hasCookieHeader,
hasAuthorizationHeader: typeof newItem.hasAuthorizationHeader === 'boolean' ? newItem.hasAuthorizationHeader : !!oldItem.hasAuthorizationHeader,
status: selectProgressStatus(oldItem.status, newItem.status),
lastError: newItem.lastError || oldItem.lastError || '',
time: newItem.time || oldItem.time || Date.now(),
})
}
function trimTabState(state) {
while (state.recordsByKey.size > Shared.MAX_MEDIA_PER_TAB) {
const firstKey = state.recordsByKey.keys().next().value
state.recordsByKey.delete(firstKey)
}
}
function cleanupRequestContexts() {
const now = Date.now()
for (const [requestId, entry] of requestContextById.entries()) {
if (!entry || now - entry.createdAt > REQUEST_CONTEXT_TTL_MS) {
requestContextById.delete(requestId)
}
}
while (requestContextById.size > REQUEST_CONTEXT_LIMIT) {
const firstKey = requestContextById.keys().next().value
requestContextById.delete(firstKey)
}
}
function storeRequestContext(requestId, context) {
cleanupRequestContexts()
requestContextById.set(requestId, {
...context,
createdAt: Date.now(),
})
cleanupRequestContexts()
}
function takeRequestContext(requestId) {
const entry = requestContextById.get(requestId) || null
requestContextById.delete(requestId)
return entry
}
function ignoreLastError() {
void chrome.runtime.lastError
}
function updateBadge(tabId) {
const count = mediaByTab.get(tabId)?.recordsByKey.size || 0
chrome.action.setBadgeText({ text: count > 0 ? String(count) : '', tabId })
chrome.action.setBadgeBackgroundColor({ color: '#409eff', tabId })
}
function notifyMediaUpdated(tabId) {
updateBadge(tabId)
chrome.tabs.sendMessage(
tabId,
{
type: Shared.MESSAGE_TYPES.MEDIA_UPDATED,
tabId,
count: mediaByTab.get(tabId)?.recordsByKey.size || 0,
},
ignoreLastError
)
chrome.runtime.sendMessage(
{
type: Shared.MESSAGE_TYPES.MEDIA_UPDATED,
tabId,
count: mediaByTab.get(tabId)?.recordsByKey.size || 0,
},
ignoreLastError
)
}
function upsertMediaRecord(tabId, nextItem) {
const state = getTabState(tabId)
const key = nextItem.key || Shared.buildMediaKey(nextItem.url, nextItem.referer || '', nextItem.frameId)
const existing = state.recordsByKey.get(key)
const normalized = decorateMediaRecord({
...nextItem,
key,
id: existing?.id || nextItem.id || `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
})
if (!Shared.isCategoryEnabled(captureSettings, normalized.category)) return
if (!existing && normalized.source === 'webRequest' && !Shared.isLikelyUsefulResource(normalized)) return
state.recordsByKey.set(key, existing ? mergeMediaRecord(existing, normalized) : normalized)
trimTabState(state)
notifyMediaUpdated(tabId)
scheduleSessionSave()
}
function patchMediaRecord(tabId, recordKey, patch) {
const state = mediaByTab.get(tabId)
if (!state || !recordKey || !state.recordsByKey.has(recordKey)) return
const existing = state.recordsByKey.get(recordKey)
const merged = mergeMediaRecord(existing, {
...existing,
...patch,
id: existing.id,
key: existing.key,
status: selectProgressStatus(existing.status, patch.status || existing.status),
})
state.recordsByKey.set(recordKey, merged)
notifyMediaUpdated(tabId)
scheduleSessionSave()
}
function filterByCaptureSettings() {
for (const [tabId, state] of mediaByTab.entries()) {
for (const [key, item] of state.recordsByKey.entries()) {
if (!Shared.isCategoryEnabled(captureSettings, item.category || 'other')) {
state.recordsByKey.delete(key)
}
}
notifyMediaUpdated(tabId)
}
}
function clearTabMedia(tabId) {
if (!mediaByTab.has(tabId)) return
mediaByTab.get(tabId).recordsByKey.clear()
notifyMediaUpdated(tabId)
scheduleSessionSave()
}
function blobToDataUrl(blob) {
return new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onloadend = () => resolve(reader.result)
reader.onerror = () => reject(new Error('Blob 转换失败'))
reader.readAsDataURL(blob)
})
}
function downloadFile(options) {
return new Promise((resolve) => {
chrome.downloads.download(options, (downloadId) => {
if (chrome.runtime.lastError) {
resolve({ ok: false, error: chrome.runtime.lastError.message || '下载失败' })
return
}
resolve({ ok: !!downloadId, downloadId, filename: options.filename })
})
})
}
function getActiveTabId() {
return new Promise((resolve) => {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
resolve(tabs[0]?.id || null)
})
})
}
function fetchBlobFromTab(tabId, frameId, url) {
return new Promise((resolve) => {
const callback = (resp) => {
if (chrome.runtime.lastError) {
resolve({ ok: false, error: chrome.runtime.lastError.message || '页面内 Blob 抓取失败' })
return
}
resolve(resp || { ok: false, error: '页面内 Blob 抓取失败' })
}
if (Number.isInteger(frameId)) {
chrome.tabs.sendMessage(tabId, { type: Shared.MESSAGE_TYPES.FETCH_BLOB, url }, { frameId }, callback)
return
}
chrome.tabs.sendMessage(tabId, { type: Shared.MESSAGE_TYPES.FETCH_BLOB, url }, callback)
})
}
function fetchTextFromTab(tabId, frameId, url) {
return new Promise((resolve) => {
const callback = (resp) => {
if (chrome.runtime.lastError) {
resolve({ ok: false, error: chrome.runtime.lastError.message || '页面内文本抓取失败' })
return
}
resolve(resp || { ok: false, error: '页面内文本抓取失败' })
}
if (Number.isInteger(frameId)) {
chrome.tabs.sendMessage(tabId, { type: Shared.MESSAGE_TYPES.FETCH_TEXT, url }, { frameId }, callback)
return
}
chrome.tabs.sendMessage(tabId, { type: Shared.MESSAGE_TYPES.FETCH_TEXT, url }, callback)
})
}
async function resolveMediaDataUrl(record, tabId) {
if (Shared.isBlobUrl(record.url)) {
const tabResp = await fetchBlobFromTab(tabId, record.frameId, record.url)
if (!tabResp?.ok || !tabResp?.dataUrl) throw new Error(tabResp?.error || 'Blob 下载失败')
return tabResp.dataUrl
}
try {
const resp = await fetch(record.url, { credentials: 'omit', cache: 'no-store' })
if (!resp.ok) throw new Error(`HTTP ${resp.status}`)
const blob = await resp.blob()
return await blobToDataUrl(blob)
} catch (bgErr) {
const tabResp = await fetchBlobFromTab(tabId, record.frameId, record.url)
if (!tabResp?.ok || !tabResp?.dataUrl) throw new Error(tabResp?.error || bgErr.message)
return tabResp.dataUrl
}
}
function parseAttributeList(line) {
const source = String(line || '').split(':').slice(1).join(':')
const attrs = {}
const re = /([A-Z0-9-]+)=("[^"]*"|[^",]*)/gi
let match = re.exec(source)
while (match) {
let value = match[2] || ''
if (value.startsWith('"') && value.endsWith('"')) value = value.slice(1, -1)
attrs[match[1].toLowerCase()] = value
match = re.exec(source)
}
return attrs
}
function parseIsoDurationToSeconds(value) {
const match = String(value || '').match(
/^P(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+(?:\.\d+)?)S)?)?$/i
)
if (!match) return 0
const years = parseFloat(match[1] || 0)
const months = parseFloat(match[2] || 0)
const days = parseFloat(match[3] || 0)
const hours = parseFloat(match[4] || 0)
const minutes = parseFloat(match[5] || 0)
const seconds = parseFloat(match[6] || 0)
return Math.round(years * 31536000 + months * 2592000 + days * 86400 + hours * 3600 + minutes * 60 + seconds)
}
function formatSeconds(totalSeconds) {
const seconds = Math.max(0, Math.round(Number(totalSeconds) || 0))
const hours = Math.floor(seconds / 3600)
const minutes = Math.floor((seconds % 3600) / 60)
const remain = seconds % 60
if (hours > 0) return `${hours}:${String(minutes).padStart(2, '0')}:${String(remain).padStart(2, '0')}`
return `${minutes}:${String(remain).padStart(2, '0')}`
}
function parseHlsManifest(text, manifestUrl) {
const lines = String(text || '')
.replace(/^\uFEFF/, '')
.replace(/\r/g, '')
.split('\n')
.map((line) => line.trim())
.filter(Boolean)
if (!lines.length || lines[0] !== '#EXTM3U') {
throw new Error('无效的 HLS 索引文件')
}
let variantCount = 0
let segmentCount = 0
let encrypted = false
let encryptionMethod = ''
let targetDuration = 0
let playlistType = ''
let hasEndList = false
let firstVariantUrl = ''
let firstSegmentUrl = ''
let totalDurationSeconds = 0
let waitingVariantAttrs = null
const variants = []
const mediaTracks = []
const resolutions = []
const bandwidths = []
for (const line of lines) {
if (line.startsWith('#EXT-X-MEDIA')) {
const attrs = parseAttributeList(line)
mediaTracks.push({
type: String(attrs.type || '').toLowerCase(),
groupId: attrs['group-id'] || '',
name: attrs.name || '',
language: attrs.language || '',
default: attrs.default || '',
autoselect: attrs.autoselect || '',
uri: attrs.uri ? Shared.toAbsoluteUrl(attrs.uri, manifestUrl) : '',
instreamId: attrs['instream-id'] || '',
})
continue
}
if (line.startsWith('#EXT-X-STREAM-INF')) {
variantCount += 1
waitingVariantAttrs = parseAttributeList(line)
if (waitingVariantAttrs.resolution) resolutions.push(waitingVariantAttrs.resolution)
if (waitingVariantAttrs.bandwidth) {
const numericBandwidth = parseInt(waitingVariantAttrs.bandwidth, 10)
if (Number.isFinite(numericBandwidth)) bandwidths.push(numericBandwidth)
}
continue
}
if (line.startsWith('#EXT-X-I-FRAME-STREAM-INF')) {
variantCount += 1
const attrs = parseAttributeList(line)
const absoluteUrl = attrs.uri ? Shared.toAbsoluteUrl(attrs.uri, manifestUrl) : ''
variants.push({
type: 'iframe',
url: absoluteUrl,
resolution: attrs.resolution || '',
bandwidth: parseInt(attrs.bandwidth || '0', 10) || 0,
codecs: attrs.codecs || '',
audioGroup: attrs.audio || '',
subtitlesGroup: attrs.subtitles || '',
})
if (absoluteUrl && !firstVariantUrl) firstVariantUrl = absoluteUrl
continue
}
if (line.startsWith('#EXTINF:')) {
totalDurationSeconds += parseFloat(line.split(':')[1]?.split(',')[0] || '0') || 0
}
if (line.startsWith('#EXT-X-KEY')) {
const attrs = parseAttributeList(line)
const method = String(attrs.method || '').toUpperCase()
if (method && method !== 'NONE') {
encrypted = true
if (!encryptionMethod) encryptionMethod = method
}
}
if (line.startsWith('#EXT-X-TARGETDURATION:')) targetDuration = parseInt(line.split(':')[1] || '0', 10) || 0
if (line.startsWith('#EXT-X-PLAYLIST-TYPE:')) playlistType = (line.split(':')[1] || '').trim()
if (line.startsWith('#EXT-X-ENDLIST')) hasEndList = true
if (line.startsWith('#')) continue
const absoluteUrl = Shared.toAbsoluteUrl(line, manifestUrl)
if (waitingVariantAttrs) {
if (!firstVariantUrl) firstVariantUrl = absoluteUrl
variants.push({
type: 'variant',
url: absoluteUrl,
resolution: waitingVariantAttrs.resolution || '',
bandwidth: parseInt(waitingVariantAttrs.bandwidth || '0', 10) || 0,
codecs: waitingVariantAttrs.codecs || '',
audioGroup: waitingVariantAttrs.audio || '',
subtitlesGroup: waitingVariantAttrs.subtitles || '',
frameRate: waitingVariantAttrs['frame-rate'] || '',
})
waitingVariantAttrs = null
continue
}
segmentCount += 1
if (!firstSegmentUrl) firstSegmentUrl = absoluteUrl
}
const manifestType = variantCount > 0 ? 'master' : 'media'
const isLive = manifestType === 'media' ? !hasEndList && String(playlistType).toUpperCase() !== 'VOD' : false
const durationLabel = totalDurationSeconds ? formatSeconds(totalDurationSeconds) : ''
const bandwidthSummary = bandwidths.length
? `${Math.round(Math.min(...bandwidths) / 1000)}-${Math.round(Math.max(...bandwidths) / 1000)} kbps`
: ''
const details = []
if (targetDuration) details.push(`目标分片时长 ${targetDuration}s`)
if (resolutions.length) details.push(`分辨率 ${resolutions.slice(0, 3).join(', ')}`)
if (bandwidthSummary) details.push(`码率 ${bandwidthSummary}`)
if (durationLabel) details.push(`总时长约 ${durationLabel}`)
if (encryptionMethod) details.push(`加密方式 ${encryptionMethod}`)
if (firstVariantUrl) details.push(`示例变体 ${firstVariantUrl}`)
if (firstSegmentUrl) details.push(`首个分片 ${firstSegmentUrl}`)
return {
kind: 'hls',
manifestType,
variantCount,
segmentCount,
encrypted,
isLive,
playlistType: playlistType || (isLive ? 'LIVE' : 'VOD'),
targetDuration,
totalDurationSeconds: Math.round(totalDurationSeconds),
durationLabel,
encryptionMethod,
variants,
mediaTracks,
firstVariantUrl,
firstSegmentUrl,
details,
summary: [
manifestType === 'master' ? 'HLS 主索引' : 'HLS 媒体列表',
manifestType === 'master' ? `${variantCount} 个变体` : `${segmentCount} 个分片`,
encrypted ? '已加密' : '未加密',
manifestType === 'media' ? (isLive ? '直播' : '点播') : '',
]
.filter(Boolean)
.join(' | '),
}
}
function parseXmlAttributes(fragment) {
const attrs = {}
const re = /([A-Za-z_:][\w:.-]*)="([^"]*)"/g
let match = re.exec(String(fragment || ''))
while (match) {
attrs[String(match[1] || '').toLowerCase()] = match[2] || ''
match = re.exec(String(fragment || ''))
}
return attrs
}
function parseDashManifest(text, manifestUrl) {
const source = String(text || '').replace(/^\uFEFF/, '')
const mpdMatch = source.match(/<MPD\b([^>]*)>/i)
if (!mpdMatch) throw new Error('无效的 DASH 索引文件')
const mpdAttrs = parseXmlAttributes(mpdMatch[1] || '')
const type = mpdAttrs.type || 'static'
const durationRaw = mpdAttrs.mediapresentationduration || ''
const segmentTemplateCount = (source.match(/<SegmentTemplate\b/gi) || []).length
const segmentTimelineEntryCount = (source.match(/<S\b/gi) || []).length
const encrypted = /<ContentProtection\b/i.test(source)
const baseUrls = Array.from(source.matchAll(/<BaseURL>([^<]+)<\/BaseURL>/gi)).map((match) => {
return Shared.toAbsoluteUrl(match[1]?.trim() || '', manifestUrl)
})
const firstBaseUrl = baseUrls[0] || ''
const durationSeconds = parseIsoDurationToSeconds(durationRaw)
const isLive = type.toLowerCase() === 'dynamic'
const durationLabel = durationSeconds ? formatSeconds(durationSeconds) : ''
const adaptationSets = Array.from(source.matchAll(/<AdaptationSet\b([^>]*)>([\s\S]*?)<\/AdaptationSet>/gi)).map(
(match, index) => {
const attrs = parseXmlAttributes(match[1] || '')
const body = match[2] || ''
const mimeType = attrs.mimetype || ''
const rawType = String(attrs.contenttype || '').toLowerCase()
const inferredType = rawType || (
/^video\//i.test(mimeType) ? 'video' :
/^audio\//i.test(mimeType) ? 'audio' :
/(text|subtitle|ttml|vtt)/i.test(mimeType) ? 'subtitle' :
'unknown'
)
const representations = Array.from(body.matchAll(/<Representation\b([^>]*)/gi)).map((repMatch, repIndex) => {
const repAttrs = parseXmlAttributes(repMatch[1] || '')
return {
id: repAttrs.id || `rep-${index + 1}-${repIndex + 1}`,
bandwidth: parseInt(repAttrs.bandwidth || '0', 10) || 0,
codecs: repAttrs.codecs || '',
width: parseInt(repAttrs.width || '0', 10) || 0,
height: parseInt(repAttrs.height || '0', 10) || 0,
mimeType: repAttrs.mimetype || mimeType,
}
})
return {
id: attrs.id || `as-${index + 1}`,
type: inferredType,
mimeType,
language: attrs.lang || attrs.language || '',
segmentAlignment: attrs.segmentalignment || '',
representations,
}
}
)
const adaptationSetCount = adaptationSets.length
const representationCount = adaptationSets.reduce((sum, item) => sum + item.representations.length, 0)
const details = []
if (adaptationSetCount) details.push(`${adaptationSetCount} 个 AdaptationSet`)
if (segmentTemplateCount) details.push(`${segmentTemplateCount} 个 SegmentTemplate 节点`)
if (segmentTimelineEntryCount) details.push(`${segmentTimelineEntryCount} 条时间线条目`)
if (durationLabel) details.push(`时长 ${durationLabel}`)
if (firstBaseUrl) details.push(`基础地址 ${Shared.toAbsoluteUrl(firstBaseUrl, manifestUrl)}`)
return {
kind: 'dash',
manifestType: 'mpd',
representationCount,
adaptationSetCount,
segmentTemplateCount,
segmentTimelineEntryCount,
encrypted,
isLive,
durationSeconds,
durationLabel,
baseUrls,
adaptationSets,
details,
summary: [
'DASH 索引',
representationCount ? `${representationCount} 个表示层` : '',
encrypted ? '已加密' : '未加密',
isLive ? '直播' : '点播',
]
.filter(Boolean)
.join(' | '),
}
}
function escapePowerShellArgument(value) {
return String(value || '')
.replace(/`/g, '``')
.replace(/"/g, '`"')
}
function buildStreamOutputFilename(record) {
return Shared.replaceFileExtension(record.filename || Shared.extractFilename(record.url), 'mp4')
}
function buildReplayHeaders(record) {
const headers = []
if (record.referer) headers.push({ name: 'Referer', value: record.referer })
const origin = Shared.getOrigin(record.referer || record.url, record.url)
if (origin) headers.push({ name: 'Origin', value: origin })
return headers
}
function buildFfmpegCommand(record) {
const parts = ['ffmpeg']
parts.push(`-user_agent "${escapePowerShellArgument(DEFAULT_USER_AGENT)}"`)
if (record.referer) {
parts.push(`-referer "${escapePowerShellArgument(record.referer)}"`)
}
const headerLines = buildReplayHeaders(record)
.filter((header) => header.name !== 'Referer')
.map((header) => `${header.name}: ${header.value}`)
if (headerLines.length) {
parts.push(`-headers "${escapePowerShellArgument(headerLines.join('`r`n'))}"`)
}
parts.push(`-i "${escapePowerShellArgument(record.url)}"`)
parts.push('-c copy')
parts.push(`"${escapePowerShellArgument(buildStreamOutputFilename(record))}"`)
return parts.join(' ')
}
function buildYtDlpCommand(record) {
const parts = ['yt-dlp']
parts.push(`--user-agent "${escapePowerShellArgument(DEFAULT_USER_AGENT)}"`)
if (record.referer) {
parts.push(`--referer "${escapePowerShellArgument(record.referer)}"`)
}
for (const header of buildReplayHeaders(record)) {
if (header.name === 'Referer') continue
parts.push(`--add-header "${escapePowerShellArgument(`${header.name}: ${header.value}`)}"`)
}
parts.push(`-o "${escapePowerShellArgument(buildStreamOutputFilename(record))}"`)
parts.push(`"${escapePowerShellArgument(record.url)}"`)
return parts.join(' ')
}
function buildCurlCommand(record) {
const parts = ['curl.exe', '-L']
parts.push(`-A "${escapePowerShellArgument(DEFAULT_USER_AGENT)}"`)
if (record.referer) {
parts.push(`-e "${escapePowerShellArgument(record.referer)}"`)
}
for (const header of buildReplayHeaders(record)) {
if (header.name === 'Referer') continue
parts.push(`-H "${escapePowerShellArgument(`${header.name}: ${header.value}`)}"`)
}
parts.push(`-o "${escapePowerShellArgument(record.filename || Shared.extractFilename(record.url))}"`)
parts.push(`"${escapePowerShellArgument(record.url)}"`)
return parts.join(' ')
}
function buildExportTaskPayload(record, context) {
return {
version: 1,
exportedAt: new Date().toISOString(),
resource: {
id: record.id || '',
key: record.key || Shared.buildMediaKey(record.url, record.referer || '', record.frameId),
status: record.status || 'discovered',
category: record.category || Shared.normalizeCategory(record),
filename: record.filename || Shared.extractFilename(record.url),
url: record.url,
finalUrl: context?.resolvedUrl || record.finalUrl || record.url,
contentType: record.contentType || '',
sizeBytes: Shared.parseContentLength(record.sizeBytes),
size: record.size || '',
referer: record.referer || '',
refererOrigin: record.refererOrigin || Shared.getOrigin(record.referer || '', record.url || ''),
frameId: Number.isInteger(record.frameId) ? record.frameId : null,
method: record.method || '',
initiator: record.initiator || '',
fromCache: !!record.fromCache,
sourceList: record.sourceList || [],
requestHeaders: record.requestHeaders || {},
responseHeaders: record.responseHeaders || {},
cookieState: record.hasCookieHeader ? 'present-redacted' : 'not-observed',
authorizationState: record.hasAuthorizationHeader ? 'present-redacted' : 'not-observed',
},
stream: context
? {
kind: context.kind,
summary: context.summary,
resolvedUrl: context.resolvedUrl || record.url,
analyzedAt: context.analyzedAt || null,
analysis: context.analysis || null,
commands: {
ffmpeg: buildFfmpegCommand(record),
ytDlp: buildYtDlpCommand(record),
curl: buildCurlCommand(record),
},
}
: null,
}
}
function attachStreamExports(baseContext, record) {
const exports = {
commands: {
ffmpeg: buildFfmpegCommand(record),
ytDlp: buildYtDlpCommand(record),
curl: buildCurlCommand(record),
},
task: buildExportTaskPayload(record, baseContext),
}
return {
...baseContext,
exports,
command: exports.commands.ffmpeg,
}
}
function getStreamCacheKey(record) {
return record.key || Shared.buildMediaKey(record.url, record.referer || '', record.frameId)
}
function cleanupStreamContextCache() {
const now = Date.now()
for (const [key, entry] of streamContextCache.entries()) {
if (!entry || now - entry.updatedAt > STREAM_CACHE_TTL_MS) {
streamContextCache.delete(key)
}
}
while (streamContextCache.size > STREAM_CACHE_LIMIT) {
const firstKey = streamContextCache.keys().next().value
streamContextCache.delete(firstKey)
}
}
async function fetchTextInBackground(url) {
const credentialsModes = ['omit', 'include', 'same-origin']
let lastError = new Error('后台文本抓取失败')
for (const credentials of credentialsModes) {
try {
const response = await fetch(url, { credentials, cache: 'no-store' })
if (!response.ok) throw new Error(`HTTP ${response.status}`)
return { ok: true, text: await response.text(), finalUrl: response.url || url }
} catch (err) {
lastError = err
}
}
throw lastError
}
async function fetchStreamText(record, tabId) {
try {
return await fetchTextInBackground(record.url)
} catch (bgErr) {
const tabResp = await fetchTextFromTab(tabId, record.frameId, record.url)
if (!tabResp?.ok || typeof tabResp.text !== 'string') {
throw new Error(tabResp?.error || bgErr.message)
}
return { ok: true, text: tabResp.text, finalUrl: tabResp.finalUrl || record.url }
}
}
async function getStreamContext(record, tabId, forceRefresh) {
if (!Shared.isStreamManifest(record.url, record.contentType || '')) {
throw new Error('当前选择的资源不是流媒体索引文件')
}
cleanupStreamContextCache()
const cacheKey = getStreamCacheKey(record)
if (!forceRefresh) {
const cached = streamContextCache.get(cacheKey)
if (cached && Date.now() - cached.updatedAt <= STREAM_CACHE_TTL_MS) {
return attachStreamExports(cached.context, {
...record,
finalUrl: cached.context.resolvedUrl || record.finalUrl || record.url,
})
}
}
const fetched = await fetchStreamText(record, tabId)
const manifestUrl = fetched.finalUrl || record.url
const analysis = /\.mpd(\?|$)/i.test(record.url) || /dash\+xml/i.test(record.contentType || '')
? parseDashManifest(fetched.text, manifestUrl)
: parseHlsManifest(fetched.text, manifestUrl)
const context = {
kind: analysis.kind,
summary: analysis.summary,
details: analysis.details || [],
analysis,
resolvedUrl: manifestUrl,
analyzedAt: Date.now(),
}
streamContextCache.set(cacheKey, {
updatedAt: Date.now(),
context,
})
cleanupStreamContextCache()
return attachStreamExports(context, {
...record,
finalUrl: manifestUrl,
})
}
async function handleDownloadRequest(msg, sender, sendResponse) {
const tabId = msg.tabId || sender.tab?.id || (await getActiveTabId())
if (!tabId) {
sendResponse({ ok: false, error: '未找到目标标签页' })
return
}
const record = decorateMediaRecord({
key: msg.key,
url: msg.url,
filename: msg.filename || Shared.extractFilename(msg.url),
category: msg.category,
categoryHint: msg.categoryHint,
contentType: msg.contentType || '',
sizeBytes: Shared.parseContentLength(msg.sizeBytes),
frameId: Number.isInteger(msg.frameId) ? msg.frameId : sender.frameId,
referer: msg.referer || '',
requestHeaders: msg.requestHeaders || {},
responseHeaders: msg.responseHeaders || {},
time: Date.now(),
})
const filename = Shared.buildDownloadPath(record.filename, record.category)
const mode = record.downloadMode
const warning = record.downloadNotice
if (mode === 'manifest' || mode === 'segment' || mode === 'direct') {
const directResp = await downloadFile({ url: record.url, filename })
patchMediaRecord(tabId, record.key, {
status: directResp.ok ? 'downloaded' : 'failed',
lastError: directResp.ok ? '' : directResp.error || '',
})
sendResponse({ ...directResp, warning })
return
}
try {
const dataUrl = await resolveMediaDataUrl(record, tabId)
const result = await downloadFile({ url: dataUrl, filename })
patchMediaRecord(tabId, record.key, {
status: result.ok ? 'downloaded' : 'failed',
lastError: result.ok ? '' : result.error || '',
})
sendResponse({ ...result, warning })
} catch (err) {
const fallbackResp = await downloadFile({ url: record.url, filename })
if (fallbackResp.ok) {
patchMediaRecord(tabId, record.key, {
status: 'downloaded',
lastError: '',
})
sendResponse({ ...fallbackResp, warning })
return
}
patchMediaRecord(tabId, record.key, {
status: 'failed',
lastError: `${err.message}; ${fallbackResp.error || ''}`.trim(),
})
sendResponse({
ok: false,
error: `所有下载方式都失败了:${err.message}; ${fallbackResp.error || ''}`,
warning,
})
}
}
chrome.webRequest.onBeforeSendHeaders.addListener(
(details) => {
if (details.tabId < 0) return
const requestHeaders = normalizeHeaderMap(details.requestHeaders || [])
storeRequestContext(details.requestId, {