mirror of
https://github.com/the1812/Bilibili-Evolved.git
synced 2025-11-04 21:22:45 +08:00
1 line
7.0 KiB
JavaScript
1 line
7.0 KiB
JavaScript
(()=>{return(e,t)=>{const{getFriendlyTitle:n}=t.import("title");const s={entity:null,aid:undefined,cid:undefined};class o{constructor(){this.menuClasses=["quality","action","progress"];this.currentMenuClass="quality"}get menuPanel(){return document.querySelector(".download-video-panel")}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=${s.aid}&cid=${s.cid}&qn=${e}&otype=json`}else{return`https://api.bilibili.com/x/player/playurl?avid=${s.aid}&cid=${s.cid}&otype=json`}}}class i extends o{async getUrl(e){if(e){return`https://api.bilibili.com/pgc/player/web/playurl?avid=${s.aid}&cid=${s.cid}&qn=${e}&otype=json`}else{return`https://api.bilibili.com/pgc/player/web/playurl?avid=${s.aid}&cid=${s.cid}&qn=&otype=json`}}}class a{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)=>{s.entity.getUrl().then(n=>{const s=new XMLHttpRequest;s.addEventListener("load",()=>{const n=JSON.parse(s.responseText);if(n.code!==0){t("获取清晰度信息失败.")}const o=n.data||n.result||n;const i=o.accept_quality;const r=o.accept_format.split(",");const l=o.accept_description;const d=[];while(i.length>0){const e=new a(i.pop(),r.pop(),l.pop());d.push(e)}e(d)});s.addEventListener("error",()=>t(`获取清晰度信息失败.`));s.withCredentials=true;s.open("GET",n);s.send()})})}}class r{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)=>{s.entity.getUrl(this.format.quality).then(n=>{const s=new XMLHttpRequest;s.addEventListener("load",()=>{const n=JSON.parse(s.responseText.replace(/http:/g,"https:"));const o=n.data||n.result||n;if(o.quality!==this.format.quality){t("获取下载链接失败, 请确认当前账号有下载权限后重试.")}const i=o.durl;this.fragments=i.map(e=>new r(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 n=Math.round(e.size/this.fragmentSplitFactor);let s=0;while(s<e.size){const o=`bytes=${s}-${Math.min(e.size-1,Math.round(s+n))}`;t.push(new Promise((t,n)=>{let s=0;const i=new XMLHttpRequest;i.open("GET",e.url);i.responseType="arraybuffer";i.withCredentials=false;i.addEventListener("progress",e=>{this.loaded+=e.loaded-s;s=e.loaded;this.progress&&this.progress(this.loaded/this.totalSize)});i.addEventListener("load",()=>{if((""+i.status)[0]==="2"){t(i.response)}else{n(`请求失败.`)}});i.addEventListener("abort",()=>n("下载已取消."));i.addEventListener("error",()=>{this.loaded-=s;s=0;i.open("GET",e.url);i.send()});i.setRequestHeader("Range",o);i.send();this.workingXhr.push(i)}));s=Math.round(s+n)+1}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 s=this.makeBlob(t);const o=n()+this.extension();return[s,o]}async downloadMultiple(e){const t=new JSZip;const s=n();if(e.length>1){e.forEach((e,n)=>{const o=this.fragments[n];t.file(`${s} - ${n+1}${this.extension(o)}`,this.makeBlob(e,o))})}else{const[n]=e;t.file(`${s}${this.extension()}`,this.makeBlob(n))}const o=await t.generateAsync({type:"blob"});const i=s+".zip";return[o,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 d(){const e=await SpinQuery.select(()=>(unsafeWindow||window).aid);const t=await SpinQuery.select(()=>(unsafeWindow||window).cid);s.aid=e;s.cid=t;if(document.URL.indexOf("bangumi")!==-1){s.entity=new i}else{s.entity=new o}return Boolean(e&&t)}async function c(){let e=await a.availableFormats;let[n]=e;const o=async()=>{await d();e=await a.availableFormats;const t=$("ol.video-quality");t.html("");e.forEach(e=>{$(`<li>${e.displayName}</li>`).on("click",()=>{n=e;s.entity.nextMenuClass()}).prependTo(t)})};if(Observer.videoChange){Observer.videoChange(o)}else{Observer.childList("#bofqi",o)}const i=()=>n.downloadInfo().catch(e=>{s.entity.addError();$(".video-error").text(e)});async function r(){if(!n){return}s.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=>{s.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 a=`下载完成. <a class="link" href="${t.url}" download="${t.filename.replace(/"/g,""")}">再次保存</a>`;Toast.success(a,"下载视频");s.entity.resetMenuClass()}async function l(){if(!n){return}const e=await i();e.copyUrl();Toast.success("已复制链接到剪贴板.","复制链接",3e3);s.entity.resetMenuClass()}$(".video-action>#video-action-download").on("click",r);$(".video-action>#video-action-copy").on("click",l);t.applyStyle("downloadVideoStyle");const c=document.querySelector(".download-video-panel");const u=()=>$(".download-video-panel").toggleClass("opened");$("#download-video").on("click",e=>{if(!c.contains(e.target)){u()}});$(".video-error").on("click",()=>{$(".video-error").text("");s.entity.removeError()});await SpinQuery.select(()=>document.querySelector(".download-video-panel"));s.entity.addMenuClass()}return{widget:{content:(t.data.downloadVideoDom||t.data.downloadVideoHtml).text,condition:d,success:c}}}})(); |