-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.html
639 lines (584 loc) · 24.6 KB
/
index.html
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
<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>M3U8 下載工具</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue-virtual-scroller.css">
<script>
// 自動注入跨域代碼
fetch = new Proxy(fetch, {
apply(target, that, args) {
const [url, options = {}] = args;
options.credentials = 'include';
options.mode = 'cors';
return target.apply(that, [url, options]);
}
});
// 注入 XMLHttpRequest 跨域支持
XMLHttpRequest.prototype.setRequestHeader = new Proxy(XMLHttpRequest.prototype.setRequestHeader, {
apply(target, that, args) {
const [header, value] = args;
if (header === 'Origin') return;
return target.apply(that, args);
}
});
// 修改 open 方法
XMLHttpRequest.prototype.open = new Proxy(XMLHttpRequest.prototype.open, {
apply(target, that, args) {
const [method, url, async = true, user, password] = args;
that.withCredentials = true;
return target.apply(that, [method, url, async, user, password]);
}
});
</script>
<style>
[v-cloak] {
display: none;
}
body {
margin: 0;
padding: 20px;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}
.container {
max-width: 1200px;
margin: 0 auto;
}
.header {
text-align: center;
margin-bottom: 30px;
}
.input-group {
display: flex;
gap: 10px;
margin-bottom: 20px;
}
.input-group input {
flex: 1;
padding: 10px;
font-size: 16px;
border: 1px solid #ddd;
border-radius: 4px;
}
.range-input {
display: flex;
gap: 10px;
margin-bottom: 20px;
align-items: center;
}
.range-input input {
width: 100px;
padding: 10px;
font-size: 16px;
border: 1px solid #ddd;
border-radius: 4px;
}
.btn {
padding: 10px 20px;
font-size: 16px;
color: white;
background-color: #3D8AC7;
border: none;
border-radius: 4px;
cursor: pointer;
}
.btn:hover {
opacity: 0.9;
}
.btn:disabled {
background-color: #ccc;
cursor: not-allowed;
}
.progress-container {
margin-top: 20px;
}
.progress-info {
margin-bottom: 10px;
color: #666;
}
.segments {
display: flex;
flex-wrap: wrap;
gap: 5px;
margin-top: 10px;
}
.segment {
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
background-color: #eee;
border-radius: 4px;
color: #666;
}
.segment.finished {
background-color: #4CAF50;
color: white;
}
.segment.error {
background-color: #f44336;
color: white;
cursor: pointer;
}
.virtual-scroller {
height: 300px;
border: 1px solid #eee;
border-radius: 4px;
margin-top: 20px;
}
.download-item {
padding: 10px;
border-bottom: 1px solid #eee;
}
.progress-bar {
height: 20px;
background-color: #f5f5f5;
border-radius: 4px;
overflow: hidden;
margin-top: 5px;
}
.progress-bar-inner {
height: 100%;
background-color: #3D8AC7;
transition: width 0.3s ease;
color: white;
text-align: center;
line-height: 20px;
font-size: 12px;
}
.cross-domain {
margin: 20px 0;
padding: 20px;
background-color: #f8f9fa;
border-radius: 4px;
}
</style>
</head>
<body>
<div id="app" v-cloak>
<div class="container">
<div class="header">
<h1>{{ tips }}</h1>
</div>
<div class="input-group">
<input type="text" v-model="url" :disabled="downloading" placeholder="請輸入 M3U8 網址">
<button class="btn" @click="getM3U8" :disabled="downloading || !url">下載原格式</button>
<button class="btn" @click="getMP4" :disabled="downloading || !url">下載 MP4</button>
<button class="btn" v-if="downloading" @click="togglePause">
{{ isPause ? '繼續' : '暫停' }}
</button>
</div>
<div class="cross-domain">
<button class="btn" @click="copyCode">複製跨域代碼</button>
<p style="margin-top: 10px; color: #666;">
如果遇到跨域問題,請將此代碼複製並貼到視頻頁面的瀏覽器控制台中執行。
</p>
</div>
<div class="range-input" v-if="!downloading">
<span>下載範圍:</span>
<input type="number" v-model.number="startSegment" placeholder="起始片段" min="1">
<span>至</span>
<input type="number" v-model.number="endSegment" placeholder="結束片段" min="1">
<span>(可選)</span>
</div>
<div class="progress-container" v-if="finishList.length > 0">
<div class="progress-info">
<div>總片段:{{ tsUrlList.length }}</div>
<div>已完成:{{ finishNum }}</div>
<div>錯誤:{{ errorNum }}</div>
<div>進度:{{ (finishNum / tsUrlList.length * 100).toFixed(2) }}%</div>
</div>
<div class="segments">
<div v-for="(item, index) in finishList"
:key="index"
class="segment"
:class="{
finished: item.status === 'finish',
error: item.status === 'error'
}"
@click="retry(index)">
{{ index + 1 }}
</div>
</div>
<div class="virtual-scroller" v-if="downloadList.length > 0">
<RecycleScroller
class="scroller"
:items="downloadList"
:item-size="50"
key-field="id">
<template v-slot="{ item }">
<div class="download-item">
<div>{{ item.title }}</div>
<div class="progress-bar">
<div class="progress-bar-inner"
:style="{ width: item.progress + '%' }">
{{ item.progress }}%
</div>
</div>
</div>
</template>
</RecycleScroller>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue-virtual-scroller.min.js"></script>
<script src="./aes-decryptor.js"></script>
<script src="./mux-mp4.js"></script>
<script>
Vue.use(window.VueVirtualScroller);
new Vue({
el: '#app',
data() {
return {
url: '',
tips: 'M3U8 下載工具',
isPause: false,
isGetMP4: false,
durationSecond: 0,
downloading: false,
beginTime: '',
errorNum: 0,
finishNum: 0,
downloadIndex: 0,
finishList: [],
tsUrlList: [],
mediaFileList: [],
downloadList: [],
startSegment: null,
endSegment: null,
aesConf: {
method: '',
uri: '',
iv: '',
key: '',
decryptor: null,
stringToBuffer: function(str) {
return new TextEncoder().encode(str)
},
},
chunkSize: 1024 * 1024 * 2,
maxConcurrentDownloads: 3,
downloadQueue: [],
activeDownloads: 0,
mediaCache: new Map(),
cleanupInterval: null
}
},
created() {
this.getSource();
window.addEventListener('keyup', this.onKeyup);
this.cleanupInterval = setInterval(this.cleanupResources, 30000);
},
beforeDestroy() {
window.removeEventListener('keyup', this.onKeyup);
clearInterval(this.cleanupInterval);
this.cleanupResources();
},
methods: {
getSource() {
const urlParams = new URLSearchParams(window.location.search);
const source = urlParams.get('source');
if (source) {
this.url = source;
}
},
onKeyup(event) {
if (event.key === 'Enter') {
this.getM3U8();
}
},
getMP4() {
this.isGetMP4 = true;
this.getM3U8();
},
getM3U8() {
if (!this.url) {
alert('請輸入 M3U8 網址');
return;
}
if (this.url.toLowerCase().indexOf('.m3u8') === -1) {
alert('網址格式錯誤,請確認是否為 M3U8 網址');
return;
}
if (this.downloading) {
alert('下載中,請等待目前的下載完成');
return;
}
this.resetState();
this.downloading = true;
this.tips = 'M3U8 檔案下載中...';
this.beginTime = new Date();
fetch(this.url)
.then(response => response.text())
.then(this.processM3U8)
.catch(error => {
console.error('下載失敗:', error);
this.alertError('下載失敗,請確認網址是否正確');
});
},
processM3U8(m3u8Content) {
const lines = m3u8Content.split('\n');
for (const line of lines) {
if (line.toLowerCase().indexOf('.ts') > -1) {
const tsUrl = this.applyURL(line, this.url);
this.tsUrlList.push(tsUrl);
this.finishList.push({
title: line,
status: ''
});
} else if (this.isGetMP4 && line.toUpperCase().indexOf('#EXTINF:') > -1) {
this.durationSecond += parseFloat(line.split('#EXTINF:')[1]);
}
}
// 處理下載範圍
if (this.startSegment && this.endSegment) {
const start = Math.max(0, this.startSegment - 1);
const end = Math.min(this.tsUrlList.length, this.endSegment);
this.tsUrlList = this.tsUrlList.slice(start, end);
this.finishList = this.finishList.slice(start, end);
}
if (m3u8Content.indexOf('#EXT-X-KEY') > -1) {
this.processAESConfig(m3u8Content);
} else if (this.tsUrlList.length > 0) {
this.startDownload();
} else {
this.alertError('沒有找到可下載的影片片段');
}
},
processAESConfig(m3u8Content) {
this.aesConf.method = (m3u8Content.match(/(.*METHOD=([^,\s]+))/) || ['', '', ''])[2];
this.aesConf.uri = (m3u8Content.match(/(.*URI="([^"]+))"/) || ['', '', ''])[2];
this.aesConf.iv = (m3u8Content.match(/(.*IV=([^,\s]+))/) || ['', '', ''])[2];
this.aesConf.iv = this.aesConf.iv ? this.aesConf.stringToBuffer(this.aesConf.iv) : '';
this.aesConf.uri = this.applyURL(this.aesConf.uri, this.url);
fetch(this.aesConf.uri)
.then(response => response.arrayBuffer())
.then(key => {
this.aesConf.key = key;
this.aesConf.decryptor = new AESDecryptor();
this.aesConf.decryptor.constructor();
this.aesConf.decryptor.expandKey(this.aesConf.key);
this.startDownload();
})
.catch(error => {
console.error('AES 金鑰下載失敗:', error);
this.alertError('AES 金鑰下載失敗');
});
},
startDownload() {
this.downloadQueue = [...Array(this.tsUrlList.length).keys()];
this.processDownloadQueue();
},
async processDownloadQueue() {
const processChunk = async () => {
if (this.downloadQueue.length === 0 || this.isPause) return;
while (this.downloadQueue.length > 0 &&
this.activeDownloads < this.maxConcurrentDownloads &&
!this.isPause) {
const index = this.downloadQueue.shift();
this.activeDownloads++;
try {
await this.downloadTsChunk(index);
} catch (error) {
console.error('下載錯誤:', error);
this.errorNum++;
this.finishList[index].status = 'error';
} finally {
this.activeDownloads--;
}
}
if (this.downloadQueue.length > 0 && !this.isPause) {
setTimeout(processChunk, 100);
}
};
await processChunk();
},
async downloadTsChunk(index) {
if (!this.finishList[index] || this.finishList[index].status !== '') {
return;
}
const response = await fetch(this.tsUrlList[index]);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const arrayBuffer = await response.arrayBuffer();
await this.processTsChunk(arrayBuffer, index);
},
async processTsChunk(arrayBuffer, index) {
try {
const data = this.aesConf.uri ?
this.aesConf.decryptor.decrypt(
arrayBuffer,
0,
this.aesConf.iv || new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, index]),
true
) : arrayBuffer;
let processedData;
if (this.isGetMP4) {
processedData = await this.convertToMP4(data, index);
} else {
processedData = data;
}
this.mediaCache.set(index, {
data: processedData,
status: 'finish'
});
this.finishList[index].status = 'finish';
this.finishNum++;
this.updateProgress(index, 100);
if (this.finishNum === this.tsUrlList.length) {
await this.mergeAndDownload();
}
} catch (error) {
console.error('處理 TS 片段時發生錯誤:', error);
throw error;
}
},
async convertToMP4(data, index) {
return new Promise((resolve) => {
const transmuxer = new muxjs.Transmuxer({
keepOriginalTimestamps: true,
duration: parseInt(this.durationSecond),
});
transmuxer.on('data', segment => {
if (index === 0) {
const data = new Uint8Array(segment.initSegment.byteLength + segment.data.byteLength);
data.set(segment.initSegment, 0);
data.set(segment.data, segment.initSegment.byteLength);
resolve(data.buffer);
} else {
resolve(segment.data);
}
});
transmuxer.push(new Uint8Array(data));
transmuxer.flush();
});
},
updateProgress(index, percent) {
if (!this.downloadList[index]) {
this.$set(this.downloadList, index, {
id: index,
title: `片段 ${index + 1}`,
progress: 0
});
}
this.$set(this.downloadList[index], 'progress', percent.toFixed(2));
},
async mergeAndDownload() {
this.tips = '正在合併檔案...';
const sortedData = Array.from(this.mediaCache.entries())
.sort(([a], [b]) => a - b)
.map(([_, value]) => value.data);
try {
const blob = new Blob(sortedData, {
type: this.isGetMP4 ? 'video/mp4' : 'video/MP2T'
});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `video_${this.formatTime(this.beginTime)}${this.isGetMP4 ? '.mp4' : '.ts'}`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
this.mediaCache.clear();
this.downloading = false;
this.tips = 'M3U8 下載工具';
} catch (error) {
console.error('合併檔案時發生錯誤:', error);
this.alertError('合併檔案時發生錯誤');
}
},
formatTime(date) {
return date.toISOString().slice(0, 19).replace(/[-:]/g, '');
},
applyURL(targetURL, baseURL) {
try {
return new URL(targetURL, baseURL).href;
} catch {
return targetURL;
}
},
togglePause() {
this.isPause = !this.isPause;
if (!this.isPause) {
this.processDownloadQueue();
}
},
retry(index) {
if (this.finishList[index].status === 'error') {
this.finishList[index].status = '';
this.downloadQueue.push(index);
this.errorNum--;
this.processDownloadQueue();
}
},
resetState() {
this.tsUrlList = [];
this.finishList = [];
this.downloadList = [];
this.mediaFileList = [];
this.mediaCache.clear();
this.errorNum = 0;
this.finishNum = 0;
this.downloadIndex = 0;
this.durationSecond = 0;
this.downloadQueue = [];
this.activeDownloads = 0;
},
cleanupResources() {
for (let [key, value] of this.mediaCache) {
if (value.status === 'finish') {
this.mediaCache.delete(key);
}
}
},
alertError(message) {
alert(message);
this.downloading = false;
this.tips = 'M3U8 下載工具';
},
copyCode() {
const code = `
// 修改 fetch
fetch = new Proxy(fetch, {
apply(target, that, args) {
const [url, options = {}] = args;
options.credentials = 'include';
options.mode = 'cors';
return target.apply(that, [url, options]);
}
});
// 修改 XMLHttpRequest
XMLHttpRequest.prototype.setRequestHeader = new Proxy(XMLHttpRequest.prototype.setRequestHeader, {
apply(target, that, args) {
const [header, value] = args;
if (header === 'Origin') return;
return target.apply(that, args);
}
});
XMLHttpRequest.prototype.open = new Proxy(XMLHttpRequest.prototype.open, {
apply(target, that, args) {
const [method, url, async = true, user, password] = args;
that.withCredentials = true;
return target.apply(that, [method, url, async, user, password]);
}
});
`;
const textarea = document.createElement('textarea');
textarea.value = code;
document.body.appendChild(textarea);
textarea.select();
document.execCommand('copy');
document.body.removeChild(textarea);
alert('跨域代碼已複製!請將其貼到視頻頁面的瀏覽器控制台中執行。');
}
}
});
</script>
</body>
</html>