Bilibili-Evolved/min/download-video.min.js
2019-07-13 16:48:25 +08:00

1 line
11 KiB
JavaScript

(()=>{return(e,t)=>{const{getFriendlyTitle:n}=t.import("title");class s{constructor(){this.menuClasses=["quality","action","progress"];[this.currentMenuClass]=this.menuClasses}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=${i.aid}&cid=${i.cid}&qn=${e}&otype=json`}else{return`https://api.bilibili.com/x/player/playurl?avid=${i.aid}&cid=${i.cid}&otype=json`}}}class o extends s{async getUrl(e){if(e){return`https://api.bilibili.com/pgc/player/web/playurl?avid=${i.aid}&cid=${i.cid}&qn=${e}&otype=json`}else{return`https://api.bilibili.com/pgc/player/web/playurl?avid=${i.aid}&cid=${i.cid}&qn=&otype=json`}}}const i={entity:new s,aid:"",cid:""};let r=[];let a=null;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)=>{i.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 i=o.accept_quality;const r=o.accept_format.split(",");const a=o.accept_description;const c=[];while(i.length>0){const e=new l(i.pop(),r.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.fragmentSplitFactor=6*5;this.workingXhr=null;this.totalSize=0;this.progressMap=new Map;this.format=e;this.fragments=t||[]}fetchVideoInfo(){return new Promise((e,t)=>{i.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 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(this.workingXhr!==null){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 i=Math.min(e.size-1,Math.round(s+n));const r=`bytes=${s}-${i}`;const a=i-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, ${r}`);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)}下载失败: ${r}`);this.progressMap.set(s,0);this.updateProgress();s.open("GET",e.url);s.setRequestHeader("Range",r);s.send()});s.setRequestHeader("Range",r);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")}static 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"});d.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 split=${this.fragmentSplitFactor}\n `.trim()}).join("\n")}\n `.trim();const t=new Blob([e],{type:"text/plain"});d.downloadBlob(t,`${n(true)}.txt`)}}extension(e){return(e||this.fragments[0]).url.indexOf(".flv")!==-1?".flv":".mp4"}makeBlob(e,t){return new Blob(Array.isArray(e)?e:[e],{type:this.extension(t)===".flv"?"video/x-flv":"video/mp4"})}cleanUpOldBlobUrl(){const e=dq("a#video-complete").getAttribute("href");if(e&&!dq(`.link[href="${e}"]`)){URL.revokeObjectURL(e)}dqa(".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{blob:s,filename: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{blob:o,filename:i}}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{blob:t,filename:n}=await(async()=>{if(e.length===1){return this.downloadSingle(e)}else{return 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:s}=await t.importAsync("batch-download");if(await s.test()!==true){return}const o=new s;document.getElementById("download-video").classList.add("batch");document.getElementById("video-action-batch-data").addEventListener("click",async()=>{if(!a){return}i.entity.closeMenu();const e=Toast.info("获取链接中...","批量下载");const t=await o.collectData(a,e);if(!t){return}GM_setClipboard(t,{type:"text/json"});Toast.success("已复制批量数据到剪贴板.","复制批量数据",3e3)});document.getElementById("video-action-batch-download-data").addEventListener("click",async()=>{if(!a){return}i.entity.closeMenu();const e=Toast.info("获取链接中...","批量下载");const t=await o.collectData(a,e);if(!t){return}const n=new Blob([t],{type:"text/json"});d.downloadBlob(n,"export.json")});document.getElementById("video-action-aria2-batch").addEventListener("click",async()=>{if(!a){return}i.entity.closeMenu();const e=Toast.info("获取链接中...","批量下载");const t=await o.collectAria2(a,e);if(!t){return}const s=new Blob([t],{type:"text/plain"});d.downloadBlob(s,`${n(false)}.txt`)})}async function p(){const e=await SpinQuery.select(()=>(unsafeWindow||window).aid);const t=await SpinQuery.select(()=>(unsafeWindow||window).cid);if(!(e&&t)){return false}i.aid=e;i.cid=t;if(document.URL.indexOf("bangumi")!==-1){i.entity=new o}else{i.entity=new s}try{r=await l.availableFormats}catch(e){return false}return true}async function h(){a=r[0];const e=async()=>{const e=await p();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);r.forEach(e=>{const n=document.createElement("li");n.innerHTML=e.displayName;n.addEventListener("click",()=>{a=e;i.entity.nextMenuClass()});t.insertAdjacentElement("afterbegin",n)})};Observer.videoChange(e);const n=()=>a.downloadInfo().catch(e=>{i.entity.addError();dq(".video-error").innerHTML=e});async function s(){if(!a){return}i.entity.nextMenuClass();const e=await n();if(!e){return}e.progress=(e=>{dq(".download-progress-value").innerHTML=`${fixed(e*100)}`;dq(".download-progress-foreground").style.transform=`scaleX(${e})`});dq(".download-progress-cancel>span").onclick=(()=>e.cancelDownload());const t=await e.download().catch(e=>{i.entity.addError();dq(".video-error").innerHTML=e});if(!t){return}const s=document.getElementById("video-complete");s.setAttribute("href",t.url);s.setAttribute("download",t.filename);s.click();const o=`下载完成. <a class="link" href="${t.url}" download="${t.filename.replace(/"/g,"&quot;")}">再次保存</a>`;Toast.success(o,"下载视频");i.entity.closeMenu()}async function o(){if(!a){return}const e=await n();if(!e){return}e.copyUrl();Toast.success("已复制链接到剪贴板.","复制链接",3e3);i.entity.closeMenu()}dq("#video-action-download").addEventListener("click",s);dq("#video-action-copy").addEventListener("click",o);dq("#video-action-copy-data").addEventListener("click",async()=>{if(!a){return}const e=await n();if(!e){return}e.exportData(true);Toast.success("已复制数据到剪贴板.","复制数据",3e3);i.entity.closeMenu()});dq("#video-action-download-data").addEventListener("click",async()=>{if(!a){return}const e=await n();if(!e){return}e.exportData(false);i.entity.closeMenu()});dq("#video-action-aria2").addEventListener("click",async()=>{if(!a){return}const e=await n();if(!e){return}e.exportAria2(false);i.entity.closeMenu()});t.applyStyle("downloadVideoStyle");const l=document.querySelector(".download-video-panel");const c=()=>dq(".download-video-panel").classList.toggle("opened");dq("#download-video").addEventListener("click",e=>{if(!l.contains(e.target)){c()}});document.querySelector(".video-error").addEventListener("click",()=>{document.querySelector(".video-error").innerHTML="";i.entity.removeError()});await SpinQuery.select(".download-video-panel");i.entity.addMenuClass();u()}return{widget:{content:`\n <button class="gui-settings-flat-button" style="position: relative; z-index: 100;" id="download-video">\n <i class="icon-download"></i>\n <span>下载视频</span>\n </button>`,condition:p,success:h}}}})();