mirror of
https://github.com/the1812/Bilibili-Evolved.git
synced 2025-11-04 21:22:45 +08:00
1 line
6.3 KiB
JavaScript
1 line
6.3 KiB
JavaScript
(()=>{return(e,t)=>{const o={aid:undefined,cid:undefined,isBangumi:false,isMovie:false};const n=[];$(document).ajaxSend((e,t,o)=>{if(o.url.indexOf("https://bangumi.bilibili.com/player/web_api/v2/playurl")!==-1){n.unshift(o.url)}});class s{constructor(e,t,o){this.quality=e;this.internalName=t;this.displayName=o}async downloadInfo(){const e=new a(this);await e.fetchVideoInfo();return e}static get availableFormats(){return new Promise((e,t)=>{function i(o){const n=new XMLHttpRequest;n.addEventListener("load",()=>{const o=JSON.parse(n.responseText);if(o.code!==0){t("获取清晰度信息失败.")}const i=o.data||o;const a=i.accept_quality;const r=i.accept_format.split(",");const l=i.accept_description;const d=[];while(a.length>0){const e=new s(a.pop(),r.pop(),l.pop());d.push(e)}e(d)});n.addEventListener("error",()=>t(`获取清晰度信息失败.`));n.withCredentials=true;n.open("GET",o);n.send()}let a=`https://api.bilibili.com/x/player/playurl?avid=${o.aid}&cid=${o.cid}&otype=json`;if(o.isBangumi){SpinQuery.select(()=>{const[e]=n;return e},e=>{a=e;i(a)},()=>logError("获取番剧下载链接失败."))}else{i(a)}})}}class i{constructor(e,t,o,n){this.length=e;this.size=t;this.url=o;this.backupUrls=n}}class a{constructor(e,t){this.format=e;this.fragments=t||[];this.progress=null;this.loaded=0;this.totalSize=null;this.workingXhr=null;this.fragmentSplitFactor=6*5}fetchVideoInfo(){return new Promise((e,t)=>{const n=`https://api.bilibili.com/x/player/playurl?avid=${o.aid}&cid=${o.cid}&qn=${this.format.quality}&otype=json`;const s=new XMLHttpRequest;s.addEventListener("load",()=>{const o=JSON.parse(s.responseText.replace(/http:/g,"https:")).data;if(o.quality!==this.format.quality){t("获取下载链接失败, 请确认当前账号有下载权限后重试.")}const n=o.durl;this.fragments=n.map(e=>new i(e.length,e.size,e.url,e.backup_url));e(this.fragments)});s.withCredentials=true;s.open("GET",n);s.send()})}cancelDownload(){if("forEach"in this.workingXhr){this.workingXhr.forEach(e=>e.abort())}else{logError("Cancel Download Failed: forEach in this.workingXhr not found.")}}downloadFragment(e){const t=[];this.workingXhr=[];const o=Math.round(e.size/this.fragmentSplitFactor);let n=0;while(n<e.size){const s=`bytes=${n}-${Math.min(e.size-1,Math.round(n+o))}`;t.push(new Promise((t,o)=>{let n=0;const i=new XMLHttpRequest;i.open("GET",e.url);i.responseType="arraybuffer";i.withCredentials=false;i.addEventListener("progress",e=>{this.loaded+=e.loaded-n;n=e.loaded;this.progress&&this.progress(this.loaded/this.totalSize)});i.addEventListener("load",()=>{if((""+i.status)[0]==="2"){t(i.response)}else{o(`请求失败.`)}});i.addEventListener("abort",()=>o("下载已取消."));i.addEventListener("error",()=>o(`下载失败.`));i.setRequestHeader("Range",s);i.send();this.workingXhr.push(i)}));n=Math.round(n+o)}return Promise.all(t)}copyUrl(){const e=this.fragments.map(e=>e.url).reduce((e,t)=>e+"\r\n"+t);GM_setClipboard(e,"text")}extension(e){return(e||this.fragments[0]).url.indexOf(".flv")!==-1?".flv":".mp4"}makeBlob(e,t=null){return new Blob(Array.isArray(e)?e:[e],{type:this.extension(t)===".flv"?"video/x-flv":"video/mp4"})}cleanUpOldBlobUrl(){const e=$("a#video-complete").attr("href");if(e&&$(`.link[href=${e}]`).length===0){URL.revokeObjectURL(e)}}downloadSingle(e){const[t]=e;const o=this.makeBlob(t);const n=document.title.replace("_哔哩哔哩 (゜-゜)つロ 干杯~-bilibili","")+this.extension();return[o,n]}async downloadMultiple(e){const t=new JSZip;const o=document.title.replace("_哔哩哔哩 (゜-゜)つロ 干杯~-bilibili","");if(e.length>1){e.forEach((e,n)=>{const s=this.fragments[n];t.file(`${o} - ${n+1}${this.extension(s)}`,this.makeBlob(e,s))})}else{const[n]=e;t.file(`${o}${this.extension()}`,this.makeBlob(n))}const n=await t.generateAsync({type:"blob"});const s=o+".zip";return[n,s]}async download(){const e=[];this.loaded=0;this.totalSize=this.fragments.map(e=>e.size).reduce((e,t)=>e+t);for(const t of this.fragments){const o=await this.downloadFragment(t);e.push(o)}if(e.length<1){throw new Error("下载失败.")}let t=null;let o=null;if(e.length===1){[t,o]=this.downloadSingle(e)}else{[t,o]=await this.downloadMultiple(e)}const n=URL.createObjectURL(t);this.cleanUpOldBlobUrl();this.progress&&this.progress(0);return{url:n,filename:o}}}async function r(){const e=await SpinQuery.select(()=>(unsafeWindow||window).aid);const t=await SpinQuery.select(()=>(unsafeWindow||window).cid);o.aid=e;o.cid=t;if(document.URL.indexOf("bangumi")!==-1){o.isBangumi=true}return e!==undefined&&t!==undefined}async function l(){await r();const e=await s.availableFormats;let[o]=e;const n=()=>o.downloadInfo().catch(e=>{$(".download-video-panel").addClass("error");$(".video-error").text(e)});async function i(){if(!o){return}$(".download-video-panel").removeClass("action").addClass("progress");const e=await n();e.progress=(e=>{$(".download-progress-value").text(`${fixed(e*100)}`);$(".download-progress-foreground").css("transform",`scaleX(${e})`)});document.querySelector(".download-progress-cancel>span").onclick=(()=>e.cancelDownload());const t=await e.download().catch(e=>{$(".download-video-panel").addClass("error");$(".video-error").text(e)});if(!t){return}const s=document.getElementById("video-complete");s.setAttribute("href",t.url);s.setAttribute("download",t.filename);s.click();const i=`下载完成. <a class="link" href="${t.url}" download="${t.filename}">再次保存</a>`;Toast.success(i,"下载视频");$(".download-video-panel").removeClass("progress").addClass("quality")}async function a(){if(!o){return}const e=await n();e.copyUrl();Toast.success("已复制链接到剪贴板.","复制链接",3e3);$(".download-video-panel").removeClass("action").addClass("quality")}$(".video-action>#video-action-download").on("click",i);$(".video-action>#video-action-copy").on("click",a);e.forEach(e=>{$(`<li>${e.displayName}</li>`).on("click",()=>{o=e;$(".download-video-panel").removeClass("quality").addClass("action")}).prependTo("ol.video-quality")});t.applyStyle("downloadVideoStyle");const l=document.querySelector(".download-video-panel");const d=()=>$(".download-video-panel").toggleClass("opened");$("#download-video").on("click",e=>{if(!l.contains(e.target)){d()}});$(".video-error").on("click",()=>{$(".video-error").text("");$(".download-video-panel").removeClass("error").removeClass("progress").addClass("quality")})}return{widget:{content:t.data.downloadVideoDom.text,condition:r,success:l}}}})(); |