Bilibili-Evolved/min/download-video.min.js

1 line
11 KiB
JavaScript

(()=>{return(e,t)=>{const{getFriendlyTitle:n}=t.import("title");const s={entity:null,aid:undefined,cid:undefined};let o=[];let r=null;class i{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}closeMenu(){this.menuPanel.classList.remove("opened");setTimeout(()=>this.resetMenuClass(),200)}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 a extends i{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 l{constructor(e,t,n){this.quality=e;this.internalName=t;this.displayName=n}async downloadInfo(){const e=new d(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("获取清晰度信息失败.");return}const o=n.data||n.result||n;const r=o.accept_quality;const i=o.accept_format.split(",");const a=o.accept_description;const c=[];while(r.length>0){const e=new l(r.pop(),i.pop(),a.pop());c.push(e)}e(c)});s.addEventListener("error",()=>t(`获取清晰度信息失败.`));s.withCredentials=true;s.open("GET",n);s.send()})})}}class c{constructor(e,t,n,s){this.length=e;this.size=t;this.url=n;this.backupUrls=s}}class d{constructor(e,t){this.format=e;this.fragments=t||[];this.progress=null;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 r=o.durl;this.fragments=r.map(e=>new c(e.length,e.size,e.url,e.backup_url));e(this.fragments)});s.withCredentials=true;s.open("GET",n);s.send()})})}updateProgress(){const e=this.progressMap?[...this.progressMap.values()].reduce((e,t)=>e+t,0)/this.totalSize:0;if(e>1||e<0){console.error(`[下载视频] 进度异常: ${e}`,this.progressMap.values())}this.progress&&this.progress(e)}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=[];this.progressMap=new Map;this.updateProgress();const n=Math.round(e.size/this.fragmentSplitFactor);let s=0;const o=e=>[...this.progressMap.keys()].indexOf(e)+1;while(s<e.size){const r=Math.min(e.size-1,Math.round(s+n));const i=`bytes=${s}-${r}`;const a=r-s+1;t.push(new Promise((t,n)=>{const s=new XMLHttpRequest;s.open("GET",e.url);s.responseType="arraybuffer";s.withCredentials=false;s.addEventListener("progress",e=>{console.log(`[下载视频] 视频片段${o(s)}下载进度: ${e.loaded}/${a} bytes loaded, ${i}`);this.progressMap.set(s,e.loaded);this.updateProgress()});s.addEventListener("load",()=>{if((""+s.status)[0]==="2"){t(s.response)}else{n(`请求失败.`)}});s.addEventListener("abort",()=>n("下载已取消."));s.addEventListener("error",()=>{console.error(`[下载视频] 视频片段${o(s)}下载失败: ${i}`);this.progressMap.set(s,0);this.updateProgress();s.open("GET",e.url);s.setRequestHeader("Range",i);s.send()});s.setRequestHeader("Range",i);this.progressMap.set(s,0);s.send();this.workingXhr.push(s)}));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")}downloadBlob(e,t){const n=document.createElement("a");const s=URL.createObjectURL(e);n.setAttribute("href",s);n.setAttribute("download",t);document.body.appendChild(n);n.click();n.remove();URL.revokeObjectURL(s)}exportData(e=false){const t=JSON.stringify([{fragments:this.fragments,title:n(true),totalSize:this.fragments.map(e=>e.size).reduce((e,t)=>e+t),referer:document.URL.replace(window.location.search,"")}]);if(e){GM_setClipboard(t,"text")}else{const e=new Blob([t],{type:"text/json"});this.downloadBlob(e,`cid${unsafeWindow.cid}.json`)}}exportAria2(e=false){if(e){}else{const e=`\n# Generated by Bilibili Evolved Video Export\n# https://github.com/the1812/Bilibili-Evolved/\n${this.fragments.map((e,t)=>{let s="";if(this.fragments.length>1){s=" - "+(t+1)}return`\n${e.url}\n referer=${document.URL.replace(window.location.search,"")}\n user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0\n out=${n(true)}${s}.flv\n `.trim()}).join("\n")}\n `.trim();const t=new Blob([e],{type:"text/plain"});this.downloadBlob(t,`${n(true)}.txt`)}}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=document.querySelector("a#video-complete").getAttribute("href");if(e&&!document.querySelector(`.link[href="${e}"]`)){URL.revokeObjectURL(e)}[...document.querySelectorAll(".toast-card-header")].filter(e=>e.innerText.includes("下载视频")).forEach(e=>e.querySelector(".toast-card-dismiss").click())}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 r=s+".zip";return[o,r]}async download(){const e=[];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)}this.cleanUpOldBlobUrl();const s=URL.createObjectURL(t);this.progress&&this.progress(0);return{url:s,filename:n}}}async function u(){const e=["/www.bilibili.com/bangumi","/www.bilibili.com/video/av"];if(!e.some(e=>document.URL.includes(e))){return}const{BatchExtractor:n}=await t.importAsync("batchDownload");if(await n.test()!==true){return}const o=new n;document.getElementById("download-video").classList.add("batch");document.getElementById("video-action-batch-data").addEventListener("click",async()=>{if(!r){return}s.entity.resetMenuClass();const e=Toast.info("获取链接中...","批量下载");const t=await o.collectData(r,e);if(!t){return}GM_setClipboard(t,{type:"text/json"});Toast.success("已复制批量数据到剪贴板.","复制批量数据",3e3)});document.getElementById("video-action-batch-download-data").addEventListener("click",async()=>{if(!r){return}s.entity.resetMenuClass();const e=Toast.info("获取链接中...","批量下载");const t=await o.collectData(r,e);if(!t){return}const n=document.createElement("a");const i=new Blob([t],{type:"text/json"});const a=URL.createObjectURL(i);n.setAttribute("href",a);n.setAttribute("download",`export.json`);document.body.appendChild(n);n.click();n.remove();URL.revokeObjectURL(a)})}async function h(){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 a}else{s.entity=new i}try{o=await l.availableFormats}catch(e){return false}return Boolean(e&&t)}async function p(){r=o[0];const e=async()=>{const e=await h();document.querySelector("#download-video").style.display=e?"flex":"none";if(e===false){return}const t=document.querySelector("ol.video-quality");t.childNodes.forEach(t.removeChild);o.forEach(e=>{const n=document.createElement("li");n.innerHTML=e.displayName;n.addEventListener("click",()=>{r=e;s.entity.nextMenuClass()});t.insertAdjacentElement("afterbegin",n)})};Observer.videoChange(e);const n=()=>r.downloadInfo().catch(e=>{s.entity.addError();$(".video-error").text(e)});async function i(){if(!r){return}s.entity.nextMenuClass();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=>{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 i=`下载完成. <a class="link" href="${t.url}" download="${t.filename.replace(/"/g,"&quot;")}">再次保存</a>`;Toast.success(i,"下载视频");s.entity.closeMenu()}async function a(){if(!r){return}const e=await n();e.copyUrl();Toast.success("已复制链接到剪贴板.","复制链接",3e3);s.entity.closeMenu()}dq("#video-action-download").addEventListener("click",i);dq("#video-action-copy").addEventListener("click",a);dq("#video-action-copy-data").addEventListener("click",async()=>{if(!r){return}const e=await n();e.exportData(true);Toast.success("已复制数据到剪贴板.","复制数据",3e3);s.entity.closeMenu()});dq("#video-action-download-data").addEventListener("click",async()=>{if(!r){return}const e=await n();e.exportData(false);s.entity.closeMenu()});dq("#video-action-aria2").addEventListener("click",async()=>{if(!r){return}const e=await n();e.exportAria2(false);s.entity.closeMenu()});t.applyStyle("downloadVideoStyle");const l=document.querySelector(".download-video-panel");const c=()=>$(".download-video-panel").toggleClass("opened");document.querySelector("#download-video").addEventListener("click",e=>{if(!l.contains(e.target)){c()}});document.querySelector(".video-error").addEventListener("click",()=>{document.querySelector(".video-error").innerHTML="";s.entity.removeError()});await SpinQuery.select(".download-video-panel");s.entity.addMenuClass();u()}return{widget:{content:t.data.downloadVideoHtml.text,condition:h,success:p}}}})();