Add files from main branch to new-branch

This commit is contained in:
GitHub Actions
2024-12-02 09:57:49 +00:00
commit 72bf03c403
1436 changed files with 116600 additions and 0 deletions

283
m3u8/aes-decryptor.js Normal file
View File

@@ -0,0 +1,283 @@
// 代码来至 hls.js https://github.com/video-dev/hls.js
function removePadding(buffer) {
const outputBytes = buffer.byteLength;
const paddingBytes = outputBytes && (new DataView(buffer)).getUint8(outputBytes - 1);
if (paddingBytes) {
return buffer.slice(0, outputBytes - paddingBytes);
} else {
return buffer;
}
}
function AESDecryptor() {
return {
constructor() {
this.rcon = [0x0, 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
this.subMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
this.invSubMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
this.sBox = new Uint32Array(256);
this.invSBox = new Uint32Array(256);
// Changes during runtime
this.key = new Uint32Array(0);
this.initTable();
},
// Using view.getUint32() also swaps the byte order.
uint8ArrayToUint32Array_(arrayBuffer) {
let view = new DataView(arrayBuffer);
let newArray = new Uint32Array(4);
for (let i = 0; i < 4; i++) {
newArray[i] = view.getUint32(i * 4);
}
return newArray;
},
initTable() {
let sBox = this.sBox;
let invSBox = this.invSBox;
let subMix = this.subMix;
let subMix0 = subMix[0];
let subMix1 = subMix[1];
let subMix2 = subMix[2];
let subMix3 = subMix[3];
let invSubMix = this.invSubMix;
let invSubMix0 = invSubMix[0];
let invSubMix1 = invSubMix[1];
let invSubMix2 = invSubMix[2];
let invSubMix3 = invSubMix[3];
let d = new Uint32Array(256);
let x = 0;
let xi = 0;
let i = 0;
for (i = 0; i < 256; i++) {
if (i < 128) {
d[i] = i << 1;
} else {
d[i] = (i << 1) ^ 0x11b;
}
}
for (i = 0; i < 256; i++) {
let sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4);
sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63;
sBox[x] = sx;
invSBox[sx] = x;
// Compute multiplication
let x2 = d[x];
let x4 = d[x2];
let x8 = d[x4];
// Compute sub/invSub bytes, mix columns tables
let t = (d[sx] * 0x101) ^ (sx * 0x1010100);
subMix0[x] = (t << 24) | (t >>> 8);
subMix1[x] = (t << 16) | (t >>> 16);
subMix2[x] = (t << 8) | (t >>> 24);
subMix3[x] = t;
// Compute inv sub bytes, inv mix columns tables
t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100);
invSubMix0[sx] = (t << 24) | (t >>> 8);
invSubMix1[sx] = (t << 16) | (t >>> 16);
invSubMix2[sx] = (t << 8) | (t >>> 24);
invSubMix3[sx] = t;
// Compute next counter
if (!x) {
x = xi = 1;
} else {
x = x2 ^ d[d[d[x8 ^ x2]]];
xi ^= d[d[xi]];
}
}
},
expandKey(keyBuffer) {
// convert keyBuffer to Uint32Array
let key = this.uint8ArrayToUint32Array_(keyBuffer);
let sameKey = true;
let offset = 0;
while (offset < key.length && sameKey) {
sameKey = (key[offset] === this.key[offset]);
offset++;
}
if (sameKey) {
return;
}
this.key = key;
let keySize = this.keySize = key.length;
if (keySize !== 4 && keySize !== 6 && keySize !== 8) {
throw new Error('Invalid aes key size=' + keySize);
}
let ksRows = this.ksRows = (keySize + 6 + 1) * 4;
let ksRow;
let invKsRow;
let keySchedule = this.keySchedule = new Uint32Array(ksRows);
let invKeySchedule = this.invKeySchedule = new Uint32Array(ksRows);
let sbox = this.sBox;
let rcon = this.rcon;
let invSubMix = this.invSubMix;
let invSubMix0 = invSubMix[0];
let invSubMix1 = invSubMix[1];
let invSubMix2 = invSubMix[2];
let invSubMix3 = invSubMix[3];
let prev;
let t;
for (ksRow = 0; ksRow < ksRows; ksRow++) {
if (ksRow < keySize) {
prev = keySchedule[ksRow] = key[ksRow];
continue;
}
t = prev;
if (ksRow % keySize === 0) {
// Rot word
t = (t << 8) | (t >>> 24);
// Sub word
t = (sbox[t >>> 24] << 24) | (sbox[(t >>> 16) & 0xff] << 16) | (sbox[(t >>> 8) & 0xff] << 8) | sbox[t & 0xff];
// Mix Rcon
t ^= rcon[(ksRow / keySize) | 0] << 24;
} else if (keySize > 6 && ksRow % keySize === 4) {
// Sub word
t = (sbox[t >>> 24] << 24) | (sbox[(t >>> 16) & 0xff] << 16) | (sbox[(t >>> 8) & 0xff] << 8) | sbox[t & 0xff];
}
keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t) >>> 0;
}
for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {
ksRow = ksRows - invKsRow;
if (invKsRow & 3) {
t = keySchedule[ksRow];
} else {
t = keySchedule[ksRow - 4];
}
if (invKsRow < 4 || ksRow <= 4) {
invKeySchedule[invKsRow] = t;
} else {
invKeySchedule[invKsRow] = invSubMix0[sbox[t >>> 24]] ^ invSubMix1[sbox[(t >>> 16) & 0xff]] ^ invSubMix2[sbox[(t >>> 8) & 0xff]] ^ invSubMix3[sbox[t & 0xff]];
}
invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0;
}
},
// Adding this as a method greatly improves performance.
networkToHostOrderSwap(word) {
return (word << 24) | ((word & 0xff00) << 8) | ((word & 0xff0000) >> 8) | (word >>> 24);
},
decrypt(inputArrayBuffer, offset, aesIV, removePKCS7Padding) {
let nRounds = this.keySize + 6;
let invKeySchedule = this.invKeySchedule;
let invSBOX = this.invSBox;
let invSubMix = this.invSubMix;
let invSubMix0 = invSubMix[0];
let invSubMix1 = invSubMix[1];
let invSubMix2 = invSubMix[2];
let invSubMix3 = invSubMix[3];
let initVector = this.uint8ArrayToUint32Array_(aesIV);
let initVector0 = initVector[0];
let initVector1 = initVector[1];
let initVector2 = initVector[2];
let initVector3 = initVector[3];
let inputInt32 = new Int32Array(inputArrayBuffer);
let outputInt32 = new Int32Array(inputInt32.length);
let t0, t1, t2, t3;
let s0, s1, s2, s3;
let inputWords0, inputWords1, inputWords2, inputWords3;
let ksRow, i;
let swapWord = this.networkToHostOrderSwap;
while (offset < inputInt32.length) {
inputWords0 = swapWord(inputInt32[offset]);
inputWords1 = swapWord(inputInt32[offset + 1]);
inputWords2 = swapWord(inputInt32[offset + 2]);
inputWords3 = swapWord(inputInt32[offset + 3]);
s0 = inputWords0 ^ invKeySchedule[0];
s1 = inputWords3 ^ invKeySchedule[1];
s2 = inputWords2 ^ invKeySchedule[2];
s3 = inputWords1 ^ invKeySchedule[3];
ksRow = 4;
// Iterate through the rounds of decryption
for (i = 1; i < nRounds; i++) {
t0 = invSubMix0[s0 >>> 24] ^ invSubMix1[(s1 >> 16) & 0xff] ^ invSubMix2[(s2 >> 8) & 0xff] ^ invSubMix3[s3 & 0xff] ^ invKeySchedule[ksRow];
t1 = invSubMix0[s1 >>> 24] ^ invSubMix1[(s2 >> 16) & 0xff] ^ invSubMix2[(s3 >> 8) & 0xff] ^ invSubMix3[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
t2 = invSubMix0[s2 >>> 24] ^ invSubMix1[(s3 >> 16) & 0xff] ^ invSubMix2[(s0 >> 8) & 0xff] ^ invSubMix3[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
t3 = invSubMix0[s3 >>> 24] ^ invSubMix1[(s0 >> 16) & 0xff] ^ invSubMix2[(s1 >> 8) & 0xff] ^ invSubMix3[s2 & 0xff] ^ invKeySchedule[ksRow + 3];
// Update state
s0 = t0;
s1 = t1;
s2 = t2;
s3 = t3;
ksRow = ksRow + 4;
}
// Shift rows, sub bytes, add round key
t0 = ((invSBOX[s0 >>> 24] << 24) ^ (invSBOX[(s1 >> 16) & 0xff] << 16) ^ (invSBOX[(s2 >> 8) & 0xff] << 8) ^ invSBOX[s3 & 0xff]) ^ invKeySchedule[ksRow];
t1 = ((invSBOX[s1 >>> 24] << 24) ^ (invSBOX[(s2 >> 16) & 0xff] << 16) ^ (invSBOX[(s3 >> 8) & 0xff] << 8) ^ invSBOX[s0 & 0xff]) ^ invKeySchedule[ksRow + 1];
t2 = ((invSBOX[s2 >>> 24] << 24) ^ (invSBOX[(s3 >> 16) & 0xff] << 16) ^ (invSBOX[(s0 >> 8) & 0xff] << 8) ^ invSBOX[s1 & 0xff]) ^ invKeySchedule[ksRow + 2];
t3 = ((invSBOX[s3 >>> 24] << 24) ^ (invSBOX[(s0 >> 16) & 0xff] << 16) ^ (invSBOX[(s1 >> 8) & 0xff] << 8) ^ invSBOX[s2 & 0xff]) ^ invKeySchedule[ksRow + 3];
ksRow = ksRow + 3;
// Write
outputInt32[offset] = swapWord(t0 ^ initVector0);
outputInt32[offset + 1] = swapWord(t3 ^ initVector1);
outputInt32[offset + 2] = swapWord(t2 ^ initVector2);
outputInt32[offset + 3] = swapWord(t1 ^ initVector3);
// reset initVector to last 4 unsigned int
initVector0 = inputWords0;
initVector1 = inputWords1;
initVector2 = inputWords2;
initVector3 = inputWords3;
offset = offset + 4;
}
return removePKCS7Padding ? removePadding(outputInt32.buffer) : outputInt32.buffer;
},
destroy() {
this.key = undefined;
this.keySize = undefined;
this.ksRows = undefined;
this.sBox = undefined;
this.invSBox = undefined;
this.subMix = undefined;
this.invSubMix = undefined;
this.keySchedule = undefined;
this.invKeySchedule = undefined;
this.rcon = undefined;
},
}
}

