mirror of
https://github.com/the1812/Bilibili-Evolved.git
synced 2025-11-04 21:22:45 +08:00
1 line
13 KiB
JavaScript
1 line
13 KiB
JavaScript
(()=>{return(e,t)=>{const{getFriendlyTitle:n}=t.import("title");const{VideoInfo:s,DanmakuInfo:o}=t.import("video-info");class a{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=${r.aid}&cid=${r.cid}&qn=${e}&otype=json`}else{return`https://api.bilibili.com/x/player/playurl?avid=${r.aid}&cid=${r.cid}&otype=json`}}}class i extends a{async getUrl(e){if(e){return`https://api.bilibili.com/pgc/player/web/playurl?avid=${r.aid}&cid=${r.cid}&qn=${e}&otype=json`}else{return`https://api.bilibili.com/pgc/player/web/playurl?avid=${r.aid}&cid=${r.cid}&qn=&otype=json`}}}const r={entity:new a,aid:"",cid:""};let l=[];let d=null;class c{constructor(e,t,n){this.quality=e;this.internalName=t;this.displayName=n}async downloadInfo(){const e=new p(this);await e.fetchVideoInfo();return e}static get availableFormats(){return new Promise((e,t)=>{r.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 a=o.accept_quality;const i=o.accept_format.split(",");const r=o.accept_description;const l=[];while(a.length>0){const e=new c(a.pop(),i.pop(),r.pop());l.push(e)}e(l.reverse())});s.addEventListener("error",()=>t(`获取清晰度信息失败.`));s.withCredentials=true;s.open("GET",n);s.send()})})}}class u{constructor(e,t,n,s){this.length=e;this.size=t;this.url=n;this.backupUrls=s}}class p{constructor(e,t){this.fragmentSplitFactor=6*5;this.workingXhr=null;this.progressMap=new Map;this.format=e;this.fragments=t||[]}get totalSize(){return this.fragments.map(e=>e.size).reduce((e,t)=>e+t)}fetchVideoInfo(){return new Promise((e,t)=>{r.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 a=o.durl;this.fragments=a.map(e=>new u(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 a=Math.min(e.size-1,Math.round(s+n));const i=`bytes=${s}-${a}`;const r=a-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}/${r} 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")}static downloadBlob(e,t){const n=document.createElement("a");let s;if(typeof e==="string"){s=e}else{s=URL.createObjectURL(e)}n.setAttribute("href",s);n.setAttribute("download",t);document.body.appendChild(n);n.click();n.remove();URL.revokeObjectURL(s)}async exportData(e=false){const t=JSON.stringify([{fragments:this.fragments,title:n(),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"});const s=await this.downloadDanmaku();if(s!==null){const t=new JSZip;t.file(`${n()}.json`,e);t.file(n()+"."+this.danmakuOption.toLowerCase(),s);p.downloadBlob(await t.generateAsync({type:"blob"}),`${n()}.zip`)}else{p.downloadBlob(e,`${n()}.json`)}}}async 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()}${s}.flv\n split=${this.fragmentSplitFactor}\n `.trim()}).join("\n")}\n `.trim();const t=new Blob([e],{type:"text/plain"});const s=await this.downloadDanmaku();if(s!==null){const e=new JSZip;e.file(`${n()}.txt`,t);e.file(n()+"."+this.danmakuOption.toLowerCase(),s);p.downloadBlob(await e.generateAsync({type:"blob"}),`${n()}.zip`)}else{p.downloadBlob(t,`${n()}.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())}async downloadDanmaku(){if(this.danmakuOption!=="无"){const e=new o(parseInt(r.cid));await e.fetchInfo();if(this.danmakuOption==="XML"){return e.rawXML}else{const{convertToAss:n}=await t.importAsync("download-danmaku");return n(e.rawXML)}}else{return null}}async downloadSingle(e){const t=await this.downloadDanmaku();const[s]=e;if(t===null){const e=this.makeBlob(s);const t=n()+this.extension();return{blob:e,filename:t}}else{const e=new JSZip;e.file(n()+this.extension(),this.makeBlob(s));e.file(n()+"."+this.danmakuOption.toLowerCase(),t);const o=await e.generateAsync({type:"blob"});const a=n()+".zip";return{blob:o,filename:a}}}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 this.downloadDanmaku();if(o!==null){t.file(n()+"."+this.danmakuOption.toLowerCase(),o)}const a=await t.generateAsync({type:"blob"});const i=s+".zip";return{blob:a,filename:i}}async download(){const e=[];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 await 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 h(){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(!d){return}r.entity.closeMenu();const e=Toast.info("获取链接中...","批量下载");const t=await o.collectData(d,e);if(!t){return}GM_setClipboard(t,{type:"text/json"});Toast.success("已复制批量数据到剪贴板.","复制批量数据",3e3)});document.getElementById("video-action-batch-download-data").addEventListener("click",async()=>{if(!d){return}r.entity.closeMenu();const e=Toast.info("获取链接中...","批量下载");const t=await o.collectData(d,e);if(!t){return}const n=new Blob([t],{type:"text/json"});p.downloadBlob(n,"export.json")});document.getElementById("video-action-aria2-batch").addEventListener("click",async()=>{if(!d){return}r.entity.closeMenu();const e=Toast.info("获取链接中...","批量下载");const t=await o.collectAria2(d,e);if(!t){return}const s=new Blob([t],{type:"text/plain"});p.downloadBlob(s,`${n(false)}.txt`)})}async function m(){const e=await SpinQuery.select(()=>(unsafeWindow||window).aid);const t=await SpinQuery.select(()=>(unsafeWindow||window).cid);if(!(e&&t)){return false}r.aid=e;r.cid=t;if(document.URL.indexOf("bangumi")!==-1){r.entity=new i}else{r.entity=new a}try{l=await c.availableFormats}catch(e){return false}return true}async function w(){d=l[0];t.applyStyle("downloadVideoStyle");dq("#download-video").addEventListener("click",()=>{dq(".download-video").classList.toggle("opened");dq(".gui-settings-mask").click()});dq("#download-video").addEventListener("mouseover",()=>{document.body.insertAdjacentHTML("beforeend",t.import("downloadVideoHtml"));f()},{once:true});h()}async function f(){Vue.component("v-dropdown",{template:`\n <div class="v-dropdown" v-on:click="toggleDropDown()">\n <span class="selected">{{value}}</span>\n <ul class="dropdown-menu" v-bind:class="{opened: dropdownOpen}">\n <li v-for="item in model.items" v-bind:key="item" v-bind:data-value="item" v-on:click="select(item)">{{item}}</li>\n </ul>\n <i class="mdi mdi-chevron-down"></i>\n </div>\n `,props:["model"],data(){return{dropdownOpen:false}},computed:{value(){return this.model.value}},methods:{toggleDropDown(){this.dropdownOpen=!this.dropdownOpen},select(e){this.model.value=e;this.$emit("change")}}});let t;const o=new Map;const a=new Vue({el:".download-video",data:{downloadSingle:true,coverUrl:"",qualityModel:{value:d.displayName,items:l.map(e=>e.displayName)},danmakuModel:{value:e.downloadVideoDefaultDanmaku,items:["无","XML","ASS"]},progressPercent:0,title:n(false),size:"",blobUrl:"",episodeList:[],downloading:false},mounted(){this.formatChange()},methods:{close(){this.$el.classList.remove("opened")},danmakuOptionChange(){e.downloadVideoDefaultDanmaku=this.danmakuModel.value},async formatChange(){const e=this.getFormat();const t=o.get(e);if(t){this.size=t;return}try{this.size="获取大小中";const t=await e.downloadInfo();const n=t.totalSize;const s=["B","KB","MB","GB","TB","PB","EB","ZB","YB"];let a=n;let i=0;while(a>=1024){a/=1024;i++}const r=`${Math.round(a*10)/10}${s[i]}`;this.size=r;o.set(e,r)}catch(e){this.size="获取大小失败"}},getFormat(){const e=l.find(e=>e.displayName===this.qualityModel.value);if(!e){console.error(`No format found. model value = ${this.qualityModel.value}`);return null}return e},async exportData(e){const t=this.getFormat();const n=await t.downloadInfo();n.danmakuOption=this.danmakuModel.value;switch(e){case"copyLink":n.copyUrl();Toast.success("已复制链接到剪贴板.","下载视频",3e3);break;case"aria2":n.exportAria2(false);break;case"copyVLD":n.exportData(true);Toast.success("已复制VLD数据到剪贴板.","下载视频",3e3);break;case"exportVLD":n.exportData(false);break;default:break}},cancelDownload(){if(t){t.cancelDownload()}},async startDownload(){const e=this.getFormat();try{this.downloading=true;const n=await e.downloadInfo();n.danmakuOption=this.danmakuModel.value;n.progress=(e=>{this.progressPercent=Math.trunc(e*100)});t=n;const s=await n.download();const o=document.getElementById("video-complete");o.setAttribute("href",s.url);o.setAttribute("download",s.filename);o.click();Toast.success(`下载完成: ${s.filename} <a class="link" href="${s.url}" download="${s.filename.replace(/"/g,""")}">再次保存</a>`,"下载视频")}catch(e){if(e!=="下载已取消."){logError(e)}this.progressPercent=0}finally{this.downloading=false}}}});const i=new s(parseInt(r.aid));await i.fetchInfo();a.coverUrl=i.coverUrl.replace("http:","https:")}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:m,success:w}}}})(); |