mirror of
https://github.com/the1812/Bilibili-Evolved.git
synced 2025-11-04 21:22:45 +08:00
1 line
7.1 KiB
JavaScript
1 line
7.1 KiB
JavaScript
(()=>{return(e,t)=>{const n={entity:null,aid:undefined,cid:undefined,isBangumi:false};const s=[];SpinQuery.unsafeJquery().then(()=>{unsafeWindow.$(unsafeWindow.document).ajaxSend((e,t,n)=>{if(n.url.indexOf("https://bangumi.bilibili.com/player/web_api/v2/playurl")!==-1){s.unshift(n.url)}})});class i{constructor(){this.menuPanel=document.querySelector(".download-video-panel");this.menuClasses=["quality","action","progress"];this.currentMenuClass="quality"}addMenuClass(){this.menuPanel.classList.remove(...this.menuClasses);this.menuPanel.classList.add(this.currentMenuClass);return this.currentMenuClass}resetMenuClass(){[this.currentMenuClass]=this.menuClasses;this.addMenuClass()}nextMenuClass(){const e=this.menuClasses.indexOf(this.currentMenuClass)+1;const t=this.menuClasses[e>=this.menuClasses.length?0:e];this.currentMenuClass=t;this.addMenuClass();return t}addError(){this.menuPanel.classList.add("error")}removeError(){this.menuPanel.classList.remove("error");this.resetMenuClass()}async getUrl(e){if(e){return`https://api.bilibili.com/x/player/playurl?avid=${n.aid}&cid=${n.cid}&qn=${e}&otype=json`}else{return`https://api.bilibili.com/x/player/playurl?avid=${n.aid}&cid=${n.cid}&otype=json`}}}class o extends i{constructor(e){super(e);this.menuClasses=["action","progress"];this.currentMenuClass="action"}async getUrl(){const e=await SpinQuery.select(()=>s[0]).catch(()=>logError("获取番剧下载链接失败."));return e}}class r{constructor(e,t,n){this.quality=e;this.internalName=t;this.displayName=n}async downloadInfo(){const e=new l(this);await e.fetchVideoInfo();return e}static get availableFormats(){return new Promise((e,t)=>{n.entity.getUrl().then(n=>{const s=new XMLHttpRequest;s.addEventListener("load",()=>{const n=JSON.parse(s.responseText);if(n.code!==0){t("获取清晰度信息失败.")}const i=n.data||n;const o=i.accept_quality;const a=i.accept_format.split(",");const l=i.accept_description;const c=[];while(o.length>0){const e=new r(o.pop(),a.pop(),l.pop());c.push(e)}e(c)});s.addEventListener("error",()=>t(`获取清晰度信息失败.`));s.withCredentials=true;s.open("GET",n);s.send()})})}}class a{constructor(e,t,n,s){this.length=e;this.size=t;this.url=n;this.backupUrls=s}}class l{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)=>{n.entity.getUrl(this.format.quality).then(s=>{const i=new XMLHttpRequest;i.addEventListener("load",()=>{const s=JSON.parse(i.responseText.replace(/http:/g,"https:"));const o=s.data||s;if(!n.isBangumi&&o.quality!==this.format.quality){t("获取下载链接失败, 请确认当前账号有下载权限后重试.")}const r=o.durl;this.fragments=r.map(e=>new a(e.length,e.size,e.url,e.backup_url));e(this.fragments)});i.withCredentials=true;i.open("GET",s);i.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 n=Math.round(e.size/this.fragmentSplitFactor);let s=0;while(s<e.size){const i=`bytes=${s}-${Math.min(e.size-1,Math.round(s+n))}`;t.push(new Promise((t,n)=>{let s=0;const o=new XMLHttpRequest;o.open("GET",e.url);o.responseType="arraybuffer";o.withCredentials=false;o.addEventListener("progress",e=>{this.loaded+=e.loaded-s;s=e.loaded;this.progress&&this.progress(this.loaded/this.totalSize)});o.addEventListener("load",()=>{if((""+o.status)[0]==="2"){t(o.response)}else{n(`请求失败.`)}});o.addEventListener("abort",()=>n("下载已取消."));o.addEventListener("error",()=>n(`下载失败.`));o.setRequestHeader("Range",i);o.send();this.workingXhr.push(o)}));s=Math.round(s+n)}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 n=this.makeBlob(t);const s=document.title.replace("_哔哩哔哩 (゜-゜)つロ 干杯~-bilibili","").replace("_番剧_bilibili_哔哩哔哩","")+this.extension();return[n,s]}async downloadMultiple(e){const t=new JSZip;const n=document.title.replace("_哔哩哔哩 (゜-゜)つロ 干杯~-bilibili","").replace("_番剧_bilibili_哔哩哔哩","");if(e.length>1){e.forEach((e,s)=>{const i=this.fragments[s];t.file(`${n} - ${s+1}${this.extension(i)}`,this.makeBlob(e,i))})}else{const[s]=e;t.file(`${n}${this.extension()}`,this.makeBlob(s))}const s=await t.generateAsync({type:"blob"});const i=n+".zip";return[s,i]}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 n=await this.downloadFragment(t);e.push(n)}if(e.length<1){throw new Error("下载失败.")}let t=null;let n=null;if(e.length===1){[t,n]=this.downloadSingle(e)}else{[t,n]=await this.downloadMultiple(e)}const s=URL.createObjectURL(t);this.cleanUpOldBlobUrl();this.progress&&this.progress(0);return{url:s,filename:n}}}async function c(){const e=await SpinQuery.select(()=>(unsafeWindow||window).aid);const t=await SpinQuery.select(()=>(unsafeWindow||window).cid);n.aid=e;n.cid=t;if(document.URL.indexOf("bangumi")!==-1){n.isBangumi=true;n.entity=new o}else{n.entity=new i}return e!==undefined&&t!==undefined}async function d(){await c();const e=await r.availableFormats;let[s]=e;const i=()=>s.downloadInfo().catch(e=>{n.entity.addError();$(".video-error").text(e)});async function o(){if(!s){return}n.entity.nextMenuClass();const e=await i();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=>{n.entity.addError();$(".video-error").text(e)});if(!t){return}const o=document.getElementById("video-complete");o.setAttribute("href",t.url);o.setAttribute("download",t.filename);o.click();const r=`下载完成. <a class="link" href="${t.url}" download="${t.filename.replace(/"/g,""")}">再次保存</a>`;Toast.success(r,"下载视频");n.entity.resetMenuClass()}async function a(){if(!s){return}const e=await i();e.copyUrl();Toast.success("已复制链接到剪贴板.","复制链接",3e3);n.entity.resetMenuClass()}$(".video-action>#video-action-download").on("click",o);$(".video-action>#video-action-copy").on("click",a);e.forEach(e=>{$(`<li>${e.displayName}</li>`).on("click",()=>{s=e;n.entity.nextMenuClass()}).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("");n.entity.removeError()});n.entity.addMenuClass()}return{widget:{content:t.data.downloadVideoDom.text,condition:c,success:d}}}})(); |