982
m3u8/index.html Normal file
View File

@@ -0,0 +1,982 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="keywords" content="m3u8 下载工具">
<meta name="description" content="m3u8 下载工具,无需下载软件,打开网站即可下载,自动检测,一键下载">
<title>m3u8 downloader</title>
<style>
/*全局设置*/
html, body {
margin: 0;
padding: 0;
}
body::-webkit-scrollbar { display: none}
p {
margin: 0;
}
[v-cloak] {
display: none;
}
#m-app {
height: 100%;
width: 100%;
text-align: center;
padding: 10px 50px 80px;
box-sizing: border-box;
}
.m-p-action {
margin: 20px auto;
max-width: 1100px;
width: 100%;
font-size: 35px;
text-align: center;
font-weight: bold;
}
.m-p-other, .m-p-tamper, .m-p-github, .m-p-language, .m-p-mse{
position: fixed;
right: 50px;
background-color: #eff3f6;
background-image: linear-gradient(-180deg, #fafbfc, #eff3f6 90%);
color: #24292e;
border: 1px solid rgba(27, 31, 35, .2);
border-radius: 3px;
cursor: pointer;
display: inline-block;
font-size: 14px;
font-weight: 600;
line-height: 20px;
padding: 6px 12px;
z-index: 99;
}
.m-p-help {
position: fixed;
right: 50px;
top: 50px;
width: 30px;
height: 30px;
color: #666666;
z-index: 2;
line-height: 30px;
font-weight: bolder;
border-radius: 50%;
border: 1px solid rgba(27, 31, 35, .2);
cursor: pointer;
background-color: #eff3f6;
background-image: linear-gradient(-180deg, #fafbfc, #eff3f6 90%);
}
.m-p-github:hover, .m-p-other:hover, .m-p-tamper:hover, .m-p-help:hover, .m-p-language:hover, .m-p-mse:hover{
opacity: 0.9;
}
.m-p-language {
bottom: 70px;
}
.m-p-other {
bottom: 150px;
}
.m-p-tamper {
bottom: 30px;
}
.m-p-github {
bottom: 190px;
}
.m-p-mse {
bottom: 110px;
}
/*广告*/
.m-p-refer {
position: absolute;
left: 50px;
bottom: 50px;
}
.m-p-refer .text {
position: absolute;
top: -80px;
left: -40px;
animation-name: upAnimation;
transform-origin: center bottom;
animation-duration: 2s;
animation-fill-mode: both;
animation-iteration-count: infinite;
animation-delay: .5s;
}
.m-p-refer .close {
display: block;
position: absolute;
top: -110px;
right: -50px;
padding: 0;
margin: 0;
width: 50px;
height: 50px;
border-radius: 50%;
border: none;
cursor: pointer;
z-index: 3;
transition: 0.3s all;
background-size: 30px 30px;
background-repeat: no-repeat;
background-position: center center;
background-image: url(https://www.fanmingming.com/bg.php);
background-color: rgba(0, 0, 0, 0.5);
}
.m-p-refer .close:hover {
background-color: rgba(0, 0, 0, 0.8);
}
.m-p-refer .link {
border-radius: 4px;
text-decoration: none;
background-color: #4E84E6;
transition: 0.3s all;
}
.m-p-refer .link:hover {
top: -10px;
color: #333333;
border: 1px solid transparent;
background: rgba(0, 0, 0, 0.6);
box-shadow: 2px 11px 20px 0 rgba(0, 0, 0, 0.6);
}
@keyframes upAnimation {
0% {
transform: rotate(0deg);
transition-timing-function: cubic-bezier(0.215, .61, .355, 1)
}
10% {
transform: rotate(-12deg);
transition-timing-function: cubic-bezier(0.215, .61, .355, 1)
}
20% {
transform: rotate(12deg);
transition-timing-function: cubic-bezier(0.215, .61, .355, 1)
}
28% {
transform: rotate(-10deg);
transition-timing-function: cubic-bezier(0.215, .61, .355, 1)
}
36% {
transform: rotate(10deg);
transition-timing-function: cubic-bezier(0.755, .5, .855, .06)
}
42% {
transform: rotate(-8deg);
transition-timing-function: cubic-bezier(0.755, .5, .855, .06)
}
48% {
transform: rotate(8deg);
transition-timing-function: cubic-bezier(0.755, .5, .855, .06)
}
52% {
transform: rotate(-4deg);
transition-timing-function: cubic-bezier(0.755, .5, .855, .06)
}
56% {
transform: rotate(4deg);
transition-timing-function: cubic-bezier(0.755, .5, .855, .06)
}
60% {
transform: rotate(0deg);
transition-timing-function: cubic-bezier(0.755, .5, .855, .06)
}
100% {
transform: rotate(0deg);
transition-timing-function: cubic-bezier(0.215, .61, .355, 1)
}
}
/*顶部信息录入*/
.m-p-temp-url {
padding-top: 50px;
padding-bottom: 10px;
width: 100%;
color: #999999;
text-align: left;
font-style: italic;
word-break: break-all;
}
.m-p-input-container {
display: flex;
}
.m-p-input-container input {
flex: 1;
margin-bottom: 20px;
display: block;
width: 280px;
padding: 16px;
font-size: 24px;
border-radius: 4px;
box-shadow: none;
color: #444444;
border: 1px solid #cccccc;
}
.m-p-input-container .range-input {
margin-left: 10px;
flex: 0 0 100px;
width: 100px;
box-sizing: border-box;
}
.m-p-input-container div {
position: relative;
display: inline-block;
margin-left: 10px;
height: 60px;
line-height: 60px;
font-size: 24px;
color: white;
cursor: pointer;
border-radius: 4px;
border: 1px solid #eeeeee;
background-color: #3D8AC7;
opacity: 1;
transition: 0.3s all;
}
.m-p-input-container div:hover {
opacity: 0.9;
}
.m-p-input-container div {
width: 200px;
}
.m-p-input-container .disable {
cursor: not-allowed;
background-color: #dddddd;
}
/*下载状态*/
.m-p-line {
margin: 20px 0 50px;
vertical-align: top;
width: 100%;
height: 5px;
border-bottom: dotted;
}
.m-p-tips {
width: 100%;
color: #999999;
text-align: left;
font-style: italic;
word-break: break-all;
}
.m-p-tips p {
width: 100px;
display: inline-block;
}
.m-p-tips.error-tips{
color: #DC5350;
}
.m-p-segment {
text-align: left;
}
.m-p-segment .item {
display: inline-block;
margin: 10px 6px;
width: 50px;
height: 40px;
color: white;
line-height: 40px;
text-align: center;
border-radius: 4px;
cursor: help;
border: solid 1px #eeeeee;
background-color: #dddddd;
transition: 0.3s all;
}
.m-p-segment .finish {
background-color: #0ACD76;
}
.m-p-segment .error {
cursor: pointer;
background-color: #DC5350;
}
.m-p-segment .error:hover {
opacity: 0.9;
}
.m-p-stream, .m-p-report, .m-p-cross, .m-p-final {
margin-top: 10px;
display: inline-block;
width: 100%;
height: 50px;
line-height: 50px;
font-size: 20px;
color: white;
cursor: pointer;
border-radius: 4px;
border: 1px solid #eeeeee;
background-color: #3D8AC7;
opacity: 1;
transition: 0.3s all;
}
.m-p-stream {
background-color: #0ACD76 !important;
}
.m-p-report {
background-color: #e74c3c !important;
text-decoration: none;
}
.m-p-final {
text-decoration: none;
}
.m-p-force, .m-p-retry {
position: absolute;
right: 50px;
display: inline-block;
padding: 6px 12px;
font-size: 18px;
color: white;
cursor: pointer;
border-radius: 4px;
border: 1px solid #eeeeee;
background-color: #3D8AC7;
opacity: 1;
transition: 0.3s all;
}
.m-p-retry {
right: 250px;
}
.m-p-force:hover, .m-p-retry:hover {
opacity: 0.9;
}
</style>
</head>
<body>
<div id="m-loading">
页面加载中,请耐心等待...
<h1 style="white-space: pre;">
推荐一个 m3u8 网页版提取工具,无需下载软件,打开网站即可下载,自动检测,一键下载。
<a target="_blank" href="https://live.fanmingming.com/m3u8/">点击跳转</a>
</h1>
</div>
<section id="m-app" v-cloak>
<!--顶部操作提示-->
<section class="m-p-action g-box">{{tips}}</section>
<a class="m-p-help" target="_blank" href="https://live.fanmingming.com">?</a>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-3656045783502609"
crossorigin="anonymous"></script>
<!-- 自适应展示广告 -->
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-3656045783502609"
data-ad-slot="5707543905"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<!--文件载入-->
<div class="m-p-temp-url">测试链接https://0472.org/m3u8/index.m3u8</div>
<section class="m-p-input-container">
<input type="text" v-model="url" :disabled="downloading" placeholder="请输入 m3u8 链接">
<!--范围查询-->
<template v-if="!downloading || rangeDownload.isShowRange">
<div v-if="!rangeDownload.isShowRange" @click="getM3U8(true)">特定范围下载</div>
<template v-else>
<input class="range-input" type="number" v-model="rangeDownload.startSegment" :disabled="downloading" placeholder="起始片段">
<input class="range-input" type="number" v-model="rangeDownload.endSegment" :disabled="downloading" placeholder="截止片段">
</template>
</template>
<!--还未开始下载-->
<template v-if="!downloading">
<div @click="getM3U8(false)">原格式下载</div>
<div @click="getMP4">转码为MP4下载</div>
</template>
<div v-else-if="finishNum === rangeDownload.targetSegment && rangeDownload.targetSegment > 0" class="disable">下载完成</div>
<div v-else @click="togglePause">{{ isPause ? '恢复下载' : '暂停下载' }}</div>
</section>
<div v-if="!downloading && isSupperStreamWrite" class="m-p-stream" @click="streamDownload(true)">特大视频 MP4 格式下载,边下载边保存,彻底解决大文件下载内存不足问题 </div>
<a class="m-p-final" href="https://live.fanmingming.com/m3u8/">下载完成?点击返回 m3u8 Downloader 首页</a>
<template v-if="finishList.length > 0">
<div class="m-p-line"></div>
<!-- <div class="m-p-retry" v-if="errorNum && downloadIndex >= rangeDownload.targetSegment" @click="retryAll">重新下载错误片段</div> -->
<div class="m-p-force" v-if="mediaFileList.length && !streamWriter" @click="forceDownload">强制下载现有片段</div>
<div class="m-p-tips">待下载碎片总量:{{ rangeDownload.targetSegment }},已下载:{{ finishNum }},错误:{{ errorNum }},进度:{{ (finishNum / rangeDownload.targetSegment * 100).toFixed(2) }}%</div>
<div class="m-p-tips" :class="[errorNum ? 'error-tips' : '']">若某视频碎片下载发生错误,将标记为红色,可点击相应图标进行重试</div>
<section class="m-p-segment">
<div class="item" v-for="(item, index) in finishList" :class="[item.status]" :title="item.title" @click="retry(index)">{{ index + 1 }}</div>
</section>
</template>
</section>
</body>
<!--vue 前端框架-->
<script src="https://live.fanmingming.com/m3u8/vue.js"></script>
<script src="https://live.fanmingming.com/m3u8/aes-decryptor.js"></script>
<script src="https://live.fanmingming.com/m3u8/mux-mp4.js"></script>
<script src="https://live.fanmingming.com/m3u8/stream-saver.js"></script>
<script>
// script注入
document.getElementById('m-loading') && document.getElementById('m-loading').remove()
new Vue({
el: '#m-app',
data() {
return {
url: '', // 在线链接
tips: 'm3u8 视频在线提取工具', // 顶部提示
title: '', // 视频标题
isPause: false, // 是否暂停下载
isGetMP4: false, // 是否转码为 MP4 下载
durationSecond: 0, // 视频持续时长
isShowRefer: false, // 是否显示推送
downloading: false, // 是否下载中
beginTime: '', // 开始下载的时间
errorNum: 0, // 错误数
finishNum: 0, // 已下载数
downloadIndex: 0, // 当前下载片段
finishList: [], // 下载完成项目
tsUrlList: [], // ts URL数组
mediaFileList: [], // 下载的媒体数组
isSupperStreamWrite: window.streamSaver && !window.streamSaver.useBlobFallback, // 当前浏览器是否支持流式下载
streamWriter: null, // 文件流写入器
streamDownloadIndex: 0, // 文件流写入器,正准备写入第几个视频片段
rangeDownload: { // 特定范围下载
isShowRange: false, // 是否显示范围下载
startSegment: '', // 起始片段
endSegment: '', // 截止片段
targetSegment: 1, // 待下载片段
},
aesConf: { // AES 视频解密配置
method: '', // 加密算法
uri: '', // key 所在文件路径
iv: '', // 偏移值
key: '', // 秘钥
decryptor: null, // 解码器对象
stringToBuffer: function (str) {
return new TextEncoder().encode(str)
},
},
}
},
created() {
this.getSource();
window.addEventListener('keyup', this.onKeyup)
setInterval(this.retryAll.bind(this), 2000) // 每两秒重新下载一遍错误片段,实现错误自动重试
},
beforeDestroy() {
window.removeEventListener('keyup', this.onKeyup)
},
methods: {
// 获取链接中携带的资源链接
getSource() {
let { href } = location
if (href.indexOf('?source=') > -1) {
this.url = href.split('?source=')[1]
}
},
// 获取顶部 window title因可能存在跨域问题故使用 try catch 进行保护
getDocumentTitle(){
let title = document.title;
try {
title = window.top.document.title
} catch (error) {
console.log(error)
}
return title
},
// 退出弹窗
onKeyup(event) {
if (event.keyCode === 13) { // 键入ESC
this.getM3U8()
}
},
// ajax 请求
ajax(options) {
options = options || {};
let xhr = new XMLHttpRequest();
if (options.type === 'file') {
xhr.responseType = 'arraybuffer';
}
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
let status = xhr.status;
if (status >= 200 && status < 300) {
options.success && options.success(xhr.response);
} else {
options.fail && options.fail(status);
}
}
};
xhr.open("GET", options.url, true);
xhr.send(null);
},
// 合成URL
applyURL(targetURL, baseURL) {
baseURL = baseURL || location.href
if (targetURL.indexOf('http') === 0) {
// 当前页面使用 https 协议时,强制使 ts 资源也使用 https 协议获取
if(location.href.indexOf('https') === 0){
return targetURL.replace('http://','https://')
}
return targetURL
} else if (targetURL[0] === '/') {
let domain = baseURL.split('/')
return domain[0] + '//' + domain[2] + targetURL
} else {
let domain = baseURL.split('/')
domain.pop()
return domain.join('/') + '/' + targetURL
}
},
// 使用流式下载,边下载边保存,解决大视频文件内存不足的难题
streamDownload(isMp4){
this.isGetMP4 = isMp4
this.title = new URL(this.url).searchParams.get('title') || this.title // 获取视频标题
let fileName = this.title || this.formatTime(new Date(), 'YYYY_MM_DD hh_mm_ss')
if(document.title !== 'm3u8 downloader'){
fileName = this.getDocumentTitle()
}
this.streamWriter = window.streamSaver.createWriteStream(`${fileName}.${isMp4 ? 'mp4' : 'ts'}`).getWriter()
this.getM3U8()
},
// 解析为 mp4 下载
getMP4() {
this.isGetMP4 = true
this.getM3U8()
},
// 获取在线文件
getM3U8(onlyGetRange) {
if (!this.url) {
alert('请输入链接')
return
}
if (this.url.toLowerCase().indexOf('m3u8') === -1) {
alert('链接有误,请重新输入')
return
}
if (this.downloading) {
alert('资源下载中,请稍后')
return
}
// 在下载页面才触发,代码注入的页面不需要校验
// 当前协议不一致,切换协议
if (location.href.indexOf('blog.luckly-mjw.cn') > -1 && this.url.indexOf(location.protocol) === -1) {
//alert('当前协议不一致,跳转至正确页面重新下载')
location.href = `${this.url.split(':')[0]}://live.fanmingming.com/m3u8/index.html?source=${this.url}`
return
}
// 在下载页面才触发,修改页面 URL携带下载路径避免刷新后丢失
if (location.href.indexOf('blog.luckly-mjw.cn') > -1) {
window.history.replaceState(null, '', `${location.href.split('?')[0]}?source=${this.url}`)
}
this.title = new URL(this.url).searchParams.get('title') || this.title // 获取视频标题
this.tips = 'm3u8 文件下载中,请稍后'
this.beginTime = new Date()
this.ajax({
url: this.url,
success: (m3u8Str) => {
this.tsUrlList = []
this.finishList = []
// 提取 ts 视频片段地址
m3u8Str.split('\n').forEach((item) => {
// if (/.(png|image|ts|jpg|mp4|jpeg)/.test(item)) {
// 放开片段后缀限制,下载非 # 开头的链接片段
if (/^[^#]/.test(item)) {
console.log(item)
this.tsUrlList.push(this.applyURL(item, this.url))
this.finishList.push({
title: item,
status: ''
})
}
})
// 仅获取视频片段数
if (onlyGetRange) {
this.rangeDownload.isShowRange = true
this.rangeDownload.endSegment = this.tsUrlList.length
this.rangeDownload.targetSegment = this.tsUrlList.length
return
} else {
let startSegment = Math.max(this.rangeDownload.startSegment || 1, 1) // 最小为 1
let endSegment = Math.max(this.rangeDownload.endSegment || this.tsUrlList.length, 1)
startSegment = Math.min(startSegment, this.tsUrlList.length) // 最大为 this.tsUrlList.length
endSegment = Math.min(endSegment, this.tsUrlList.length)
this.rangeDownload.startSegment = Math.min(startSegment, endSegment)
this.rangeDownload.endSegment = Math.max(startSegment, endSegment)
this.rangeDownload.targetSegment = this.rangeDownload.endSegment - this.rangeDownload.startSegment + 1
this.downloadIndex = this.rangeDownload.startSegment - 1
this.downloading = true
}
// 获取需要下载的 MP4 视频长度
if (this.isGetMP4) {
let infoIndex = 0
m3u8Str.split('\n').forEach(item => {
if (item.toUpperCase().indexOf('#EXTINF:') > -1) { // 计算视频总时长,设置 mp4 信息时使用
infoIndex++
if (this.rangeDownload.startSegment <= infoIndex && infoIndex <= this.rangeDownload.endSegment) {
this.durationSecond += parseFloat(item.split('#EXTINF:')[1])
}
}
})
}
// 检测视频 AES 加密
if (m3u8Str.indexOf('#EXT-X-KEY') > -1) {
this.aesConf.method = (m3u8Str.match(/(.*METHOD=([^,\s]+))/) || ['', '', ''])[2]
this.aesConf.uri = (m3u8Str.match(/(.*URI="([^"]+))"/) || ['', '', ''])[2]
this.aesConf.iv = (m3u8Str.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)
// let params = m3u8Str.match(/#EXT-X-KEY:([^,]*,?METHOD=([^,]+))?([^,]*,?URI="([^,]+)")?([^,]*,?IV=([^,^\n]+))?/)
// this.aesConf.method = params[2]
// this.aesConf.uri = this.applyURL(params[4], this.url)
// this.aesConf.iv = params[6] ? this.aesConf.stringToBuffer(params[6]) : ''
this.getAES();
} else if (this.tsUrlList.length > 0) { // 如果视频没加密,则直接下载片段,否则先下载秘钥
this.downloadTS()
} else {
this.alertError('资源为空,请查看链接是否有效')
}
},
fail: () => {
this.alertError('链接不正确,请查看链接是否有效')
}
})
},
// 获取AES配置
getAES() {
// alert('视频被 AES 加密,点击确认,进行视频解码')
this.ajax({
type: 'file',
url: this.aesConf.uri,
success: (key) => {
// console.log('getAES', key)
// this.aesConf.key = this.aesConf.stringToBuffer(key)
this.aesConf.key = key
this.aesConf.decryptor = new AESDecryptor()
this.aesConf.decryptor.constructor()
this.aesConf.decryptor.expandKey(this.aesConf.key);
this.downloadTS()
},
fail: () => {
this.alertError('视频已加密,可试用右下角入口的「无差别提取工具」')
}
})
},
// ts 片段的 AES 解码
aesDecrypt(data, index) {
let iv = this.aesConf.iv || new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, index])
return this.aesConf.decryptor.decrypt(data, 0, iv.buffer || iv, true)
},
// 下载分片
downloadTS() {
this.tips = 'ts 视频碎片下载中,请稍后'
let download = () => {
let isPause = this.isPause // 使用另一个变量来保持下载前的暂停状态,避免回调后没修改
let index = this.downloadIndex
if (index >= this.rangeDownload.endSegment) {
return
}
this.downloadIndex++
if (this.finishList[index] && this.finishList[index].status === '') {
this.finishList[index].status = 'downloading'
this.ajax({
url: this.tsUrlList[index],
type: 'file',
success: (file) => {
this.dealTS(file, index, () => this.downloadIndex < this.rangeDownload.endSegment && !isPause && download())
},
fail: () => {
this.errorNum++
this.finishList[index].status = 'error'
if (this.downloadIndex < this.rangeDownload.endSegment) {
!isPause && download()
}
}
})
} else if (this.downloadIndex < this.rangeDownload.endSegment) { // 跳过已经成功的片段
!isPause && download()
}
}
// 建立多少个 ajax 线程
for (let i = 0; i < Math.min(6, this.rangeDownload.targetSegment - this.finishNum); i++) {
download()
}
},
// 处理 ts 片段AES 解密、mp4 转码
dealTS(file, index, callback) {
const data = this.aesConf.uri ? this.aesDecrypt(file, index) : file
this.conversionMp4(data, index, (afterData) => { // mp4 转码
this.mediaFileList[index - this.rangeDownload.startSegment + 1] = afterData // 判断文件是否需要解密
this.finishList[index].status = 'finish'
this.finishNum++
if (this.streamWriter){
for (let index = this.streamDownloadIndex; index < this.mediaFileList.length; index++) {
if(this.mediaFileList[index]){
this.streamWriter.write(new Uint8Array(this.mediaFileList[index]))
this.mediaFileList[index] = null
this.streamDownloadIndex = index + 1
} else {
break
}
}
if (this.streamDownloadIndex >= this.rangeDownload.targetSegment){
this.streamWriter.close()
}
} else if (this.finishNum === this.rangeDownload.targetSegment) {
let fileName = this.title || this.formatTime(this.beginTime, 'YYYY_MM_DD hh_mm_ss')
if(document.title !== 'm3u8 downloader'){
fileName = this.getDocumentTitle()
}
this.downloadFile(this.mediaFileList, fileName)
}
callback && callback()
})
},
// 转码为 mp4
conversionMp4(data, index, callback) {
if (this.isGetMP4) {
let transmuxer = new muxjs.Transmuxer({
keepOriginalTimestamps: true,
duration: parseInt(this.durationSecond),
});
transmuxer.on('data', segment => {
if (index === this.rangeDownload.startSegment - 1) {
let data = new Uint8Array(segment.initSegment.byteLength + segment.data.byteLength);
data.set(segment.initSegment, 0);
data.set(segment.data, segment.initSegment.byteLength);
callback(data.buffer)
} else {
callback(segment.data)
}
})
transmuxer.push(new Uint8Array(data));
transmuxer.flush();
} else {
callback(data)
}
},
// 暂停与恢复
togglePause() {
this.isPause = !this.isPause
!this.isPause && this.retryAll(true)
},
// 重新下载某个片段
retry(index) {
if (this.finishList[index].status === 'error') {
this.finishList[index].status = ''
this.ajax({
url: this.tsUrlList[index],
type: 'file',
success: (file) => {
this.errorNum--
this.dealTS(file, index)
},
fail: () => {
this.finishList[index].status = 'error'
}
})
}
},
// 重新下载所有错误片段
retryAll(forceRestart) {
if (!this.finishList.length || this.isPause) {
return
}
let firstErrorIndex = this.downloadIndex // 没有错误项目,则每次都递增
this.finishList.forEach((item, index) => { // 重置所有错误片段状态
if (item.status === 'error') {
item.status = ''
firstErrorIndex = Math.min(firstErrorIndex, index)
}
})
this.errorNum = 0
// 已经全部下载进程都跑完了,则重新启动下载进程
if (this.downloadIndex >= this.rangeDownload.endSegment || forceRestart) {
this.downloadIndex = firstErrorIndex
this.downloadTS()
} else { // 否则只是将下载索引,改为最近一个错误的项目,从那里开始遍历
this.downloadIndex = firstErrorIndex
}
},
// 下载整合后的TS文件
downloadFile(fileDataList, fileName) {
this.tips = 'ts 碎片整合中,请留意浏览器下载'
let fileBlob = null
let a = document.createElement('a')
if (this.isGetMP4) {
fileBlob = new Blob(fileDataList, { type: 'video/mp4' }) // 创建一个Blob对象并设置文件的 MIME 类型
a.download = fileName + '.mp4'
} else {
fileBlob = new Blob(fileDataList, { type: 'video/MP2T' }) // 创建一个Blob对象并设置文件的 MIME 类型
a.download = fileName + '.ts'
}
a.href = URL.createObjectURL(fileBlob)
a.style.display = 'none'
document.body.appendChild(a)
a.click()
a.remove()
},
// 格式化时间
formatTime(date, formatStr) {
const formatType = {
Y: date.getFullYear(),
M: date.getMonth() + 1,
D: date.getDate(),
h: date.getHours(),
m: date.getMinutes(),
s: date.getSeconds(),
}
return formatStr.replace(
/Y+|M+|D+|h+|m+|s+/g,
target => (new Array(target.length).join('0') + formatType[target[0]]).substr(-target.length)
)
},
// 强制下载现有片段
forceDownload() {
if (this.mediaFileList.length) {
let fileName = this.title || this.formatTime(this.beginTime, 'YYYY_MM_DD hh_mm_ss')
if(document.title !== 'm3u8 downloader'){
fileName = this.getDocumentTitle()
}
this.downloadFile(this.mediaFileList, fileName)
} else {
alert('当前无已下载片段')
}
},
// 发生错误,进行提示
alertError(tips) {
alert(tips)
this.downloading = false
this.tips = 'm3u8 视频在线提取工具';
},
// 拷贝本页面本身,解决跨域问题
copyCode() {
if (this.tips !== '代码下载中,请稍后') {
this.tips = '代码下载中,请稍后';
this.ajax({
url: './index.html',
success: (fileStr) => {
let fileList = fileStr.split(`<!--vue 前端框架--\>`);
let dom = fileList[0];
let script = fileList[1] + fileList[2];
script = script.split('// script注入');
script = script[1] + script[2];
if (this.url) {
script = script.replace(`url: '', // 在线链接`, `url: '${this.url}',`);
}
let codeStr = `
// 注入html
let $section = document.createElement('section')
$section.innerHTML = \`${dom}\`
$section.style.width = '100%'
$section.style.height = '800px'
$section.style.top = '0'
$section.style.left = '0'
$section.style.position = 'relative'
$section.style.zIndex = '9999'
$section.style.backgroundColor = 'white'
document.body.appendChild($section);
// 加载 ASE 解密
let $ase = document.createElement('script')
$ase.src = 'https://live.fanmingming.com/m3u8/aes-decryptor.js'
// 加载 mp4 转码
let $mp4 = document.createElement('script')
$mp4.src = 'https://live.fanmingming.com/m3u8/mux-mp4.js'
// 加载 vue
let $vue = document.createElement('script')
$vue.src = 'https://live.fanmingming.com/m3u8/vue.js'
// 加载 stream 流式下载器
let $streamSaver = document.createElement('script')
$streamSaver.src = 'https://live.fanmingming.com/m3u8/stream-saver.js'
// 监听 vue 加载完成,执行业务代码
$vue.addEventListener('load', () => {${script}})
document.body.appendChild($mp4);
document.body.appendChild($ase);
document.body.appendChild($streamSaver);
document.body.appendChild($vue);
alert('注入成功,请滚动到页面底部,若白屏则等待资源加载')
`;
this.copyToClipboard(codeStr);
this.tips = '复制成功,打开视频网页控制台,注入本代码';
},
fail: () => {
this.alertError('链接不正确,请查看链接是否有效');
},
})
}
},
// 拷贝剪切板
copyToClipboard(content) {
clearTimeout(this.timeouter)
if (!document.queryCommandSupported('copy')) {
return false
}
let $input = document.createElement('textarea')
$input.style.opacity = '0'
$input.value = content
document.body.appendChild($input)
$input.select()
const result = document.execCommand('copy')
document.body.removeChild($input)
$input = null
return result
},
}
})
// script注入
</script>
</html>

