diff --git a/bilibili-evolved.offline.user.js b/bilibili-evolved.offline.user.js index 8202ec72f..461e286c2 100644 --- a/bilibili-evolved.offline.user.js +++ b/bilibili-evolved.offline.user.js @@ -1,6 +1,6 @@ // ==UserScript== // @name Bilibili Evolved (Offline) -// @version 371.19 +// @version 371.22 // @description Bilibili Evolved 的离线版, 所有功能都已内置于脚本中. // @author Grant Howard, Coulomb-G // @copyright 2019, Grant Howard (https://github.com/the1812) & Coulomb-G (https://github.com/Coulomb-G) @@ -960,7 +960,7 @@ offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/m offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/about.min.js"] = (()=>{return(t,e)=>{(async()=>{const i=await e.importAsync("aboutHtml");document.body.insertAdjacentHTML("beforeend",i);const o=(t,e)=>t.charCodeAt(0)-e.charCodeAt(0);const n=(t,e)=>o(t.name,e.name);const s=GM_info.script.name.match(/Bilibili Evolved \((.*)\)/);const a=s?s[1]:"Stable";new Vue({el:".bilibili-evolved-about",data:{version:t.currentVersion,clientType:a,logoImage:null,logoImageDark:null,branch:null,authors:[{name:"Grant Howard",link:"https://github.com/the1812"},{name:"Coulomb-G",link:"https://github.com/Coulomb-G"}],contributors:[{name:"PleiadeSubaru",link:"https://github.com/Etherrrr"}].sort(n),fetching:true,participants:[],supporters:["*飞","N*v","*博睿","*杨","*泽鹏"].sort(o),websites:[{name:"GitHub",link:"https://github.com/the1812/Bilibili-Evolved/"},{name:"Greasy Fork",link:"https://greasyfork.org/zh-CN/scripts/373563-bilibili-evolved"}],components:[{name:"Vue.js",link:"https://cn.vuejs.org/index.html"},{name:"JSZip",link:"https://stuk.github.io/jszip/"},{name:"jQuery",link:"http://jquery.com/"},{name:"debounce",link:"https://github.com/component/debounce/"},{name:"Slip.js",link:"https://github.com/kornelski/slip"},{name:"MDI",link:"https://materialdesignicons.com"}]},mounted(){document.querySelector(".bilibili-evolved-about").addEventListener("be:about-load",()=>{this.init()},{once:true})},methods:{async getLogos(){this.logoImage=await Ajax.getText(`https://raw.githubusercontent.com/the1812/Bilibili-Evolved/preview/images/bilibili-evolved-wide.svg`);this.logoImageDark=await Ajax.getText(`https://raw.githubusercontent.com/the1812/Bilibili-Evolved/preview/images/bilibili-evolved-wide-dark.svg`)},async init(){this.branch=/Preview|Local/.test(a)?"preview":"master";this.getLogos();const t=new Set;let e=[];let i=1;do{e=await Ajax.getJson(`https://api.github.com/repos/the1812/Bilibili-Evolved/issues?state=all&direction=asc&per_page=100&page=${i}`).catch(()=>{e=[{name:"电波无法到达(´・_・`)",link:null}]});i++;for(const i of e){t.add(i.user.login)}}while(e.length>0);this.participants=[...t].map(t=>{return{name:t,link:`https://github.com/${t}`}}).filter(({link:t})=>{return!this.authors.some(e=>e.link===t)&&!this.contributors.some(e=>e.link===t)}).sort(n);this.fetching=false}}})})()}})(); offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/auto-continue.min.js"] = (()=>{return(e,i)=>{if(typeof isEmbeddedPlayer!=="undefined"&&isEmbeddedPlayer()){return}function t(i){const t=i.text();if(/第(\d+)话/.test(t)){if(e.allowJumpContinue){i.parent().find(".bilibili-player-video-toast-item-jump").click()}return}const n=/((\d)*:)?(\d)*:(\d)*/g;const r=t.match(n);if(!r){return}const o=r[0].split(":");const l=(()=>{if(o.length===3){const[e,i,t]=o.map(e=>parseInt(e));return e*60*60+i*60+t}else if(o.length===2){const[e,i]=o.map(e=>parseInt(e));return e*60+i}else{logError(`解析历史时间发生错误: historyTime=${JSON.stringify(o)}`);return NaN}})();const s=i.parent();const a=document.querySelector("video");if(l从头开始`);e.appendTo(s).on("click",()=>{a.currentTime=0;s.find(".bilibili-player-video-toast-item-close").get(0).click()});i.html(`已跳转到上次历史记录${r[0]}`)}else{s.find(".bilibili-player-video-toast-item-close").get(0).click()}}function n(){SpinQuery.condition(()=>$(".bilibili-player-video-toast-item-text"),e=>e.text().indexOf("上次看到")!==-1,e=>t(e.filter((e,i)=>i.innerText.indexOf("上次看到")!==-1)))}Observer.videoChange(n)}})(); offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/auto-play.min.js"] = (()=>{return(e,d)=>{if(typeof isEmbeddedPlayer!=="undefined"&&isEmbeddedPlayer()){return}SpinQuery.condition(()=>document.querySelector(".bilibili-player-video video"),e=>e&&e.paused===true,e=>e.play())}})(); -offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/batch-download.min.js"] = (()=>{return(t,e)=>{const i=12;class r{constructor(){this.itemList=[];this.itemFilter=(()=>true)}async getItemList(){}async collectData(){}async collectAria2(e,r){const s=JSON.parse(await this.collectData(e));if(r){const e=t.aria2RpcOption;const r=e.host.startsWith("http://")?e.host:"http://"+e.host;const n="aria2.addUri";for(const t of s){const s=t.fragments.map((r,s)=>{let n="";if(t.fragments.length>1){n=" - "+(s+1)}const a=[];if(e.secretKey!==""){a.push(`token:${e.secretKey}`)}a.push([r.url]);a.push({referer:document.URL.replace(window.location.search,""),"user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0",out:`${t.title}${n}.flv`,split:i,dir:e.dir});const o=window.btoa(unescape(encodeURIComponent(JSON.stringify(a))));const c=`${t.title}${n}`;return{base64Params:o,id:c}});for(const t of s){try{const i=await Ajax.getJson(`${r}:${e.port}/jsonrpc?method=${n}&id=${t.id}¶ms=${t.base64Params}`);if(i.error!==undefined){if(i.error.code===1){logError(`请求遭到拒绝, 请检查您的密钥相关设置.`)}else{logError(`请求发生错误, code = ${i.error.code}, message = ${i.error.message}`)}return}}catch(t){logError(`无法连接到RPC主机, error = ${t}`);return}}}}else{return`\n# Generated by Bilibili Evolved Video Export\n# https://github.com/the1812/Bilibili-Evolved/\n${s.map(t=>{return t.fragments.map(e=>{return`\n${e.url}\n referer=${t.referer}\n user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0\n out=${t.title}.flv\n split=${i}\n `.trim()})}).join("\n")}\n `.trim()}}}class s extends r{static async test(){if(!document.URL.includes("/www.bilibili.com/video/av")){return false}return await SpinQuery.select("#multi_page")!==null}async getItemList(){if(this.itemList.length>0){return this.itemList}const t=`https://api.bilibili.com/x/web-interface/view?aid=${unsafeWindow.aid}`;const e=await Ajax.getJson(t);if(e.code!==0){Toast.error(`获取视频选集列表失败, message=${e.message}`,"批量下载");return""}const i=e.data.pages;if(i===undefined){Toast.error(`获取视频选集列表失败, 没有找到选集信息.`,"批量下载");return""}this.itemList=i.map(t=>{return{title:`P${t.page} ${t.part}`,cid:t.cid,aid:unsafeWindow.aid}});return this.itemList}async collectData(t){const e=[];for(const i of(await this.getItemList()).filter(this.itemFilter)){const r=`https://api.bilibili.com/x/player/playurl?avid=${i.aid}&cid=${i.cid}&qn=${t}&otype=json`;const s=await Ajax.getJsonWithCredentials(r);const n=s.data||s.result||s;if(n.quality!==t){Toast.error("获取下载链接失败, 请确认当前账号有下载权限后重试.","批量下载");return""}const a=n.durl.map(t=>{return{length:t.length,size:t.size,url:t.url}});e.push({fragments:a,title:i.title,totalSize:a.map(t=>t.size).reduce((t,e)=>t+e),cid:i.cid,referer:document.URL.replace(window.location.search,"")})}return JSON.stringify(e)}}class n extends r{static async test(){return document.URL.includes("/www.bilibili.com/bangumi")}async getItemList(){if(this.itemList.length>0){return this.itemList}const t=document.querySelector("meta[property='og:url']");if(t===null){Toast.error("获取番剧数据失败: 无法找到 Season ID","批量下载");return""}const e=t.getAttribute("content").match(/play\/ss(\d+)/)[1];if(e===undefined){Toast.error("获取番剧数据失败: 无法解析 Season ID","批量下载");return""}const i=await Ajax.getJson(`https://api.bilibili.com/pgc/web/season/section?season_id=${e}`);if(i.code!==0){Toast.error(`获取番剧数据失败: 无法获取番剧集数列表, message=${i.message}`,"批量下载");return""}this.itemList=i.result.main_section.episodes.map((t,e)=>{return{aid:t.aid,cid:t.cid,title:t.long_title?`${t.title} - ${t.long_title}`:`${e+1} - ${t.title}`}});return this.itemList}async collectData(t){const e=[];for(const i of(await this.getItemList()).filter(this.itemFilter)){const r=`https://api.bilibili.com/pgc/player/web/playurl?avid=${i.aid}&cid=${i.cid}&qn=${t}&otype=json`;const s=await Ajax.getJsonWithCredentials(r);const n=s.data||s.result||s;if(n.quality!==t){Toast.error("获取下载链接失败, 请确认当前账号有下载权限后重试.","批量下载");return""}const a=n.durl.map(t=>{return{length:t.length,size:t.size,url:t.url}});e.push({fragments:a,title:i.title,totalSize:a.map(t=>t.size).reduce((t,e)=>t+e),cid:i.cid,referer:document.URL.replace(window.location.search,"")})}return JSON.stringify(e)}}const a=[n,s];let o=null;class c{constructor(){this.itemFilter=(()=>true)}static async test(){for(const t of a){if(await t.test()===true){o=t;return true}}o=null;return false}getExtractor(){if(o===null){logError("[批量下载] 未找到合适的解析模块.");throw new Error(`[Batch Download] module not found.`)}const t=new o;t.itemFilter=this.itemFilter;return t}async getItemList(){const t=this.getExtractor();return await t.getItemList()}async collectData(t,e){const i=this.getExtractor();const r=await i.collectData(t.quality);e.dismiss();return r}async collectAria2(t,e,i){const r=this.getExtractor();const s=await r.collectAria2(t.quality,i);e.dismiss();return s}}return{export:{BatchExtractor:c}}}})(); +offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/batch-download.min.js"] = (()=>{return(t,e)=>{const i=12;class r{constructor(){this.itemList=[];this.itemFilter=(()=>true)}async getItemList(){}async collectData(){}async collectAria2(e,r){const s=JSON.parse(await this.collectData(e));if(r){const e=t.aria2RpcOption;const r=e.host.match(/^http[s]?:\/\//)?e.host:"http://"+e.host;const n="aria2.addUri";for(const t of s){const s=t.fragments.map((r,s)=>{let n="";if(t.fragments.length>1){n=" - "+(s+1)}const a=[];if(e.secretKey!==""){a.push(`token:${e.secretKey}`)}a.push([r.url]);a.push({referer:document.URL.replace(window.location.search,""),"user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0",out:`${t.title}${n}.flv`,split:i,dir:e.dir});const o=window.btoa(unescape(encodeURIComponent(JSON.stringify(a))));const c=`${t.title}${n}`;return{base64Params:o,id:c}});for(const t of s){try{const i=await Ajax.getJson(`${r}:${e.port}/jsonrpc?method=${n}&id=${t.id}¶ms=${t.base64Params}`);if(i.error!==undefined){if(i.error.code===1){logError(`请求遭到拒绝, 请检查您的密钥相关设置.`)}else{logError(`请求发生错误, code = ${i.error.code}, message = ${i.error.message}`)}return}}catch(t){logError(`无法连接到RPC主机, error = ${t}`);return}}}}else{return`\n# Generated by Bilibili Evolved Video Export\n# https://github.com/the1812/Bilibili-Evolved/\n${s.map(t=>{return t.fragments.map(e=>{return`\n${e.url}\n referer=${t.referer}\n user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0\n out=${t.title}.flv\n split=${i}\n `.trim()})}).join("\n")}\n `.trim()}}}class s extends r{static async test(){if(!document.URL.includes("/www.bilibili.com/video/av")){return false}return await SpinQuery.select("#multi_page")!==null}async getItemList(){if(this.itemList.length>0){return this.itemList}const t=`https://api.bilibili.com/x/web-interface/view?aid=${unsafeWindow.aid}`;const e=await Ajax.getJson(t);if(e.code!==0){Toast.error(`获取视频选集列表失败, message=${e.message}`,"批量下载");return""}const i=e.data.pages;if(i===undefined){Toast.error(`获取视频选集列表失败, 没有找到选集信息.`,"批量下载");return""}this.itemList=i.map(t=>{return{title:`P${t.page} ${t.part}`,cid:t.cid,aid:unsafeWindow.aid}});return this.itemList}async collectData(t){const e=[];for(const i of(await this.getItemList()).filter(this.itemFilter)){const r=`https://api.bilibili.com/x/player/playurl?avid=${i.aid}&cid=${i.cid}&qn=${t}&otype=json`;const s=await Ajax.getJsonWithCredentials(r);const n=s.data||s.result||s;if(n.quality!==t){Toast.error("获取下载链接失败, 请确认当前账号有下载权限后重试.","批量下载");return""}const a=n.durl.map(t=>{return{length:t.length,size:t.size,url:t.url}});e.push({fragments:a,title:i.title,totalSize:a.map(t=>t.size).reduce((t,e)=>t+e),cid:i.cid,referer:document.URL.replace(window.location.search,"")})}return JSON.stringify(e)}}class n extends r{static async test(){return document.URL.includes("/www.bilibili.com/bangumi")}async getItemList(){if(this.itemList.length>0){return this.itemList}const t=document.querySelector("meta[property='og:url']");if(t===null){Toast.error("获取番剧数据失败: 无法找到 Season ID","批量下载");return""}const e=t.getAttribute("content").match(/play\/ss(\d+)/)[1];if(e===undefined){Toast.error("获取番剧数据失败: 无法解析 Season ID","批量下载");return""}const i=await Ajax.getJson(`https://api.bilibili.com/pgc/web/season/section?season_id=${e}`);if(i.code!==0){Toast.error(`获取番剧数据失败: 无法获取番剧集数列表, message=${i.message}`,"批量下载");return""}this.itemList=i.result.main_section.episodes.map((t,e)=>{return{aid:t.aid,cid:t.cid,title:t.long_title?`${t.title} - ${t.long_title}`:`${e+1} - ${t.title}`}});return this.itemList}async collectData(t){const e=[];for(const i of(await this.getItemList()).filter(this.itemFilter)){const r=`https://api.bilibili.com/pgc/player/web/playurl?avid=${i.aid}&cid=${i.cid}&qn=${t}&otype=json`;const s=await Ajax.getJsonWithCredentials(r);const n=s.data||s.result||s;if(n.quality!==t){Toast.error("获取下载链接失败, 请确认当前账号有下载权限后重试.","批量下载");return""}const a=n.durl.map(t=>{return{length:t.length,size:t.size,url:t.url}});e.push({fragments:a,title:i.title,totalSize:a.map(t=>t.size).reduce((t,e)=>t+e),cid:i.cid,referer:document.URL.replace(window.location.search,"")})}return JSON.stringify(e)}}const a=[n,s];let o=null;class c{constructor(){this.itemFilter=(()=>true)}static async test(){for(const t of a){if(await t.test()===true){o=t;return true}}o=null;return false}getExtractor(){if(o===null){logError("[批量下载] 未找到合适的解析模块.");throw new Error(`[Batch Download] module not found.`)}const t=new o;t.itemFilter=this.itemFilter;return t}async getItemList(){const t=this.getExtractor();return await t.getItemList()}async collectData(t,e){const i=this.getExtractor();const r=await i.collectData(t.quality);e.dismiss();return r}async collectAria2(t,e,i){const r=this.getExtractor();const s=await r.collectAria2(t.quality,i);e.dismiss();return s}}return{export:{BatchExtractor:c}}}})(); offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/biliplus-redirect.min.js"] = (()=>{return(i,e)=>{const n=`hd.biliplus.com`;const c=["bilibili.com/video/av","bilibili.com/bangumi/play","bilibili.com/bangumi/media","space.bilibili.com"];return{widget:{condition:()=>{return c.some(i=>document.URL.includes(i))},content:`\n `,success:()=>{const i=document.querySelector("#biliplus-redirect");i.addEventListener("click",()=>{if(location.host==="space.bilibili.com"){location.assign(document.URL.replace("space.bilibili.com/",`${n}/space/`))}else if(document.URL.includes("/bangumi/")){const i=unsafeWindow.aid||document.querySelector(".av-link,.info-sec-av").innerText.replace(/[aAvV]/g,"");location.assign(`https://${n}/video/av${i}/`)}else{location.host=n}})}}}}})(); offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/blur-video-control.min.css"] = `.video-control-blur-layer{width:100%;height:100%;position:absolute;-webkit-backdrop-filter:blur(48px);backdrop-filter:blur(48px);z-index:-1;top:0}.bilibili-player-video-control-mask{background:0 0!important}.bilibili-player-video-control-bottom,.bui-slider .bui-track.bui-track-video-progress .bui-bar-wrap{background-color:transparent!important}.bilibili-player-video-control-bottom{position:relative}.bilibili-player-area .bilibili-player-video-control-bottom,.bilibili-player-area .bilibili-player-video-control-wrap{transition:none!important}`; offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/blur-video-control.min.js"] = (()=>{return(o,e)=>{const l=async()=>{const o=await SpinQuery.count(".bui-slider .bui-track.bui-track-video-progress,.bilibili-player-video-control-bottom",2);o.forEach(o=>{if(!o.classList.contains("video-control-blur-container")){o.classList.add("video-control-blur-container");o.insertAdjacentHTML("afterbegin",`
`)}})};e.applyStyle("blurVideoControlStyle");Observer.videoChange(l);return{reload:()=>{document.querySelectorAll(".video-control-blur-layer").forEach(o=>o.style.display="block");e.applyStyle("blurVideoControlStyle")},unload:()=>{document.querySelectorAll(".video-control-blur-layer").forEach(o=>o.style.display="none");e.removeStyle("blurVideoControlStyle")}}}})(); @@ -993,7 +993,7 @@ offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/m offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/download-danmaku.min.js"] = (()=>{return(t,e)=>{const{getFriendlyTitle:n}=e.import("title");const{DanmakuInfo:i}=e.import("video-info");const{DanmakuConverter:a}=e.import("danmaku-converter");async function o(t){const e=n();let i={title:e};try{await loadDanmakuSettingsPanel();const t=t=>{const e=parseFloat(dq(t).style.transform.replace(/translateX\(([\d\.]+)/,"$1"));const n={0:0,44:1,94:2,144:3,188:4}[e];return n};i.font=dq(".bilibili-player-video-danmaku-setting-right-font .bui-select-result").innerText;i.alpha=parseFloat(dq(".bilibili-player-setting-opacity .bui-bar").style.transform.replace(/scaleX\(([\d\.]+)\)/,"$1"));i.duration=(()=>{const e=[18,14,10,8,6][t(".bilibili-player-setting-speedplus .bui-thumb")];return t=>{switch(t.type){case 4:case 5:return 4;default:return e}}})();i.blockTypes=(()=>{let t=[];const e={".bilibili-player-block-filter-type[ftype=scroll]":[1,2,3],".bilibili-player-block-filter-type[ftype=top]":[5],".bilibili-player-block-filter-type[ftype=bottom]":[4],".bilibili-player-block-filter-type[ftype=color]":["color"]};for(const[n,i]of Object.entries(e)){if(dq(n).classList.contains("disabled")){t=t.concat(i)}}return t.concat(7,8)})();const e=[1.4,1.2,1,.8,.6][t(".bilibili-player-setting-fontsize .bui-thumb")];i.resolution={x:1920*e,y:1080*e};i.bottomMarginPercent=[.75,.5,.25,0,0][t(".bilibili-player-setting-area .bui-thumb")];if(i.bottomMarginPercent===0&&dq(".bilibili-player-video-danmaku-setting-left-preventshade input").checked){i.bottomMarginPercent=.15}i.bold=dq(".bilibili-player-video-danmaku-setting-right-font-bold input").checked}catch(t){i={font:"微软雅黑",alpha:.6,duration:t=>{switch(t.type){case 4:case 5:return 4;default:return 6}},blockTypes:[7,8],resolution:{x:1920,y:1080},bottomMarginPercent:.15,bold:false}}const o=new a(i);const l=o.convertToAssDocument(t);return l.generateAss()}async function l(t,e){const a=n();const l=new i((unsafeWindow||window).cid);await l.fetchInfo();const r=await(async()=>{if(t===true){return new Blob([await o(l.rawXML)],{type:"text/plain"})}else{return new Blob([l.rawXML],{type:"text/plain"})}})();const s=URL.createObjectURL(r);const c=dq("#danmaku-link");const d=c.getAttribute("href");if(d){URL.revokeObjectURL(d)}clearTimeout(e);dq("#download-danmaku>span").innerHTML="下载弹幕";c.setAttribute("download",`${a}.${t?"ass":"xml"}`);c.setAttribute("href",s);c.click()}return{export:{downloadDanmaku:l,convertToAss:o},widget:{content:`\n \n \n 下载弹幕\n \n `,condition:async()=>{let t=await SpinQuery.select(()=>(unsafeWindow||window).cid);return Boolean(t)},success:()=>{const t=document.querySelector("#danmaku-link");dq("#download-danmaku").addEventListener("click",e=>{if(e.target!==t){const t=setTimeout(()=>dq("#download-danmaku>span").innerHTML="请稍侯...",200);l(e.shiftKey,t)}})}}}}})(); offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/download-video.min.css"] = `.download-video.opened{pointer-events:initial;opacity:1;transform:translate(-50%,-50%) scale(1)}.download-video{--download-video-background:white;--download-video-foreground:black;position:fixed;top:50%;left:50%;transform:translate(-50%,-50%) scale(.95);background:var(--download-video-background);color:var(--download-video-foreground);box-shadow:rgba(0,0,0,.2) 0 4px 8px 0;z-index:10001;pointer-events:none;opacity:0;padding:16px;width:300px;display:flex;flex-direction:column;align-items:stretch;justify-content:space-between}body.dark .download-video{--download-video-background:#222;--download-video-foreground:#eee}.round-corner .download-video,.round-corner .download-video .episode-list .v-checkbox,.round-corner .download-video .rpc-settings{border-radius:var(--large-corner-radius)}.round-corner .download-video .button,.round-corner .download-video .cover,.round-corner .download-video .direct-download .progress .background,.round-corner .download-video .direct-download .progress .foreground,.round-corner .download-video .rpc-settings input[type=text],.round-corner .download-video .title,.round-corner .download-video button,.round-corner .v-dropdown,.round-corner .v-dropdown .dropdown-menu,.round-corner .v-dropdown .dropdown-menu li{border-radius:var(--corner-radius)}.download-video,.download-video *{transition:.2s ease-out;-webkit-tap-highlight-color:transparent!important}.download-video .cover{width:240px;min-height:135px;background-color:#8882}.download-video .header{display:flex;justify-content:space-between;align-items:center}.download-video h1{font-size:16pt;font-weight:700;color:var(--download-video-foreground)}.download-video i.mdi.mdi-close{font-size:16pt;color:var(--download-video-foreground);cursor:pointer}.download-video i.mdi.mdi-close:hover{color:var(--theme-color)}.download-video .info{display:flex;flex-direction:column;align-items:center;margin-top:12px}.download-video .title{display:flex;flex-direction:column;justify-content:space-between;align-items:stretch;margin-top:12px}.download-video .bold{color:var(--download-video-foreground);font-weight:700;font-size:12pt}.download-video .title .bold{width:300px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;text-align:center}.download-video .title .size{font-size:10pt;color:var(--download-video-foreground);align-self:center;display:flex;align-items:center;height:24px}.download-video .option-item{display:flex;justify-content:space-between;align-items:center;padding-top:12px;font-size:10pt}.v-dropdown{position:relative;background-color:#8884;cursor:pointer;display:flex;align-items:center;justify-content:space-between;min-width:100px}.v-dropdown .dropdown-menu{transform-origin:top;transform:scaleY(0) translateX(-50%);position:absolute;top:calc(100% + 2px);left:50%;background-color:var(--download-video-background);z-index:1;transition:.2s cubic-bezier(.6,-.28,.74,.05);box-shadow:rgba(0,0,0,.2) 0 4px 8px 0}.v-dropdown .dropdown-menu.opened{transform:scaleY(1) translateX(-50%);transition-timing-function:cubic-bezier(.18,.89,.32,1.28)}.v-dropdown .dropdown-menu li{padding:4px 8px;white-space:nowrap;min-width:80px;text-align:center;cursor:pointer;color:var(--download-video-foreground);background-color:transparent}.v-dropdown .dropdown-menu li:hover{background-color:rgba(0,0,0,.16)}.v-dropdown .mdi-chevron-down{font-size:16pt;line-height:1;transform:rotate(0)}.v-dropdown .dropdown-menu.opened~.mdi-chevron-down{transform:rotate(180deg)}.v-dropdown .selected{user-select:none;padding:4px 8px}.download-video .tabs{display:flex;padding-top:12px;font-size:10pt}.download-video .tabs .tab{padding:6px 12px;border-bottom:2px solid transparent;cursor:pointer}.download-video .tab.active{color:var(--theme-color);border-bottom-color:var(--theme-color)}.download-video .separator{height:1px;background:#8884;width:100%;margin:12px 0}.download-video h2{font-size:12pt;font-weight:700;color:var(--download-video-foreground)}.download-video .direct-download{display:flex;flex-direction:column;align-items:start;justify-content:space-between}.download-video .button,.download-video button{border:none;outline:0!important;padding:6px 16px;font-size:10pt;cursor:pointer;background:#8884;color:var(--download-video-foreground)}.download-video .button:hover,.download-video button:hover{background:#8886}.download-video .primary{background:var(--theme-color);color:var(--foreground-color);align-self:center}.download-video .primary:hover{background:var(--theme-color-90)}.download-video .busy .button,.download-video .busy .primary,.download-video .busy button,.download-video button:disabled{background-color:#0001;color:#8884;cursor:not-allowed}.download-video .busy .button,.download-video .busy button{cursor:wait!important}.download-video .direct-download .progress{align-self:stretch;display:flex;align-items:center;margin-top:8px}.download-video .direct-download .progress .background{flex-grow:1;height:4px;background:#8884;margin-right:4px;position:relative}.download-video .direct-download .progress .foreground{position:absolute;top:0;left:0;height:4px;background:linear-gradient(to right,var(--theme-color),var(--theme-color-60))}body.dark .download-video .direct-download .progress .foreground{background:linear-gradient(to right,var(--theme-color-70),var(--theme-color))}.download-video .direct-download .progress .percent{width:50px;text-align:right}.download-video .actions{display:flex;flex-wrap:wrap;justify-content:space-between;margin-top:8px}.download-video .actions>*{margin:4px;flex-grow:1;flex-basis:calc(50% - 16px);display:flex;justify-content:center;align-items:center}.download-video i.mdi-alert-circle{font-size:14pt;color:#ff9800}.download-video .size-warning{position:relative;padding:0 8px}.download-video .size-warning-tip{position:absolute;bottom:100%;left:50%;transform:translateX(-50%);background:var(--download-video-background);color:var(--download-video-foreground);border:1px dashed var(--theme-color);z-index:2;font-size:10pt;width:300px;padding:8px;box-shadow:rgba(0,0,0,.2) 0 4px 8px 0;pointer-events:none;opacity:0}.download-video .size-warning:hover .size-warning-tip{opacity:1}.download-video .episode-list .v-checkbox{padding:4px 8px;margin:4px 0;position:relative;background-color:transparent}.download-video .episode-list .v-checkbox.checked{background-color:#8882}.v-checkbox{font-size:10pt;cursor:pointer;display:flex;align-items:center}.v-checkbox .mdi{font-size:15pt;line-height:1}.v-checkbox .content{flex-grow:1;text-align:left;padding:0 8px}.v-checkbox .mdi-checkbox-marked-circle{color:var(--theme-color);position:absolute;top:0;left:0;transform:scale(0);transition-timing-function:cubic-bezier(.6,-.28,.74,.05)}.v-checkbox .mdi-checkbox-blank-circle-outline{color:#8884;position:relative}.v-checkbox.checked .mdi-checkbox-blank-circle-outline{color:var(--theme-color)}.v-checkbox.checked .mdi-checkbox-marked-circle{transform:scale(1);transition-timing-function:cubic-bezier(.18,.89,.32,1.28)}.download-video .episode-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:12px}.download-video .episode-list{overflow:auto;max-height:320px}.download-video button.list-tool{padding:4px;line-height:1;font-size:12pt;margin:0 4px}.download-video .episode-header h2{flex-grow:1}.download-video .selected-count{width:64px;text-align:right}.download-video .aria2-rpc .mdi{margin-left:8px;font-size:14pt;line-height:1}.download-video .aria2-rpc{position:relative}.download-video .rpc-settings{position:absolute;display:flex;flex-direction:column;align-items:center;color:var(--download-video-foreground);background:var(--download-video-background);bottom:120%;left:50%;cursor:initial;box-shadow:rgba(0,0,0,.2) 0 4px 8px 0;transform-origin:bottom;transform:translateX(-50%);opacity:0;pointer-events:none;padding:8px;z-index:3}.download-video .rpc-settings>*{margin:8px}.download-video .rpc-settings.show{opacity:1;pointer-events:initial}.download-video .rpc-settings-item{display:flex;align-items:center;justify-content:space-between;white-space:nowrap}.download-video .rpc-settings input[type=text]{background:0 0;color:var(--download-video-foreground);border:1px solid #8884;padding:4px;margin-left:8px}.download-video .rpc-settings input[type=text]:focus{border-color:var(--theme-color)}`; offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/download-video.min.html"] = `

下载视频

单个视频
批量导出
警告: 过大的视频大小会在直接下载时占用大量内存, 并可能导致浏览器标签页崩溃. 请考虑降低清晰度或使用导出选项.
预计大小: {{displaySize}}
清晰度
弹幕

直接下载

{{progressPercent}}%

选集

{{selectedEpisodeCount}}/{{episodeList.length}}

导出

导出aria2 RPC

aria2 RPC 配置

主机
端口
密钥
路径
确定
`; -offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/download-video.min.js"] = (()=>{return(e,t)=>{const{getFriendlyTitle:s}=t.import("title");const{VideoInfo:a,DanmakuInfo:n}=t.import("video-info");class i{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 o extends i{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 i,aid:"",cid:""};let l=[];let c=null;class d{constructor(e,t,s){this.quality=e;this.internalName=t;this.displayName=s}async downloadInfo(){const e=new u(this);await e.fetchVideoInfo();return e}static get availableFormats(){return new Promise((e,t)=>{r.entity.getUrl().then(s=>{const a=new XMLHttpRequest;a.addEventListener("load",()=>{const s=JSON.parse(a.responseText);if(s.code!==0){t("获取清晰度信息失败.");return}const n=s.data||s.result||s;const i=n.accept_quality;const o=n.accept_format.split(",");const r=n.accept_description;const l=[];while(i.length>0){const e=new d(i.pop(),o.pop(),r.pop());l.push(e)}e(l.reverse())});a.addEventListener("error",()=>t(`获取清晰度信息失败.`));a.withCredentials=true;a.open("GET",s);a.send()})})}}class h{constructor(e,t,s,a){this.length=e;this.size=t;this.url=s;this.backupUrls=a}}class u{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(s=>{const a=new XMLHttpRequest;a.addEventListener("load",()=>{const s=JSON.parse(a.responseText.replace(/http:/g,"https:"));const n=s.data||s.result||s;if(n.quality!==this.format.quality){t("获取下载链接失败, 请确认当前账号有下载权限后重试.")}const i=n.durl;this.fragments=i.map(e=>new h(e.length,e.size,e.url,e.backup_url));e(this.fragments)});a.withCredentials=true;a.open("GET",s);a.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 s=Math.round(e.size/this.fragmentSplitFactor);let a=0;const n=e=>[...this.progressMap.keys()].indexOf(e)+1;while(a{const a=new XMLHttpRequest;a.open("GET",e.url);a.responseType="arraybuffer";a.withCredentials=false;a.addEventListener("progress",e=>{console.log(`[下载视频] 视频片段${n(a)}下载进度: ${e.loaded}/${r} bytes loaded, ${o}`);this.progressMap.set(a,e.loaded);this.updateProgress()});a.addEventListener("load",()=>{if((""+a.status)[0]==="2"){t(a.response)}else{s(`请求失败.`)}});a.addEventListener("abort",()=>s("canceled"));a.addEventListener("error",()=>{console.error(`[下载视频] 视频片段${n(a)}下载失败: ${o}`);this.progressMap.set(a,0);this.updateProgress();a.open("GET",e.url);a.setRequestHeader("Range",o);a.send()});a.setRequestHeader("Range",o);this.progressMap.set(a,0);a.send();this.workingXhr.push(a)}));a=Math.round(a+s)+1}return Promise.all(t)}async 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 s=document.createElement("a");let a;if(typeof e==="string"){a=e}else{a=URL.createObjectURL(e)}s.setAttribute("href",a);s.setAttribute("download",t);document.body.appendChild(s);s.click();s.remove();URL.revokeObjectURL(a)}async exportData(e=false){const t=JSON.stringify([{fragments:this.fragments,title:s(),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 a=await this.downloadDanmaku();if(a!==null){const t=new JSZip;t.file(`${s()}.json`,e);t.file(s()+"."+this.danmakuOption.toLowerCase(),a);u.downloadBlob(await t.generateAsync({type:"blob"}),`${s()}.zip`)}else{u.downloadBlob(e,`${s()}.json`)}}}async exportAria2(t=false){if(t){const t=await this.downloadDanmaku();if(t!==null){u.downloadBlob(new Blob([t]),`${s()}.${this.danmakuOption==="ASS"?"ass":"xml"}`)}const a=e.aria2RpcOption;const n=a.host.startsWith("http://")?a.host:"http://"+a.host;const i="aria2.addUri";const o=this.fragments.map((e,t)=>{let n="";if(this.fragments.length>1){n=" - "+(t+1)}const i=[];if(a.secretKey!==""){i.push(`token:${a.secretKey}`)}i.push([e.url]);i.push({referer:document.URL.replace(window.location.search,""),"user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0",out:`${s()}${n}${this.extension(e)}`,split:this.fragmentSplitFactor,dir:a.dir});const o=window.btoa(unescape(encodeURIComponent(JSON.stringify(i))));const r=`${s()}${n}`;return{base64Params:o,id:r}});for(const e of o){try{const t=await Ajax.getJson(`${n}:${a.port}/jsonrpc?method=${i}&id=${e.id}¶ms=${e.base64Params}`);if(t.error!==undefined){if(t.error.code===1){logError(`请求遭到拒绝, 请检查您的密钥相关设置.`)}else{logError(`请求发生错误, code = ${t.error.code}, message = ${t.error.message}`)}return}Toast.success(`成功发送了请求, GID = ${t.result}`,"aria2 RPC",5e3)}catch(e){logError(`无法连接到RPC主机, error = ${e}`);return}}}else{const e=`\n# Generated by Bilibili Evolved Video Export\n# https://github.com/the1812/Bilibili-Evolved/\n${this.fragments.map((e,t)=>{let a="";if(this.fragments.length>1){a=" - "+(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=${s()}${a}${this.extension(e)}\n split=${this.fragmentSplitFactor}\n `.trim()}).join("\n")}\n `.trim();const t=new Blob([e],{type:"text/plain"});const a=await this.downloadDanmaku();if(a!==null){const e=new JSZip;e.file(`${s()}.txt`,t);e.file(s()+"."+this.danmakuOption.toLowerCase(),a);u.downloadBlob(await e.generateAsync({type:"blob"}),`${s()}.zip`)}else{u.downloadBlob(t,`${s()}.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 n(r.cid);await e.fetchInfo();if(this.danmakuOption==="XML"){return e.rawXML}else{const{convertToAss:s}=await t.importAsync("download-danmaku");return s(e.rawXML)}}else{return null}}async downloadSingle(e){const t=await this.downloadDanmaku();const[a]=e;if(t===null){const e=this.makeBlob(a);const t=s()+this.extension();return{blob:e,filename:t}}else{const e=new JSZip;e.file(s()+this.extension(),this.makeBlob(a));e.file(s()+"."+this.danmakuOption.toLowerCase(),t);const n=await e.generateAsync({type:"blob"});const i=s()+".zip";return{blob:n,filename:i}}}async downloadMultiple(e){const t=new JSZip;const a=s();if(e.length>1){e.forEach((e,s)=>{const n=this.fragments[s];t.file(`${a} - ${s+1}${this.extension(n)}`,this.makeBlob(e,n))})}else{const[s]=e;t.file(`${a}${this.extension()}`,this.makeBlob(s))}const n=await this.downloadDanmaku();if(n!==null){t.file(s()+"."+this.danmakuOption.toLowerCase(),n)}const i=await t.generateAsync({type:"blob"});const o=a+".zip";return{blob:i,filename:o}}async download(){const e=[];for(const t of this.fragments){const s=await this.downloadFragment(t);e.push(s)}if(e.length<1){throw new Error("下载失败.")}let{blob:t,filename:s}=await(async()=>{if(e.length===1){return await this.downloadSingle(e)}else{return await this.downloadMultiple(e)}})();this.cleanUpOldBlobUrl();const a=URL.createObjectURL(t);this.progress&&this.progress(0);return{url:a,filename:s}}}async function p(){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 o}else{r.entity=new i}try{l=await d.availableFormats}catch(e){return false}return true}async function m(){c=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"));w()},{once:true})}async function w(){Vue.component("v-dropdown",{template:`\n
\n {{value}}\n \n \n
\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")}}});Vue.component("v-checkbox",{template:`\n
\n \n \n \n {{model.title}}\n
\n `,props:["model"],methods:{toggleCheck(){this.model.checked=!this.model.checked}}});let i;const o=new Map;const h=new Vue({el:".download-video",data:{downloadSingle:true,coverUrl:'data:image/svg+xml;utf-8,',aid:r.aid,cid:r.cid,qualityModel:{value:c.displayName,items:l.map(e=>e.displayName)},danmakuModel:{value:e.downloadVideoDefaultDanmaku,items:["无","XML","ASS"]},progressPercent:0,size:"获取大小中",blobUrl:"",episodeList:[],downloading:false,batch:false,rpcSettings:e.aria2RpcOption,showRpcSettings:false,busy:false},computed:{displaySize(){if(typeof this.size==="string"){return this.size}const e=["B","KB","MB","GB","TB","PB","EB","ZB","YB"];let t=this.size;let s=0;while(t>=1024){t/=1024;s++}return`${Math.round(t*10)/10}${e[s]}`},sizeWarning(){if(typeof this.size==="string"){return false}return this.size>1073741824},selectedEpisodeCount(){return this.episodeList.filter(e=>e.checked).length}},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();this.size=t.totalSize;o.set(e,this.size)}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){if(this.busy===true){return}try{this.busy=true;if(!this.downloadSingle){await this.exportBatchData(e);return}const t=this.getFormat();const s=await t.downloadInfo();s.danmakuOption=this.danmakuModel.value;switch(e){case"copyLink":await s.copyUrl();Toast.success("已复制链接到剪贴板.","下载视频",3e3);break;case"aria2":await s.exportAria2(false);break;case"aria2RPC":await s.exportAria2(true);break;case"copyVLD":await s.exportData(true);Toast.success("已复制VLD数据到剪贴板.","下载视频",3e3);break;case"exportVLD":await s.exportData(false);break;default:break}}catch(e){logError(e)}finally{this.busy=false}},async exportBatchData(e){const a=this.episodeList;if(a.every(e=>e.checked===false)){Toast.info("请至少选择1集或以上的数量!","批量导出",3e3);return}const i=this.getFormat();if(this.danmakuModel.value!=="无"){const e=Toast.info("下载弹幕中...","批量导出");const s=new JSZip;try{if(this.danmakuModel.value==="XML"){for(const e of a){const t=new n(e.cid);await t.fetchInfo();s.file(e.title+".xml",t.rawXML)}}else{const{convertToAss:e}=await t.importAsync("download-danmaku");for(const t of a){const a=new n(t.cid);await a.fetchInfo();s.file(t.title+".ass",await e(a.rawXML))}}u.downloadBlob(await s.generateAsync({type:"blob"}),this.cid+".danmakus.zip")}catch(e){logError(e)}finally{e.dismiss()}}const o=Toast.info("获取链接中...","批量导出");const r=e=>{const t=a.find(t=>t.cid===e.cid);if(t===undefined){return false}return t.checked};this.batchExtractor.itemFilter=r;let l;try{switch(e){case"aria2":l=await this.batchExtractor.collectAria2(i,o);u.downloadBlob(new Blob([l],{type:"text/plain"}),s(false)+".txt");return;case"aria2RPC":await this.batchExtractor.collectAria2(i,o,true);Toast.success(`成功发送了批量请求.`,"aria2 RPC",3e3);return;case"copyVLD":GM_setClipboard(await this.batchExtractor.collectData(i,o),{mimetype:"text/plain"});Toast.success("已复制批量vld数据到剪贴板.","批量导出",3e3);return;case"exportVLD":l=await this.batchExtractor.collectData(i,o);u.downloadBlob(new Blob([l],{type:"text/json"}),s(false)+".json");return;default:return}}catch(e){logError(e)}finally{o.dismiss()}},async checkBatch(){const e=["/www.bilibili.com/bangumi","/www.bilibili.com/video/av"];if(!e.some(e=>document.URL.includes(e))){this.batch=false;this.episodeList=[];return}const{BatchExtractor:s}=await t.importAsync("batch-download");if(await s.test()!==true){this.batch=false;this.episodeList=[];return}this.batchExtractor=new s;this.batch=true;this.episodeList=(await this.batchExtractor.getItemList()).map((e,t)=>{return{aid:e.aid,cid:e.cid,title:e.title,index:t,checked:true}})},cancelDownload(){if(i){i.cancelDownload()}},async startDownload(){const e=this.getFormat();try{this.downloading=true;const t=await e.downloadInfo();t.danmakuOption=this.danmakuModel.value;t.progress=(e=>{this.progressPercent=Math.trunc(e*100)});i=t;const s=await t.download();const a=document.getElementById("video-complete");a.setAttribute("href",s.url);a.setAttribute("download",s.filename);a.click();Toast.success(`下载完成: ${s.filename} 再次保存`,"下载视频")}catch(e){if(e!=="canceled"){logError(e)}this.progressPercent=0}finally{this.downloading=false}},selectAllEpisodes(){this.episodeList.forEach(e=>e.checked=true)},unselectAllEpisodes(){this.episodeList.forEach(e=>e.checked=false)},inverseAllEpisodes(){this.episodeList.forEach(e=>e.checked=!e.checked)},toggleRpcSettings(){this.showRpcSettings=!this.showRpcSettings},saveRpcSettings(){if(this.rpcSettings.host===""){this.rpcSettings.host="127.0.0.1"}if(this.rpcSettings.port===""){this.rpcSettings.port="6800"}e.aria2RpcOption=this.rpcSettings}}});Observer.videoChange(async()=>{h.close();h.batch=false;h.downloadSingle=true;const e=dq("#download-video");const t=await p();e.style.display=t?"flex":"none";if(!t){return}h.aid=r.aid;h.cid=r.cid;const s=new a(r.aid);await s.fetchInfo();h.coverUrl=s.coverUrl.replace("http:","https:");l=await d.availableFormats;[c]=l;h.qualityModel={value:c.displayName,items:l.map(e=>e.displayName)};h.formatChange();await h.checkBatch()})}return{widget:{content:`\n `,condition:p,success:m}}}})(); +offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/download-video.min.js"] = (()=>{return(e,t)=>{const{getFriendlyTitle:s}=t.import("title");const{VideoInfo:a,DanmakuInfo:n}=t.import("video-info");class i{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 o extends i{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 i,aid:"",cid:""};let l=[];let c=null;class d{constructor(e,t,s){this.quality=e;this.internalName=t;this.displayName=s}async downloadInfo(){const e=new u(this);await e.fetchVideoInfo();return e}static get availableFormats(){return new Promise((e,t)=>{r.entity.getUrl().then(s=>{const a=new XMLHttpRequest;a.addEventListener("load",()=>{const s=JSON.parse(a.responseText);if(s.code!==0){t("获取清晰度信息失败.");return}const n=s.data||s.result||s;const i=n.accept_quality;const o=n.accept_format.split(",");const r=n.accept_description;const l=[];while(i.length>0){const e=new d(i.pop(),o.pop(),r.pop());l.push(e)}e(l.reverse())});a.addEventListener("error",()=>t(`获取清晰度信息失败.`));a.withCredentials=true;a.open("GET",s);a.send()})})}}class h{constructor(e,t,s,a){this.length=e;this.size=t;this.url=s;this.backupUrls=a}}class u{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(s=>{const a=new XMLHttpRequest;a.addEventListener("load",()=>{const s=JSON.parse(a.responseText.replace(/http:/g,"https:"));const n=s.data||s.result||s;if(n.quality!==this.format.quality){t("获取下载链接失败, 请确认当前账号有下载权限后重试.")}const i=n.durl;this.fragments=i.map(e=>new h(e.length,e.size,e.url,e.backup_url));e(this.fragments)});a.withCredentials=true;a.open("GET",s);a.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 s=Math.round(e.size/this.fragmentSplitFactor);let a=0;const n=e=>[...this.progressMap.keys()].indexOf(e)+1;while(a{const a=new XMLHttpRequest;a.open("GET",e.url);a.responseType="arraybuffer";a.withCredentials=false;a.addEventListener("progress",e=>{console.log(`[下载视频] 视频片段${n(a)}下载进度: ${e.loaded}/${r} bytes loaded, ${o}`);this.progressMap.set(a,e.loaded);this.updateProgress()});a.addEventListener("load",()=>{if((""+a.status)[0]==="2"){t(a.response)}else{s(`请求失败.`)}});a.addEventListener("abort",()=>s("canceled"));a.addEventListener("error",()=>{console.error(`[下载视频] 视频片段${n(a)}下载失败: ${o}`);this.progressMap.set(a,0);this.updateProgress();a.open("GET",e.url);a.setRequestHeader("Range",o);a.send()});a.setRequestHeader("Range",o);this.progressMap.set(a,0);a.send();this.workingXhr.push(a)}));a=Math.round(a+s)+1}return Promise.all(t)}async 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 s=document.createElement("a");let a;if(typeof e==="string"){a=e}else{a=URL.createObjectURL(e)}s.setAttribute("href",a);s.setAttribute("download",t);document.body.appendChild(s);s.click();s.remove();URL.revokeObjectURL(a)}async exportData(e=false){const t=JSON.stringify([{fragments:this.fragments,title:s(),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 a=await this.downloadDanmaku();if(a!==null){const t=new JSZip;t.file(`${s()}.json`,e);t.file(s()+"."+this.danmakuOption.toLowerCase(),a);u.downloadBlob(await t.generateAsync({type:"blob"}),`${s()}.zip`)}else{u.downloadBlob(e,`${s()}.json`)}}}async exportAria2(t=false){if(t){const t=await this.downloadDanmaku();if(t!==null){u.downloadBlob(new Blob([t]),`${s()}.${this.danmakuOption==="ASS"?"ass":"xml"}`)}const a=e.aria2RpcOption;const n=a.host.match(/^http[s]?:\/\//)?a.host:"http://"+a.host;const i="aria2.addUri";const o=this.fragments.map((e,t)=>{let n="";if(this.fragments.length>1){n=" - "+(t+1)}const i=[];if(a.secretKey!==""){i.push(`token:${a.secretKey}`)}i.push([e.url]);i.push({referer:document.URL.replace(window.location.search,""),"user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0",out:`${s()}${n}${this.extension(e)}`,split:this.fragmentSplitFactor,dir:a.dir});const o=window.btoa(unescape(encodeURIComponent(JSON.stringify(i))));const r=`${s()}${n}`;return{base64Params:o,id:r}});for(const e of o){try{const t=await Ajax.getJson(`${n}:${a.port}/jsonrpc?method=${i}&id=${e.id}¶ms=${e.base64Params}`);if(t.error!==undefined){if(t.error.code===1){logError(`请求遭到拒绝, 请检查您的密钥相关设置.`)}else{logError(`请求发生错误, code = ${t.error.code}, message = ${t.error.message}`)}return}Toast.success(`成功发送了请求, GID = ${t.result}`,"aria2 RPC",5e3)}catch(e){logError(`无法连接到RPC主机, error = ${e}`);return}}}else{const e=`\n# Generated by Bilibili Evolved Video Export\n# https://github.com/the1812/Bilibili-Evolved/\n${this.fragments.map((e,t)=>{let a="";if(this.fragments.length>1){a=" - "+(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=${s()}${a}${this.extension(e)}\n split=${this.fragmentSplitFactor}\n `.trim()}).join("\n")}\n `.trim();const t=new Blob([e],{type:"text/plain"});const a=await this.downloadDanmaku();if(a!==null){const e=new JSZip;e.file(`${s()}.txt`,t);e.file(s()+"."+this.danmakuOption.toLowerCase(),a);u.downloadBlob(await e.generateAsync({type:"blob"}),`${s()}.zip`)}else{u.downloadBlob(t,`${s()}.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 n(r.cid);await e.fetchInfo();if(this.danmakuOption==="XML"){return e.rawXML}else{const{convertToAss:s}=await t.importAsync("download-danmaku");return s(e.rawXML)}}else{return null}}async downloadSingle(e){const t=await this.downloadDanmaku();const[a]=e;if(t===null){const e=this.makeBlob(a);const t=s()+this.extension();return{blob:e,filename:t}}else{const e=new JSZip;e.file(s()+this.extension(),this.makeBlob(a));e.file(s()+"."+this.danmakuOption.toLowerCase(),t);const n=await e.generateAsync({type:"blob"});const i=s()+".zip";return{blob:n,filename:i}}}async downloadMultiple(e){const t=new JSZip;const a=s();if(e.length>1){e.forEach((e,s)=>{const n=this.fragments[s];t.file(`${a} - ${s+1}${this.extension(n)}`,this.makeBlob(e,n))})}else{const[s]=e;t.file(`${a}${this.extension()}`,this.makeBlob(s))}const n=await this.downloadDanmaku();if(n!==null){t.file(s()+"."+this.danmakuOption.toLowerCase(),n)}const i=await t.generateAsync({type:"blob"});const o=a+".zip";return{blob:i,filename:o}}async download(){const e=[];for(const t of this.fragments){const s=await this.downloadFragment(t);e.push(s)}if(e.length<1){throw new Error("下载失败.")}let{blob:t,filename:s}=await(async()=>{if(e.length===1){return await this.downloadSingle(e)}else{return await this.downloadMultiple(e)}})();this.cleanUpOldBlobUrl();const a=URL.createObjectURL(t);this.progress&&this.progress(0);return{url:a,filename:s}}}async function p(){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 o}else{r.entity=new i}try{l=await d.availableFormats}catch(e){return false}return true}async function m(){c=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"));w()},{once:true})}async function w(){Vue.component("v-dropdown",{template:`\n
\n {{value}}\n \n \n
\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")}}});Vue.component("v-checkbox",{template:`\n
\n \n \n \n {{model.title}}\n
\n `,props:["model"],methods:{toggleCheck(){this.model.checked=!this.model.checked}}});let i;const o=new Map;const h=new Vue({el:".download-video",data:{downloadSingle:true,coverUrl:'data:image/svg+xml;utf-8,',aid:r.aid,cid:r.cid,qualityModel:{value:c.displayName,items:l.map(e=>e.displayName)},danmakuModel:{value:e.downloadVideoDefaultDanmaku,items:["无","XML","ASS"]},progressPercent:0,size:"获取大小中",blobUrl:"",episodeList:[],downloading:false,batch:false,rpcSettings:e.aria2RpcOption,showRpcSettings:false,busy:false},computed:{displaySize(){if(typeof this.size==="string"){return this.size}const e=["B","KB","MB","GB","TB","PB","EB","ZB","YB"];let t=this.size;let s=0;while(t>=1024){t/=1024;s++}return`${Math.round(t*10)/10}${e[s]}`},sizeWarning(){if(typeof this.size==="string"){return false}return this.size>1073741824},selectedEpisodeCount(){return this.episodeList.filter(e=>e.checked).length}},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();this.size=t.totalSize;o.set(e,this.size)}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){if(this.busy===true){return}try{this.busy=true;if(!this.downloadSingle){await this.exportBatchData(e);return}const t=this.getFormat();const s=await t.downloadInfo();s.danmakuOption=this.danmakuModel.value;switch(e){case"copyLink":await s.copyUrl();Toast.success("已复制链接到剪贴板.","下载视频",3e3);break;case"aria2":await s.exportAria2(false);break;case"aria2RPC":await s.exportAria2(true);break;case"copyVLD":await s.exportData(true);Toast.success("已复制VLD数据到剪贴板.","下载视频",3e3);break;case"exportVLD":await s.exportData(false);break;default:break}}catch(e){logError(e)}finally{this.busy=false}},async exportBatchData(e){const a=this.episodeList;if(a.every(e=>e.checked===false)){Toast.info("请至少选择1集或以上的数量!","批量导出",3e3);return}const i=this.getFormat();if(this.danmakuModel.value!=="无"){const e=Toast.info("下载弹幕中...","批量导出");const s=new JSZip;try{if(this.danmakuModel.value==="XML"){for(const e of a){const t=new n(e.cid);await t.fetchInfo();s.file(e.title+".xml",t.rawXML)}}else{const{convertToAss:e}=await t.importAsync("download-danmaku");for(const t of a){const a=new n(t.cid);await a.fetchInfo();s.file(t.title+".ass",await e(a.rawXML))}}u.downloadBlob(await s.generateAsync({type:"blob"}),this.cid+".danmakus.zip")}catch(e){logError(e)}finally{e.dismiss()}}const o=Toast.info("获取链接中...","批量导出");const r=e=>{const t=a.find(t=>t.cid===e.cid);if(t===undefined){return false}return t.checked};this.batchExtractor.itemFilter=r;let l;try{switch(e){case"aria2":l=await this.batchExtractor.collectAria2(i,o);u.downloadBlob(new Blob([l],{type:"text/plain"}),s(false)+".txt");return;case"aria2RPC":await this.batchExtractor.collectAria2(i,o,true);Toast.success(`成功发送了批量请求.`,"aria2 RPC",3e3);return;case"copyVLD":GM_setClipboard(await this.batchExtractor.collectData(i,o),{mimetype:"text/plain"});Toast.success("已复制批量vld数据到剪贴板.","批量导出",3e3);return;case"exportVLD":l=await this.batchExtractor.collectData(i,o);u.downloadBlob(new Blob([l],{type:"text/json"}),s(false)+".json");return;default:return}}catch(e){logError(e)}finally{o.dismiss()}},async checkBatch(){const e=["/www.bilibili.com/bangumi","/www.bilibili.com/video/av"];if(!e.some(e=>document.URL.includes(e))){this.batch=false;this.episodeList=[];return}const{BatchExtractor:s}=await t.importAsync("batch-download");if(await s.test()!==true){this.batch=false;this.episodeList=[];return}this.batchExtractor=new s;this.batch=true;this.episodeList=(await this.batchExtractor.getItemList()).map((e,t)=>{return{aid:e.aid,cid:e.cid,title:e.title,index:t,checked:true}})},cancelDownload(){if(i){i.cancelDownload()}},async startDownload(){const e=this.getFormat();try{this.downloading=true;const t=await e.downloadInfo();t.danmakuOption=this.danmakuModel.value;t.progress=(e=>{this.progressPercent=Math.trunc(e*100)});i=t;const s=await t.download();const a=document.getElementById("video-complete");a.setAttribute("href",s.url);a.setAttribute("download",s.filename);a.click();Toast.success(`下载完成: ${s.filename} 再次保存`,"下载视频")}catch(e){if(e!=="canceled"){logError(e)}this.progressPercent=0}finally{this.downloading=false}},selectAllEpisodes(){this.episodeList.forEach(e=>e.checked=true)},unselectAllEpisodes(){this.episodeList.forEach(e=>e.checked=false)},inverseAllEpisodes(){this.episodeList.forEach(e=>e.checked=!e.checked)},toggleRpcSettings(){this.showRpcSettings=!this.showRpcSettings},saveRpcSettings(){if(this.rpcSettings.host===""){this.rpcSettings.host="127.0.0.1"}if(this.rpcSettings.port===""){this.rpcSettings.port="6800"}e.aria2RpcOption=this.rpcSettings}}});Observer.videoChange(async()=>{h.close();h.batch=false;h.downloadSingle=true;const e=dq("#download-video");const t=await p();e.style.display=t?"flex":"none";if(!t){return}h.aid=r.aid;h.cid=r.cid;const s=new a(r.aid);await s.fetchInfo();h.coverUrl=s.coverUrl.replace("http:","https:");l=await d.availableFormats;[c]=l;h.qualityModel={value:c.displayName,items:l.map(e=>e.displayName)};h.formatChange();await h.checkBatch()})}return{widget:{content:`\n `,condition:p,success:m}}}})(); offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/expand-danmaku.min.js"] = (()=>{return(e,a)=>{if(typeof isEmbeddedPlayer!=="undefined"&&isEmbeddedPlayer()){return}Observer.videoChange(async()=>{const e=await SpinQuery.select(".bui-collapse-wrap");if(e&&e.classList.contains("bui-collapse-wrap-folded")){const e=await SpinQuery.select(".bui-collapse-header");e.click()}})}})(); offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/expand-description.min.css"] = `.play-up-info .play-up-self,.video-desc .info{height:auto!important}.play-up-info .play-up-self-btn,.video-desc .btn{display:none!important}`; offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/expand-description.min.js"] = (()=>{return(e,p)=>{p.applyStyle("expandDescriptionStyle")}})(); diff --git a/bilibili-evolved.preview-offline.user.js b/bilibili-evolved.preview-offline.user.js index ba112cdf3..f5790dba5 100644 --- a/bilibili-evolved.preview-offline.user.js +++ b/bilibili-evolved.preview-offline.user.js @@ -1,6 +1,6 @@ // ==UserScript== // @name Bilibili Evolved (Preview Offline) -// @version 371.19 +// @version 371.22 // @description Bilibili Evolved 的预览离线版, 可以抢先体验新功能, 并且所有功能都已内置于脚本中. // @author Grant Howard, Coulomb-G // @copyright 2019, Grant Howard (https://github.com/the1812) & Coulomb-G (https://github.com/Coulomb-G) @@ -960,7 +960,7 @@ offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/m offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/about.min.js"] = (()=>{return(t,e)=>{(async()=>{const i=await e.importAsync("aboutHtml");document.body.insertAdjacentHTML("beforeend",i);const o=(t,e)=>t.charCodeAt(0)-e.charCodeAt(0);const n=(t,e)=>o(t.name,e.name);const s=GM_info.script.name.match(/Bilibili Evolved \((.*)\)/);const a=s?s[1]:"Stable";new Vue({el:".bilibili-evolved-about",data:{version:t.currentVersion,clientType:a,logoImage:null,logoImageDark:null,branch:null,authors:[{name:"Grant Howard",link:"https://github.com/the1812"},{name:"Coulomb-G",link:"https://github.com/Coulomb-G"}],contributors:[{name:"PleiadeSubaru",link:"https://github.com/Etherrrr"}].sort(n),fetching:true,participants:[],supporters:["*飞","N*v","*博睿","*杨","*泽鹏"].sort(o),websites:[{name:"GitHub",link:"https://github.com/the1812/Bilibili-Evolved/"},{name:"Greasy Fork",link:"https://greasyfork.org/zh-CN/scripts/373563-bilibili-evolved"}],components:[{name:"Vue.js",link:"https://cn.vuejs.org/index.html"},{name:"JSZip",link:"https://stuk.github.io/jszip/"},{name:"jQuery",link:"http://jquery.com/"},{name:"debounce",link:"https://github.com/component/debounce/"},{name:"Slip.js",link:"https://github.com/kornelski/slip"},{name:"MDI",link:"https://materialdesignicons.com"}]},mounted(){document.querySelector(".bilibili-evolved-about").addEventListener("be:about-load",()=>{this.init()},{once:true})},methods:{async getLogos(){this.logoImage=await Ajax.getText(`https://raw.githubusercontent.com/the1812/Bilibili-Evolved/preview/images/bilibili-evolved-wide.svg`);this.logoImageDark=await Ajax.getText(`https://raw.githubusercontent.com/the1812/Bilibili-Evolved/preview/images/bilibili-evolved-wide-dark.svg`)},async init(){this.branch=/Preview|Local/.test(a)?"preview":"master";this.getLogos();const t=new Set;let e=[];let i=1;do{e=await Ajax.getJson(`https://api.github.com/repos/the1812/Bilibili-Evolved/issues?state=all&direction=asc&per_page=100&page=${i}`).catch(()=>{e=[{name:"电波无法到达(´・_・`)",link:null}]});i++;for(const i of e){t.add(i.user.login)}}while(e.length>0);this.participants=[...t].map(t=>{return{name:t,link:`https://github.com/${t}`}}).filter(({link:t})=>{return!this.authors.some(e=>e.link===t)&&!this.contributors.some(e=>e.link===t)}).sort(n);this.fetching=false}}})})()}})(); offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/auto-continue.min.js"] = (()=>{return(e,i)=>{if(typeof isEmbeddedPlayer!=="undefined"&&isEmbeddedPlayer()){return}function t(i){const t=i.text();if(/第(\d+)话/.test(t)){if(e.allowJumpContinue){i.parent().find(".bilibili-player-video-toast-item-jump").click()}return}const n=/((\d)*:)?(\d)*:(\d)*/g;const r=t.match(n);if(!r){return}const o=r[0].split(":");const l=(()=>{if(o.length===3){const[e,i,t]=o.map(e=>parseInt(e));return e*60*60+i*60+t}else if(o.length===2){const[e,i]=o.map(e=>parseInt(e));return e*60+i}else{logError(`解析历史时间发生错误: historyTime=${JSON.stringify(o)}`);return NaN}})();const s=i.parent();const a=document.querySelector("video");if(l从头开始`);e.appendTo(s).on("click",()=>{a.currentTime=0;s.find(".bilibili-player-video-toast-item-close").get(0).click()});i.html(`已跳转到上次历史记录${r[0]}`)}else{s.find(".bilibili-player-video-toast-item-close").get(0).click()}}function n(){SpinQuery.condition(()=>$(".bilibili-player-video-toast-item-text"),e=>e.text().indexOf("上次看到")!==-1,e=>t(e.filter((e,i)=>i.innerText.indexOf("上次看到")!==-1)))}Observer.videoChange(n)}})(); offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/auto-play.min.js"] = (()=>{return(e,d)=>{if(typeof isEmbeddedPlayer!=="undefined"&&isEmbeddedPlayer()){return}SpinQuery.condition(()=>document.querySelector(".bilibili-player-video video"),e=>e&&e.paused===true,e=>e.play())}})(); -offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/batch-download.min.js"] = (()=>{return(t,e)=>{const i=12;class r{constructor(){this.itemList=[];this.itemFilter=(()=>true)}async getItemList(){}async collectData(){}async collectAria2(e,r){const s=JSON.parse(await this.collectData(e));if(r){const e=t.aria2RpcOption;const r=e.host.startsWith("http://")?e.host:"http://"+e.host;const n="aria2.addUri";for(const t of s){const s=t.fragments.map((r,s)=>{let n="";if(t.fragments.length>1){n=" - "+(s+1)}const a=[];if(e.secretKey!==""){a.push(`token:${e.secretKey}`)}a.push([r.url]);a.push({referer:document.URL.replace(window.location.search,""),"user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0",out:`${t.title}${n}.flv`,split:i,dir:e.dir});const o=window.btoa(unescape(encodeURIComponent(JSON.stringify(a))));const c=`${t.title}${n}`;return{base64Params:o,id:c}});for(const t of s){try{const i=await Ajax.getJson(`${r}:${e.port}/jsonrpc?method=${n}&id=${t.id}¶ms=${t.base64Params}`);if(i.error!==undefined){if(i.error.code===1){logError(`请求遭到拒绝, 请检查您的密钥相关设置.`)}else{logError(`请求发生错误, code = ${i.error.code}, message = ${i.error.message}`)}return}}catch(t){logError(`无法连接到RPC主机, error = ${t}`);return}}}}else{return`\n# Generated by Bilibili Evolved Video Export\n# https://github.com/the1812/Bilibili-Evolved/\n${s.map(t=>{return t.fragments.map(e=>{return`\n${e.url}\n referer=${t.referer}\n user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0\n out=${t.title}.flv\n split=${i}\n `.trim()})}).join("\n")}\n `.trim()}}}class s extends r{static async test(){if(!document.URL.includes("/www.bilibili.com/video/av")){return false}return await SpinQuery.select("#multi_page")!==null}async getItemList(){if(this.itemList.length>0){return this.itemList}const t=`https://api.bilibili.com/x/web-interface/view?aid=${unsafeWindow.aid}`;const e=await Ajax.getJson(t);if(e.code!==0){Toast.error(`获取视频选集列表失败, message=${e.message}`,"批量下载");return""}const i=e.data.pages;if(i===undefined){Toast.error(`获取视频选集列表失败, 没有找到选集信息.`,"批量下载");return""}this.itemList=i.map(t=>{return{title:`P${t.page} ${t.part}`,cid:t.cid,aid:unsafeWindow.aid}});return this.itemList}async collectData(t){const e=[];for(const i of(await this.getItemList()).filter(this.itemFilter)){const r=`https://api.bilibili.com/x/player/playurl?avid=${i.aid}&cid=${i.cid}&qn=${t}&otype=json`;const s=await Ajax.getJsonWithCredentials(r);const n=s.data||s.result||s;if(n.quality!==t){Toast.error("获取下载链接失败, 请确认当前账号有下载权限后重试.","批量下载");return""}const a=n.durl.map(t=>{return{length:t.length,size:t.size,url:t.url}});e.push({fragments:a,title:i.title,totalSize:a.map(t=>t.size).reduce((t,e)=>t+e),cid:i.cid,referer:document.URL.replace(window.location.search,"")})}return JSON.stringify(e)}}class n extends r{static async test(){return document.URL.includes("/www.bilibili.com/bangumi")}async getItemList(){if(this.itemList.length>0){return this.itemList}const t=document.querySelector("meta[property='og:url']");if(t===null){Toast.error("获取番剧数据失败: 无法找到 Season ID","批量下载");return""}const e=t.getAttribute("content").match(/play\/ss(\d+)/)[1];if(e===undefined){Toast.error("获取番剧数据失败: 无法解析 Season ID","批量下载");return""}const i=await Ajax.getJson(`https://api.bilibili.com/pgc/web/season/section?season_id=${e}`);if(i.code!==0){Toast.error(`获取番剧数据失败: 无法获取番剧集数列表, message=${i.message}`,"批量下载");return""}this.itemList=i.result.main_section.episodes.map((t,e)=>{return{aid:t.aid,cid:t.cid,title:t.long_title?`${t.title} - ${t.long_title}`:`${e+1} - ${t.title}`}});return this.itemList}async collectData(t){const e=[];for(const i of(await this.getItemList()).filter(this.itemFilter)){const r=`https://api.bilibili.com/pgc/player/web/playurl?avid=${i.aid}&cid=${i.cid}&qn=${t}&otype=json`;const s=await Ajax.getJsonWithCredentials(r);const n=s.data||s.result||s;if(n.quality!==t){Toast.error("获取下载链接失败, 请确认当前账号有下载权限后重试.","批量下载");return""}const a=n.durl.map(t=>{return{length:t.length,size:t.size,url:t.url}});e.push({fragments:a,title:i.title,totalSize:a.map(t=>t.size).reduce((t,e)=>t+e),cid:i.cid,referer:document.URL.replace(window.location.search,"")})}return JSON.stringify(e)}}const a=[n,s];let o=null;class c{constructor(){this.itemFilter=(()=>true)}static async test(){for(const t of a){if(await t.test()===true){o=t;return true}}o=null;return false}getExtractor(){if(o===null){logError("[批量下载] 未找到合适的解析模块.");throw new Error(`[Batch Download] module not found.`)}const t=new o;t.itemFilter=this.itemFilter;return t}async getItemList(){const t=this.getExtractor();return await t.getItemList()}async collectData(t,e){const i=this.getExtractor();const r=await i.collectData(t.quality);e.dismiss();return r}async collectAria2(t,e,i){const r=this.getExtractor();const s=await r.collectAria2(t.quality,i);e.dismiss();return s}}return{export:{BatchExtractor:c}}}})(); +offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/batch-download.min.js"] = (()=>{return(t,e)=>{const i=12;class r{constructor(){this.itemList=[];this.itemFilter=(()=>true)}async getItemList(){}async collectData(){}async collectAria2(e,r){const s=JSON.parse(await this.collectData(e));if(r){const e=t.aria2RpcOption;const r=e.host.match(/^http[s]?:\/\//)?e.host:"http://"+e.host;const n="aria2.addUri";for(const t of s){const s=t.fragments.map((r,s)=>{let n="";if(t.fragments.length>1){n=" - "+(s+1)}const a=[];if(e.secretKey!==""){a.push(`token:${e.secretKey}`)}a.push([r.url]);a.push({referer:document.URL.replace(window.location.search,""),"user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0",out:`${t.title}${n}.flv`,split:i,dir:e.dir});const o=window.btoa(unescape(encodeURIComponent(JSON.stringify(a))));const c=`${t.title}${n}`;return{base64Params:o,id:c}});for(const t of s){try{const i=await Ajax.getJson(`${r}:${e.port}/jsonrpc?method=${n}&id=${t.id}¶ms=${t.base64Params}`);if(i.error!==undefined){if(i.error.code===1){logError(`请求遭到拒绝, 请检查您的密钥相关设置.`)}else{logError(`请求发生错误, code = ${i.error.code}, message = ${i.error.message}`)}return}}catch(t){logError(`无法连接到RPC主机, error = ${t}`);return}}}}else{return`\n# Generated by Bilibili Evolved Video Export\n# https://github.com/the1812/Bilibili-Evolved/\n${s.map(t=>{return t.fragments.map(e=>{return`\n${e.url}\n referer=${t.referer}\n user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0\n out=${t.title}.flv\n split=${i}\n `.trim()})}).join("\n")}\n `.trim()}}}class s extends r{static async test(){if(!document.URL.includes("/www.bilibili.com/video/av")){return false}return await SpinQuery.select("#multi_page")!==null}async getItemList(){if(this.itemList.length>0){return this.itemList}const t=`https://api.bilibili.com/x/web-interface/view?aid=${unsafeWindow.aid}`;const e=await Ajax.getJson(t);if(e.code!==0){Toast.error(`获取视频选集列表失败, message=${e.message}`,"批量下载");return""}const i=e.data.pages;if(i===undefined){Toast.error(`获取视频选集列表失败, 没有找到选集信息.`,"批量下载");return""}this.itemList=i.map(t=>{return{title:`P${t.page} ${t.part}`,cid:t.cid,aid:unsafeWindow.aid}});return this.itemList}async collectData(t){const e=[];for(const i of(await this.getItemList()).filter(this.itemFilter)){const r=`https://api.bilibili.com/x/player/playurl?avid=${i.aid}&cid=${i.cid}&qn=${t}&otype=json`;const s=await Ajax.getJsonWithCredentials(r);const n=s.data||s.result||s;if(n.quality!==t){Toast.error("获取下载链接失败, 请确认当前账号有下载权限后重试.","批量下载");return""}const a=n.durl.map(t=>{return{length:t.length,size:t.size,url:t.url}});e.push({fragments:a,title:i.title,totalSize:a.map(t=>t.size).reduce((t,e)=>t+e),cid:i.cid,referer:document.URL.replace(window.location.search,"")})}return JSON.stringify(e)}}class n extends r{static async test(){return document.URL.includes("/www.bilibili.com/bangumi")}async getItemList(){if(this.itemList.length>0){return this.itemList}const t=document.querySelector("meta[property='og:url']");if(t===null){Toast.error("获取番剧数据失败: 无法找到 Season ID","批量下载");return""}const e=t.getAttribute("content").match(/play\/ss(\d+)/)[1];if(e===undefined){Toast.error("获取番剧数据失败: 无法解析 Season ID","批量下载");return""}const i=await Ajax.getJson(`https://api.bilibili.com/pgc/web/season/section?season_id=${e}`);if(i.code!==0){Toast.error(`获取番剧数据失败: 无法获取番剧集数列表, message=${i.message}`,"批量下载");return""}this.itemList=i.result.main_section.episodes.map((t,e)=>{return{aid:t.aid,cid:t.cid,title:t.long_title?`${t.title} - ${t.long_title}`:`${e+1} - ${t.title}`}});return this.itemList}async collectData(t){const e=[];for(const i of(await this.getItemList()).filter(this.itemFilter)){const r=`https://api.bilibili.com/pgc/player/web/playurl?avid=${i.aid}&cid=${i.cid}&qn=${t}&otype=json`;const s=await Ajax.getJsonWithCredentials(r);const n=s.data||s.result||s;if(n.quality!==t){Toast.error("获取下载链接失败, 请确认当前账号有下载权限后重试.","批量下载");return""}const a=n.durl.map(t=>{return{length:t.length,size:t.size,url:t.url}});e.push({fragments:a,title:i.title,totalSize:a.map(t=>t.size).reduce((t,e)=>t+e),cid:i.cid,referer:document.URL.replace(window.location.search,"")})}return JSON.stringify(e)}}const a=[n,s];let o=null;class c{constructor(){this.itemFilter=(()=>true)}static async test(){for(const t of a){if(await t.test()===true){o=t;return true}}o=null;return false}getExtractor(){if(o===null){logError("[批量下载] 未找到合适的解析模块.");throw new Error(`[Batch Download] module not found.`)}const t=new o;t.itemFilter=this.itemFilter;return t}async getItemList(){const t=this.getExtractor();return await t.getItemList()}async collectData(t,e){const i=this.getExtractor();const r=await i.collectData(t.quality);e.dismiss();return r}async collectAria2(t,e,i){const r=this.getExtractor();const s=await r.collectAria2(t.quality,i);e.dismiss();return s}}return{export:{BatchExtractor:c}}}})(); offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/biliplus-redirect.min.js"] = (()=>{return(i,e)=>{const n=`hd.biliplus.com`;const c=["bilibili.com/video/av","bilibili.com/bangumi/play","bilibili.com/bangumi/media","space.bilibili.com"];return{widget:{condition:()=>{return c.some(i=>document.URL.includes(i))},content:`\n `,success:()=>{const i=document.querySelector("#biliplus-redirect");i.addEventListener("click",()=>{if(location.host==="space.bilibili.com"){location.assign(document.URL.replace("space.bilibili.com/",`${n}/space/`))}else if(document.URL.includes("/bangumi/")){const i=unsafeWindow.aid||document.querySelector(".av-link,.info-sec-av").innerText.replace(/[aAvV]/g,"");location.assign(`https://${n}/video/av${i}/`)}else{location.host=n}})}}}}})(); offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/blur-video-control.min.css"] = `.video-control-blur-layer{width:100%;height:100%;position:absolute;-webkit-backdrop-filter:blur(48px);backdrop-filter:blur(48px);z-index:-1;top:0}.bilibili-player-video-control-mask{background:0 0!important}.bilibili-player-video-control-bottom,.bui-slider .bui-track.bui-track-video-progress .bui-bar-wrap{background-color:transparent!important}.bilibili-player-video-control-bottom{position:relative}.bilibili-player-area .bilibili-player-video-control-bottom,.bilibili-player-area .bilibili-player-video-control-wrap{transition:none!important}`; offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/blur-video-control.min.js"] = (()=>{return(o,e)=>{const l=async()=>{const o=await SpinQuery.count(".bui-slider .bui-track.bui-track-video-progress,.bilibili-player-video-control-bottom",2);o.forEach(o=>{if(!o.classList.contains("video-control-blur-container")){o.classList.add("video-control-blur-container");o.insertAdjacentHTML("afterbegin",`
`)}})};e.applyStyle("blurVideoControlStyle");Observer.videoChange(l);return{reload:()=>{document.querySelectorAll(".video-control-blur-layer").forEach(o=>o.style.display="block");e.applyStyle("blurVideoControlStyle")},unload:()=>{document.querySelectorAll(".video-control-blur-layer").forEach(o=>o.style.display="none");e.removeStyle("blurVideoControlStyle")}}}})(); @@ -993,7 +993,7 @@ offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/m offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/download-danmaku.min.js"] = (()=>{return(t,e)=>{const{getFriendlyTitle:n}=e.import("title");const{DanmakuInfo:i}=e.import("video-info");const{DanmakuConverter:a}=e.import("danmaku-converter");async function o(t){const e=n();let i={title:e};try{await loadDanmakuSettingsPanel();const t=t=>{const e=parseFloat(dq(t).style.transform.replace(/translateX\(([\d\.]+)/,"$1"));const n={0:0,44:1,94:2,144:3,188:4}[e];return n};i.font=dq(".bilibili-player-video-danmaku-setting-right-font .bui-select-result").innerText;i.alpha=parseFloat(dq(".bilibili-player-setting-opacity .bui-bar").style.transform.replace(/scaleX\(([\d\.]+)\)/,"$1"));i.duration=(()=>{const e=[18,14,10,8,6][t(".bilibili-player-setting-speedplus .bui-thumb")];return t=>{switch(t.type){case 4:case 5:return 4;default:return e}}})();i.blockTypes=(()=>{let t=[];const e={".bilibili-player-block-filter-type[ftype=scroll]":[1,2,3],".bilibili-player-block-filter-type[ftype=top]":[5],".bilibili-player-block-filter-type[ftype=bottom]":[4],".bilibili-player-block-filter-type[ftype=color]":["color"]};for(const[n,i]of Object.entries(e)){if(dq(n).classList.contains("disabled")){t=t.concat(i)}}return t.concat(7,8)})();const e=[1.4,1.2,1,.8,.6][t(".bilibili-player-setting-fontsize .bui-thumb")];i.resolution={x:1920*e,y:1080*e};i.bottomMarginPercent=[.75,.5,.25,0,0][t(".bilibili-player-setting-area .bui-thumb")];if(i.bottomMarginPercent===0&&dq(".bilibili-player-video-danmaku-setting-left-preventshade input").checked){i.bottomMarginPercent=.15}i.bold=dq(".bilibili-player-video-danmaku-setting-right-font-bold input").checked}catch(t){i={font:"微软雅黑",alpha:.6,duration:t=>{switch(t.type){case 4:case 5:return 4;default:return 6}},blockTypes:[7,8],resolution:{x:1920,y:1080},bottomMarginPercent:.15,bold:false}}const o=new a(i);const l=o.convertToAssDocument(t);return l.generateAss()}async function l(t,e){const a=n();const l=new i((unsafeWindow||window).cid);await l.fetchInfo();const r=await(async()=>{if(t===true){return new Blob([await o(l.rawXML)],{type:"text/plain"})}else{return new Blob([l.rawXML],{type:"text/plain"})}})();const s=URL.createObjectURL(r);const c=dq("#danmaku-link");const d=c.getAttribute("href");if(d){URL.revokeObjectURL(d)}clearTimeout(e);dq("#download-danmaku>span").innerHTML="下载弹幕";c.setAttribute("download",`${a}.${t?"ass":"xml"}`);c.setAttribute("href",s);c.click()}return{export:{downloadDanmaku:l,convertToAss:o},widget:{content:`\n \n \n 下载弹幕\n \n `,condition:async()=>{let t=await SpinQuery.select(()=>(unsafeWindow||window).cid);return Boolean(t)},success:()=>{const t=document.querySelector("#danmaku-link");dq("#download-danmaku").addEventListener("click",e=>{if(e.target!==t){const t=setTimeout(()=>dq("#download-danmaku>span").innerHTML="请稍侯...",200);l(e.shiftKey,t)}})}}}}})(); offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/download-video.min.css"] = `.download-video.opened{pointer-events:initial;opacity:1;transform:translate(-50%,-50%) scale(1)}.download-video{--download-video-background:white;--download-video-foreground:black;position:fixed;top:50%;left:50%;transform:translate(-50%,-50%) scale(.95);background:var(--download-video-background);color:var(--download-video-foreground);box-shadow:rgba(0,0,0,.2) 0 4px 8px 0;z-index:10001;pointer-events:none;opacity:0;padding:16px;width:300px;display:flex;flex-direction:column;align-items:stretch;justify-content:space-between}body.dark .download-video{--download-video-background:#222;--download-video-foreground:#eee}.round-corner .download-video,.round-corner .download-video .episode-list .v-checkbox,.round-corner .download-video .rpc-settings{border-radius:var(--large-corner-radius)}.round-corner .download-video .button,.round-corner .download-video .cover,.round-corner .download-video .direct-download .progress .background,.round-corner .download-video .direct-download .progress .foreground,.round-corner .download-video .rpc-settings input[type=text],.round-corner .download-video .title,.round-corner .download-video button,.round-corner .v-dropdown,.round-corner .v-dropdown .dropdown-menu,.round-corner .v-dropdown .dropdown-menu li{border-radius:var(--corner-radius)}.download-video,.download-video *{transition:.2s ease-out;-webkit-tap-highlight-color:transparent!important}.download-video .cover{width:240px;min-height:135px;background-color:#8882}.download-video .header{display:flex;justify-content:space-between;align-items:center}.download-video h1{font-size:16pt;font-weight:700;color:var(--download-video-foreground)}.download-video i.mdi.mdi-close{font-size:16pt;color:var(--download-video-foreground);cursor:pointer}.download-video i.mdi.mdi-close:hover{color:var(--theme-color)}.download-video .info{display:flex;flex-direction:column;align-items:center;margin-top:12px}.download-video .title{display:flex;flex-direction:column;justify-content:space-between;align-items:stretch;margin-top:12px}.download-video .bold{color:var(--download-video-foreground);font-weight:700;font-size:12pt}.download-video .title .bold{width:300px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;text-align:center}.download-video .title .size{font-size:10pt;color:var(--download-video-foreground);align-self:center;display:flex;align-items:center;height:24px}.download-video .option-item{display:flex;justify-content:space-between;align-items:center;padding-top:12px;font-size:10pt}.v-dropdown{position:relative;background-color:#8884;cursor:pointer;display:flex;align-items:center;justify-content:space-between;min-width:100px}.v-dropdown .dropdown-menu{transform-origin:top;transform:scaleY(0) translateX(-50%);position:absolute;top:calc(100% + 2px);left:50%;background-color:var(--download-video-background);z-index:1;transition:.2s cubic-bezier(.6,-.28,.74,.05);box-shadow:rgba(0,0,0,.2) 0 4px 8px 0}.v-dropdown .dropdown-menu.opened{transform:scaleY(1) translateX(-50%);transition-timing-function:cubic-bezier(.18,.89,.32,1.28)}.v-dropdown .dropdown-menu li{padding:4px 8px;white-space:nowrap;min-width:80px;text-align:center;cursor:pointer;color:var(--download-video-foreground);background-color:transparent}.v-dropdown .dropdown-menu li:hover{background-color:rgba(0,0,0,.16)}.v-dropdown .mdi-chevron-down{font-size:16pt;line-height:1;transform:rotate(0)}.v-dropdown .dropdown-menu.opened~.mdi-chevron-down{transform:rotate(180deg)}.v-dropdown .selected{user-select:none;padding:4px 8px}.download-video .tabs{display:flex;padding-top:12px;font-size:10pt}.download-video .tabs .tab{padding:6px 12px;border-bottom:2px solid transparent;cursor:pointer}.download-video .tab.active{color:var(--theme-color);border-bottom-color:var(--theme-color)}.download-video .separator{height:1px;background:#8884;width:100%;margin:12px 0}.download-video h2{font-size:12pt;font-weight:700;color:var(--download-video-foreground)}.download-video .direct-download{display:flex;flex-direction:column;align-items:start;justify-content:space-between}.download-video .button,.download-video button{border:none;outline:0!important;padding:6px 16px;font-size:10pt;cursor:pointer;background:#8884;color:var(--download-video-foreground)}.download-video .button:hover,.download-video button:hover{background:#8886}.download-video .primary{background:var(--theme-color);color:var(--foreground-color);align-self:center}.download-video .primary:hover{background:var(--theme-color-90)}.download-video .busy .button,.download-video .busy .primary,.download-video .busy button,.download-video button:disabled{background-color:#0001;color:#8884;cursor:not-allowed}.download-video .busy .button,.download-video .busy button{cursor:wait!important}.download-video .direct-download .progress{align-self:stretch;display:flex;align-items:center;margin-top:8px}.download-video .direct-download .progress .background{flex-grow:1;height:4px;background:#8884;margin-right:4px;position:relative}.download-video .direct-download .progress .foreground{position:absolute;top:0;left:0;height:4px;background:linear-gradient(to right,var(--theme-color),var(--theme-color-60))}body.dark .download-video .direct-download .progress .foreground{background:linear-gradient(to right,var(--theme-color-70),var(--theme-color))}.download-video .direct-download .progress .percent{width:50px;text-align:right}.download-video .actions{display:flex;flex-wrap:wrap;justify-content:space-between;margin-top:8px}.download-video .actions>*{margin:4px;flex-grow:1;flex-basis:calc(50% - 16px);display:flex;justify-content:center;align-items:center}.download-video i.mdi-alert-circle{font-size:14pt;color:#ff9800}.download-video .size-warning{position:relative;padding:0 8px}.download-video .size-warning-tip{position:absolute;bottom:100%;left:50%;transform:translateX(-50%);background:var(--download-video-background);color:var(--download-video-foreground);border:1px dashed var(--theme-color);z-index:2;font-size:10pt;width:300px;padding:8px;box-shadow:rgba(0,0,0,.2) 0 4px 8px 0;pointer-events:none;opacity:0}.download-video .size-warning:hover .size-warning-tip{opacity:1}.download-video .episode-list .v-checkbox{padding:4px 8px;margin:4px 0;position:relative;background-color:transparent}.download-video .episode-list .v-checkbox.checked{background-color:#8882}.v-checkbox{font-size:10pt;cursor:pointer;display:flex;align-items:center}.v-checkbox .mdi{font-size:15pt;line-height:1}.v-checkbox .content{flex-grow:1;text-align:left;padding:0 8px}.v-checkbox .mdi-checkbox-marked-circle{color:var(--theme-color);position:absolute;top:0;left:0;transform:scale(0);transition-timing-function:cubic-bezier(.6,-.28,.74,.05)}.v-checkbox .mdi-checkbox-blank-circle-outline{color:#8884;position:relative}.v-checkbox.checked .mdi-checkbox-blank-circle-outline{color:var(--theme-color)}.v-checkbox.checked .mdi-checkbox-marked-circle{transform:scale(1);transition-timing-function:cubic-bezier(.18,.89,.32,1.28)}.download-video .episode-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:12px}.download-video .episode-list{overflow:auto;max-height:320px}.download-video button.list-tool{padding:4px;line-height:1;font-size:12pt;margin:0 4px}.download-video .episode-header h2{flex-grow:1}.download-video .selected-count{width:64px;text-align:right}.download-video .aria2-rpc .mdi{margin-left:8px;font-size:14pt;line-height:1}.download-video .aria2-rpc{position:relative}.download-video .rpc-settings{position:absolute;display:flex;flex-direction:column;align-items:center;color:var(--download-video-foreground);background:var(--download-video-background);bottom:120%;left:50%;cursor:initial;box-shadow:rgba(0,0,0,.2) 0 4px 8px 0;transform-origin:bottom;transform:translateX(-50%);opacity:0;pointer-events:none;padding:8px;z-index:3}.download-video .rpc-settings>*{margin:8px}.download-video .rpc-settings.show{opacity:1;pointer-events:initial}.download-video .rpc-settings-item{display:flex;align-items:center;justify-content:space-between;white-space:nowrap}.download-video .rpc-settings input[type=text]{background:0 0;color:var(--download-video-foreground);border:1px solid #8884;padding:4px;margin-left:8px}.download-video .rpc-settings input[type=text]:focus{border-color:var(--theme-color)}`; offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/download-video.min.html"] = `

下载视频

单个视频
批量导出
警告: 过大的视频大小会在直接下载时占用大量内存, 并可能导致浏览器标签页崩溃. 请考虑降低清晰度或使用导出选项.
预计大小: {{displaySize}}
清晰度
弹幕

直接下载

{{progressPercent}}%

选集

{{selectedEpisodeCount}}/{{episodeList.length}}

导出

导出aria2 RPC

aria2 RPC 配置

主机
端口
密钥
路径
确定
`; -offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/download-video.min.js"] = (()=>{return(e,t)=>{const{getFriendlyTitle:s}=t.import("title");const{VideoInfo:a,DanmakuInfo:n}=t.import("video-info");class i{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 o extends i{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 i,aid:"",cid:""};let l=[];let c=null;class d{constructor(e,t,s){this.quality=e;this.internalName=t;this.displayName=s}async downloadInfo(){const e=new u(this);await e.fetchVideoInfo();return e}static get availableFormats(){return new Promise((e,t)=>{r.entity.getUrl().then(s=>{const a=new XMLHttpRequest;a.addEventListener("load",()=>{const s=JSON.parse(a.responseText);if(s.code!==0){t("获取清晰度信息失败.");return}const n=s.data||s.result||s;const i=n.accept_quality;const o=n.accept_format.split(",");const r=n.accept_description;const l=[];while(i.length>0){const e=new d(i.pop(),o.pop(),r.pop());l.push(e)}e(l.reverse())});a.addEventListener("error",()=>t(`获取清晰度信息失败.`));a.withCredentials=true;a.open("GET",s);a.send()})})}}class h{constructor(e,t,s,a){this.length=e;this.size=t;this.url=s;this.backupUrls=a}}class u{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(s=>{const a=new XMLHttpRequest;a.addEventListener("load",()=>{const s=JSON.parse(a.responseText.replace(/http:/g,"https:"));const n=s.data||s.result||s;if(n.quality!==this.format.quality){t("获取下载链接失败, 请确认当前账号有下载权限后重试.")}const i=n.durl;this.fragments=i.map(e=>new h(e.length,e.size,e.url,e.backup_url));e(this.fragments)});a.withCredentials=true;a.open("GET",s);a.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 s=Math.round(e.size/this.fragmentSplitFactor);let a=0;const n=e=>[...this.progressMap.keys()].indexOf(e)+1;while(a{const a=new XMLHttpRequest;a.open("GET",e.url);a.responseType="arraybuffer";a.withCredentials=false;a.addEventListener("progress",e=>{console.log(`[下载视频] 视频片段${n(a)}下载进度: ${e.loaded}/${r} bytes loaded, ${o}`);this.progressMap.set(a,e.loaded);this.updateProgress()});a.addEventListener("load",()=>{if((""+a.status)[0]==="2"){t(a.response)}else{s(`请求失败.`)}});a.addEventListener("abort",()=>s("canceled"));a.addEventListener("error",()=>{console.error(`[下载视频] 视频片段${n(a)}下载失败: ${o}`);this.progressMap.set(a,0);this.updateProgress();a.open("GET",e.url);a.setRequestHeader("Range",o);a.send()});a.setRequestHeader("Range",o);this.progressMap.set(a,0);a.send();this.workingXhr.push(a)}));a=Math.round(a+s)+1}return Promise.all(t)}async 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 s=document.createElement("a");let a;if(typeof e==="string"){a=e}else{a=URL.createObjectURL(e)}s.setAttribute("href",a);s.setAttribute("download",t);document.body.appendChild(s);s.click();s.remove();URL.revokeObjectURL(a)}async exportData(e=false){const t=JSON.stringify([{fragments:this.fragments,title:s(),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 a=await this.downloadDanmaku();if(a!==null){const t=new JSZip;t.file(`${s()}.json`,e);t.file(s()+"."+this.danmakuOption.toLowerCase(),a);u.downloadBlob(await t.generateAsync({type:"blob"}),`${s()}.zip`)}else{u.downloadBlob(e,`${s()}.json`)}}}async exportAria2(t=false){if(t){const t=await this.downloadDanmaku();if(t!==null){u.downloadBlob(new Blob([t]),`${s()}.${this.danmakuOption==="ASS"?"ass":"xml"}`)}const a=e.aria2RpcOption;const n=a.host.startsWith("http://")?a.host:"http://"+a.host;const i="aria2.addUri";const o=this.fragments.map((e,t)=>{let n="";if(this.fragments.length>1){n=" - "+(t+1)}const i=[];if(a.secretKey!==""){i.push(`token:${a.secretKey}`)}i.push([e.url]);i.push({referer:document.URL.replace(window.location.search,""),"user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0",out:`${s()}${n}${this.extension(e)}`,split:this.fragmentSplitFactor,dir:a.dir});const o=window.btoa(unescape(encodeURIComponent(JSON.stringify(i))));const r=`${s()}${n}`;return{base64Params:o,id:r}});for(const e of o){try{const t=await Ajax.getJson(`${n}:${a.port}/jsonrpc?method=${i}&id=${e.id}¶ms=${e.base64Params}`);if(t.error!==undefined){if(t.error.code===1){logError(`请求遭到拒绝, 请检查您的密钥相关设置.`)}else{logError(`请求发生错误, code = ${t.error.code}, message = ${t.error.message}`)}return}Toast.success(`成功发送了请求, GID = ${t.result}`,"aria2 RPC",5e3)}catch(e){logError(`无法连接到RPC主机, error = ${e}`);return}}}else{const e=`\n# Generated by Bilibili Evolved Video Export\n# https://github.com/the1812/Bilibili-Evolved/\n${this.fragments.map((e,t)=>{let a="";if(this.fragments.length>1){a=" - "+(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=${s()}${a}${this.extension(e)}\n split=${this.fragmentSplitFactor}\n `.trim()}).join("\n")}\n `.trim();const t=new Blob([e],{type:"text/plain"});const a=await this.downloadDanmaku();if(a!==null){const e=new JSZip;e.file(`${s()}.txt`,t);e.file(s()+"."+this.danmakuOption.toLowerCase(),a);u.downloadBlob(await e.generateAsync({type:"blob"}),`${s()}.zip`)}else{u.downloadBlob(t,`${s()}.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 n(r.cid);await e.fetchInfo();if(this.danmakuOption==="XML"){return e.rawXML}else{const{convertToAss:s}=await t.importAsync("download-danmaku");return s(e.rawXML)}}else{return null}}async downloadSingle(e){const t=await this.downloadDanmaku();const[a]=e;if(t===null){const e=this.makeBlob(a);const t=s()+this.extension();return{blob:e,filename:t}}else{const e=new JSZip;e.file(s()+this.extension(),this.makeBlob(a));e.file(s()+"."+this.danmakuOption.toLowerCase(),t);const n=await e.generateAsync({type:"blob"});const i=s()+".zip";return{blob:n,filename:i}}}async downloadMultiple(e){const t=new JSZip;const a=s();if(e.length>1){e.forEach((e,s)=>{const n=this.fragments[s];t.file(`${a} - ${s+1}${this.extension(n)}`,this.makeBlob(e,n))})}else{const[s]=e;t.file(`${a}${this.extension()}`,this.makeBlob(s))}const n=await this.downloadDanmaku();if(n!==null){t.file(s()+"."+this.danmakuOption.toLowerCase(),n)}const i=await t.generateAsync({type:"blob"});const o=a+".zip";return{blob:i,filename:o}}async download(){const e=[];for(const t of this.fragments){const s=await this.downloadFragment(t);e.push(s)}if(e.length<1){throw new Error("下载失败.")}let{blob:t,filename:s}=await(async()=>{if(e.length===1){return await this.downloadSingle(e)}else{return await this.downloadMultiple(e)}})();this.cleanUpOldBlobUrl();const a=URL.createObjectURL(t);this.progress&&this.progress(0);return{url:a,filename:s}}}async function p(){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 o}else{r.entity=new i}try{l=await d.availableFormats}catch(e){return false}return true}async function m(){c=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"));w()},{once:true})}async function w(){Vue.component("v-dropdown",{template:`\n
\n {{value}}\n \n \n
\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")}}});Vue.component("v-checkbox",{template:`\n
\n \n \n \n {{model.title}}\n
\n `,props:["model"],methods:{toggleCheck(){this.model.checked=!this.model.checked}}});let i;const o=new Map;const h=new Vue({el:".download-video",data:{downloadSingle:true,coverUrl:'data:image/svg+xml;utf-8,',aid:r.aid,cid:r.cid,qualityModel:{value:c.displayName,items:l.map(e=>e.displayName)},danmakuModel:{value:e.downloadVideoDefaultDanmaku,items:["无","XML","ASS"]},progressPercent:0,size:"获取大小中",blobUrl:"",episodeList:[],downloading:false,batch:false,rpcSettings:e.aria2RpcOption,showRpcSettings:false,busy:false},computed:{displaySize(){if(typeof this.size==="string"){return this.size}const e=["B","KB","MB","GB","TB","PB","EB","ZB","YB"];let t=this.size;let s=0;while(t>=1024){t/=1024;s++}return`${Math.round(t*10)/10}${e[s]}`},sizeWarning(){if(typeof this.size==="string"){return false}return this.size>1073741824},selectedEpisodeCount(){return this.episodeList.filter(e=>e.checked).length}},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();this.size=t.totalSize;o.set(e,this.size)}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){if(this.busy===true){return}try{this.busy=true;if(!this.downloadSingle){await this.exportBatchData(e);return}const t=this.getFormat();const s=await t.downloadInfo();s.danmakuOption=this.danmakuModel.value;switch(e){case"copyLink":await s.copyUrl();Toast.success("已复制链接到剪贴板.","下载视频",3e3);break;case"aria2":await s.exportAria2(false);break;case"aria2RPC":await s.exportAria2(true);break;case"copyVLD":await s.exportData(true);Toast.success("已复制VLD数据到剪贴板.","下载视频",3e3);break;case"exportVLD":await s.exportData(false);break;default:break}}catch(e){logError(e)}finally{this.busy=false}},async exportBatchData(e){const a=this.episodeList;if(a.every(e=>e.checked===false)){Toast.info("请至少选择1集或以上的数量!","批量导出",3e3);return}const i=this.getFormat();if(this.danmakuModel.value!=="无"){const e=Toast.info("下载弹幕中...","批量导出");const s=new JSZip;try{if(this.danmakuModel.value==="XML"){for(const e of a){const t=new n(e.cid);await t.fetchInfo();s.file(e.title+".xml",t.rawXML)}}else{const{convertToAss:e}=await t.importAsync("download-danmaku");for(const t of a){const a=new n(t.cid);await a.fetchInfo();s.file(t.title+".ass",await e(a.rawXML))}}u.downloadBlob(await s.generateAsync({type:"blob"}),this.cid+".danmakus.zip")}catch(e){logError(e)}finally{e.dismiss()}}const o=Toast.info("获取链接中...","批量导出");const r=e=>{const t=a.find(t=>t.cid===e.cid);if(t===undefined){return false}return t.checked};this.batchExtractor.itemFilter=r;let l;try{switch(e){case"aria2":l=await this.batchExtractor.collectAria2(i,o);u.downloadBlob(new Blob([l],{type:"text/plain"}),s(false)+".txt");return;case"aria2RPC":await this.batchExtractor.collectAria2(i,o,true);Toast.success(`成功发送了批量请求.`,"aria2 RPC",3e3);return;case"copyVLD":GM_setClipboard(await this.batchExtractor.collectData(i,o),{mimetype:"text/plain"});Toast.success("已复制批量vld数据到剪贴板.","批量导出",3e3);return;case"exportVLD":l=await this.batchExtractor.collectData(i,o);u.downloadBlob(new Blob([l],{type:"text/json"}),s(false)+".json");return;default:return}}catch(e){logError(e)}finally{o.dismiss()}},async checkBatch(){const e=["/www.bilibili.com/bangumi","/www.bilibili.com/video/av"];if(!e.some(e=>document.URL.includes(e))){this.batch=false;this.episodeList=[];return}const{BatchExtractor:s}=await t.importAsync("batch-download");if(await s.test()!==true){this.batch=false;this.episodeList=[];return}this.batchExtractor=new s;this.batch=true;this.episodeList=(await this.batchExtractor.getItemList()).map((e,t)=>{return{aid:e.aid,cid:e.cid,title:e.title,index:t,checked:true}})},cancelDownload(){if(i){i.cancelDownload()}},async startDownload(){const e=this.getFormat();try{this.downloading=true;const t=await e.downloadInfo();t.danmakuOption=this.danmakuModel.value;t.progress=(e=>{this.progressPercent=Math.trunc(e*100)});i=t;const s=await t.download();const a=document.getElementById("video-complete");a.setAttribute("href",s.url);a.setAttribute("download",s.filename);a.click();Toast.success(`下载完成: ${s.filename} 再次保存`,"下载视频")}catch(e){if(e!=="canceled"){logError(e)}this.progressPercent=0}finally{this.downloading=false}},selectAllEpisodes(){this.episodeList.forEach(e=>e.checked=true)},unselectAllEpisodes(){this.episodeList.forEach(e=>e.checked=false)},inverseAllEpisodes(){this.episodeList.forEach(e=>e.checked=!e.checked)},toggleRpcSettings(){this.showRpcSettings=!this.showRpcSettings},saveRpcSettings(){if(this.rpcSettings.host===""){this.rpcSettings.host="127.0.0.1"}if(this.rpcSettings.port===""){this.rpcSettings.port="6800"}e.aria2RpcOption=this.rpcSettings}}});Observer.videoChange(async()=>{h.close();h.batch=false;h.downloadSingle=true;const e=dq("#download-video");const t=await p();e.style.display=t?"flex":"none";if(!t){return}h.aid=r.aid;h.cid=r.cid;const s=new a(r.aid);await s.fetchInfo();h.coverUrl=s.coverUrl.replace("http:","https:");l=await d.availableFormats;[c]=l;h.qualityModel={value:c.displayName,items:l.map(e=>e.displayName)};h.formatChange();await h.checkBatch()})}return{widget:{content:`\n `,condition:p,success:m}}}})(); +offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/download-video.min.js"] = (()=>{return(e,t)=>{const{getFriendlyTitle:s}=t.import("title");const{VideoInfo:a,DanmakuInfo:n}=t.import("video-info");class i{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 o extends i{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 i,aid:"",cid:""};let l=[];let c=null;class d{constructor(e,t,s){this.quality=e;this.internalName=t;this.displayName=s}async downloadInfo(){const e=new u(this);await e.fetchVideoInfo();return e}static get availableFormats(){return new Promise((e,t)=>{r.entity.getUrl().then(s=>{const a=new XMLHttpRequest;a.addEventListener("load",()=>{const s=JSON.parse(a.responseText);if(s.code!==0){t("获取清晰度信息失败.");return}const n=s.data||s.result||s;const i=n.accept_quality;const o=n.accept_format.split(",");const r=n.accept_description;const l=[];while(i.length>0){const e=new d(i.pop(),o.pop(),r.pop());l.push(e)}e(l.reverse())});a.addEventListener("error",()=>t(`获取清晰度信息失败.`));a.withCredentials=true;a.open("GET",s);a.send()})})}}class h{constructor(e,t,s,a){this.length=e;this.size=t;this.url=s;this.backupUrls=a}}class u{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(s=>{const a=new XMLHttpRequest;a.addEventListener("load",()=>{const s=JSON.parse(a.responseText.replace(/http:/g,"https:"));const n=s.data||s.result||s;if(n.quality!==this.format.quality){t("获取下载链接失败, 请确认当前账号有下载权限后重试.")}const i=n.durl;this.fragments=i.map(e=>new h(e.length,e.size,e.url,e.backup_url));e(this.fragments)});a.withCredentials=true;a.open("GET",s);a.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 s=Math.round(e.size/this.fragmentSplitFactor);let a=0;const n=e=>[...this.progressMap.keys()].indexOf(e)+1;while(a{const a=new XMLHttpRequest;a.open("GET",e.url);a.responseType="arraybuffer";a.withCredentials=false;a.addEventListener("progress",e=>{console.log(`[下载视频] 视频片段${n(a)}下载进度: ${e.loaded}/${r} bytes loaded, ${o}`);this.progressMap.set(a,e.loaded);this.updateProgress()});a.addEventListener("load",()=>{if((""+a.status)[0]==="2"){t(a.response)}else{s(`请求失败.`)}});a.addEventListener("abort",()=>s("canceled"));a.addEventListener("error",()=>{console.error(`[下载视频] 视频片段${n(a)}下载失败: ${o}`);this.progressMap.set(a,0);this.updateProgress();a.open("GET",e.url);a.setRequestHeader("Range",o);a.send()});a.setRequestHeader("Range",o);this.progressMap.set(a,0);a.send();this.workingXhr.push(a)}));a=Math.round(a+s)+1}return Promise.all(t)}async 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 s=document.createElement("a");let a;if(typeof e==="string"){a=e}else{a=URL.createObjectURL(e)}s.setAttribute("href",a);s.setAttribute("download",t);document.body.appendChild(s);s.click();s.remove();URL.revokeObjectURL(a)}async exportData(e=false){const t=JSON.stringify([{fragments:this.fragments,title:s(),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 a=await this.downloadDanmaku();if(a!==null){const t=new JSZip;t.file(`${s()}.json`,e);t.file(s()+"."+this.danmakuOption.toLowerCase(),a);u.downloadBlob(await t.generateAsync({type:"blob"}),`${s()}.zip`)}else{u.downloadBlob(e,`${s()}.json`)}}}async exportAria2(t=false){if(t){const t=await this.downloadDanmaku();if(t!==null){u.downloadBlob(new Blob([t]),`${s()}.${this.danmakuOption==="ASS"?"ass":"xml"}`)}const a=e.aria2RpcOption;const n=a.host.match(/^http[s]?:\/\//)?a.host:"http://"+a.host;const i="aria2.addUri";const o=this.fragments.map((e,t)=>{let n="";if(this.fragments.length>1){n=" - "+(t+1)}const i=[];if(a.secretKey!==""){i.push(`token:${a.secretKey}`)}i.push([e.url]);i.push({referer:document.URL.replace(window.location.search,""),"user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0",out:`${s()}${n}${this.extension(e)}`,split:this.fragmentSplitFactor,dir:a.dir});const o=window.btoa(unescape(encodeURIComponent(JSON.stringify(i))));const r=`${s()}${n}`;return{base64Params:o,id:r}});for(const e of o){try{const t=await Ajax.getJson(`${n}:${a.port}/jsonrpc?method=${i}&id=${e.id}¶ms=${e.base64Params}`);if(t.error!==undefined){if(t.error.code===1){logError(`请求遭到拒绝, 请检查您的密钥相关设置.`)}else{logError(`请求发生错误, code = ${t.error.code}, message = ${t.error.message}`)}return}Toast.success(`成功发送了请求, GID = ${t.result}`,"aria2 RPC",5e3)}catch(e){logError(`无法连接到RPC主机, error = ${e}`);return}}}else{const e=`\n# Generated by Bilibili Evolved Video Export\n# https://github.com/the1812/Bilibili-Evolved/\n${this.fragments.map((e,t)=>{let a="";if(this.fragments.length>1){a=" - "+(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=${s()}${a}${this.extension(e)}\n split=${this.fragmentSplitFactor}\n `.trim()}).join("\n")}\n `.trim();const t=new Blob([e],{type:"text/plain"});const a=await this.downloadDanmaku();if(a!==null){const e=new JSZip;e.file(`${s()}.txt`,t);e.file(s()+"."+this.danmakuOption.toLowerCase(),a);u.downloadBlob(await e.generateAsync({type:"blob"}),`${s()}.zip`)}else{u.downloadBlob(t,`${s()}.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 n(r.cid);await e.fetchInfo();if(this.danmakuOption==="XML"){return e.rawXML}else{const{convertToAss:s}=await t.importAsync("download-danmaku");return s(e.rawXML)}}else{return null}}async downloadSingle(e){const t=await this.downloadDanmaku();const[a]=e;if(t===null){const e=this.makeBlob(a);const t=s()+this.extension();return{blob:e,filename:t}}else{const e=new JSZip;e.file(s()+this.extension(),this.makeBlob(a));e.file(s()+"."+this.danmakuOption.toLowerCase(),t);const n=await e.generateAsync({type:"blob"});const i=s()+".zip";return{blob:n,filename:i}}}async downloadMultiple(e){const t=new JSZip;const a=s();if(e.length>1){e.forEach((e,s)=>{const n=this.fragments[s];t.file(`${a} - ${s+1}${this.extension(n)}`,this.makeBlob(e,n))})}else{const[s]=e;t.file(`${a}${this.extension()}`,this.makeBlob(s))}const n=await this.downloadDanmaku();if(n!==null){t.file(s()+"."+this.danmakuOption.toLowerCase(),n)}const i=await t.generateAsync({type:"blob"});const o=a+".zip";return{blob:i,filename:o}}async download(){const e=[];for(const t of this.fragments){const s=await this.downloadFragment(t);e.push(s)}if(e.length<1){throw new Error("下载失败.")}let{blob:t,filename:s}=await(async()=>{if(e.length===1){return await this.downloadSingle(e)}else{return await this.downloadMultiple(e)}})();this.cleanUpOldBlobUrl();const a=URL.createObjectURL(t);this.progress&&this.progress(0);return{url:a,filename:s}}}async function p(){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 o}else{r.entity=new i}try{l=await d.availableFormats}catch(e){return false}return true}async function m(){c=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"));w()},{once:true})}async function w(){Vue.component("v-dropdown",{template:`\n
\n {{value}}\n \n \n
\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")}}});Vue.component("v-checkbox",{template:`\n
\n \n \n \n {{model.title}}\n
\n `,props:["model"],methods:{toggleCheck(){this.model.checked=!this.model.checked}}});let i;const o=new Map;const h=new Vue({el:".download-video",data:{downloadSingle:true,coverUrl:'data:image/svg+xml;utf-8,',aid:r.aid,cid:r.cid,qualityModel:{value:c.displayName,items:l.map(e=>e.displayName)},danmakuModel:{value:e.downloadVideoDefaultDanmaku,items:["无","XML","ASS"]},progressPercent:0,size:"获取大小中",blobUrl:"",episodeList:[],downloading:false,batch:false,rpcSettings:e.aria2RpcOption,showRpcSettings:false,busy:false},computed:{displaySize(){if(typeof this.size==="string"){return this.size}const e=["B","KB","MB","GB","TB","PB","EB","ZB","YB"];let t=this.size;let s=0;while(t>=1024){t/=1024;s++}return`${Math.round(t*10)/10}${e[s]}`},sizeWarning(){if(typeof this.size==="string"){return false}return this.size>1073741824},selectedEpisodeCount(){return this.episodeList.filter(e=>e.checked).length}},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();this.size=t.totalSize;o.set(e,this.size)}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){if(this.busy===true){return}try{this.busy=true;if(!this.downloadSingle){await this.exportBatchData(e);return}const t=this.getFormat();const s=await t.downloadInfo();s.danmakuOption=this.danmakuModel.value;switch(e){case"copyLink":await s.copyUrl();Toast.success("已复制链接到剪贴板.","下载视频",3e3);break;case"aria2":await s.exportAria2(false);break;case"aria2RPC":await s.exportAria2(true);break;case"copyVLD":await s.exportData(true);Toast.success("已复制VLD数据到剪贴板.","下载视频",3e3);break;case"exportVLD":await s.exportData(false);break;default:break}}catch(e){logError(e)}finally{this.busy=false}},async exportBatchData(e){const a=this.episodeList;if(a.every(e=>e.checked===false)){Toast.info("请至少选择1集或以上的数量!","批量导出",3e3);return}const i=this.getFormat();if(this.danmakuModel.value!=="无"){const e=Toast.info("下载弹幕中...","批量导出");const s=new JSZip;try{if(this.danmakuModel.value==="XML"){for(const e of a){const t=new n(e.cid);await t.fetchInfo();s.file(e.title+".xml",t.rawXML)}}else{const{convertToAss:e}=await t.importAsync("download-danmaku");for(const t of a){const a=new n(t.cid);await a.fetchInfo();s.file(t.title+".ass",await e(a.rawXML))}}u.downloadBlob(await s.generateAsync({type:"blob"}),this.cid+".danmakus.zip")}catch(e){logError(e)}finally{e.dismiss()}}const o=Toast.info("获取链接中...","批量导出");const r=e=>{const t=a.find(t=>t.cid===e.cid);if(t===undefined){return false}return t.checked};this.batchExtractor.itemFilter=r;let l;try{switch(e){case"aria2":l=await this.batchExtractor.collectAria2(i,o);u.downloadBlob(new Blob([l],{type:"text/plain"}),s(false)+".txt");return;case"aria2RPC":await this.batchExtractor.collectAria2(i,o,true);Toast.success(`成功发送了批量请求.`,"aria2 RPC",3e3);return;case"copyVLD":GM_setClipboard(await this.batchExtractor.collectData(i,o),{mimetype:"text/plain"});Toast.success("已复制批量vld数据到剪贴板.","批量导出",3e3);return;case"exportVLD":l=await this.batchExtractor.collectData(i,o);u.downloadBlob(new Blob([l],{type:"text/json"}),s(false)+".json");return;default:return}}catch(e){logError(e)}finally{o.dismiss()}},async checkBatch(){const e=["/www.bilibili.com/bangumi","/www.bilibili.com/video/av"];if(!e.some(e=>document.URL.includes(e))){this.batch=false;this.episodeList=[];return}const{BatchExtractor:s}=await t.importAsync("batch-download");if(await s.test()!==true){this.batch=false;this.episodeList=[];return}this.batchExtractor=new s;this.batch=true;this.episodeList=(await this.batchExtractor.getItemList()).map((e,t)=>{return{aid:e.aid,cid:e.cid,title:e.title,index:t,checked:true}})},cancelDownload(){if(i){i.cancelDownload()}},async startDownload(){const e=this.getFormat();try{this.downloading=true;const t=await e.downloadInfo();t.danmakuOption=this.danmakuModel.value;t.progress=(e=>{this.progressPercent=Math.trunc(e*100)});i=t;const s=await t.download();const a=document.getElementById("video-complete");a.setAttribute("href",s.url);a.setAttribute("download",s.filename);a.click();Toast.success(`下载完成: ${s.filename} 再次保存`,"下载视频")}catch(e){if(e!=="canceled"){logError(e)}this.progressPercent=0}finally{this.downloading=false}},selectAllEpisodes(){this.episodeList.forEach(e=>e.checked=true)},unselectAllEpisodes(){this.episodeList.forEach(e=>e.checked=false)},inverseAllEpisodes(){this.episodeList.forEach(e=>e.checked=!e.checked)},toggleRpcSettings(){this.showRpcSettings=!this.showRpcSettings},saveRpcSettings(){if(this.rpcSettings.host===""){this.rpcSettings.host="127.0.0.1"}if(this.rpcSettings.port===""){this.rpcSettings.port="6800"}e.aria2RpcOption=this.rpcSettings}}});Observer.videoChange(async()=>{h.close();h.batch=false;h.downloadSingle=true;const e=dq("#download-video");const t=await p();e.style.display=t?"flex":"none";if(!t){return}h.aid=r.aid;h.cid=r.cid;const s=new a(r.aid);await s.fetchInfo();h.coverUrl=s.coverUrl.replace("http:","https:");l=await d.availableFormats;[c]=l;h.qualityModel={value:c.displayName,items:l.map(e=>e.displayName)};h.formatChange();await h.checkBatch()})}return{widget:{content:`\n `,condition:p,success:m}}}})(); offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/expand-danmaku.min.js"] = (()=>{return(e,a)=>{if(typeof isEmbeddedPlayer!=="undefined"&&isEmbeddedPlayer()){return}Observer.videoChange(async()=>{const e=await SpinQuery.select(".bui-collapse-wrap");if(e&&e.classList.contains("bui-collapse-wrap-folded")){const e=await SpinQuery.select(".bui-collapse-header");e.click()}})}})(); offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/expand-description.min.css"] = `.play-up-info .play-up-self,.video-desc .info{height:auto!important}.play-up-info .play-up-self-btn,.video-desc .btn{display:none!important}`; offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/expand-description.min.js"] = (()=>{return(e,p)=>{p.applyStyle("expandDescriptionStyle")}})(); diff --git a/min/batch-download.min.js b/min/batch-download.min.js index c6daf5e2c..f2b1a60e4 100644 --- a/min/batch-download.min.js +++ b/min/batch-download.min.js @@ -1 +1 @@ -(()=>{return(t,e)=>{const i=12;class r{constructor(){this.itemList=[];this.itemFilter=(()=>true)}async getItemList(){}async collectData(){}async collectAria2(e,r){const s=JSON.parse(await this.collectData(e));if(r){const e=t.aria2RpcOption;const r=e.host.startsWith("http://")?e.host:"http://"+e.host;const n="aria2.addUri";for(const t of s){const s=t.fragments.map((r,s)=>{let n="";if(t.fragments.length>1){n=" - "+(s+1)}const a=[];if(e.secretKey!==""){a.push(`token:${e.secretKey}`)}a.push([r.url]);a.push({referer:document.URL.replace(window.location.search,""),"user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0",out:`${t.title}${n}.flv`,split:i,dir:e.dir});const o=window.btoa(unescape(encodeURIComponent(JSON.stringify(a))));const c=`${t.title}${n}`;return{base64Params:o,id:c}});for(const t of s){try{const i=await Ajax.getJson(`${r}:${e.port}/jsonrpc?method=${n}&id=${t.id}¶ms=${t.base64Params}`);if(i.error!==undefined){if(i.error.code===1){logError(`请求遭到拒绝, 请检查您的密钥相关设置.`)}else{logError(`请求发生错误, code = ${i.error.code}, message = ${i.error.message}`)}return}}catch(t){logError(`无法连接到RPC主机, error = ${t}`);return}}}}else{return`\n# Generated by Bilibili Evolved Video Export\n# https://github.com/the1812/Bilibili-Evolved/\n${s.map(t=>{return t.fragments.map(e=>{return`\n${e.url}\n referer=${t.referer}\n user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0\n out=${t.title}.flv\n split=${i}\n `.trim()})}).join("\n")}\n `.trim()}}}class s extends r{static async test(){if(!document.URL.includes("/www.bilibili.com/video/av")){return false}return await SpinQuery.select("#multi_page")!==null}async getItemList(){if(this.itemList.length>0){return this.itemList}const t=`https://api.bilibili.com/x/web-interface/view?aid=${unsafeWindow.aid}`;const e=await Ajax.getJson(t);if(e.code!==0){Toast.error(`获取视频选集列表失败, message=${e.message}`,"批量下载");return""}const i=e.data.pages;if(i===undefined){Toast.error(`获取视频选集列表失败, 没有找到选集信息.`,"批量下载");return""}this.itemList=i.map(t=>{return{title:`P${t.page} ${t.part}`,cid:t.cid,aid:unsafeWindow.aid}});return this.itemList}async collectData(t){const e=[];for(const i of(await this.getItemList()).filter(this.itemFilter)){const r=`https://api.bilibili.com/x/player/playurl?avid=${i.aid}&cid=${i.cid}&qn=${t}&otype=json`;const s=await Ajax.getJsonWithCredentials(r);const n=s.data||s.result||s;if(n.quality!==t){Toast.error("获取下载链接失败, 请确认当前账号有下载权限后重试.","批量下载");return""}const a=n.durl.map(t=>{return{length:t.length,size:t.size,url:t.url}});e.push({fragments:a,title:i.title,totalSize:a.map(t=>t.size).reduce((t,e)=>t+e),cid:i.cid,referer:document.URL.replace(window.location.search,"")})}return JSON.stringify(e)}}class n extends r{static async test(){return document.URL.includes("/www.bilibili.com/bangumi")}async getItemList(){if(this.itemList.length>0){return this.itemList}const t=document.querySelector("meta[property='og:url']");if(t===null){Toast.error("获取番剧数据失败: 无法找到 Season ID","批量下载");return""}const e=t.getAttribute("content").match(/play\/ss(\d+)/)[1];if(e===undefined){Toast.error("获取番剧数据失败: 无法解析 Season ID","批量下载");return""}const i=await Ajax.getJson(`https://api.bilibili.com/pgc/web/season/section?season_id=${e}`);if(i.code!==0){Toast.error(`获取番剧数据失败: 无法获取番剧集数列表, message=${i.message}`,"批量下载");return""}this.itemList=i.result.main_section.episodes.map((t,e)=>{return{aid:t.aid,cid:t.cid,title:t.long_title?`${t.title} - ${t.long_title}`:`${e+1} - ${t.title}`}});return this.itemList}async collectData(t){const e=[];for(const i of(await this.getItemList()).filter(this.itemFilter)){const r=`https://api.bilibili.com/pgc/player/web/playurl?avid=${i.aid}&cid=${i.cid}&qn=${t}&otype=json`;const s=await Ajax.getJsonWithCredentials(r);const n=s.data||s.result||s;if(n.quality!==t){Toast.error("获取下载链接失败, 请确认当前账号有下载权限后重试.","批量下载");return""}const a=n.durl.map(t=>{return{length:t.length,size:t.size,url:t.url}});e.push({fragments:a,title:i.title,totalSize:a.map(t=>t.size).reduce((t,e)=>t+e),cid:i.cid,referer:document.URL.replace(window.location.search,"")})}return JSON.stringify(e)}}const a=[n,s];let o=null;class c{constructor(){this.itemFilter=(()=>true)}static async test(){for(const t of a){if(await t.test()===true){o=t;return true}}o=null;return false}getExtractor(){if(o===null){logError("[批量下载] 未找到合适的解析模块.");throw new Error(`[Batch Download] module not found.`)}const t=new o;t.itemFilter=this.itemFilter;return t}async getItemList(){const t=this.getExtractor();return await t.getItemList()}async collectData(t,e){const i=this.getExtractor();const r=await i.collectData(t.quality);e.dismiss();return r}async collectAria2(t,e,i){const r=this.getExtractor();const s=await r.collectAria2(t.quality,i);e.dismiss();return s}}return{export:{BatchExtractor:c}}}})(); \ No newline at end of file +(()=>{return(t,e)=>{const i=12;class r{constructor(){this.itemList=[];this.itemFilter=(()=>true)}async getItemList(){}async collectData(){}async collectAria2(e,r){const s=JSON.parse(await this.collectData(e));if(r){const e=t.aria2RpcOption;const r=e.host.match(/^http[s]?:\/\//)?e.host:"http://"+e.host;const n="aria2.addUri";for(const t of s){const s=t.fragments.map((r,s)=>{let n="";if(t.fragments.length>1){n=" - "+(s+1)}const a=[];if(e.secretKey!==""){a.push(`token:${e.secretKey}`)}a.push([r.url]);a.push({referer:document.URL.replace(window.location.search,""),"user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0",out:`${t.title}${n}.flv`,split:i,dir:e.dir});const o=window.btoa(unescape(encodeURIComponent(JSON.stringify(a))));const c=`${t.title}${n}`;return{base64Params:o,id:c}});for(const t of s){try{const i=await Ajax.getJson(`${r}:${e.port}/jsonrpc?method=${n}&id=${t.id}¶ms=${t.base64Params}`);if(i.error!==undefined){if(i.error.code===1){logError(`请求遭到拒绝, 请检查您的密钥相关设置.`)}else{logError(`请求发生错误, code = ${i.error.code}, message = ${i.error.message}`)}return}}catch(t){logError(`无法连接到RPC主机, error = ${t}`);return}}}}else{return`\n# Generated by Bilibili Evolved Video Export\n# https://github.com/the1812/Bilibili-Evolved/\n${s.map(t=>{return t.fragments.map(e=>{return`\n${e.url}\n referer=${t.referer}\n user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0\n out=${t.title}.flv\n split=${i}\n `.trim()})}).join("\n")}\n `.trim()}}}class s extends r{static async test(){if(!document.URL.includes("/www.bilibili.com/video/av")){return false}return await SpinQuery.select("#multi_page")!==null}async getItemList(){if(this.itemList.length>0){return this.itemList}const t=`https://api.bilibili.com/x/web-interface/view?aid=${unsafeWindow.aid}`;const e=await Ajax.getJson(t);if(e.code!==0){Toast.error(`获取视频选集列表失败, message=${e.message}`,"批量下载");return""}const i=e.data.pages;if(i===undefined){Toast.error(`获取视频选集列表失败, 没有找到选集信息.`,"批量下载");return""}this.itemList=i.map(t=>{return{title:`P${t.page} ${t.part}`,cid:t.cid,aid:unsafeWindow.aid}});return this.itemList}async collectData(t){const e=[];for(const i of(await this.getItemList()).filter(this.itemFilter)){const r=`https://api.bilibili.com/x/player/playurl?avid=${i.aid}&cid=${i.cid}&qn=${t}&otype=json`;const s=await Ajax.getJsonWithCredentials(r);const n=s.data||s.result||s;if(n.quality!==t){Toast.error("获取下载链接失败, 请确认当前账号有下载权限后重试.","批量下载");return""}const a=n.durl.map(t=>{return{length:t.length,size:t.size,url:t.url}});e.push({fragments:a,title:i.title,totalSize:a.map(t=>t.size).reduce((t,e)=>t+e),cid:i.cid,referer:document.URL.replace(window.location.search,"")})}return JSON.stringify(e)}}class n extends r{static async test(){return document.URL.includes("/www.bilibili.com/bangumi")}async getItemList(){if(this.itemList.length>0){return this.itemList}const t=document.querySelector("meta[property='og:url']");if(t===null){Toast.error("获取番剧数据失败: 无法找到 Season ID","批量下载");return""}const e=t.getAttribute("content").match(/play\/ss(\d+)/)[1];if(e===undefined){Toast.error("获取番剧数据失败: 无法解析 Season ID","批量下载");return""}const i=await Ajax.getJson(`https://api.bilibili.com/pgc/web/season/section?season_id=${e}`);if(i.code!==0){Toast.error(`获取番剧数据失败: 无法获取番剧集数列表, message=${i.message}`,"批量下载");return""}this.itemList=i.result.main_section.episodes.map((t,e)=>{return{aid:t.aid,cid:t.cid,title:t.long_title?`${t.title} - ${t.long_title}`:`${e+1} - ${t.title}`}});return this.itemList}async collectData(t){const e=[];for(const i of(await this.getItemList()).filter(this.itemFilter)){const r=`https://api.bilibili.com/pgc/player/web/playurl?avid=${i.aid}&cid=${i.cid}&qn=${t}&otype=json`;const s=await Ajax.getJsonWithCredentials(r);const n=s.data||s.result||s;if(n.quality!==t){Toast.error("获取下载链接失败, 请确认当前账号有下载权限后重试.","批量下载");return""}const a=n.durl.map(t=>{return{length:t.length,size:t.size,url:t.url}});e.push({fragments:a,title:i.title,totalSize:a.map(t=>t.size).reduce((t,e)=>t+e),cid:i.cid,referer:document.URL.replace(window.location.search,"")})}return JSON.stringify(e)}}const a=[n,s];let o=null;class c{constructor(){this.itemFilter=(()=>true)}static async test(){for(const t of a){if(await t.test()===true){o=t;return true}}o=null;return false}getExtractor(){if(o===null){logError("[批量下载] 未找到合适的解析模块.");throw new Error(`[Batch Download] module not found.`)}const t=new o;t.itemFilter=this.itemFilter;return t}async getItemList(){const t=this.getExtractor();return await t.getItemList()}async collectData(t,e){const i=this.getExtractor();const r=await i.collectData(t.quality);e.dismiss();return r}async collectAria2(t,e,i){const r=this.getExtractor();const s=await r.collectAria2(t.quality,i);e.dismiss();return s}}return{export:{BatchExtractor:c}}}})(); \ No newline at end of file diff --git a/min/download-video.min.js b/min/download-video.min.js index fbab28ae6..fb0cd2443 100644 --- a/min/download-video.min.js +++ b/min/download-video.min.js @@ -1 +1 @@ -(()=>{return(e,t)=>{const{getFriendlyTitle:s}=t.import("title");const{VideoInfo:a,DanmakuInfo:n}=t.import("video-info");class i{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 o extends i{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 i,aid:"",cid:""};let l=[];let c=null;class d{constructor(e,t,s){this.quality=e;this.internalName=t;this.displayName=s}async downloadInfo(){const e=new u(this);await e.fetchVideoInfo();return e}static get availableFormats(){return new Promise((e,t)=>{r.entity.getUrl().then(s=>{const a=new XMLHttpRequest;a.addEventListener("load",()=>{const s=JSON.parse(a.responseText);if(s.code!==0){t("获取清晰度信息失败.");return}const n=s.data||s.result||s;const i=n.accept_quality;const o=n.accept_format.split(",");const r=n.accept_description;const l=[];while(i.length>0){const e=new d(i.pop(),o.pop(),r.pop());l.push(e)}e(l.reverse())});a.addEventListener("error",()=>t(`获取清晰度信息失败.`));a.withCredentials=true;a.open("GET",s);a.send()})})}}class h{constructor(e,t,s,a){this.length=e;this.size=t;this.url=s;this.backupUrls=a}}class u{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(s=>{const a=new XMLHttpRequest;a.addEventListener("load",()=>{const s=JSON.parse(a.responseText.replace(/http:/g,"https:"));const n=s.data||s.result||s;if(n.quality!==this.format.quality){t("获取下载链接失败, 请确认当前账号有下载权限后重试.")}const i=n.durl;this.fragments=i.map(e=>new h(e.length,e.size,e.url,e.backup_url));e(this.fragments)});a.withCredentials=true;a.open("GET",s);a.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 s=Math.round(e.size/this.fragmentSplitFactor);let a=0;const n=e=>[...this.progressMap.keys()].indexOf(e)+1;while(a{const a=new XMLHttpRequest;a.open("GET",e.url);a.responseType="arraybuffer";a.withCredentials=false;a.addEventListener("progress",e=>{console.log(`[下载视频] 视频片段${n(a)}下载进度: ${e.loaded}/${r} bytes loaded, ${o}`);this.progressMap.set(a,e.loaded);this.updateProgress()});a.addEventListener("load",()=>{if((""+a.status)[0]==="2"){t(a.response)}else{s(`请求失败.`)}});a.addEventListener("abort",()=>s("canceled"));a.addEventListener("error",()=>{console.error(`[下载视频] 视频片段${n(a)}下载失败: ${o}`);this.progressMap.set(a,0);this.updateProgress();a.open("GET",e.url);a.setRequestHeader("Range",o);a.send()});a.setRequestHeader("Range",o);this.progressMap.set(a,0);a.send();this.workingXhr.push(a)}));a=Math.round(a+s)+1}return Promise.all(t)}async 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 s=document.createElement("a");let a;if(typeof e==="string"){a=e}else{a=URL.createObjectURL(e)}s.setAttribute("href",a);s.setAttribute("download",t);document.body.appendChild(s);s.click();s.remove();URL.revokeObjectURL(a)}async exportData(e=false){const t=JSON.stringify([{fragments:this.fragments,title:s(),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 a=await this.downloadDanmaku();if(a!==null){const t=new JSZip;t.file(`${s()}.json`,e);t.file(s()+"."+this.danmakuOption.toLowerCase(),a);u.downloadBlob(await t.generateAsync({type:"blob"}),`${s()}.zip`)}else{u.downloadBlob(e,`${s()}.json`)}}}async exportAria2(t=false){if(t){const t=await this.downloadDanmaku();if(t!==null){u.downloadBlob(new Blob([t]),`${s()}.${this.danmakuOption==="ASS"?"ass":"xml"}`)}const a=e.aria2RpcOption;const n=a.host.startsWith("http://")?a.host:"http://"+a.host;const i="aria2.addUri";const o=this.fragments.map((e,t)=>{let n="";if(this.fragments.length>1){n=" - "+(t+1)}const i=[];if(a.secretKey!==""){i.push(`token:${a.secretKey}`)}i.push([e.url]);i.push({referer:document.URL.replace(window.location.search,""),"user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0",out:`${s()}${n}${this.extension(e)}`,split:this.fragmentSplitFactor,dir:a.dir});const o=window.btoa(unescape(encodeURIComponent(JSON.stringify(i))));const r=`${s()}${n}`;return{base64Params:o,id:r}});for(const e of o){try{const t=await Ajax.getJson(`${n}:${a.port}/jsonrpc?method=${i}&id=${e.id}¶ms=${e.base64Params}`);if(t.error!==undefined){if(t.error.code===1){logError(`请求遭到拒绝, 请检查您的密钥相关设置.`)}else{logError(`请求发生错误, code = ${t.error.code}, message = ${t.error.message}`)}return}Toast.success(`成功发送了请求, GID = ${t.result}`,"aria2 RPC",5e3)}catch(e){logError(`无法连接到RPC主机, error = ${e}`);return}}}else{const e=`\n# Generated by Bilibili Evolved Video Export\n# https://github.com/the1812/Bilibili-Evolved/\n${this.fragments.map((e,t)=>{let a="";if(this.fragments.length>1){a=" - "+(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=${s()}${a}${this.extension(e)}\n split=${this.fragmentSplitFactor}\n `.trim()}).join("\n")}\n `.trim();const t=new Blob([e],{type:"text/plain"});const a=await this.downloadDanmaku();if(a!==null){const e=new JSZip;e.file(`${s()}.txt`,t);e.file(s()+"."+this.danmakuOption.toLowerCase(),a);u.downloadBlob(await e.generateAsync({type:"blob"}),`${s()}.zip`)}else{u.downloadBlob(t,`${s()}.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 n(r.cid);await e.fetchInfo();if(this.danmakuOption==="XML"){return e.rawXML}else{const{convertToAss:s}=await t.importAsync("download-danmaku");return s(e.rawXML)}}else{return null}}async downloadSingle(e){const t=await this.downloadDanmaku();const[a]=e;if(t===null){const e=this.makeBlob(a);const t=s()+this.extension();return{blob:e,filename:t}}else{const e=new JSZip;e.file(s()+this.extension(),this.makeBlob(a));e.file(s()+"."+this.danmakuOption.toLowerCase(),t);const n=await e.generateAsync({type:"blob"});const i=s()+".zip";return{blob:n,filename:i}}}async downloadMultiple(e){const t=new JSZip;const a=s();if(e.length>1){e.forEach((e,s)=>{const n=this.fragments[s];t.file(`${a} - ${s+1}${this.extension(n)}`,this.makeBlob(e,n))})}else{const[s]=e;t.file(`${a}${this.extension()}`,this.makeBlob(s))}const n=await this.downloadDanmaku();if(n!==null){t.file(s()+"."+this.danmakuOption.toLowerCase(),n)}const i=await t.generateAsync({type:"blob"});const o=a+".zip";return{blob:i,filename:o}}async download(){const e=[];for(const t of this.fragments){const s=await this.downloadFragment(t);e.push(s)}if(e.length<1){throw new Error("下载失败.")}let{blob:t,filename:s}=await(async()=>{if(e.length===1){return await this.downloadSingle(e)}else{return await this.downloadMultiple(e)}})();this.cleanUpOldBlobUrl();const a=URL.createObjectURL(t);this.progress&&this.progress(0);return{url:a,filename:s}}}async function p(){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 o}else{r.entity=new i}try{l=await d.availableFormats}catch(e){return false}return true}async function m(){c=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"));w()},{once:true})}async function w(){Vue.component("v-dropdown",{template:`\n
\n {{value}}\n \n \n
\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")}}});Vue.component("v-checkbox",{template:`\n
\n \n \n \n {{model.title}}\n
\n `,props:["model"],methods:{toggleCheck(){this.model.checked=!this.model.checked}}});let i;const o=new Map;const h=new Vue({el:".download-video",data:{downloadSingle:true,coverUrl:'data:image/svg+xml;utf-8,',aid:r.aid,cid:r.cid,qualityModel:{value:c.displayName,items:l.map(e=>e.displayName)},danmakuModel:{value:e.downloadVideoDefaultDanmaku,items:["无","XML","ASS"]},progressPercent:0,size:"获取大小中",blobUrl:"",episodeList:[],downloading:false,batch:false,rpcSettings:e.aria2RpcOption,showRpcSettings:false,busy:false},computed:{displaySize(){if(typeof this.size==="string"){return this.size}const e=["B","KB","MB","GB","TB","PB","EB","ZB","YB"];let t=this.size;let s=0;while(t>=1024){t/=1024;s++}return`${Math.round(t*10)/10}${e[s]}`},sizeWarning(){if(typeof this.size==="string"){return false}return this.size>1073741824},selectedEpisodeCount(){return this.episodeList.filter(e=>e.checked).length}},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();this.size=t.totalSize;o.set(e,this.size)}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){if(this.busy===true){return}try{this.busy=true;if(!this.downloadSingle){await this.exportBatchData(e);return}const t=this.getFormat();const s=await t.downloadInfo();s.danmakuOption=this.danmakuModel.value;switch(e){case"copyLink":await s.copyUrl();Toast.success("已复制链接到剪贴板.","下载视频",3e3);break;case"aria2":await s.exportAria2(false);break;case"aria2RPC":await s.exportAria2(true);break;case"copyVLD":await s.exportData(true);Toast.success("已复制VLD数据到剪贴板.","下载视频",3e3);break;case"exportVLD":await s.exportData(false);break;default:break}}catch(e){logError(e)}finally{this.busy=false}},async exportBatchData(e){const a=this.episodeList;if(a.every(e=>e.checked===false)){Toast.info("请至少选择1集或以上的数量!","批量导出",3e3);return}const i=this.getFormat();if(this.danmakuModel.value!=="无"){const e=Toast.info("下载弹幕中...","批量导出");const s=new JSZip;try{if(this.danmakuModel.value==="XML"){for(const e of a){const t=new n(e.cid);await t.fetchInfo();s.file(e.title+".xml",t.rawXML)}}else{const{convertToAss:e}=await t.importAsync("download-danmaku");for(const t of a){const a=new n(t.cid);await a.fetchInfo();s.file(t.title+".ass",await e(a.rawXML))}}u.downloadBlob(await s.generateAsync({type:"blob"}),this.cid+".danmakus.zip")}catch(e){logError(e)}finally{e.dismiss()}}const o=Toast.info("获取链接中...","批量导出");const r=e=>{const t=a.find(t=>t.cid===e.cid);if(t===undefined){return false}return t.checked};this.batchExtractor.itemFilter=r;let l;try{switch(e){case"aria2":l=await this.batchExtractor.collectAria2(i,o);u.downloadBlob(new Blob([l],{type:"text/plain"}),s(false)+".txt");return;case"aria2RPC":await this.batchExtractor.collectAria2(i,o,true);Toast.success(`成功发送了批量请求.`,"aria2 RPC",3e3);return;case"copyVLD":GM_setClipboard(await this.batchExtractor.collectData(i,o),{mimetype:"text/plain"});Toast.success("已复制批量vld数据到剪贴板.","批量导出",3e3);return;case"exportVLD":l=await this.batchExtractor.collectData(i,o);u.downloadBlob(new Blob([l],{type:"text/json"}),s(false)+".json");return;default:return}}catch(e){logError(e)}finally{o.dismiss()}},async checkBatch(){const e=["/www.bilibili.com/bangumi","/www.bilibili.com/video/av"];if(!e.some(e=>document.URL.includes(e))){this.batch=false;this.episodeList=[];return}const{BatchExtractor:s}=await t.importAsync("batch-download");if(await s.test()!==true){this.batch=false;this.episodeList=[];return}this.batchExtractor=new s;this.batch=true;this.episodeList=(await this.batchExtractor.getItemList()).map((e,t)=>{return{aid:e.aid,cid:e.cid,title:e.title,index:t,checked:true}})},cancelDownload(){if(i){i.cancelDownload()}},async startDownload(){const e=this.getFormat();try{this.downloading=true;const t=await e.downloadInfo();t.danmakuOption=this.danmakuModel.value;t.progress=(e=>{this.progressPercent=Math.trunc(e*100)});i=t;const s=await t.download();const a=document.getElementById("video-complete");a.setAttribute("href",s.url);a.setAttribute("download",s.filename);a.click();Toast.success(`下载完成: ${s.filename} 再次保存`,"下载视频")}catch(e){if(e!=="canceled"){logError(e)}this.progressPercent=0}finally{this.downloading=false}},selectAllEpisodes(){this.episodeList.forEach(e=>e.checked=true)},unselectAllEpisodes(){this.episodeList.forEach(e=>e.checked=false)},inverseAllEpisodes(){this.episodeList.forEach(e=>e.checked=!e.checked)},toggleRpcSettings(){this.showRpcSettings=!this.showRpcSettings},saveRpcSettings(){if(this.rpcSettings.host===""){this.rpcSettings.host="127.0.0.1"}if(this.rpcSettings.port===""){this.rpcSettings.port="6800"}e.aria2RpcOption=this.rpcSettings}}});Observer.videoChange(async()=>{h.close();h.batch=false;h.downloadSingle=true;const e=dq("#download-video");const t=await p();e.style.display=t?"flex":"none";if(!t){return}h.aid=r.aid;h.cid=r.cid;const s=new a(r.aid);await s.fetchInfo();h.coverUrl=s.coverUrl.replace("http:","https:");l=await d.availableFormats;[c]=l;h.qualityModel={value:c.displayName,items:l.map(e=>e.displayName)};h.formatChange();await h.checkBatch()})}return{widget:{content:`\n `,condition:p,success:m}}}})(); \ No newline at end of file +(()=>{return(e,t)=>{const{getFriendlyTitle:s}=t.import("title");const{VideoInfo:a,DanmakuInfo:n}=t.import("video-info");class i{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 o extends i{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 i,aid:"",cid:""};let l=[];let c=null;class d{constructor(e,t,s){this.quality=e;this.internalName=t;this.displayName=s}async downloadInfo(){const e=new u(this);await e.fetchVideoInfo();return e}static get availableFormats(){return new Promise((e,t)=>{r.entity.getUrl().then(s=>{const a=new XMLHttpRequest;a.addEventListener("load",()=>{const s=JSON.parse(a.responseText);if(s.code!==0){t("获取清晰度信息失败.");return}const n=s.data||s.result||s;const i=n.accept_quality;const o=n.accept_format.split(",");const r=n.accept_description;const l=[];while(i.length>0){const e=new d(i.pop(),o.pop(),r.pop());l.push(e)}e(l.reverse())});a.addEventListener("error",()=>t(`获取清晰度信息失败.`));a.withCredentials=true;a.open("GET",s);a.send()})})}}class h{constructor(e,t,s,a){this.length=e;this.size=t;this.url=s;this.backupUrls=a}}class u{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(s=>{const a=new XMLHttpRequest;a.addEventListener("load",()=>{const s=JSON.parse(a.responseText.replace(/http:/g,"https:"));const n=s.data||s.result||s;if(n.quality!==this.format.quality){t("获取下载链接失败, 请确认当前账号有下载权限后重试.")}const i=n.durl;this.fragments=i.map(e=>new h(e.length,e.size,e.url,e.backup_url));e(this.fragments)});a.withCredentials=true;a.open("GET",s);a.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 s=Math.round(e.size/this.fragmentSplitFactor);let a=0;const n=e=>[...this.progressMap.keys()].indexOf(e)+1;while(a{const a=new XMLHttpRequest;a.open("GET",e.url);a.responseType="arraybuffer";a.withCredentials=false;a.addEventListener("progress",e=>{console.log(`[下载视频] 视频片段${n(a)}下载进度: ${e.loaded}/${r} bytes loaded, ${o}`);this.progressMap.set(a,e.loaded);this.updateProgress()});a.addEventListener("load",()=>{if((""+a.status)[0]==="2"){t(a.response)}else{s(`请求失败.`)}});a.addEventListener("abort",()=>s("canceled"));a.addEventListener("error",()=>{console.error(`[下载视频] 视频片段${n(a)}下载失败: ${o}`);this.progressMap.set(a,0);this.updateProgress();a.open("GET",e.url);a.setRequestHeader("Range",o);a.send()});a.setRequestHeader("Range",o);this.progressMap.set(a,0);a.send();this.workingXhr.push(a)}));a=Math.round(a+s)+1}return Promise.all(t)}async 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 s=document.createElement("a");let a;if(typeof e==="string"){a=e}else{a=URL.createObjectURL(e)}s.setAttribute("href",a);s.setAttribute("download",t);document.body.appendChild(s);s.click();s.remove();URL.revokeObjectURL(a)}async exportData(e=false){const t=JSON.stringify([{fragments:this.fragments,title:s(),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 a=await this.downloadDanmaku();if(a!==null){const t=new JSZip;t.file(`${s()}.json`,e);t.file(s()+"."+this.danmakuOption.toLowerCase(),a);u.downloadBlob(await t.generateAsync({type:"blob"}),`${s()}.zip`)}else{u.downloadBlob(e,`${s()}.json`)}}}async exportAria2(t=false){if(t){const t=await this.downloadDanmaku();if(t!==null){u.downloadBlob(new Blob([t]),`${s()}.${this.danmakuOption==="ASS"?"ass":"xml"}`)}const a=e.aria2RpcOption;const n=a.host.match(/^http[s]?:\/\//)?a.host:"http://"+a.host;const i="aria2.addUri";const o=this.fragments.map((e,t)=>{let n="";if(this.fragments.length>1){n=" - "+(t+1)}const i=[];if(a.secretKey!==""){i.push(`token:${a.secretKey}`)}i.push([e.url]);i.push({referer:document.URL.replace(window.location.search,""),"user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0",out:`${s()}${n}${this.extension(e)}`,split:this.fragmentSplitFactor,dir:a.dir});const o=window.btoa(unescape(encodeURIComponent(JSON.stringify(i))));const r=`${s()}${n}`;return{base64Params:o,id:r}});for(const e of o){try{const t=await Ajax.getJson(`${n}:${a.port}/jsonrpc?method=${i}&id=${e.id}¶ms=${e.base64Params}`);if(t.error!==undefined){if(t.error.code===1){logError(`请求遭到拒绝, 请检查您的密钥相关设置.`)}else{logError(`请求发生错误, code = ${t.error.code}, message = ${t.error.message}`)}return}Toast.success(`成功发送了请求, GID = ${t.result}`,"aria2 RPC",5e3)}catch(e){logError(`无法连接到RPC主机, error = ${e}`);return}}}else{const e=`\n# Generated by Bilibili Evolved Video Export\n# https://github.com/the1812/Bilibili-Evolved/\n${this.fragments.map((e,t)=>{let a="";if(this.fragments.length>1){a=" - "+(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=${s()}${a}${this.extension(e)}\n split=${this.fragmentSplitFactor}\n `.trim()}).join("\n")}\n `.trim();const t=new Blob([e],{type:"text/plain"});const a=await this.downloadDanmaku();if(a!==null){const e=new JSZip;e.file(`${s()}.txt`,t);e.file(s()+"."+this.danmakuOption.toLowerCase(),a);u.downloadBlob(await e.generateAsync({type:"blob"}),`${s()}.zip`)}else{u.downloadBlob(t,`${s()}.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 n(r.cid);await e.fetchInfo();if(this.danmakuOption==="XML"){return e.rawXML}else{const{convertToAss:s}=await t.importAsync("download-danmaku");return s(e.rawXML)}}else{return null}}async downloadSingle(e){const t=await this.downloadDanmaku();const[a]=e;if(t===null){const e=this.makeBlob(a);const t=s()+this.extension();return{blob:e,filename:t}}else{const e=new JSZip;e.file(s()+this.extension(),this.makeBlob(a));e.file(s()+"."+this.danmakuOption.toLowerCase(),t);const n=await e.generateAsync({type:"blob"});const i=s()+".zip";return{blob:n,filename:i}}}async downloadMultiple(e){const t=new JSZip;const a=s();if(e.length>1){e.forEach((e,s)=>{const n=this.fragments[s];t.file(`${a} - ${s+1}${this.extension(n)}`,this.makeBlob(e,n))})}else{const[s]=e;t.file(`${a}${this.extension()}`,this.makeBlob(s))}const n=await this.downloadDanmaku();if(n!==null){t.file(s()+"."+this.danmakuOption.toLowerCase(),n)}const i=await t.generateAsync({type:"blob"});const o=a+".zip";return{blob:i,filename:o}}async download(){const e=[];for(const t of this.fragments){const s=await this.downloadFragment(t);e.push(s)}if(e.length<1){throw new Error("下载失败.")}let{blob:t,filename:s}=await(async()=>{if(e.length===1){return await this.downloadSingle(e)}else{return await this.downloadMultiple(e)}})();this.cleanUpOldBlobUrl();const a=URL.createObjectURL(t);this.progress&&this.progress(0);return{url:a,filename:s}}}async function p(){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 o}else{r.entity=new i}try{l=await d.availableFormats}catch(e){return false}return true}async function m(){c=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"));w()},{once:true})}async function w(){Vue.component("v-dropdown",{template:`\n
\n {{value}}\n \n \n
\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")}}});Vue.component("v-checkbox",{template:`\n
\n \n \n \n {{model.title}}\n
\n `,props:["model"],methods:{toggleCheck(){this.model.checked=!this.model.checked}}});let i;const o=new Map;const h=new Vue({el:".download-video",data:{downloadSingle:true,coverUrl:'data:image/svg+xml;utf-8,',aid:r.aid,cid:r.cid,qualityModel:{value:c.displayName,items:l.map(e=>e.displayName)},danmakuModel:{value:e.downloadVideoDefaultDanmaku,items:["无","XML","ASS"]},progressPercent:0,size:"获取大小中",blobUrl:"",episodeList:[],downloading:false,batch:false,rpcSettings:e.aria2RpcOption,showRpcSettings:false,busy:false},computed:{displaySize(){if(typeof this.size==="string"){return this.size}const e=["B","KB","MB","GB","TB","PB","EB","ZB","YB"];let t=this.size;let s=0;while(t>=1024){t/=1024;s++}return`${Math.round(t*10)/10}${e[s]}`},sizeWarning(){if(typeof this.size==="string"){return false}return this.size>1073741824},selectedEpisodeCount(){return this.episodeList.filter(e=>e.checked).length}},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();this.size=t.totalSize;o.set(e,this.size)}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){if(this.busy===true){return}try{this.busy=true;if(!this.downloadSingle){await this.exportBatchData(e);return}const t=this.getFormat();const s=await t.downloadInfo();s.danmakuOption=this.danmakuModel.value;switch(e){case"copyLink":await s.copyUrl();Toast.success("已复制链接到剪贴板.","下载视频",3e3);break;case"aria2":await s.exportAria2(false);break;case"aria2RPC":await s.exportAria2(true);break;case"copyVLD":await s.exportData(true);Toast.success("已复制VLD数据到剪贴板.","下载视频",3e3);break;case"exportVLD":await s.exportData(false);break;default:break}}catch(e){logError(e)}finally{this.busy=false}},async exportBatchData(e){const a=this.episodeList;if(a.every(e=>e.checked===false)){Toast.info("请至少选择1集或以上的数量!","批量导出",3e3);return}const i=this.getFormat();if(this.danmakuModel.value!=="无"){const e=Toast.info("下载弹幕中...","批量导出");const s=new JSZip;try{if(this.danmakuModel.value==="XML"){for(const e of a){const t=new n(e.cid);await t.fetchInfo();s.file(e.title+".xml",t.rawXML)}}else{const{convertToAss:e}=await t.importAsync("download-danmaku");for(const t of a){const a=new n(t.cid);await a.fetchInfo();s.file(t.title+".ass",await e(a.rawXML))}}u.downloadBlob(await s.generateAsync({type:"blob"}),this.cid+".danmakus.zip")}catch(e){logError(e)}finally{e.dismiss()}}const o=Toast.info("获取链接中...","批量导出");const r=e=>{const t=a.find(t=>t.cid===e.cid);if(t===undefined){return false}return t.checked};this.batchExtractor.itemFilter=r;let l;try{switch(e){case"aria2":l=await this.batchExtractor.collectAria2(i,o);u.downloadBlob(new Blob([l],{type:"text/plain"}),s(false)+".txt");return;case"aria2RPC":await this.batchExtractor.collectAria2(i,o,true);Toast.success(`成功发送了批量请求.`,"aria2 RPC",3e3);return;case"copyVLD":GM_setClipboard(await this.batchExtractor.collectData(i,o),{mimetype:"text/plain"});Toast.success("已复制批量vld数据到剪贴板.","批量导出",3e3);return;case"exportVLD":l=await this.batchExtractor.collectData(i,o);u.downloadBlob(new Blob([l],{type:"text/json"}),s(false)+".json");return;default:return}}catch(e){logError(e)}finally{o.dismiss()}},async checkBatch(){const e=["/www.bilibili.com/bangumi","/www.bilibili.com/video/av"];if(!e.some(e=>document.URL.includes(e))){this.batch=false;this.episodeList=[];return}const{BatchExtractor:s}=await t.importAsync("batch-download");if(await s.test()!==true){this.batch=false;this.episodeList=[];return}this.batchExtractor=new s;this.batch=true;this.episodeList=(await this.batchExtractor.getItemList()).map((e,t)=>{return{aid:e.aid,cid:e.cid,title:e.title,index:t,checked:true}})},cancelDownload(){if(i){i.cancelDownload()}},async startDownload(){const e=this.getFormat();try{this.downloading=true;const t=await e.downloadInfo();t.danmakuOption=this.danmakuModel.value;t.progress=(e=>{this.progressPercent=Math.trunc(e*100)});i=t;const s=await t.download();const a=document.getElementById("video-complete");a.setAttribute("href",s.url);a.setAttribute("download",s.filename);a.click();Toast.success(`下载完成: ${s.filename} 再次保存`,"下载视频")}catch(e){if(e!=="canceled"){logError(e)}this.progressPercent=0}finally{this.downloading=false}},selectAllEpisodes(){this.episodeList.forEach(e=>e.checked=true)},unselectAllEpisodes(){this.episodeList.forEach(e=>e.checked=false)},inverseAllEpisodes(){this.episodeList.forEach(e=>e.checked=!e.checked)},toggleRpcSettings(){this.showRpcSettings=!this.showRpcSettings},saveRpcSettings(){if(this.rpcSettings.host===""){this.rpcSettings.host="127.0.0.1"}if(this.rpcSettings.port===""){this.rpcSettings.port="6800"}e.aria2RpcOption=this.rpcSettings}}});Observer.videoChange(async()=>{h.close();h.batch=false;h.downloadSingle=true;const e=dq("#download-video");const t=await p();e.style.display=t?"flex":"none";if(!t){return}h.aid=r.aid;h.cid=r.cid;const s=new a(r.aid);await s.fetchInfo();h.coverUrl=s.coverUrl.replace("http:","https:");l=await d.availableFormats;[c]=l;h.qualityModel={value:c.displayName,items:l.map(e=>e.displayName)};h.formatChange();await h.checkBatch()})}return{widget:{content:`\n `,condition:p,success:m}}}})(); \ No newline at end of file diff --git a/video/download-video/batch-download.js b/video/download-video/batch-download.js index 183f5ea7d..178f6885e 100644 --- a/video/download-video/batch-download.js +++ b/video/download-video/batch-download.js @@ -10,7 +10,7 @@ class Batch { const json = JSON.parse(await this.collectData(quality)) if (rpc) { const option = settings.aria2RpcOption - const host = option.host.startsWith('http://') ? option.host : 'http://' + option.host + const host = option.host.match(/^http[s]?:\/\//) ? option.host : 'http://' + option.host const methodName = 'aria2.addUri' for (const item of json) { const params = item.fragments.map((fragment, index) => { diff --git a/video/download-video/download-video.js b/video/download-video/download-video.js index 5fde052a2..8024c680c 100644 --- a/video/download-video/download-video.js +++ b/video/download-video/download-video.js @@ -255,7 +255,7 @@ class VideoDownloader { VideoDownloader.downloadBlob(new Blob([danmaku]), `${getFriendlyTitle()}.${this.danmakuOption === 'ASS' ? 'ass' : 'xml'}`); } const option = settings.aria2RpcOption; - const host = option.host.startsWith('http://') ? option.host : 'http://' + option.host; + const host = option.host.match(/^http[s]?:\/\//) ? option.host : 'http://' + option.host; const methodName = 'aria2.addUri'; const params = this.fragments.map((fragment, index) => { let indexNumber = ''; diff --git a/video/download-video/download-video.ts b/video/download-video/download-video.ts index 6073c2da9..8f94bcd1d 100644 --- a/video/download-video/download-video.ts +++ b/video/download-video/download-video.ts @@ -279,7 +279,7 @@ class VideoDownloader { VideoDownloader.downloadBlob(new Blob([danmaku]), `${getFriendlyTitle()}.${this.danmakuOption === 'ASS' ? 'ass' : 'xml'}`) } const option = settings.aria2RpcOption - const host = option.host.startsWith('http://') ? option.host : 'http://' + option.host + const host = option.host.match(/^http[s]?:\/\//) ? option.host : 'http://' + option.host const methodName = 'aria2.addUri' const params = this.fragments.map((fragment, index) => { let indexNumber = ''