Bilibili-Evolved/min/download-video.min.js
2019-01-26 15:56:47 +08:00

1 line
7.1 KiB
JavaScript

(()=>{return(e,t)=>{const n={entity:null,aid:undefined,cid:undefined};class s{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=${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 i extends s{async getUrl(e){if(e){return`https://api.bilibili.com/pgc/player/web/playurl?avid=${n.aid}&cid=${n.cid}&qn=${e}&otype=json`}else{return`https://api.bilibili.com/pgc/player/web/playurl?avid=${n.aid}&cid=${n.cid}&qn=&otype=json`}}}class o{constructor(e,t,n){this.quality=e;this.internalName=t;this.displayName=n}async downloadInfo(){const e=new r(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.result||n;const a=i.accept_quality;const r=i.accept_format.split(",");const l=i.accept_description;const c=[];while(a.length>0){const e=new o(a.pop(),r.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 r{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(n=>{const s=new XMLHttpRequest;s.addEventListener("load",()=>{const n=JSON.parse(s.responseText.replace(/http:/g,"https:"));const i=n.data||n.result||n;if(i.quality!==this.format.quality){t("获取下载链接失败, 请确认当前账号有下载权限后重试.")}const o=i.durl;this.fragments=o.map(e=>new a(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 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)+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 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 l(){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.entity=new i}else{n.entity=new s}return Boolean(e&&t)}async function c(){let e=await o.availableFormats;let[s]=e;const i=async()=>{await l();e=await o.availableFormats;const t=$("ol.video-quality");t.html("");e.forEach(e=>{$(`<li>${e.displayName}</li>`).on("click",()=>{s=e;n.entity.nextMenuClass()}).prependTo(t)})};Observer.childList("#bofqi",i);const a=()=>s.downloadInfo().catch(e=>{n.entity.addError();$(".video-error").text(e)});async function r(){if(!s){return}n.entity.nextMenuClass();const e=await a();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 i=document.getElementById("video-complete");i.setAttribute("href",t.url);i.setAttribute("download",t.filename);i.click();const o=`下载完成. <a class="link" href="${t.url}" download="${t.filename.replace(/"/g,"&quot;")}">再次保存</a>`;Toast.success(o,"下载视频");n.entity.resetMenuClass()}async function c(){if(!s){return}const e=await a();e.copyUrl();Toast.success("已复制链接到剪贴板.","复制链接",3e3);n.entity.resetMenuClass()}$(".video-action>#video-action-download").on("click",r);$(".video-action>#video-action-copy").on("click",c);t.applyStyle("downloadVideoStyle");const d=document.querySelector(".download-video-panel");const u=()=>$(".download-video-panel").toggleClass("opened");$("#download-video").on("click",e=>{if(!d.contains(e.target)){u()}});$(".video-error").on("click",()=>{$(".video-error").text("");n.entity.removeError()});await SpinQuery.select(()=>document.querySelector(".download-video-panel"));n.entity.addMenuClass()}return{widget:{content:t.data.downloadVideoDom.text,condition:l,success:c}}}})();