154
m3u8/mitm.html Normal file
View File

@@ -0,0 +1,154 @@
<!-- 中间层页面,专门用于下载,在此页面中注册 serviceWorker并实现拦截 -->
<!-- 本页面存在的意义,在于隔离 web 主进程的请求,让 serviceWorker 仅拦截本页面的请求 -->
<!-- serviceWorker 完全异步,全程 API 均使用 Promise 完成异步操作 -->
<script>
// 保活,每 10s 执行一次 ping避免 serviceWorker 被删除
let keepAlive = () => {
keepAlive = () => { }
var ping = location.href.substr(0, location.href.lastIndexOf('/')) + '/ping'
var interval = setInterval(() => {
if (serviceWorker) {
serviceWorker.postMessage('ping')
} else {
fetch(ping).then(res => res.text(!res.ok && clearInterval(interval)))
}
}, 10000)
}
let scope = '' // 当前 serviceWorker 所在域,是其唯一标识符
let serviceWorker = null // serviceWorker 实例
let tempMessageStore = [] // 在处理函数未准备好之前,临时存储的 message
// 进入页面马上进行消息监听,再后续处理函数 ready 后,再触发这些 message 的处理
window.onmessage = evt => tempMessageStore.push(evt)
// 注册 serviceWorker检测是否有旧的实例进行复用。
function registerWorker() {
// 获取 ./ 域下已经注册过的 serviceWorkergetRegistration 返回单个getRegistrations 返回所有
return navigator.serviceWorker.getRegistration('./')
.then(serviceWorkerRegistration => {
// 如果已经存在注册过的 serviceWorkerRegistration则直接返回否则产生新的一个
return serviceWorkerRegistration || navigator.serviceWorker.register('serviceWorker.js', { scope: './' })
}).then(serviceWorkerRegistration => {
scope = serviceWorkerRegistration.scope // 保存所在域
// 如果注册已就绪,则直接赋值并返回
if (serviceWorkerRegistration.active) {
serviceWorker = serviceWorkerRegistration.active
return
}
// 如果处于注册中,返回 promise并监听其状态变更等待其就绪状态
const swRegTmp = serviceWorkerRegistration.installing || serviceWorkerRegistration.waiting
return new Promise(resolve => {
const onStatechange = () => {
if (swRegTmp.state === 'activated') {
swRegTmp.removeEventListener('statechange', onStatechange)
serviceWorker = serviceWorkerRegistration.active
resolve()
}
}
swRegTmp.addEventListener('statechange', onStatechange)
})
})
}
// 消息监听,监听 web 主进程发送过来的消息,并进行数据中转,及数据的处理与转译
function onMessage(event) {
let {
data, // 数据
ports, // channel 所在渠道
origin // 消息作用域
} = event
console.log('onMessage', event)
// 检测消息通道
if (!ports || !ports.length) {
throw new TypeError("[StreamSaver] You didn't send a messageChannel")
}
// 检测接受的数据实体
if (typeof data !== 'object') {
throw new TypeError("[StreamSaver] You didn't send a object")
}
// 检查 readableStream
if (data.readableStream) {
console.warn("[StreamSaver] You should send the readableStream in the messageChannel, not throught mitm")
}
// 检查 pathname
if (!data.pathname) {
console.warn("[StreamSaver] Please send `data.pathname` (eg: /pictures/summer.jpg)")
data.pathname = Math.random().toString().slice(-6) + '/' + data.filename
}
/** @since v2.0.0 */
if (!data.headers) {
console.warn("[StreamSaver] pass `data.headers` that you would like to pass along to the service worker\nit should be a 2D array or a key/val object that fetch's Headers api accepts")
} else {
// test if it's correct
// should throw a typeError if not
new Headers(data.headers)
}
// the default public service worker for StreamSaver is shared among others.
// so all download links needs to be prefixed to avoid any other conflict
data.origin = origin
// if we ever (in some feature versoin of streamsaver) would like to
// redirect back to the page of who initiated a http request
data.referrer = data.referrer || document.referrer || origin
// 删除所有前导斜杠
data.pathname = data.pathname.replace(/^\/+/g, '')
// remove protocol
// 去除协议
let org = origin.replace(/(^\w+:|^)\/\//, '')
// 设置绝对路径,以用于下载
data.url = new URL(`${scope + org}/${data.pathname}`).toString()
// 检查路径是否合法
if (!data.url.startsWith(`${scope + org}/`)) {
throw new TypeError('[StreamSaver] bad `data.pathname`')
}
// This sends the message data as well as transferring
// messageChannel.port2 to the service worker. The service worker can
// then use the transferred port to reply via postMessage(), which
// will in turn trigger the onmessage handler on messageChannel.port1.
const transferable = data.readableStream
? [ports[0], data.readableStream]
: [ports[0]]
if (!(data.readableStream || data.transferringReadable)) {
keepAlive()
}
// 将从 web 主进程接收到的数据,传输给 serviceWorker 接收
return serviceWorker.postMessage(data, transferable)
}
// 消息回调,告知主进程,本页面已准备就绪
if (window.opener) {
window.opener.postMessage('StreamSaver::loadedPopup', '*')
}
// 注册完成,并进行消息处理
if (navigator.serviceWorker) {
registerWorker().then(() => {
window.onmessage = onMessage
tempMessageStore.forEach(window.onmessage) // 将之前临时存储的 message 放入处理函数中执行
})
} else {
keepAlive()
}
</script>

7051
m3u8/mux-mp4.js Normal file

File diff suppressed because it is too large Load Diff

164
m3u8/serviceworker.js Normal file
View File

@@ -0,0 +1,164 @@
// Service workers 本质上充当 Web 应用程序、浏览器与网络(可用时)之间的代理服务器。
// 它会拦截网络请求并根据网络是否可用来采取适当的动作、更新来自服务器的的资源
// 相当于网页端的正向代理,监听用户请求
// Service worker 是一个注册在指定源和路径下的事件驱动 worker
// Service workers 只能由 HTTPS 承载,毕竟修改网络请求的能力暴露给中间人攻击会非常危险。
// self 在 web 主线程中等价于 windows但 worker 是无窗口no-window环境没有 window、需要通过 self 指向全局环境
// self 是 worker 中的全局对象https://www.zhangxinxu.com/wordpress/2017/07/js-window-self/
// 整体运行流程,
// 数据存储stream -> mitm -> serviceWorker 进行存储;
// 数据下载 mitm 发起请求serviceWorker 监听请求,并返回二进制流。
// serviceWorker 存在的意义,本质上在主进程层面,不支持流式下载,需要将完整的资源保存后才下载。
// 而在 URL 层面,将请求交给 浏览器运行时,浏览器能自动识别 application/octet-stream 响应类型,触发下载
// 且 new Response 可以传入 读写流 stream实现流式数据传输进行流式下载
// 所以本 serviceWorker 只会被触发两次,一次是 onMessage 监听初始化,一次是 onFetch 拦截请求,触发下载
// 通过 href 触发下载后,下载流程就由 ReadableStream 控制。
// 即整个下载过程就是 ReadableStream 的生命周期ReadableStream 这个流代表了下载进程
// ReadableStream 通过 enqueue 函数,往下载进程中填充内容。
// url 与 data 的映射 map
const urlDataMap = new Map()
// 创建数据读取流
function createStream (port) {
// 数据读取流
return new ReadableStream({
// controller 是 ReadableStreamDefaultControllerhttps://developer.mozilla.org/zh-CN/docs/Web/API/ReadableStreamDefaultController
start (controller) {
// 监听 messageChannel port 的消息,获取传递过来,需要下载的数据
port.onmessage = ({ data }) => {
// 接受结束事件,关闭流
if (data === 'end') {
return controller.close()
}
// 终止事件
if (data === 'abort') {
controller.error('Aborted the download')
return
}
// 将数据推送到队列中,等待下载
controller.enqueue(data)
}
},
// 取消
cancel (reason) {
console.log('user aborted', reason)
port.postMessage({ abort: true })
}
})
}
// 监听 worker 注册完成事件service worker 中所有状态如下https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/state
self.addEventListener('install', () => {
// 如果现有 service worker 已启用,新版本会在后台安装,但不会被激活,这个时序称为 worker in waiting。直到所有已加载的页面不再使用旧的 service worker 才会激活新的 service worker。只要页面不再依赖旧的 service worker新的 service worker 会被激活成为active worker
// 跳过等待环节,直接让当前 worker 为活跃状态,不再等待之前就得 worker 失效
self.skipWaiting()
})
// 监听当前为用状态事件
self.addEventListener('activate', event => {
// self.clients 获取当前 worker 的客户端对象,可能是 web 主进程,也可能是其他的 worker 对象。
// self.clients.claim() 将当前 worker 本身设置为所有 clients 的控制器,即从旧的 worker 中将控制权拿过来
event.waitUntil(self.clients.claim()) // 保持当前状态为 activate 可用状态,直到
})
// 进行消息监听,监听外部传递进来的事件
self.onmessage = event => {
const data = event.data // 正则传输的数据
const port = event.ports[0] // channelPort 端口,传递该消息时
// 跳过 ping 心跳检查事件
if (data === 'ping') {
return
}
// 触发该数据下载对应的 url
const downloadUrl = data.url || self.registration.scope + Math.random() + '/' + (typeof data === 'string' ? data : data.filename)
const metadata = new Array(3) // [stream, data, port]
metadata[1] = data
metadata[2] = port
// Note to self:
// old streamsaver v1.2.0 might still use `readableStream`...
// but v2.0.0 will always transfer the stream through MessageChannel #94
if (data.readableStream) {
metadata[0] = data.readableStream
} else if (data.transferringReadable) { // 如果支持 TransformStream则使用 TransformStream 双向流完成下载数据传输,关闭 messageChannel 的传输
port.onmessage = evt => {
port.onmessage = null
metadata[0] = evt.data.readableStream
}
} else {
// 如果没有外部传入的 readStream 对象,则自己创建一个,且本质是通过 messageChannel 进行数据监听与数据传输
metadata[0] = createStream(port)
}
// 进行数据与 url 的映射记录
urlDataMap.set(downloadUrl, metadata)
// 进行消息响应,返回下载地址
port.postMessage({ download: downloadUrl })
}
// service worker 的主要监听器,拦截监听该 web 下发起的所有网络请求https://developer.mozilla.org/zh-CN/docs/Web/API/FetchEvent
// 实际上,该 onfetch 除去 ping 请求外,只会被触发一次,用于拦截下载请求。
// 下载请求,则返回一个 二进制流 响应,触发浏览器下载。
self.onfetch = event => {
// event request 获得 web 发起的请求对象https://developer.mozilla.org/zh-CN/docs/Web/API/FetchEvent/request
const url = event.request.url
// 仅在 Firefox 中有效,监听到 心跳检查 ping 请求
if (url.endsWith('/ping')) {
return event.respondWith(new Response('pong'))
}
const urlCacheData = urlDataMap.get(url) // 获取之前缓存的 url 映射的信息
if (!urlCacheData) return null
const [
stream, // 需要下载的数据二进制流
data, // 配置信息
port // 端口
] = urlCacheData
urlDataMap.delete(url)
// 构造响应体,并只获取外部传入的 Content-Length 和 Content-Disposition 这两个响应头
const responseHeaders = new Headers({
'Content-Type': 'application/octet-stream; charset=utf-8', // 将响应格式设置为二进制流
// // 一些安全设置
'Content-Security-Policy': "default-src 'none'",
'X-Content-Security-Policy': "default-src 'none'",
'X-WebKit-CSP': "default-src 'none'",
'X-XSS-Protection': '1; mode=block'
})
// 通过 data.headers 配置,生成 headers 对象,获取其内部值
let headers = new Headers(data.headers || {})
// 设置长度
if (headers.has('Content-Length')) {
responseHeaders.set('Content-Length', headers.get('Content-Length'))
}
// 指示回复的内容该以何种形式展示是以内联的形式即网页或者页面的一部分还是以附件的形式下载并保存到本地。https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Content-Disposition
if (headers.has('Content-Disposition')) {
responseHeaders.set('Content-Disposition', headers.get('Content-Disposition'))
}
// 针对该请求进行响应
event.respondWith(new Response(stream, { headers: responseHeaders }))
port.postMessage({ debug: 'Download started' })
}

262
m3u8/stream-saver.js Normal file
View File

@@ -0,0 +1,262 @@
(function () {
// 下载代理,使用 iframe还是 navigate
const downloadStrategy =
window.isSecureContext // window.isSecureContext 判断是否为 https、wss 等安全环境
|| 'MozAppearance' in document.documentElement.style // 是否为 firefox 浏览器
? 'iframe' : 'navigate'
// 中间传输器
let middleTransporter = null
// 是否使用 blob 替换 service worker 的能力
// safari 不支持流式下载功能https://github.com/jimmywarting/StreamSaver.js/issues/69
let useBlobFallback = /constructor/i.test(window.HTMLElement) || !!window.safari || !!window.WebKitPoint
try {
new Response(new ReadableStream())
if (window.isSecureContext && !('serviceWorker' in navigator)) {
useBlobFallback = true
}
} catch (err) {
useBlobFallback = true
}
// 是否支持转换器传输流 TransformStream支持则直接使用他的读写流完成下载数据的传输。都在需要通过 messageChannel 进行数据传输
let isSupportTransformStream = false
try {
const { readable } = new TransformStream() // 创建读写传输流
const messageChannel = new MessageChannel() // 创建消息通道,与 iframe 或 window.open 新建的页面中进行消息通信
messageChannel.port1.postMessage(readable, [readable])
messageChannel.port1.close()
messageChannel.port2.close()
isSupportTransformStream = true
} catch (err) {
console.log(err)
}
// 创建一个隐藏式的 Iframe并通过 iframe 的 postMessage 进行消息传输
function makeIframe(src) {
console.log('makeIframe', src)
const iframe = document.createElement('iframe')
iframe.hidden = true
iframe.src = src
iframe.loaded = false
iframe.name = 'iframe'
iframe.isIframe = true
// 调用 iframe 中的 postMessage 方法,即从 iframe 中发送消息
iframe.postMessage = (...args) => iframe.contentWindow.postMessage(...args)
iframe.addEventListener('load', () => {
iframe.loaded = true
}, { once: true }) // 该事件监听器只监听一次,自动回收
document.body.appendChild(iframe)
return iframe
}
// 创建一个弹出窗口模拟iframe的基本功能
// 使用 popup 新建弹窗,来模拟 iframe 的跨页面消息传输功能
function makePopup(src) {
console.log('makePopup', src)
// 事件代理器,使用 createDocumentFragment 来实现 popup 中的消息监听效果。
// 与 document 相比,最大的区别是它不是真实 DOM 树的一部分,它的变化不会触发 DOM 树的重新渲染,且不会对性能产生影响。
const delegate = document.createDocumentFragment()
const popup = {
frame: window.open(src, 'popupTitle', 'width=200,height=100'),
loaded: false,
isIframe: false,
isPopup: true,
remove() { popup.frame.close() },
// 适配器模式,使得 popup 对象与 iframe 对象有一样的表现。发送事件,监听事件,移除事件
dispatchEvent(...args) { delegate.dispatchEvent(...args) },
addEventListener(...args) { delegate.addEventListener(...args) },
removeEventListener(...args) { delegate.removeEventListener(...args) },
// 调用
postMessage(...args) { popup.frame.postMessage(...args) }
}
// 监听 popup 是否就绪
const onReady = evt => {
// 如果接受到来自 popup 的事件,则证明 popup 已就绪
if (evt.source === popup.frame) {
popup.loaded = true
window.removeEventListener('message', onReady)
popup.dispatchEvent(new Event('load'))
}
}
window.addEventListener('message', onReady)
return popup
}
// 创建写入流
function createWriteStream(filename) {
let bytesWritten = 0 // 记录已写入的文件大小
let downloadUrl = null // 触发下载时,需要访问的 url 地址
let messageChannel = null // 消息传输通道
let transformStream = null // 中间传输流
if (!useBlobFallback) {
// middleTransporter = middleTransporter || makeIframe(streamSaver.middleTransporterUrl) // https 环境下,则执行 iframe
middleTransporter = middleTransporter || window.isSecureContext
? makeIframe(streamSaver.middleTransporterUrl) // https 环境下,则执行 iframe
: makePopup(streamSaver.middleTransporterUrl) // 普通环境下,则通过 window.open 新建弹窗来完成
messageChannel = new MessageChannel() // 创建消息通道
// 处理文件名,使其为 url 格式
filename = encodeURIComponent(filename.replace(/\//g, ':'))
.replace(/['()]/g, escape)
.replace(/\*/g, '%2A')
// 如果支持 TransformStream则将 TransformStream.readStream 传递给 port2
if (isSupportTransformStream) {
transformStream = new TransformStream(downloadStrategy === 'iframe' ? undefined : {
// 流处理,中间转换器,监听每一个流分片的经过
transform(chunk, controller) {
// 传输的内容,仅支持 Uint8Arrays 格式
if (!(chunk instanceof Uint8Array)) {
throw new TypeError('Can only write Uint8Arrays')
}
bytesWritten += chunk.length // 记录已写入的内容消大小
controller.enqueue(chunk) // 将消息推进队列
if (downloadUrl) {
location.href = downloadUrl // 由于在 response 中设置了返回类型为二进制流,可直接触发其下载。不会发生跳转
downloadUrl = null
}
},
// 结束写入时调用,如果数据量少,未经过 transform 就触发了 flush则调用 location.href 触发下载
flush() {
if (downloadUrl) {
location.href = downloadUrl
}
}
})
// 使用 port1 传递数据,将读数据端通过 channel Message 传递给 service worker
// 由 write 暴露写端,供主线程写入数据。再在 service worker 中,通过 readStream 读取该数据。完成下载数据的传输。
// 即下载数据,不需要通过 channel message 传输,而是通过 transformStream 进行传递。
messageChannel.port1.postMessage({ readableStream: transformStream.readable }, [transformStream.readable])
}
// 监听给 port1 传递的消息
messageChannel.port1.onmessage = evt => {
// 接受 Service worker 发送的 url并访问它
if (evt.data.download) {
// 为 popup 做的特殊处理
if (downloadStrategy === 'navigate') {
// 中间人完成使命,则删除中间人,后续传输通过 channelMessage直接由主进程与 service worker 进行通信
middleTransporter.remove()
middleTransporter = null
// 首次访问该 url
if (bytesWritten) {
location.href = evt.data.download
} else {
downloadUrl = evt.data.download
}
} else {
if (middleTransporter.isPopup) {
middleTransporter.remove()
middleTransporter = null
// Special case for firefox, they can keep sw alive with fetch
if (downloadStrategy === 'iframe') {
makeIframe(streamSaver.middleTransporterUrl)
}
}
makeIframe(evt.data.download)
}
} else if (evt.data.abort) { // 消息终止
chunks = []
messageChannel.port1.postMessage('abort') //send back so controller is aborted
messageChannel.port1.onmessage = null
messageChannel.port1.close()
messageChannel.port2.close()
messageChannel = null
}
}
// 往中间人容器中发送消息,将 messageChannel.port2 传递给中间人
const response = {
transferringReadable: isSupportTransformStream,
pathname: Math.random().toString().slice(-6) + '/' + filename,
headers: {
'Content-Type': 'application/octet-stream; charset=utf-8',
'Content-Disposition': "attachment; filename*=UTF-8''" + filename
}
}
if (middleTransporter.loaded) {
middleTransporter.postMessage(response, '*', [messageChannel.port2])
} else {
middleTransporter.addEventListener('load', () => {
middleTransporter.postMessage(response, '*', [messageChannel.port2])
}, { once: true })
}
}
let chunks = [] // 需要传输下载的内容数组
// 如果有 transformStream则直接返回 transformStream 读写流的 WritableStream 实例
if (!useBlobFallback && transformStream && transformStream.writable) {
// writable 返回由这个 TransformStream 控制的 WritableStream 实例。
// writable 返回的是一个实例,而不是一个 boolean 值
return transformStream.writable
}
// 如果不支持 transformStream则自行创建一个 WritableStream监听 WritableStream 的写入事件。将数据通过 messageChannel 的两个 port 进行传输
return new WritableStream({
// 写入数据
write(chunk) {
// 检查写入流,仅支持 Uint8Arrays 格式
if (!(chunk instanceof Uint8Array)) {
throw new TypeError('Can only write Uint8Arrays')
}
// 如果使用 blob 功能进行下载,则仅存储该数据,无法使用流式边获取数据边下载
if (useBlobFallback) {
chunks.push(chunk)
return
}
// service worker 可用,则通过信道传输该二进制流
messageChannel.port1.postMessage(chunk)
bytesWritten += chunk.length
if (downloadUrl) {
location.href = downloadUrl
downloadUrl = null
}
},
// 关闭写入流,将流式文件进行保存
close() {
// 使用 blob 实现功能,则将所有片段当做 blob 的内容,通过 createObjectURL 生成其链接,点击触发下载
if (useBlobFallback) {
const blob = new Blob(chunks, { type: 'application/octet-stream; charset=utf-8' })
const link = document.createElement('a')
link.href = URL.createObjectURL(blob)
link.download = filename
link.click()
} else { // service worker 有效,则仅发出 end 事件,由 service worker 执行结束操作
messageChannel.port1.postMessage('end')
}
},
// 中断,不执行下载
abort() {
chunks = []
messageChannel.port1.postMessage('abort')
messageChannel.port1.onmessage = null
messageChannel.port1.close()
messageChannel.port2.close()
messageChannel = null
}
})
}
// 全局挂载 streamSaver 对象
window.streamSaver = {
createWriteStream, // 创建写流
middleTransporterUrl: 'https://live.fanmingming.com/m3u8/mitm.html',
}
})()

11943
m3u8/vue.js Normal file

File diff suppressed because it is too large Load Diff