From 384a7e0e96ea9d5fb580ff0dd2828eaf877eddc1 Mon Sep 17 00:00:00 2001 From: the1812 Date: Sat, 4 Jan 2020 22:32:16 +0800 Subject: [PATCH] Fix NaN resolution --- bilibili-evolved.offline.user.js | 4 ++-- bilibili-evolved.preview-offline.user.js | 4 ++-- bilibili-evolved.preview.user.js | 2 +- bilibili-evolved.user.js | 2 +- min/bundle.json | 2 +- min/bundle.zip | Bin 1526779 -> 1526864 bytes min/download-danmaku.min.js | 2 +- src/video/download-danmaku.ts | 8 ++++++-- 8 files changed, 14 insertions(+), 10 deletions(-) diff --git a/bilibili-evolved.offline.user.js b/bilibili-evolved.offline.user.js index aca5c4aa7..0cddcca10 100644 --- a/bilibili-evolved.offline.user.js +++ b/bilibili-evolved.offline.user.js @@ -1,6 +1,6 @@ // ==UserScript== // @name Bilibili Evolved (Offline) -// @version 535.86 +// @version 537.27 // @description Bilibili Evolved 的离线版, 所有功能都已内置于脚本中. // @author Grant Howard, Coulomb-G // @copyright 2019, Grant Howard (https://github.com/the1812) & Coulomb-G (https://github.com/Coulomb-G) @@ -1123,7 +1123,7 @@ offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/m offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/default-video-speed.min.js"] = (()=>{return(e,a)=>{const i=a=>{const i=parseFloat(e.defaultVideoSpeed);a.playbackRate=i;SpinQuery.condition(()=>a,()=>a.playbackRate!==i,()=>a.playbackRate=i)};Observer.videoChange(()=>{const e=dq(".bilibili-player-video video");if(!e){return}i(e)})}})(); offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/double-click-fullscreen.min.js"] = (()=>{return(i,e)=>{(async()=>{const e=["https://www.bilibili.com/bangumi/","https://www.bilibili.com/video/"];if(!e.some(i=>document.URL.startsWith(i))){return}if(i.touchVideoPlayer&&i.touchVideoPlayerDoubleTapControl){Toast.info("在开启了播放器触摸支持-启用双击控制后, 双击全屏功能将无效.","提示");i.doubleClickFullscreen=false;return}await SpinQuery.unsafeJquery();const l=await SpinQuery.condition(()=>dq(".bilibili-player-area"),i=>i!==null&&unsafeWindow.$(".bilibili-player-video").data("events"));if(l===null){return}const n="double-click-fullscreen";if(!l.classList.contains(n)){l.classList.add(n);const e=unsafeWindow.$(".bilibili-player-video");const t=i.doubleClickFullscreenPreventSingleClick?e.data("events").click[0].handler:()=>{};const c=new DoubleClickEvent(()=>dq(".bilibili-player-video-btn-fullscreen").click(),i=>t(i));if(i.doubleClickFullscreenPreventSingleClick){e.unbind("click")}c.bind(e[0])}})()}})(); offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/download-audio.min.js"] = (()=>{return(e,t)=>{class n{constructor(){this.sid=null;this.progress=null}async getDownloadUrl(){const e=`https://www.bilibili.com/audio/music-service-c/web/url?sid=${this.sid}&privilege=2&quality=2`;const t=await Ajax.getJsonWithCredentials(e);if(t.code===0){return t.data.cdns.shift()}else{logError("获取下载链接失败, 请确保当前账号有下载权限.","下载音频",1e4);return null}}async download(){const e=await this.getDownloadUrl();return new Promise((t,n)=>{const s=new XMLHttpRequest;s.open("GET",e);s.responseType="blob";s.addEventListener("load",()=>t(s.response));s.addEventListener("error",()=>n(s.status));s.addEventListener("progress",e=>this.progress&&this.progress(100*e.loaded/e.total));s.send()})}}const s="下载音频";return{export:n,widget:{content:`\n\n\n${s}\n\n`,condition:()=>document.URL.includes("bilibili.com/audio"),success:async()=>{await SpinQuery.select(()=>document.querySelector("#app"));const e=document.querySelector("#download-audio");const t=e.querySelector("span");const o=new n;o.progress=(e=>{t.innerHTML=`${Math.round(e)}%`});const i=document.querySelector("#download-audio-link");e.addEventListener("click",async e=>{if(o.sid===null||e.target===i){return}const n=await o.download();t.innerHTML=s;const r=i.getAttribute("href");if(r){URL.revokeObjectURL(r)}i.setAttribute("href",URL.createObjectURL(n));const d=(()=>{const e=document.querySelector(".song-title");if(e){return e.getAttribute("title")}else{return"神秘音频"}})();i.setAttribute("download",d+".m4a");i.click()});Observer.childList("#app",()=>{const t=document.URL.match(/bilibili\.com\/audio\/au([\d]+)/);if(t&&t[1]){e.disabled=false;o.sid=t[1]}else{e.disabled=true}})}}}}})(); -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-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"));return e*4/188};const e=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-3*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 n=1.4-.2*t(".bilibili-player-setting-fontsize .bui-thumb");i.resolution={x:1920*n,y:1080*n};i.bottomMarginPercent=[.75,.5,.25,0,0][e(".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 r=o.convertToAssDocument(t);return r.generateAss()}async function r(t,e){const a=n();const r=new i((unsafeWindow||window).cid);await r.fetchInfo();const l=await(async()=>{if(t===true){return new Blob([await o(r.rawXML)],{type:"text/plain"})}else{return new Blob([r.rawXML],{type:"text/plain"})}})();const s=URL.createObjectURL(l);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:r,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);r(e.shiftKey,t)}})}}}}})(); offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/download-video.min.css"] = `.download-video{--download-video-background:white;--download-video-foreground:black;position:absolute;top:96px;left:50%;transform:translateX(-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}.download-video,.download-video *{transition:.2s ease-out;-webkit-tap-highlight-color:transparent!important}.download-video.opened{pointer-events:initial;opacity:1;transform:translateX(-50%) scale(1)}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 .size-warning-tip,.round-corner .download-video .title,.round-corner .download-video button{border-radius:var(--corner-radius)}.download-video .cover{min-height:100px;max-height:120px;object-fit:contain}.download-video h1{font-size:13pt;font-weight:700;color:var(--download-video-foreground)}.download-video h2{font-size:11pt;font-weight:700;color:var(--download-video-foreground)}.download-video .header{display:flex;justify-content:space-between;align-items:center}.download-video .header .grow{flex-grow:1}.download-video .header .mdi-download{font-size:16pt;color:var(--download-video-foreground);margin-right:8px}.download-video .header .mdi-close{font-size:16pt;color:var(--download-video-foreground);cursor:pointer}.download-video .header .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 .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 .bold{color:var(--download-video-foreground);font-weight:700;font-size:12pt}.download-video .option-item{display:flex;justify-content:space-between;align-items:center;padding-top:12px;font-size:10pt}.download-video .tabs{display:flex;padding:12px 0;font-size:10pt}.download-video .tabs .tab{cursor:pointer;position:relative;opacity:.5}.download-video .tabs .tab.active{font-weight:700;opacity:1}.download-video .tabs .tab:not(:last-child){margin-right:16px}.download-video .tabs .tab::after{content:"";position:absolute;border-radius:2px;background-color:var(--theme-color);height:3px;width:80%;left:10%;bottom:-8px;transition:.2s ease-out;transform:scaleX(0)}.download-video .tabs .tab.active::after{transform:scaleX(1)}.download-video .separator{height:1px;background:#8884;width:100%;margin:12px 0;flex-shrink:0}.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 .background .foreground{position:absolute;top:0;left:0;height:4px;background:linear-gradient(to right,var(--theme-color),var(--theme-color-60))}.download-video .direct-download .progress .percent{width:50px;text-align:right}.download-video .actions{display:flex;flex-wrap:wrap;justify-content:space-between;margin:8px -4px 0}.download-video .actions>*{margin:4px;flex-grow:1;flex-basis:calc(50% - 16px);display:flex;justify-content:center;align-items:center;white-space:nowrap}.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:200px;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}.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:stretch;color:var(--download-video-foreground);background:#fff;bottom:120%;left:50%;cursor:initial;box-shadow:rgba(0,0,0,.2) 0 4px 8px 0;transform-origin:bottom;transform:translateX(-50%) scale(.9);opacity:0;pointer-events:none;padding:8px;z-index:3;transition:.3s cubic-bezier(.18,.89,.32,1.28);width:120%}body.dark .download-video .rpc-settings{background:#282828}.download-video .rpc-settings>*{margin:8px}.download-video .rpc-settings.show{opacity:1;transform:translateX(-50%) scale(1);pointer-events:initial}.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)}.download-video .rpc-settings .operations{display:flex;align-items:center;justify-content:space-evenly}.download-video .final-dir{word-break:break-all}.download-video .rpc-settings-item{display:flex;align-items:center;justify-content:space-between;white-space:nowrap}.download-video .rpc-settings-item input[type=text]{flex-grow:1;margin-left:24px}.download-video button.cancel-download,.download-video button.start-download{margin-top:8px}.download-video .direct-download-header{align-self:stretch;display:flex;justify-content:space-between;align-items:center}body.dark .download-video .direct-download .progress .foreground{background:linear-gradient(to right,var(--theme-color-70),var(--theme-color))}`; offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/download-video.min.html"] = `

下载视频

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

直接下载

{{speed}}
{{progressPercent}}%

选集

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

导出

{{showRpcSettings ? '取消' : 'aria2 RPC'}}

aria2 RPC

配置

主机
端口
密钥
限速
默认路径
路径
最终路径: {{rpcSettings.baseDir + rpcSettings.dir}}
方法
开始下载
{{saveRpcSettingsText}}
`; offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/download-video.min.js"] = (()=>{return(t,e)=>{const{getFriendlyTitle:s}=e.import("title");const{VideoInfo:a,DanmakuInfo:i}=e.import("video-info");const{DownloadVideoPackage:n}=e.import("download-video-package");class o{async getApiGenerator(t=false){function e(e,s,a){if(t){if(a){return`https://api.bilibili.com/x/player/playurl?avid=${e}&cid=${s}&qn=${a}&otype=json&fnver=0&fnval=16`}else{return`https://api.bilibili.com/x/player/playurl?avid=${e}&cid=${s}&otype=json&fnver=0&fnval=16`}}else{if(a){return`https://api.bilibili.com/x/player/playurl?avid=${e}&cid=${s}&qn=${a}&otype=json`}else{return`https://api.bilibili.com/x/player/playurl?avid=${e}&cid=${s}&otype=json`}}}return e.bind(this)}async getDashUrl(t){return(await this.getApiGenerator(true))(c.aid,c.cid,t)}async getUrl(t){return(await this.getApiGenerator())(c.aid,c.cid,t)}}class r extends o{async getApiGenerator(t=false){function e(e,s,a){if(t){if(a){return`https://api.bilibili.com/pgc/player/web/playurl?avid=${e}&cid=${s}&qn=${a}&otype=json&fourk=1&fnval=16`}else{return`https://api.bilibili.com/pgc/player/web/playurl?avid=${e}&cid=${s}&otype=json&fourk=1&fnval=16`}}else{if(a){return`https://api.bilibili.com/pgc/player/web/playurl?avid=${e}&cid=${s}&qn=${a}&otype=json`}else{return`https://api.bilibili.com/pgc/player/web/playurl?avid=${e}&cid=${s}&qn=&otype=json`}}}return e.bind(this)}}class l extends o{constructor(t){super();this.ep=t}async getApiGenerator(t=false){function e(e,s,a){if(t){if(a){return`https://api.bilibili.com/pugv/player/web/playurl?avid=${e}&cid=${s}&qn=${a}&otype=json&ep_id=${this.ep}&fnver=0&fnval=16`}else{return`https://api.bilibili.com/pugv/player/web/playurl?avid=${e}&cid=${s}&otype=json&ep_id=${this.ep}&fnver=0&fnval=16`}}else{if(a){return`https://api.bilibili.com/pugv/player/web/playurl?avid=${e}&cid=${s}&qn=${a}&otype=json&ep_id=${this.ep}`}else{return`https://api.bilibili.com/pugv/player/web/playurl?avid=${e}&cid=${s}&otype=json&ep_id=${this.ep}`}}}return e.bind(this)}}const c={entity:new o,aid:"",cid:""};let d=[];let p=null;class h{constructor(t,e,s){this.quality=t;this.internalName=e;this.displayName=s}async downloadInfo(t=false){const e=new u(this);await e.fetchVideoInfo(t);return e}static parseFormats(t){const e=t.accept_quality;const s=t.accept_format.split(",");const a=t.accept_description;const i=e.map((t,e)=>{return new h(t,s[e],a[e])});return i}static async getAvailableDashFormats(){const t=await c.entity.getDashUrl();const e=await Ajax.getJsonWithCredentials(t);if(e.code!==0){throw new Error("获取清晰度信息失败.")}return h.parseFormats(e.data||e.result||e)}static async getAvailableFormats(){const t=await c.entity.getUrl();const e=await Ajax.getJsonWithCredentials(t);if(e.code!==0){throw new Error("获取清晰度信息失败.")}const s=e.data||e.result||e;return h.parseFormats(s)}}class u{constructor(t,e){this.fragmentSplitFactor=6*2;this.workingXhr=null;this.progressMap=new Map;this.format=t;this.fragments=e||[];this.videoSpeed=new f(this)}get danmakuOption(){return t.downloadVideoDefaultDanmaku}get isDash(){return this.fragments.some(t=>t.url.includes(".m4s"))}get totalSize(){return this.fragments.map(t=>t.size).reduce((t,e)=>t+e)}async fetchVideoInfo(t=false){if(!t){const t=await c.entity.getUrl(this.format.quality);const e=await Ajax.getTextWithCredentials(t);const s=JSON.parse(e.replace(/http:/g,"https:"));const a=s.data||s.result||s;if(a.quality!==this.format.quality){throw new Error("获取下载链接失败, 请确认当前账号有下载权限后重试.")}const i=a.durl;this.fragments=i.map(t=>{return{length:t.length,size:t.size,url:t.url,backupUrls:t.backup_url}})}else{const{dashToFragments:t,getDashInfo:s}=await e.importAsync("video-dash");const a=await s(await c.entity.getDashUrl(this.format.quality),this.format.quality);this.fragments=t(a)}return this.fragments}updateProgress(){const t=this.progressMap?[...this.progressMap.values()].reduce((t,e)=>t+e,0)/this.totalSize:0;if(t>1||t<0){console.error(`[下载视频] 进度异常: ${t}`,this.progressMap.values())}this.progress&&this.progress(t)}cancelDownload(){this.videoSpeed.stopMeasure();if(this.workingXhr!==null){this.workingXhr.forEach(t=>t.abort())}else{logError("Cancel Download Failed: forEach in this.workingXhr not found.")}}downloadFragment(t){const e=[];const s=this.isDash?4*1024*1024:16*1024*1024;let a;if(t.size<=s*6){a=t.size/this.fragmentSplitFactor}else{a=s}let i=0;const n=t=>[...this.progressMap.keys()].indexOf(t)+1;while(i{const a=new XMLHttpRequest;a.open("GET",t.url);a.responseType="arraybuffer";a.withCredentials=false;a.addEventListener("progress",t=>{console.log(`[下载视频] 视频片段${n(a)}下载进度: ${t.loaded}/${r} bytes loaded, ${o}`);this.progressMap.set(a,t.loaded);this.updateProgress()});a.addEventListener("load",()=>{if((""+a.status)[0]==="2"){console.log(`[下载视频] 视频片段${n(a)}下载完成`);e(a.response)}else{s(`视频片段${n(a)}请求失败, response = ${a.status}`)}});a.addEventListener("abort",()=>s("canceled"));a.addEventListener("error",()=>{console.error(`[下载视频] 视频片段${n(a)}下载失败: ${o}`);this.progressMap.set(a,0);this.updateProgress();a.open("GET",t.url);a.setRequestHeader("Range",o);a.send()});a.setRequestHeader("Range",o);this.progressMap.set(a,0);a.send();this.workingXhr.push(a)}));i=Math.round(i+a)+1}return Promise.all(e)}async copyUrl(){const t=this.fragments.map(t=>t.url).reduce((t,e)=>t+"\r\n"+e);GM.setClipboard(t,"text")}async showUrl(){const t=this.fragments.map(t=>`\n${t.url}\n`).reduce((t,e)=>t+"\r\n"+e);Toast.success(t+`复制全部`,"显示链接");const e=await SpinQuery.select("#copy-link");e.addEventListener("click",async()=>{await this.copyUrl()})}async exportData(t=false){const e=JSON.stringify([{fragments:this.fragments,title:s(),totalSize:this.fragments.map(t=>t.size).reduce((t,e)=>t+e),referer:document.URL.replace(window.location.search,"")}]);if(t){GM.setClipboard(e,"text")}else{const t=new Blob([e],{type:"text/json"});const a=await this.downloadDanmaku();const i=new n;i.add(`${s()}.json`,t);i.add(s()+"."+this.danmakuOption.toLowerCase(),a);await i.emit(`${s()}.zip`)}}async exportAria2(a=false){if(a){const a=await this.downloadDanmaku();const i=new n;i.add(`${s()}.${this.danmakuOption==="ASS"?"ass":"xml"}`,a);await i.emit();const o=t.aria2RpcOption;const r=this.fragments.map((t,e)=>{let a="";if(this.fragments.length>1&&!this.isDash){a=" - "+(e+1)}const i=[];if(o.secretKey!==""){i.push(`token:${o.secretKey}`)}i.push([t.url]);i.push({referer:document.URL.replace(window.location.search,""),"user-agent":UserAgent,out:`${s()}${a}${this.extension(t)}`,split:this.fragmentSplitFactor,dir:o.baseDir+o.dir||undefined,"max-download-limit":o.maxDownloadLimit||undefined});const n=encodeURIComponent(`${s()}${a}`);return{params:i,id:n}});const{sendRpc:l}=await e.importAsync("aria2-rpc");await l(r)}else{const t=`\n# Generated by Bilibili Evolved Video Export\n# https://github.com/the1812/Bilibili-Evolved/\n${this.fragments.map((t,e)=>{let a="";if(this.fragments.length>1&&!this.isDash){a=" - "+(e+1)}return`\n${t.url}\n referer=${document.URL.replace(window.location.search,"")}\n user-agent=${UserAgent}\n out=${s()}${a}${this.extension(t)}\n split=${this.fragmentSplitFactor}\n`.trim()}).join("\n")}\n`.trim();const e=new Blob([t],{type:"text/plain"});const a=await this.downloadDanmaku();const i=new n;i.add(`${s()}.txt`,e);i.add(s()+"."+this.danmakuOption.toLowerCase(),a);await i.emit(`${s()}.zip`)}}extension(t){const e=t||this.fragments[0];const s=[".flv",".mp4"].find(t=>e.url.includes(t));if(s){return s}else if(e.url.includes(".m4s")){return this.fragments.indexOf(e)===0?".mp4":".m4a"}else{console.warn("No extension detected.");return".flv"}}async downloadDanmaku(){if(this.danmakuOption!=="无"){const t=new i(c.cid);await t.fetchInfo();if(this.danmakuOption==="XML"){return t.rawXML}else{const{convertToAss:s}=await e.importAsync("download-danmaku");return s(t.rawXML)}}else{return null}}async download(){this.workingXhr=[];this.progressMap=new Map;this.updateProgress();const t=[];this.videoSpeed.startMeasure();for(const e of this.fragments){const s=await this.downloadFragment(e);t.push(s)}if(t.length<1){throw new Error("下载失败.")}const e=s();const a=new n;t.forEach((s,i)=>{let n;const o=this.fragments[i];if(t.length>1&&!this.isDash){n=`${e} - ${i+1}${this.extension(o)}`}else{n=`${e}${this.extension(o)}`}a.add(n,new Blob(Array.isArray(s)?s:[s]))});const i=await this.downloadDanmaku();a.add(`${s()}.${this.danmakuOption==="ASS"?"ass":"xml"}`,i);await a.emit(e+".zip");this.progress&&this.progress(0);this.videoSpeed.stopMeasure()}}class f{constructor(t){this.lastProgress=0;this.measureInterval=1e3;this.workingDownloader=t}startMeasure(){this.intervalTimer=setInterval(()=>{const t=this.workingDownloader.progressMap?[...this.workingDownloader.progressMap.values()].reduce((t,e)=>t+e,0):0;const e=t-this.lastProgress;if(this.speedUpdate!==undefined){this.speedUpdate(formatFileSize(e)+"/s")}this.lastProgress=t},this.measureInterval)}stopMeasure(){clearInterval(this.intervalTimer)}}async function w(){const t=await SpinQuery.select(()=>(unsafeWindow||window).aid);const e=await SpinQuery.select(()=>(unsafeWindow||window).cid);if(!(t&&e)){return false}c.aid=t;c.cid=e;if(document.URL.includes("bangumi")){c.entity=new r}else if(document.URL.includes("cheese")){const t=document.URL.match(/cheese\/play\/ep([\d]+)/);c.entity=new l(t[1])}else{c.entity=new o}try{d=await h.getAvailableFormats()}catch(t){return false}return true}async function m(){p=d[0];e.applyStyle("downloadVideoStyle");const t=dq("#download-video");t.addEventListener("click",()=>{const t=dq(".download-video");t.classList.toggle("opened");window.scroll(0,0);dq(".gui-settings-mask").click()});document.body.insertAdjacentHTML("beforeend",e.import("downloadVideoHtml"));g()}async function g(){let o;const r=new Vue({el:".download-video",components:{VDropdown:()=>e.importAsync("v-dropdown.vue"),VCheckbox:()=>e.importAsync("v-checkbox.vue"),RpcProfiles:()=>e.importAsync("aria2-rpc-profiles.vue")},data:{downloadSingle:true,coverUrl:EmptyImageUrl,aid:c.aid,cid:c.cid,dashModel:{value:t.downloadVideoFormat,items:["flv","dash"]},qualityModel:{value:p.displayName,items:d.map(t=>t.displayName)},danmakuModel:{value:t.downloadVideoDefaultDanmaku,items:["无","XML","ASS"]},codecModel:{value:t.downloadVideoDashCodec,items:["AVC/H.264","HEVC/H.265"]},progressPercent:0,size:"获取大小中",blobUrl:"",episodeList:[],downloading:false,speed:"",batch:false,rpcSettings:t.aria2RpcOption,showRpcSettings:false,busy:false,saveRpcSettingsText:"保存配置",enableDash:t.enableDashDownload,lastDirectDownloadLink:""},computed:{displaySize(){if(typeof this.size==="string"){return this.size}return formatFileSize(this.size)},sizeWarning(){if(typeof this.size==="string"){return false}return this.size>1073741824},selectedEpisodeCount(){return this.episodeList.filter(t=>t.checked).length},dash(){return this.dashModel.value==="dash"}},methods:{close(){this.$el.classList.remove("opened")},danmakuOptionChange(){t.downloadVideoDefaultDanmaku=this.danmakuModel.value},async codecChange(){t.downloadVideoDashCodec=this.codecModel.value;await this.formatChange()},async dashChange(){console.log("dash change");t.downloadVideoFormat=this.dashModel.value;const e=this.dashModel.value;let s=[];if(e==="flv"){s=await h.getAvailableFormats()}else{s=await h.getAvailableDashFormats()}d=s;[p]=e;this.qualityModel.items=s.map(t=>t.displayName);[this.qualityModel.value]=this.qualityModel.items;await this.formatChange()},async formatChange(){console.log("format change");const t=this.getFormat();try{this.size="获取大小中";const e=await t.downloadInfo(this.dash);this.size=e.totalSize}catch(t){this.size="获取大小失败";throw t}},getFormat(){const t=d.find(t=>t.displayName===this.qualityModel.value);if(!t){console.error(`No format found. model value = ${this.qualityModel.value}`);return null}return t},async exportData(t){if(this.busy===true){return}try{this.busy=true;if(!this.downloadSingle){await this.exportBatchData(t);return}const a=this.getFormat();const i=await a.downloadInfo(this.dash);switch(t){case"copyLink":await i.copyUrl();Toast.success("已复制链接到剪贴板.","下载视频",3e3);break;case"showLink":await i.showUrl();break;case"aria2":await i.exportAria2(false);break;case"aria2RPC":await i.exportAria2(true);break;case"copyVLD":await i.exportData(true);Toast.success("已复制VLD数据到剪贴板.","下载视频",3e3);break;case"exportVLD":await i.exportData(false);break;case"ffmpegFragments":if(i.fragments.length<2){Toast.info("当前视频没有分段.","分段列表",3e3)}else{const{getFragmentsList:t}=await e.importAsync("ffmpeg-support");const a=new n;a.add("ffmpeg-files.txt",t(i.fragments.length,s(),i.fragments.map(t=>i.extension(t))));await a.emit()}break;default:break}}catch(t){logError(t)}finally{this.busy=false}},async exportBatchData(t){const a=this.episodeList;if(a.every(t=>t.checked===false)){Toast.info("请至少选择1集或以上的数量!","批量导出",3e3);return}const o=t=>{const e=a.find(e=>e.cid===t.cid);if(e===undefined){return false}return e.checked};const r=this.getFormat();if(this.danmakuModel.value!=="无"){const t=Toast.info("下载弹幕中...","批量导出");const s=new n;try{if(this.danmakuModel.value==="XML"){for(const t of a.filter(o)){const e=new i(t.cid);await e.fetchInfo();s.add(t.title+".xml",e.rawXML)}}else{const{convertToAss:t}=await e.importAsync("download-danmaku");for(const e of a.filter(o)){const a=new i(e.cid);await a.fetchInfo();s.add(e.title+".ass",await t(a.rawXML))}}await s.emit(this.cid+".danmakus.zip")}catch(t){logError(`弹幕下载失败`);throw t}finally{t.dismiss()}}const l=Toast.info("获取链接中...","批量导出");const d=this.batchExtractor;d.config.itemFilter=o;d.config.api=await c.entity.getApiGenerator(this.dash);let p;try{switch(t){case"aria2":p=await d.collectAria2(r,l,false);await n.single(s(false)+".txt",new Blob([p],{type:"text/plain"}),{ffmpeg:this.ffmpegOption});return;case"aria2RPC":await d.collectAria2(r,l,true);Toast.success(`成功发送了批量请求.`,"aria2 RPC",3e3);return;case"copyVLD":GM.setClipboard(await d.collectData(r,l),{mimetype:"text/plain"});Toast.success("已复制批量vld数据到剪贴板.","批量导出",3e3);return;case"exportVLD":p=await d.collectData(r,l);await n.single(s(false)+".json",new Blob([p],{type:"text/json"}),{ffmpeg:this.ffmpegOption});return;case"ffmpegFragments":{const t=await d.getRawItems(r);const a=new u(r,t[0].fragments);const{getBatchFragmentsList:i}=await e.importAsync("ffmpeg-support");const o=i(t,this.dash||a.extension());if(!o){Toast.info("所有选择的分P都没有分段.","分段列表",3e3)}else{const t=new n;for(const[e,s]of o.entries()){t.add(e,s)}await t.emit(escapeFilename(`${s(false)}.zip`))}}break;case"ffmpegEpisodes":{const t=await d.getRawItems(r);const s=new u(r,t[0].fragments);const{getBatchEpisodesList:a}=await e.importAsync("ffmpeg-support");const i=a(t,this.dash||s.extension());const o=new n;o.add("ffmpeg-files.txt",i);await o.emit()}break;default:return}}catch(t){logError(t)}finally{l.dismiss()}},async checkBatch(){const t=["/www.bilibili.com/bangumi","/www.bilibili.com/video/av"];if(!t.some(t=>document.URL.includes(t))){this.batch=false;this.episodeList=[];return}const{BatchExtractor:s}=await e.importAsync("batch-download");if(await s.test()!==true){this.batch=false;this.episodeList=[];return}const a=this.batchExtractor=new s;this.batch=true;this.episodeList=(await a.getItemList()).map((t,e)=>{return{aid:t.aid,cid:t.cid,title:t.title,index:e,checked:true}})},cancelDownload(){if(o){o.cancelDownload()}},async startDownload(){const t=this.getFormat();try{this.downloading=true;const e=await t.downloadInfo(this.dash);e.videoSpeed.speedUpdate=(t=>this.speed=t);e.progress=(t=>{this.progressPercent=Math.trunc(t*100)});o=e;await e.download();this.lastDirectDownloadLink=n.lastPackageUrl}catch(t){if(t!=="canceled"){logError(t)}this.progressPercent=0}finally{this.downloading=false;this.speed=""}},selectAllEpisodes(){this.episodeList.forEach(t=>t.checked=true)},unselectAllEpisodes(){this.episodeList.forEach(t=>t.checked=false)},inverseAllEpisodes(){this.episodeList.forEach(t=>t.checked=!t.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"}t.aria2RpcOption=this.rpcSettings;const e=t.aria2RpcOptionProfiles.find(e=>e.name===t.aria2RpcOptionSelectedProfile);if(e){Object.assign(e,this.rpcSettings);t.aria2RpcOptionProfiles=t.aria2RpcOptionProfiles}this.saveRpcSettingsText="已保存";setTimeout(()=>this.saveRpcSettingsText="保存配置",2e3)},updateProfile(e){t.aria2RpcOption=this.rpcSettings=_.omit(e,"name")}},async mounted(){}});Observer.videoChange(async()=>{r.close();r.batch=false;r.downloadSingle=true;const t=dq("#download-video");const e=await w();t.style.display=e?"flex":"none";if(!e){return}r.aid=c.aid;r.cid=c.cid;try{const t=new a(c.aid);await t.fetchInfo();r.coverUrl=t.coverUrl.replace("http:","https:")}catch(t){r.coverUrl=EmptyImageUrl}r.dashChange();await r.checkBatch()})}return{widget:{content:`\n`,condition:w,success:m}}}})(); diff --git a/bilibili-evolved.preview-offline.user.js b/bilibili-evolved.preview-offline.user.js index 31ddadd09..abd7be594 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 535.86 +// @version 537.27 // @description Bilibili Evolved 的预览离线版, 可以抢先体验新功能, 并且所有功能都已内置于脚本中. // @author Grant Howard, Coulomb-G // @copyright 2019, Grant Howard (https://github.com/the1812) & Coulomb-G (https://github.com/Coulomb-G) @@ -1123,7 +1123,7 @@ offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/m offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/default-video-speed.min.js"] = (()=>{return(e,a)=>{const i=a=>{const i=parseFloat(e.defaultVideoSpeed);a.playbackRate=i;SpinQuery.condition(()=>a,()=>a.playbackRate!==i,()=>a.playbackRate=i)};Observer.videoChange(()=>{const e=dq(".bilibili-player-video video");if(!e){return}i(e)})}})(); offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/double-click-fullscreen.min.js"] = (()=>{return(i,e)=>{(async()=>{const e=["https://www.bilibili.com/bangumi/","https://www.bilibili.com/video/"];if(!e.some(i=>document.URL.startsWith(i))){return}if(i.touchVideoPlayer&&i.touchVideoPlayerDoubleTapControl){Toast.info("在开启了播放器触摸支持-启用双击控制后, 双击全屏功能将无效.","提示");i.doubleClickFullscreen=false;return}await SpinQuery.unsafeJquery();const l=await SpinQuery.condition(()=>dq(".bilibili-player-area"),i=>i!==null&&unsafeWindow.$(".bilibili-player-video").data("events"));if(l===null){return}const n="double-click-fullscreen";if(!l.classList.contains(n)){l.classList.add(n);const e=unsafeWindow.$(".bilibili-player-video");const t=i.doubleClickFullscreenPreventSingleClick?e.data("events").click[0].handler:()=>{};const c=new DoubleClickEvent(()=>dq(".bilibili-player-video-btn-fullscreen").click(),i=>t(i));if(i.doubleClickFullscreenPreventSingleClick){e.unbind("click")}c.bind(e[0])}})()}})(); offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/download-audio.min.js"] = (()=>{return(e,t)=>{class n{constructor(){this.sid=null;this.progress=null}async getDownloadUrl(){const e=`https://www.bilibili.com/audio/music-service-c/web/url?sid=${this.sid}&privilege=2&quality=2`;const t=await Ajax.getJsonWithCredentials(e);if(t.code===0){return t.data.cdns.shift()}else{logError("获取下载链接失败, 请确保当前账号有下载权限.","下载音频",1e4);return null}}async download(){const e=await this.getDownloadUrl();return new Promise((t,n)=>{const s=new XMLHttpRequest;s.open("GET",e);s.responseType="blob";s.addEventListener("load",()=>t(s.response));s.addEventListener("error",()=>n(s.status));s.addEventListener("progress",e=>this.progress&&this.progress(100*e.loaded/e.total));s.send()})}}const s="下载音频";return{export:n,widget:{content:`\n\n\n${s}\n\n`,condition:()=>document.URL.includes("bilibili.com/audio"),success:async()=>{await SpinQuery.select(()=>document.querySelector("#app"));const e=document.querySelector("#download-audio");const t=e.querySelector("span");const o=new n;o.progress=(e=>{t.innerHTML=`${Math.round(e)}%`});const i=document.querySelector("#download-audio-link");e.addEventListener("click",async e=>{if(o.sid===null||e.target===i){return}const n=await o.download();t.innerHTML=s;const r=i.getAttribute("href");if(r){URL.revokeObjectURL(r)}i.setAttribute("href",URL.createObjectURL(n));const d=(()=>{const e=document.querySelector(".song-title");if(e){return e.getAttribute("title")}else{return"神秘音频"}})();i.setAttribute("download",d+".m4a");i.click()});Observer.childList("#app",()=>{const t=document.URL.match(/bilibili\.com\/audio\/au([\d]+)/);if(t&&t[1]){e.disabled=false;o.sid=t[1]}else{e.disabled=true}})}}}}})(); -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-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"));return e*4/188};const e=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-3*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 n=1.4-.2*t(".bilibili-player-setting-fontsize .bui-thumb");i.resolution={x:1920*n,y:1080*n};i.bottomMarginPercent=[.75,.5,.25,0,0][e(".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 r=o.convertToAssDocument(t);return r.generateAss()}async function r(t,e){const a=n();const r=new i((unsafeWindow||window).cid);await r.fetchInfo();const l=await(async()=>{if(t===true){return new Blob([await o(r.rawXML)],{type:"text/plain"})}else{return new Blob([r.rawXML],{type:"text/plain"})}})();const s=URL.createObjectURL(l);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:r,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);r(e.shiftKey,t)}})}}}}})(); offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/download-video.min.css"] = `.download-video{--download-video-background:white;--download-video-foreground:black;position:absolute;top:96px;left:50%;transform:translateX(-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}.download-video,.download-video *{transition:.2s ease-out;-webkit-tap-highlight-color:transparent!important}.download-video.opened{pointer-events:initial;opacity:1;transform:translateX(-50%) scale(1)}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 .size-warning-tip,.round-corner .download-video .title,.round-corner .download-video button{border-radius:var(--corner-radius)}.download-video .cover{min-height:100px;max-height:120px;object-fit:contain}.download-video h1{font-size:13pt;font-weight:700;color:var(--download-video-foreground)}.download-video h2{font-size:11pt;font-weight:700;color:var(--download-video-foreground)}.download-video .header{display:flex;justify-content:space-between;align-items:center}.download-video .header .grow{flex-grow:1}.download-video .header .mdi-download{font-size:16pt;color:var(--download-video-foreground);margin-right:8px}.download-video .header .mdi-close{font-size:16pt;color:var(--download-video-foreground);cursor:pointer}.download-video .header .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 .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 .bold{color:var(--download-video-foreground);font-weight:700;font-size:12pt}.download-video .option-item{display:flex;justify-content:space-between;align-items:center;padding-top:12px;font-size:10pt}.download-video .tabs{display:flex;padding:12px 0;font-size:10pt}.download-video .tabs .tab{cursor:pointer;position:relative;opacity:.5}.download-video .tabs .tab.active{font-weight:700;opacity:1}.download-video .tabs .tab:not(:last-child){margin-right:16px}.download-video .tabs .tab::after{content:"";position:absolute;border-radius:2px;background-color:var(--theme-color);height:3px;width:80%;left:10%;bottom:-8px;transition:.2s ease-out;transform:scaleX(0)}.download-video .tabs .tab.active::after{transform:scaleX(1)}.download-video .separator{height:1px;background:#8884;width:100%;margin:12px 0;flex-shrink:0}.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 .background .foreground{position:absolute;top:0;left:0;height:4px;background:linear-gradient(to right,var(--theme-color),var(--theme-color-60))}.download-video .direct-download .progress .percent{width:50px;text-align:right}.download-video .actions{display:flex;flex-wrap:wrap;justify-content:space-between;margin:8px -4px 0}.download-video .actions>*{margin:4px;flex-grow:1;flex-basis:calc(50% - 16px);display:flex;justify-content:center;align-items:center;white-space:nowrap}.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:200px;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}.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:stretch;color:var(--download-video-foreground);background:#fff;bottom:120%;left:50%;cursor:initial;box-shadow:rgba(0,0,0,.2) 0 4px 8px 0;transform-origin:bottom;transform:translateX(-50%) scale(.9);opacity:0;pointer-events:none;padding:8px;z-index:3;transition:.3s cubic-bezier(.18,.89,.32,1.28);width:120%}body.dark .download-video .rpc-settings{background:#282828}.download-video .rpc-settings>*{margin:8px}.download-video .rpc-settings.show{opacity:1;transform:translateX(-50%) scale(1);pointer-events:initial}.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)}.download-video .rpc-settings .operations{display:flex;align-items:center;justify-content:space-evenly}.download-video .final-dir{word-break:break-all}.download-video .rpc-settings-item{display:flex;align-items:center;justify-content:space-between;white-space:nowrap}.download-video .rpc-settings-item input[type=text]{flex-grow:1;margin-left:24px}.download-video button.cancel-download,.download-video button.start-download{margin-top:8px}.download-video .direct-download-header{align-self:stretch;display:flex;justify-content:space-between;align-items:center}body.dark .download-video .direct-download .progress .foreground{background:linear-gradient(to right,var(--theme-color-70),var(--theme-color))}`; offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/download-video.min.html"] = `

下载视频

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

直接下载

{{speed}}
{{progressPercent}}%

选集

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

导出

{{showRpcSettings ? '取消' : 'aria2 RPC'}}

aria2 RPC

配置

主机
端口
密钥
限速
默认路径
路径
最终路径: {{rpcSettings.baseDir + rpcSettings.dir}}
方法
开始下载
{{saveRpcSettingsText}}
`; offlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/download-video.min.js"] = (()=>{return(t,e)=>{const{getFriendlyTitle:s}=e.import("title");const{VideoInfo:a,DanmakuInfo:i}=e.import("video-info");const{DownloadVideoPackage:n}=e.import("download-video-package");class o{async getApiGenerator(t=false){function e(e,s,a){if(t){if(a){return`https://api.bilibili.com/x/player/playurl?avid=${e}&cid=${s}&qn=${a}&otype=json&fnver=0&fnval=16`}else{return`https://api.bilibili.com/x/player/playurl?avid=${e}&cid=${s}&otype=json&fnver=0&fnval=16`}}else{if(a){return`https://api.bilibili.com/x/player/playurl?avid=${e}&cid=${s}&qn=${a}&otype=json`}else{return`https://api.bilibili.com/x/player/playurl?avid=${e}&cid=${s}&otype=json`}}}return e.bind(this)}async getDashUrl(t){return(await this.getApiGenerator(true))(c.aid,c.cid,t)}async getUrl(t){return(await this.getApiGenerator())(c.aid,c.cid,t)}}class r extends o{async getApiGenerator(t=false){function e(e,s,a){if(t){if(a){return`https://api.bilibili.com/pgc/player/web/playurl?avid=${e}&cid=${s}&qn=${a}&otype=json&fourk=1&fnval=16`}else{return`https://api.bilibili.com/pgc/player/web/playurl?avid=${e}&cid=${s}&otype=json&fourk=1&fnval=16`}}else{if(a){return`https://api.bilibili.com/pgc/player/web/playurl?avid=${e}&cid=${s}&qn=${a}&otype=json`}else{return`https://api.bilibili.com/pgc/player/web/playurl?avid=${e}&cid=${s}&qn=&otype=json`}}}return e.bind(this)}}class l extends o{constructor(t){super();this.ep=t}async getApiGenerator(t=false){function e(e,s,a){if(t){if(a){return`https://api.bilibili.com/pugv/player/web/playurl?avid=${e}&cid=${s}&qn=${a}&otype=json&ep_id=${this.ep}&fnver=0&fnval=16`}else{return`https://api.bilibili.com/pugv/player/web/playurl?avid=${e}&cid=${s}&otype=json&ep_id=${this.ep}&fnver=0&fnval=16`}}else{if(a){return`https://api.bilibili.com/pugv/player/web/playurl?avid=${e}&cid=${s}&qn=${a}&otype=json&ep_id=${this.ep}`}else{return`https://api.bilibili.com/pugv/player/web/playurl?avid=${e}&cid=${s}&otype=json&ep_id=${this.ep}`}}}return e.bind(this)}}const c={entity:new o,aid:"",cid:""};let d=[];let p=null;class h{constructor(t,e,s){this.quality=t;this.internalName=e;this.displayName=s}async downloadInfo(t=false){const e=new u(this);await e.fetchVideoInfo(t);return e}static parseFormats(t){const e=t.accept_quality;const s=t.accept_format.split(",");const a=t.accept_description;const i=e.map((t,e)=>{return new h(t,s[e],a[e])});return i}static async getAvailableDashFormats(){const t=await c.entity.getDashUrl();const e=await Ajax.getJsonWithCredentials(t);if(e.code!==0){throw new Error("获取清晰度信息失败.")}return h.parseFormats(e.data||e.result||e)}static async getAvailableFormats(){const t=await c.entity.getUrl();const e=await Ajax.getJsonWithCredentials(t);if(e.code!==0){throw new Error("获取清晰度信息失败.")}const s=e.data||e.result||e;return h.parseFormats(s)}}class u{constructor(t,e){this.fragmentSplitFactor=6*2;this.workingXhr=null;this.progressMap=new Map;this.format=t;this.fragments=e||[];this.videoSpeed=new f(this)}get danmakuOption(){return t.downloadVideoDefaultDanmaku}get isDash(){return this.fragments.some(t=>t.url.includes(".m4s"))}get totalSize(){return this.fragments.map(t=>t.size).reduce((t,e)=>t+e)}async fetchVideoInfo(t=false){if(!t){const t=await c.entity.getUrl(this.format.quality);const e=await Ajax.getTextWithCredentials(t);const s=JSON.parse(e.replace(/http:/g,"https:"));const a=s.data||s.result||s;if(a.quality!==this.format.quality){throw new Error("获取下载链接失败, 请确认当前账号有下载权限后重试.")}const i=a.durl;this.fragments=i.map(t=>{return{length:t.length,size:t.size,url:t.url,backupUrls:t.backup_url}})}else{const{dashToFragments:t,getDashInfo:s}=await e.importAsync("video-dash");const a=await s(await c.entity.getDashUrl(this.format.quality),this.format.quality);this.fragments=t(a)}return this.fragments}updateProgress(){const t=this.progressMap?[...this.progressMap.values()].reduce((t,e)=>t+e,0)/this.totalSize:0;if(t>1||t<0){console.error(`[下载视频] 进度异常: ${t}`,this.progressMap.values())}this.progress&&this.progress(t)}cancelDownload(){this.videoSpeed.stopMeasure();if(this.workingXhr!==null){this.workingXhr.forEach(t=>t.abort())}else{logError("Cancel Download Failed: forEach in this.workingXhr not found.")}}downloadFragment(t){const e=[];const s=this.isDash?4*1024*1024:16*1024*1024;let a;if(t.size<=s*6){a=t.size/this.fragmentSplitFactor}else{a=s}let i=0;const n=t=>[...this.progressMap.keys()].indexOf(t)+1;while(i{const a=new XMLHttpRequest;a.open("GET",t.url);a.responseType="arraybuffer";a.withCredentials=false;a.addEventListener("progress",t=>{console.log(`[下载视频] 视频片段${n(a)}下载进度: ${t.loaded}/${r} bytes loaded, ${o}`);this.progressMap.set(a,t.loaded);this.updateProgress()});a.addEventListener("load",()=>{if((""+a.status)[0]==="2"){console.log(`[下载视频] 视频片段${n(a)}下载完成`);e(a.response)}else{s(`视频片段${n(a)}请求失败, response = ${a.status}`)}});a.addEventListener("abort",()=>s("canceled"));a.addEventListener("error",()=>{console.error(`[下载视频] 视频片段${n(a)}下载失败: ${o}`);this.progressMap.set(a,0);this.updateProgress();a.open("GET",t.url);a.setRequestHeader("Range",o);a.send()});a.setRequestHeader("Range",o);this.progressMap.set(a,0);a.send();this.workingXhr.push(a)}));i=Math.round(i+a)+1}return Promise.all(e)}async copyUrl(){const t=this.fragments.map(t=>t.url).reduce((t,e)=>t+"\r\n"+e);GM.setClipboard(t,"text")}async showUrl(){const t=this.fragments.map(t=>`\n${t.url}\n`).reduce((t,e)=>t+"\r\n"+e);Toast.success(t+`复制全部`,"显示链接");const e=await SpinQuery.select("#copy-link");e.addEventListener("click",async()=>{await this.copyUrl()})}async exportData(t=false){const e=JSON.stringify([{fragments:this.fragments,title:s(),totalSize:this.fragments.map(t=>t.size).reduce((t,e)=>t+e),referer:document.URL.replace(window.location.search,"")}]);if(t){GM.setClipboard(e,"text")}else{const t=new Blob([e],{type:"text/json"});const a=await this.downloadDanmaku();const i=new n;i.add(`${s()}.json`,t);i.add(s()+"."+this.danmakuOption.toLowerCase(),a);await i.emit(`${s()}.zip`)}}async exportAria2(a=false){if(a){const a=await this.downloadDanmaku();const i=new n;i.add(`${s()}.${this.danmakuOption==="ASS"?"ass":"xml"}`,a);await i.emit();const o=t.aria2RpcOption;const r=this.fragments.map((t,e)=>{let a="";if(this.fragments.length>1&&!this.isDash){a=" - "+(e+1)}const i=[];if(o.secretKey!==""){i.push(`token:${o.secretKey}`)}i.push([t.url]);i.push({referer:document.URL.replace(window.location.search,""),"user-agent":UserAgent,out:`${s()}${a}${this.extension(t)}`,split:this.fragmentSplitFactor,dir:o.baseDir+o.dir||undefined,"max-download-limit":o.maxDownloadLimit||undefined});const n=encodeURIComponent(`${s()}${a}`);return{params:i,id:n}});const{sendRpc:l}=await e.importAsync("aria2-rpc");await l(r)}else{const t=`\n# Generated by Bilibili Evolved Video Export\n# https://github.com/the1812/Bilibili-Evolved/\n${this.fragments.map((t,e)=>{let a="";if(this.fragments.length>1&&!this.isDash){a=" - "+(e+1)}return`\n${t.url}\n referer=${document.URL.replace(window.location.search,"")}\n user-agent=${UserAgent}\n out=${s()}${a}${this.extension(t)}\n split=${this.fragmentSplitFactor}\n`.trim()}).join("\n")}\n`.trim();const e=new Blob([t],{type:"text/plain"});const a=await this.downloadDanmaku();const i=new n;i.add(`${s()}.txt`,e);i.add(s()+"."+this.danmakuOption.toLowerCase(),a);await i.emit(`${s()}.zip`)}}extension(t){const e=t||this.fragments[0];const s=[".flv",".mp4"].find(t=>e.url.includes(t));if(s){return s}else if(e.url.includes(".m4s")){return this.fragments.indexOf(e)===0?".mp4":".m4a"}else{console.warn("No extension detected.");return".flv"}}async downloadDanmaku(){if(this.danmakuOption!=="无"){const t=new i(c.cid);await t.fetchInfo();if(this.danmakuOption==="XML"){return t.rawXML}else{const{convertToAss:s}=await e.importAsync("download-danmaku");return s(t.rawXML)}}else{return null}}async download(){this.workingXhr=[];this.progressMap=new Map;this.updateProgress();const t=[];this.videoSpeed.startMeasure();for(const e of this.fragments){const s=await this.downloadFragment(e);t.push(s)}if(t.length<1){throw new Error("下载失败.")}const e=s();const a=new n;t.forEach((s,i)=>{let n;const o=this.fragments[i];if(t.length>1&&!this.isDash){n=`${e} - ${i+1}${this.extension(o)}`}else{n=`${e}${this.extension(o)}`}a.add(n,new Blob(Array.isArray(s)?s:[s]))});const i=await this.downloadDanmaku();a.add(`${s()}.${this.danmakuOption==="ASS"?"ass":"xml"}`,i);await a.emit(e+".zip");this.progress&&this.progress(0);this.videoSpeed.stopMeasure()}}class f{constructor(t){this.lastProgress=0;this.measureInterval=1e3;this.workingDownloader=t}startMeasure(){this.intervalTimer=setInterval(()=>{const t=this.workingDownloader.progressMap?[...this.workingDownloader.progressMap.values()].reduce((t,e)=>t+e,0):0;const e=t-this.lastProgress;if(this.speedUpdate!==undefined){this.speedUpdate(formatFileSize(e)+"/s")}this.lastProgress=t},this.measureInterval)}stopMeasure(){clearInterval(this.intervalTimer)}}async function w(){const t=await SpinQuery.select(()=>(unsafeWindow||window).aid);const e=await SpinQuery.select(()=>(unsafeWindow||window).cid);if(!(t&&e)){return false}c.aid=t;c.cid=e;if(document.URL.includes("bangumi")){c.entity=new r}else if(document.URL.includes("cheese")){const t=document.URL.match(/cheese\/play\/ep([\d]+)/);c.entity=new l(t[1])}else{c.entity=new o}try{d=await h.getAvailableFormats()}catch(t){return false}return true}async function m(){p=d[0];e.applyStyle("downloadVideoStyle");const t=dq("#download-video");t.addEventListener("click",()=>{const t=dq(".download-video");t.classList.toggle("opened");window.scroll(0,0);dq(".gui-settings-mask").click()});document.body.insertAdjacentHTML("beforeend",e.import("downloadVideoHtml"));g()}async function g(){let o;const r=new Vue({el:".download-video",components:{VDropdown:()=>e.importAsync("v-dropdown.vue"),VCheckbox:()=>e.importAsync("v-checkbox.vue"),RpcProfiles:()=>e.importAsync("aria2-rpc-profiles.vue")},data:{downloadSingle:true,coverUrl:EmptyImageUrl,aid:c.aid,cid:c.cid,dashModel:{value:t.downloadVideoFormat,items:["flv","dash"]},qualityModel:{value:p.displayName,items:d.map(t=>t.displayName)},danmakuModel:{value:t.downloadVideoDefaultDanmaku,items:["无","XML","ASS"]},codecModel:{value:t.downloadVideoDashCodec,items:["AVC/H.264","HEVC/H.265"]},progressPercent:0,size:"获取大小中",blobUrl:"",episodeList:[],downloading:false,speed:"",batch:false,rpcSettings:t.aria2RpcOption,showRpcSettings:false,busy:false,saveRpcSettingsText:"保存配置",enableDash:t.enableDashDownload,lastDirectDownloadLink:""},computed:{displaySize(){if(typeof this.size==="string"){return this.size}return formatFileSize(this.size)},sizeWarning(){if(typeof this.size==="string"){return false}return this.size>1073741824},selectedEpisodeCount(){return this.episodeList.filter(t=>t.checked).length},dash(){return this.dashModel.value==="dash"}},methods:{close(){this.$el.classList.remove("opened")},danmakuOptionChange(){t.downloadVideoDefaultDanmaku=this.danmakuModel.value},async codecChange(){t.downloadVideoDashCodec=this.codecModel.value;await this.formatChange()},async dashChange(){console.log("dash change");t.downloadVideoFormat=this.dashModel.value;const e=this.dashModel.value;let s=[];if(e==="flv"){s=await h.getAvailableFormats()}else{s=await h.getAvailableDashFormats()}d=s;[p]=e;this.qualityModel.items=s.map(t=>t.displayName);[this.qualityModel.value]=this.qualityModel.items;await this.formatChange()},async formatChange(){console.log("format change");const t=this.getFormat();try{this.size="获取大小中";const e=await t.downloadInfo(this.dash);this.size=e.totalSize}catch(t){this.size="获取大小失败";throw t}},getFormat(){const t=d.find(t=>t.displayName===this.qualityModel.value);if(!t){console.error(`No format found. model value = ${this.qualityModel.value}`);return null}return t},async exportData(t){if(this.busy===true){return}try{this.busy=true;if(!this.downloadSingle){await this.exportBatchData(t);return}const a=this.getFormat();const i=await a.downloadInfo(this.dash);switch(t){case"copyLink":await i.copyUrl();Toast.success("已复制链接到剪贴板.","下载视频",3e3);break;case"showLink":await i.showUrl();break;case"aria2":await i.exportAria2(false);break;case"aria2RPC":await i.exportAria2(true);break;case"copyVLD":await i.exportData(true);Toast.success("已复制VLD数据到剪贴板.","下载视频",3e3);break;case"exportVLD":await i.exportData(false);break;case"ffmpegFragments":if(i.fragments.length<2){Toast.info("当前视频没有分段.","分段列表",3e3)}else{const{getFragmentsList:t}=await e.importAsync("ffmpeg-support");const a=new n;a.add("ffmpeg-files.txt",t(i.fragments.length,s(),i.fragments.map(t=>i.extension(t))));await a.emit()}break;default:break}}catch(t){logError(t)}finally{this.busy=false}},async exportBatchData(t){const a=this.episodeList;if(a.every(t=>t.checked===false)){Toast.info("请至少选择1集或以上的数量!","批量导出",3e3);return}const o=t=>{const e=a.find(e=>e.cid===t.cid);if(e===undefined){return false}return e.checked};const r=this.getFormat();if(this.danmakuModel.value!=="无"){const t=Toast.info("下载弹幕中...","批量导出");const s=new n;try{if(this.danmakuModel.value==="XML"){for(const t of a.filter(o)){const e=new i(t.cid);await e.fetchInfo();s.add(t.title+".xml",e.rawXML)}}else{const{convertToAss:t}=await e.importAsync("download-danmaku");for(const e of a.filter(o)){const a=new i(e.cid);await a.fetchInfo();s.add(e.title+".ass",await t(a.rawXML))}}await s.emit(this.cid+".danmakus.zip")}catch(t){logError(`弹幕下载失败`);throw t}finally{t.dismiss()}}const l=Toast.info("获取链接中...","批量导出");const d=this.batchExtractor;d.config.itemFilter=o;d.config.api=await c.entity.getApiGenerator(this.dash);let p;try{switch(t){case"aria2":p=await d.collectAria2(r,l,false);await n.single(s(false)+".txt",new Blob([p],{type:"text/plain"}),{ffmpeg:this.ffmpegOption});return;case"aria2RPC":await d.collectAria2(r,l,true);Toast.success(`成功发送了批量请求.`,"aria2 RPC",3e3);return;case"copyVLD":GM.setClipboard(await d.collectData(r,l),{mimetype:"text/plain"});Toast.success("已复制批量vld数据到剪贴板.","批量导出",3e3);return;case"exportVLD":p=await d.collectData(r,l);await n.single(s(false)+".json",new Blob([p],{type:"text/json"}),{ffmpeg:this.ffmpegOption});return;case"ffmpegFragments":{const t=await d.getRawItems(r);const a=new u(r,t[0].fragments);const{getBatchFragmentsList:i}=await e.importAsync("ffmpeg-support");const o=i(t,this.dash||a.extension());if(!o){Toast.info("所有选择的分P都没有分段.","分段列表",3e3)}else{const t=new n;for(const[e,s]of o.entries()){t.add(e,s)}await t.emit(escapeFilename(`${s(false)}.zip`))}}break;case"ffmpegEpisodes":{const t=await d.getRawItems(r);const s=new u(r,t[0].fragments);const{getBatchEpisodesList:a}=await e.importAsync("ffmpeg-support");const i=a(t,this.dash||s.extension());const o=new n;o.add("ffmpeg-files.txt",i);await o.emit()}break;default:return}}catch(t){logError(t)}finally{l.dismiss()}},async checkBatch(){const t=["/www.bilibili.com/bangumi","/www.bilibili.com/video/av"];if(!t.some(t=>document.URL.includes(t))){this.batch=false;this.episodeList=[];return}const{BatchExtractor:s}=await e.importAsync("batch-download");if(await s.test()!==true){this.batch=false;this.episodeList=[];return}const a=this.batchExtractor=new s;this.batch=true;this.episodeList=(await a.getItemList()).map((t,e)=>{return{aid:t.aid,cid:t.cid,title:t.title,index:e,checked:true}})},cancelDownload(){if(o){o.cancelDownload()}},async startDownload(){const t=this.getFormat();try{this.downloading=true;const e=await t.downloadInfo(this.dash);e.videoSpeed.speedUpdate=(t=>this.speed=t);e.progress=(t=>{this.progressPercent=Math.trunc(t*100)});o=e;await e.download();this.lastDirectDownloadLink=n.lastPackageUrl}catch(t){if(t!=="canceled"){logError(t)}this.progressPercent=0}finally{this.downloading=false;this.speed=""}},selectAllEpisodes(){this.episodeList.forEach(t=>t.checked=true)},unselectAllEpisodes(){this.episodeList.forEach(t=>t.checked=false)},inverseAllEpisodes(){this.episodeList.forEach(t=>t.checked=!t.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"}t.aria2RpcOption=this.rpcSettings;const e=t.aria2RpcOptionProfiles.find(e=>e.name===t.aria2RpcOptionSelectedProfile);if(e){Object.assign(e,this.rpcSettings);t.aria2RpcOptionProfiles=t.aria2RpcOptionProfiles}this.saveRpcSettingsText="已保存";setTimeout(()=>this.saveRpcSettingsText="保存配置",2e3)},updateProfile(e){t.aria2RpcOption=this.rpcSettings=_.omit(e,"name")}},async mounted(){}});Observer.videoChange(async()=>{r.close();r.batch=false;r.downloadSingle=true;const t=dq("#download-video");const e=await w();t.style.display=e?"flex":"none";if(!e){return}r.aid=c.aid;r.cid=c.cid;try{const t=new a(c.aid);await t.fetchInfo();r.coverUrl=t.coverUrl.replace("http:","https:")}catch(t){r.coverUrl=EmptyImageUrl}r.dashChange();await r.checkBatch()})}return{widget:{content:`\n`,condition:w,success:m}}}})(); diff --git a/bilibili-evolved.preview.user.js b/bilibili-evolved.preview.user.js index 0647b506e..e5278ba59 100644 --- a/bilibili-evolved.preview.user.js +++ b/bilibili-evolved.preview.user.js @@ -1122,7 +1122,7 @@ onlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/preview/m onlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/preview/min/default-video-speed.min.js"] = (()=>{return(e,a)=>{const i=a=>{const i=parseFloat(e.defaultVideoSpeed);a.playbackRate=i;SpinQuery.condition(()=>a,()=>a.playbackRate!==i,()=>a.playbackRate=i)};Observer.videoChange(()=>{const e=dq(".bilibili-player-video video");if(!e){return}i(e)})}})(); onlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/preview/min/double-click-fullscreen.min.js"] = (()=>{return(i,e)=>{(async()=>{const e=["https://www.bilibili.com/bangumi/","https://www.bilibili.com/video/"];if(!e.some(i=>document.URL.startsWith(i))){return}if(i.touchVideoPlayer&&i.touchVideoPlayerDoubleTapControl){Toast.info("在开启了播放器触摸支持-启用双击控制后, 双击全屏功能将无效.","提示");i.doubleClickFullscreen=false;return}await SpinQuery.unsafeJquery();const l=await SpinQuery.condition(()=>dq(".bilibili-player-area"),i=>i!==null&&unsafeWindow.$(".bilibili-player-video").data("events"));if(l===null){return}const n="double-click-fullscreen";if(!l.classList.contains(n)){l.classList.add(n);const e=unsafeWindow.$(".bilibili-player-video");const t=i.doubleClickFullscreenPreventSingleClick?e.data("events").click[0].handler:()=>{};const c=new DoubleClickEvent(()=>dq(".bilibili-player-video-btn-fullscreen").click(),i=>t(i));if(i.doubleClickFullscreenPreventSingleClick){e.unbind("click")}c.bind(e[0])}})()}})(); onlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/preview/min/download-audio.min.js"] = (()=>{return(e,t)=>{class n{constructor(){this.sid=null;this.progress=null}async getDownloadUrl(){const e=`https://www.bilibili.com/audio/music-service-c/web/url?sid=${this.sid}&privilege=2&quality=2`;const t=await Ajax.getJsonWithCredentials(e);if(t.code===0){return t.data.cdns.shift()}else{logError("获取下载链接失败, 请确保当前账号有下载权限.","下载音频",1e4);return null}}async download(){const e=await this.getDownloadUrl();return new Promise((t,n)=>{const s=new XMLHttpRequest;s.open("GET",e);s.responseType="blob";s.addEventListener("load",()=>t(s.response));s.addEventListener("error",()=>n(s.status));s.addEventListener("progress",e=>this.progress&&this.progress(100*e.loaded/e.total));s.send()})}}const s="下载音频";return{export:n,widget:{content:`\n\n\n${s}\n\n`,condition:()=>document.URL.includes("bilibili.com/audio"),success:async()=>{await SpinQuery.select(()=>document.querySelector("#app"));const e=document.querySelector("#download-audio");const t=e.querySelector("span");const o=new n;o.progress=(e=>{t.innerHTML=`${Math.round(e)}%`});const i=document.querySelector("#download-audio-link");e.addEventListener("click",async e=>{if(o.sid===null||e.target===i){return}const n=await o.download();t.innerHTML=s;const r=i.getAttribute("href");if(r){URL.revokeObjectURL(r)}i.setAttribute("href",URL.createObjectURL(n));const d=(()=>{const e=document.querySelector(".song-title");if(e){return e.getAttribute("title")}else{return"神秘音频"}})();i.setAttribute("download",d+".m4a");i.click()});Observer.childList("#app",()=>{const t=document.URL.match(/bilibili\.com\/audio\/au([\d]+)/);if(t&&t[1]){e.disabled=false;o.sid=t[1]}else{e.disabled=true}})}}}}})(); -onlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/preview/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)}})}}}}})(); +onlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/preview/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"));return e*4/188};const e=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-3*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 n=1.4-.2*t(".bilibili-player-setting-fontsize .bui-thumb");i.resolution={x:1920*n,y:1080*n};i.bottomMarginPercent=[.75,.5,.25,0,0][e(".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 r=o.convertToAssDocument(t);return r.generateAss()}async function r(t,e){const a=n();const r=new i((unsafeWindow||window).cid);await r.fetchInfo();const l=await(async()=>{if(t===true){return new Blob([await o(r.rawXML)],{type:"text/plain"})}else{return new Blob([r.rawXML],{type:"text/plain"})}})();const s=URL.createObjectURL(l);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:r,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);r(e.shiftKey,t)}})}}}}})(); onlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/preview/min/download-video.min.css"] = `.download-video{--download-video-background:white;--download-video-foreground:black;position:absolute;top:96px;left:50%;transform:translateX(-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}.download-video,.download-video *{transition:.2s ease-out;-webkit-tap-highlight-color:transparent!important}.download-video.opened{pointer-events:initial;opacity:1;transform:translateX(-50%) scale(1)}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 .size-warning-tip,.round-corner .download-video .title,.round-corner .download-video button{border-radius:var(--corner-radius)}.download-video .cover{min-height:100px;max-height:120px;object-fit:contain}.download-video h1{font-size:13pt;font-weight:700;color:var(--download-video-foreground)}.download-video h2{font-size:11pt;font-weight:700;color:var(--download-video-foreground)}.download-video .header{display:flex;justify-content:space-between;align-items:center}.download-video .header .grow{flex-grow:1}.download-video .header .mdi-download{font-size:16pt;color:var(--download-video-foreground);margin-right:8px}.download-video .header .mdi-close{font-size:16pt;color:var(--download-video-foreground);cursor:pointer}.download-video .header .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 .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 .bold{color:var(--download-video-foreground);font-weight:700;font-size:12pt}.download-video .option-item{display:flex;justify-content:space-between;align-items:center;padding-top:12px;font-size:10pt}.download-video .tabs{display:flex;padding:12px 0;font-size:10pt}.download-video .tabs .tab{cursor:pointer;position:relative;opacity:.5}.download-video .tabs .tab.active{font-weight:700;opacity:1}.download-video .tabs .tab:not(:last-child){margin-right:16px}.download-video .tabs .tab::after{content:"";position:absolute;border-radius:2px;background-color:var(--theme-color);height:3px;width:80%;left:10%;bottom:-8px;transition:.2s ease-out;transform:scaleX(0)}.download-video .tabs .tab.active::after{transform:scaleX(1)}.download-video .separator{height:1px;background:#8884;width:100%;margin:12px 0;flex-shrink:0}.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 .background .foreground{position:absolute;top:0;left:0;height:4px;background:linear-gradient(to right,var(--theme-color),var(--theme-color-60))}.download-video .direct-download .progress .percent{width:50px;text-align:right}.download-video .actions{display:flex;flex-wrap:wrap;justify-content:space-between;margin:8px -4px 0}.download-video .actions>*{margin:4px;flex-grow:1;flex-basis:calc(50% - 16px);display:flex;justify-content:center;align-items:center;white-space:nowrap}.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:200px;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}.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:stretch;color:var(--download-video-foreground);background:#fff;bottom:120%;left:50%;cursor:initial;box-shadow:rgba(0,0,0,.2) 0 4px 8px 0;transform-origin:bottom;transform:translateX(-50%) scale(.9);opacity:0;pointer-events:none;padding:8px;z-index:3;transition:.3s cubic-bezier(.18,.89,.32,1.28);width:120%}body.dark .download-video .rpc-settings{background:#282828}.download-video .rpc-settings>*{margin:8px}.download-video .rpc-settings.show{opacity:1;transform:translateX(-50%) scale(1);pointer-events:initial}.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)}.download-video .rpc-settings .operations{display:flex;align-items:center;justify-content:space-evenly}.download-video .final-dir{word-break:break-all}.download-video .rpc-settings-item{display:flex;align-items:center;justify-content:space-between;white-space:nowrap}.download-video .rpc-settings-item input[type=text]{flex-grow:1;margin-left:24px}.download-video button.cancel-download,.download-video button.start-download{margin-top:8px}.download-video .direct-download-header{align-self:stretch;display:flex;justify-content:space-between;align-items:center}body.dark .download-video .direct-download .progress .foreground{background:linear-gradient(to right,var(--theme-color-70),var(--theme-color))}`; onlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/preview/min/download-video.min.html"] = `

下载视频

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

直接下载

{{speed}}
{{progressPercent}}%

选集

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

导出

{{showRpcSettings ? '取消' : 'aria2 RPC'}}

aria2 RPC

配置

主机
端口
密钥
限速
默认路径
路径
最终路径: {{rpcSettings.baseDir + rpcSettings.dir}}
方法
开始下载
{{saveRpcSettingsText}}
`; onlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/preview/min/download-video.min.js"] = (()=>{return(t,e)=>{const{getFriendlyTitle:s}=e.import("title");const{VideoInfo:a,DanmakuInfo:i}=e.import("video-info");const{DownloadVideoPackage:n}=e.import("download-video-package");class o{async getApiGenerator(t=false){function e(e,s,a){if(t){if(a){return`https://api.bilibili.com/x/player/playurl?avid=${e}&cid=${s}&qn=${a}&otype=json&fnver=0&fnval=16`}else{return`https://api.bilibili.com/x/player/playurl?avid=${e}&cid=${s}&otype=json&fnver=0&fnval=16`}}else{if(a){return`https://api.bilibili.com/x/player/playurl?avid=${e}&cid=${s}&qn=${a}&otype=json`}else{return`https://api.bilibili.com/x/player/playurl?avid=${e}&cid=${s}&otype=json`}}}return e.bind(this)}async getDashUrl(t){return(await this.getApiGenerator(true))(c.aid,c.cid,t)}async getUrl(t){return(await this.getApiGenerator())(c.aid,c.cid,t)}}class r extends o{async getApiGenerator(t=false){function e(e,s,a){if(t){if(a){return`https://api.bilibili.com/pgc/player/web/playurl?avid=${e}&cid=${s}&qn=${a}&otype=json&fourk=1&fnval=16`}else{return`https://api.bilibili.com/pgc/player/web/playurl?avid=${e}&cid=${s}&otype=json&fourk=1&fnval=16`}}else{if(a){return`https://api.bilibili.com/pgc/player/web/playurl?avid=${e}&cid=${s}&qn=${a}&otype=json`}else{return`https://api.bilibili.com/pgc/player/web/playurl?avid=${e}&cid=${s}&qn=&otype=json`}}}return e.bind(this)}}class l extends o{constructor(t){super();this.ep=t}async getApiGenerator(t=false){function e(e,s,a){if(t){if(a){return`https://api.bilibili.com/pugv/player/web/playurl?avid=${e}&cid=${s}&qn=${a}&otype=json&ep_id=${this.ep}&fnver=0&fnval=16`}else{return`https://api.bilibili.com/pugv/player/web/playurl?avid=${e}&cid=${s}&otype=json&ep_id=${this.ep}&fnver=0&fnval=16`}}else{if(a){return`https://api.bilibili.com/pugv/player/web/playurl?avid=${e}&cid=${s}&qn=${a}&otype=json&ep_id=${this.ep}`}else{return`https://api.bilibili.com/pugv/player/web/playurl?avid=${e}&cid=${s}&otype=json&ep_id=${this.ep}`}}}return e.bind(this)}}const c={entity:new o,aid:"",cid:""};let d=[];let p=null;class h{constructor(t,e,s){this.quality=t;this.internalName=e;this.displayName=s}async downloadInfo(t=false){const e=new u(this);await e.fetchVideoInfo(t);return e}static parseFormats(t){const e=t.accept_quality;const s=t.accept_format.split(",");const a=t.accept_description;const i=e.map((t,e)=>{return new h(t,s[e],a[e])});return i}static async getAvailableDashFormats(){const t=await c.entity.getDashUrl();const e=await Ajax.getJsonWithCredentials(t);if(e.code!==0){throw new Error("获取清晰度信息失败.")}return h.parseFormats(e.data||e.result||e)}static async getAvailableFormats(){const t=await c.entity.getUrl();const e=await Ajax.getJsonWithCredentials(t);if(e.code!==0){throw new Error("获取清晰度信息失败.")}const s=e.data||e.result||e;return h.parseFormats(s)}}class u{constructor(t,e){this.fragmentSplitFactor=6*2;this.workingXhr=null;this.progressMap=new Map;this.format=t;this.fragments=e||[];this.videoSpeed=new f(this)}get danmakuOption(){return t.downloadVideoDefaultDanmaku}get isDash(){return this.fragments.some(t=>t.url.includes(".m4s"))}get totalSize(){return this.fragments.map(t=>t.size).reduce((t,e)=>t+e)}async fetchVideoInfo(t=false){if(!t){const t=await c.entity.getUrl(this.format.quality);const e=await Ajax.getTextWithCredentials(t);const s=JSON.parse(e.replace(/http:/g,"https:"));const a=s.data||s.result||s;if(a.quality!==this.format.quality){throw new Error("获取下载链接失败, 请确认当前账号有下载权限后重试.")}const i=a.durl;this.fragments=i.map(t=>{return{length:t.length,size:t.size,url:t.url,backupUrls:t.backup_url}})}else{const{dashToFragments:t,getDashInfo:s}=await e.importAsync("video-dash");const a=await s(await c.entity.getDashUrl(this.format.quality),this.format.quality);this.fragments=t(a)}return this.fragments}updateProgress(){const t=this.progressMap?[...this.progressMap.values()].reduce((t,e)=>t+e,0)/this.totalSize:0;if(t>1||t<0){console.error(`[下载视频] 进度异常: ${t}`,this.progressMap.values())}this.progress&&this.progress(t)}cancelDownload(){this.videoSpeed.stopMeasure();if(this.workingXhr!==null){this.workingXhr.forEach(t=>t.abort())}else{logError("Cancel Download Failed: forEach in this.workingXhr not found.")}}downloadFragment(t){const e=[];const s=this.isDash?4*1024*1024:16*1024*1024;let a;if(t.size<=s*6){a=t.size/this.fragmentSplitFactor}else{a=s}let i=0;const n=t=>[...this.progressMap.keys()].indexOf(t)+1;while(i{const a=new XMLHttpRequest;a.open("GET",t.url);a.responseType="arraybuffer";a.withCredentials=false;a.addEventListener("progress",t=>{console.log(`[下载视频] 视频片段${n(a)}下载进度: ${t.loaded}/${r} bytes loaded, ${o}`);this.progressMap.set(a,t.loaded);this.updateProgress()});a.addEventListener("load",()=>{if((""+a.status)[0]==="2"){console.log(`[下载视频] 视频片段${n(a)}下载完成`);e(a.response)}else{s(`视频片段${n(a)}请求失败, response = ${a.status}`)}});a.addEventListener("abort",()=>s("canceled"));a.addEventListener("error",()=>{console.error(`[下载视频] 视频片段${n(a)}下载失败: ${o}`);this.progressMap.set(a,0);this.updateProgress();a.open("GET",t.url);a.setRequestHeader("Range",o);a.send()});a.setRequestHeader("Range",o);this.progressMap.set(a,0);a.send();this.workingXhr.push(a)}));i=Math.round(i+a)+1}return Promise.all(e)}async copyUrl(){const t=this.fragments.map(t=>t.url).reduce((t,e)=>t+"\r\n"+e);GM.setClipboard(t,"text")}async showUrl(){const t=this.fragments.map(t=>`\n${t.url}\n`).reduce((t,e)=>t+"\r\n"+e);Toast.success(t+`复制全部`,"显示链接");const e=await SpinQuery.select("#copy-link");e.addEventListener("click",async()=>{await this.copyUrl()})}async exportData(t=false){const e=JSON.stringify([{fragments:this.fragments,title:s(),totalSize:this.fragments.map(t=>t.size).reduce((t,e)=>t+e),referer:document.URL.replace(window.location.search,"")}]);if(t){GM.setClipboard(e,"text")}else{const t=new Blob([e],{type:"text/json"});const a=await this.downloadDanmaku();const i=new n;i.add(`${s()}.json`,t);i.add(s()+"."+this.danmakuOption.toLowerCase(),a);await i.emit(`${s()}.zip`)}}async exportAria2(a=false){if(a){const a=await this.downloadDanmaku();const i=new n;i.add(`${s()}.${this.danmakuOption==="ASS"?"ass":"xml"}`,a);await i.emit();const o=t.aria2RpcOption;const r=this.fragments.map((t,e)=>{let a="";if(this.fragments.length>1&&!this.isDash){a=" - "+(e+1)}const i=[];if(o.secretKey!==""){i.push(`token:${o.secretKey}`)}i.push([t.url]);i.push({referer:document.URL.replace(window.location.search,""),"user-agent":UserAgent,out:`${s()}${a}${this.extension(t)}`,split:this.fragmentSplitFactor,dir:o.baseDir+o.dir||undefined,"max-download-limit":o.maxDownloadLimit||undefined});const n=encodeURIComponent(`${s()}${a}`);return{params:i,id:n}});const{sendRpc:l}=await e.importAsync("aria2-rpc");await l(r)}else{const t=`\n# Generated by Bilibili Evolved Video Export\n# https://github.com/the1812/Bilibili-Evolved/\n${this.fragments.map((t,e)=>{let a="";if(this.fragments.length>1&&!this.isDash){a=" - "+(e+1)}return`\n${t.url}\n referer=${document.URL.replace(window.location.search,"")}\n user-agent=${UserAgent}\n out=${s()}${a}${this.extension(t)}\n split=${this.fragmentSplitFactor}\n`.trim()}).join("\n")}\n`.trim();const e=new Blob([t],{type:"text/plain"});const a=await this.downloadDanmaku();const i=new n;i.add(`${s()}.txt`,e);i.add(s()+"."+this.danmakuOption.toLowerCase(),a);await i.emit(`${s()}.zip`)}}extension(t){const e=t||this.fragments[0];const s=[".flv",".mp4"].find(t=>e.url.includes(t));if(s){return s}else if(e.url.includes(".m4s")){return this.fragments.indexOf(e)===0?".mp4":".m4a"}else{console.warn("No extension detected.");return".flv"}}async downloadDanmaku(){if(this.danmakuOption!=="无"){const t=new i(c.cid);await t.fetchInfo();if(this.danmakuOption==="XML"){return t.rawXML}else{const{convertToAss:s}=await e.importAsync("download-danmaku");return s(t.rawXML)}}else{return null}}async download(){this.workingXhr=[];this.progressMap=new Map;this.updateProgress();const t=[];this.videoSpeed.startMeasure();for(const e of this.fragments){const s=await this.downloadFragment(e);t.push(s)}if(t.length<1){throw new Error("下载失败.")}const e=s();const a=new n;t.forEach((s,i)=>{let n;const o=this.fragments[i];if(t.length>1&&!this.isDash){n=`${e} - ${i+1}${this.extension(o)}`}else{n=`${e}${this.extension(o)}`}a.add(n,new Blob(Array.isArray(s)?s:[s]))});const i=await this.downloadDanmaku();a.add(`${s()}.${this.danmakuOption==="ASS"?"ass":"xml"}`,i);await a.emit(e+".zip");this.progress&&this.progress(0);this.videoSpeed.stopMeasure()}}class f{constructor(t){this.lastProgress=0;this.measureInterval=1e3;this.workingDownloader=t}startMeasure(){this.intervalTimer=setInterval(()=>{const t=this.workingDownloader.progressMap?[...this.workingDownloader.progressMap.values()].reduce((t,e)=>t+e,0):0;const e=t-this.lastProgress;if(this.speedUpdate!==undefined){this.speedUpdate(formatFileSize(e)+"/s")}this.lastProgress=t},this.measureInterval)}stopMeasure(){clearInterval(this.intervalTimer)}}async function w(){const t=await SpinQuery.select(()=>(unsafeWindow||window).aid);const e=await SpinQuery.select(()=>(unsafeWindow||window).cid);if(!(t&&e)){return false}c.aid=t;c.cid=e;if(document.URL.includes("bangumi")){c.entity=new r}else if(document.URL.includes("cheese")){const t=document.URL.match(/cheese\/play\/ep([\d]+)/);c.entity=new l(t[1])}else{c.entity=new o}try{d=await h.getAvailableFormats()}catch(t){return false}return true}async function m(){p=d[0];e.applyStyle("downloadVideoStyle");const t=dq("#download-video");t.addEventListener("click",()=>{const t=dq(".download-video");t.classList.toggle("opened");window.scroll(0,0);dq(".gui-settings-mask").click()});document.body.insertAdjacentHTML("beforeend",e.import("downloadVideoHtml"));g()}async function g(){let o;const r=new Vue({el:".download-video",components:{VDropdown:()=>e.importAsync("v-dropdown.vue"),VCheckbox:()=>e.importAsync("v-checkbox.vue"),RpcProfiles:()=>e.importAsync("aria2-rpc-profiles.vue")},data:{downloadSingle:true,coverUrl:EmptyImageUrl,aid:c.aid,cid:c.cid,dashModel:{value:t.downloadVideoFormat,items:["flv","dash"]},qualityModel:{value:p.displayName,items:d.map(t=>t.displayName)},danmakuModel:{value:t.downloadVideoDefaultDanmaku,items:["无","XML","ASS"]},codecModel:{value:t.downloadVideoDashCodec,items:["AVC/H.264","HEVC/H.265"]},progressPercent:0,size:"获取大小中",blobUrl:"",episodeList:[],downloading:false,speed:"",batch:false,rpcSettings:t.aria2RpcOption,showRpcSettings:false,busy:false,saveRpcSettingsText:"保存配置",enableDash:t.enableDashDownload,lastDirectDownloadLink:""},computed:{displaySize(){if(typeof this.size==="string"){return this.size}return formatFileSize(this.size)},sizeWarning(){if(typeof this.size==="string"){return false}return this.size>1073741824},selectedEpisodeCount(){return this.episodeList.filter(t=>t.checked).length},dash(){return this.dashModel.value==="dash"}},methods:{close(){this.$el.classList.remove("opened")},danmakuOptionChange(){t.downloadVideoDefaultDanmaku=this.danmakuModel.value},async codecChange(){t.downloadVideoDashCodec=this.codecModel.value;await this.formatChange()},async dashChange(){console.log("dash change");t.downloadVideoFormat=this.dashModel.value;const e=this.dashModel.value;let s=[];if(e==="flv"){s=await h.getAvailableFormats()}else{s=await h.getAvailableDashFormats()}d=s;[p]=e;this.qualityModel.items=s.map(t=>t.displayName);[this.qualityModel.value]=this.qualityModel.items;await this.formatChange()},async formatChange(){console.log("format change");const t=this.getFormat();try{this.size="获取大小中";const e=await t.downloadInfo(this.dash);this.size=e.totalSize}catch(t){this.size="获取大小失败";throw t}},getFormat(){const t=d.find(t=>t.displayName===this.qualityModel.value);if(!t){console.error(`No format found. model value = ${this.qualityModel.value}`);return null}return t},async exportData(t){if(this.busy===true){return}try{this.busy=true;if(!this.downloadSingle){await this.exportBatchData(t);return}const a=this.getFormat();const i=await a.downloadInfo(this.dash);switch(t){case"copyLink":await i.copyUrl();Toast.success("已复制链接到剪贴板.","下载视频",3e3);break;case"showLink":await i.showUrl();break;case"aria2":await i.exportAria2(false);break;case"aria2RPC":await i.exportAria2(true);break;case"copyVLD":await i.exportData(true);Toast.success("已复制VLD数据到剪贴板.","下载视频",3e3);break;case"exportVLD":await i.exportData(false);break;case"ffmpegFragments":if(i.fragments.length<2){Toast.info("当前视频没有分段.","分段列表",3e3)}else{const{getFragmentsList:t}=await e.importAsync("ffmpeg-support");const a=new n;a.add("ffmpeg-files.txt",t(i.fragments.length,s(),i.fragments.map(t=>i.extension(t))));await a.emit()}break;default:break}}catch(t){logError(t)}finally{this.busy=false}},async exportBatchData(t){const a=this.episodeList;if(a.every(t=>t.checked===false)){Toast.info("请至少选择1集或以上的数量!","批量导出",3e3);return}const o=t=>{const e=a.find(e=>e.cid===t.cid);if(e===undefined){return false}return e.checked};const r=this.getFormat();if(this.danmakuModel.value!=="无"){const t=Toast.info("下载弹幕中...","批量导出");const s=new n;try{if(this.danmakuModel.value==="XML"){for(const t of a.filter(o)){const e=new i(t.cid);await e.fetchInfo();s.add(t.title+".xml",e.rawXML)}}else{const{convertToAss:t}=await e.importAsync("download-danmaku");for(const e of a.filter(o)){const a=new i(e.cid);await a.fetchInfo();s.add(e.title+".ass",await t(a.rawXML))}}await s.emit(this.cid+".danmakus.zip")}catch(t){logError(`弹幕下载失败`);throw t}finally{t.dismiss()}}const l=Toast.info("获取链接中...","批量导出");const d=this.batchExtractor;d.config.itemFilter=o;d.config.api=await c.entity.getApiGenerator(this.dash);let p;try{switch(t){case"aria2":p=await d.collectAria2(r,l,false);await n.single(s(false)+".txt",new Blob([p],{type:"text/plain"}),{ffmpeg:this.ffmpegOption});return;case"aria2RPC":await d.collectAria2(r,l,true);Toast.success(`成功发送了批量请求.`,"aria2 RPC",3e3);return;case"copyVLD":GM.setClipboard(await d.collectData(r,l),{mimetype:"text/plain"});Toast.success("已复制批量vld数据到剪贴板.","批量导出",3e3);return;case"exportVLD":p=await d.collectData(r,l);await n.single(s(false)+".json",new Blob([p],{type:"text/json"}),{ffmpeg:this.ffmpegOption});return;case"ffmpegFragments":{const t=await d.getRawItems(r);const a=new u(r,t[0].fragments);const{getBatchFragmentsList:i}=await e.importAsync("ffmpeg-support");const o=i(t,this.dash||a.extension());if(!o){Toast.info("所有选择的分P都没有分段.","分段列表",3e3)}else{const t=new n;for(const[e,s]of o.entries()){t.add(e,s)}await t.emit(escapeFilename(`${s(false)}.zip`))}}break;case"ffmpegEpisodes":{const t=await d.getRawItems(r);const s=new u(r,t[0].fragments);const{getBatchEpisodesList:a}=await e.importAsync("ffmpeg-support");const i=a(t,this.dash||s.extension());const o=new n;o.add("ffmpeg-files.txt",i);await o.emit()}break;default:return}}catch(t){logError(t)}finally{l.dismiss()}},async checkBatch(){const t=["/www.bilibili.com/bangumi","/www.bilibili.com/video/av"];if(!t.some(t=>document.URL.includes(t))){this.batch=false;this.episodeList=[];return}const{BatchExtractor:s}=await e.importAsync("batch-download");if(await s.test()!==true){this.batch=false;this.episodeList=[];return}const a=this.batchExtractor=new s;this.batch=true;this.episodeList=(await a.getItemList()).map((t,e)=>{return{aid:t.aid,cid:t.cid,title:t.title,index:e,checked:true}})},cancelDownload(){if(o){o.cancelDownload()}},async startDownload(){const t=this.getFormat();try{this.downloading=true;const e=await t.downloadInfo(this.dash);e.videoSpeed.speedUpdate=(t=>this.speed=t);e.progress=(t=>{this.progressPercent=Math.trunc(t*100)});o=e;await e.download();this.lastDirectDownloadLink=n.lastPackageUrl}catch(t){if(t!=="canceled"){logError(t)}this.progressPercent=0}finally{this.downloading=false;this.speed=""}},selectAllEpisodes(){this.episodeList.forEach(t=>t.checked=true)},unselectAllEpisodes(){this.episodeList.forEach(t=>t.checked=false)},inverseAllEpisodes(){this.episodeList.forEach(t=>t.checked=!t.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"}t.aria2RpcOption=this.rpcSettings;const e=t.aria2RpcOptionProfiles.find(e=>e.name===t.aria2RpcOptionSelectedProfile);if(e){Object.assign(e,this.rpcSettings);t.aria2RpcOptionProfiles=t.aria2RpcOptionProfiles}this.saveRpcSettingsText="已保存";setTimeout(()=>this.saveRpcSettingsText="保存配置",2e3)},updateProfile(e){t.aria2RpcOption=this.rpcSettings=_.omit(e,"name")}},async mounted(){}});Observer.videoChange(async()=>{r.close();r.batch=false;r.downloadSingle=true;const t=dq("#download-video");const e=await w();t.style.display=e?"flex":"none";if(!e){return}r.aid=c.aid;r.cid=c.cid;try{const t=new a(c.aid);await t.fetchInfo();r.coverUrl=t.coverUrl.replace("http:","https:")}catch(t){r.coverUrl=EmptyImageUrl}r.dashChange();await r.checkBatch()})}return{widget:{content:`\n`,condition:w,success:m}}}})(); diff --git a/bilibili-evolved.user.js b/bilibili-evolved.user.js index bc051a171..52142a661 100644 --- a/bilibili-evolved.user.js +++ b/bilibili-evolved.user.js @@ -1122,7 +1122,7 @@ onlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/mi onlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/default-video-speed.min.js"] = (()=>{return(e,a)=>{const i=a=>{const i=parseFloat(e.defaultVideoSpeed);a.playbackRate=i;SpinQuery.condition(()=>a,()=>a.playbackRate!==i,()=>a.playbackRate=i)};Observer.videoChange(()=>{const e=dq(".bilibili-player-video video");if(!e){return}i(e)})}})(); onlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/double-click-fullscreen.min.js"] = (()=>{return(i,e)=>{(async()=>{const e=["https://www.bilibili.com/bangumi/","https://www.bilibili.com/video/"];if(!e.some(i=>document.URL.startsWith(i))){return}if(i.touchVideoPlayer&&i.touchVideoPlayerDoubleTapControl){Toast.info("在开启了播放器触摸支持-启用双击控制后, 双击全屏功能将无效.","提示");i.doubleClickFullscreen=false;return}await SpinQuery.unsafeJquery();const l=await SpinQuery.condition(()=>dq(".bilibili-player-area"),i=>i!==null&&unsafeWindow.$(".bilibili-player-video").data("events"));if(l===null){return}const n="double-click-fullscreen";if(!l.classList.contains(n)){l.classList.add(n);const e=unsafeWindow.$(".bilibili-player-video");const t=i.doubleClickFullscreenPreventSingleClick?e.data("events").click[0].handler:()=>{};const c=new DoubleClickEvent(()=>dq(".bilibili-player-video-btn-fullscreen").click(),i=>t(i));if(i.doubleClickFullscreenPreventSingleClick){e.unbind("click")}c.bind(e[0])}})()}})(); onlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/download-audio.min.js"] = (()=>{return(e,t)=>{class n{constructor(){this.sid=null;this.progress=null}async getDownloadUrl(){const e=`https://www.bilibili.com/audio/music-service-c/web/url?sid=${this.sid}&privilege=2&quality=2`;const t=await Ajax.getJsonWithCredentials(e);if(t.code===0){return t.data.cdns.shift()}else{logError("获取下载链接失败, 请确保当前账号有下载权限.","下载音频",1e4);return null}}async download(){const e=await this.getDownloadUrl();return new Promise((t,n)=>{const s=new XMLHttpRequest;s.open("GET",e);s.responseType="blob";s.addEventListener("load",()=>t(s.response));s.addEventListener("error",()=>n(s.status));s.addEventListener("progress",e=>this.progress&&this.progress(100*e.loaded/e.total));s.send()})}}const s="下载音频";return{export:n,widget:{content:`\n\n\n${s}\n\n`,condition:()=>document.URL.includes("bilibili.com/audio"),success:async()=>{await SpinQuery.select(()=>document.querySelector("#app"));const e=document.querySelector("#download-audio");const t=e.querySelector("span");const o=new n;o.progress=(e=>{t.innerHTML=`${Math.round(e)}%`});const i=document.querySelector("#download-audio-link");e.addEventListener("click",async e=>{if(o.sid===null||e.target===i){return}const n=await o.download();t.innerHTML=s;const r=i.getAttribute("href");if(r){URL.revokeObjectURL(r)}i.setAttribute("href",URL.createObjectURL(n));const d=(()=>{const e=document.querySelector(".song-title");if(e){return e.getAttribute("title")}else{return"神秘音频"}})();i.setAttribute("download",d+".m4a");i.click()});Observer.childList("#app",()=>{const t=document.URL.match(/bilibili\.com\/audio\/au([\d]+)/);if(t&&t[1]){e.disabled=false;o.sid=t[1]}else{e.disabled=true}})}}}}})(); -onlineData["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)}})}}}}})(); +onlineData["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"));return e*4/188};const e=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-3*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 n=1.4-.2*t(".bilibili-player-setting-fontsize .bui-thumb");i.resolution={x:1920*n,y:1080*n};i.bottomMarginPercent=[.75,.5,.25,0,0][e(".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 r=o.convertToAssDocument(t);return r.generateAss()}async function r(t,e){const a=n();const r=new i((unsafeWindow||window).cid);await r.fetchInfo();const l=await(async()=>{if(t===true){return new Blob([await o(r.rawXML)],{type:"text/plain"})}else{return new Blob([r.rawXML],{type:"text/plain"})}})();const s=URL.createObjectURL(l);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:r,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);r(e.shiftKey,t)}})}}}}})(); onlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/download-video.min.css"] = `.download-video{--download-video-background:white;--download-video-foreground:black;position:absolute;top:96px;left:50%;transform:translateX(-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}.download-video,.download-video *{transition:.2s ease-out;-webkit-tap-highlight-color:transparent!important}.download-video.opened{pointer-events:initial;opacity:1;transform:translateX(-50%) scale(1)}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 .size-warning-tip,.round-corner .download-video .title,.round-corner .download-video button{border-radius:var(--corner-radius)}.download-video .cover{min-height:100px;max-height:120px;object-fit:contain}.download-video h1{font-size:13pt;font-weight:700;color:var(--download-video-foreground)}.download-video h2{font-size:11pt;font-weight:700;color:var(--download-video-foreground)}.download-video .header{display:flex;justify-content:space-between;align-items:center}.download-video .header .grow{flex-grow:1}.download-video .header .mdi-download{font-size:16pt;color:var(--download-video-foreground);margin-right:8px}.download-video .header .mdi-close{font-size:16pt;color:var(--download-video-foreground);cursor:pointer}.download-video .header .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 .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 .bold{color:var(--download-video-foreground);font-weight:700;font-size:12pt}.download-video .option-item{display:flex;justify-content:space-between;align-items:center;padding-top:12px;font-size:10pt}.download-video .tabs{display:flex;padding:12px 0;font-size:10pt}.download-video .tabs .tab{cursor:pointer;position:relative;opacity:.5}.download-video .tabs .tab.active{font-weight:700;opacity:1}.download-video .tabs .tab:not(:last-child){margin-right:16px}.download-video .tabs .tab::after{content:"";position:absolute;border-radius:2px;background-color:var(--theme-color);height:3px;width:80%;left:10%;bottom:-8px;transition:.2s ease-out;transform:scaleX(0)}.download-video .tabs .tab.active::after{transform:scaleX(1)}.download-video .separator{height:1px;background:#8884;width:100%;margin:12px 0;flex-shrink:0}.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 .background .foreground{position:absolute;top:0;left:0;height:4px;background:linear-gradient(to right,var(--theme-color),var(--theme-color-60))}.download-video .direct-download .progress .percent{width:50px;text-align:right}.download-video .actions{display:flex;flex-wrap:wrap;justify-content:space-between;margin:8px -4px 0}.download-video .actions>*{margin:4px;flex-grow:1;flex-basis:calc(50% - 16px);display:flex;justify-content:center;align-items:center;white-space:nowrap}.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:200px;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}.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:stretch;color:var(--download-video-foreground);background:#fff;bottom:120%;left:50%;cursor:initial;box-shadow:rgba(0,0,0,.2) 0 4px 8px 0;transform-origin:bottom;transform:translateX(-50%) scale(.9);opacity:0;pointer-events:none;padding:8px;z-index:3;transition:.3s cubic-bezier(.18,.89,.32,1.28);width:120%}body.dark .download-video .rpc-settings{background:#282828}.download-video .rpc-settings>*{margin:8px}.download-video .rpc-settings.show{opacity:1;transform:translateX(-50%) scale(1);pointer-events:initial}.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)}.download-video .rpc-settings .operations{display:flex;align-items:center;justify-content:space-evenly}.download-video .final-dir{word-break:break-all}.download-video .rpc-settings-item{display:flex;align-items:center;justify-content:space-between;white-space:nowrap}.download-video .rpc-settings-item input[type=text]{flex-grow:1;margin-left:24px}.download-video button.cancel-download,.download-video button.start-download{margin-top:8px}.download-video .direct-download-header{align-self:stretch;display:flex;justify-content:space-between;align-items:center}body.dark .download-video .direct-download .progress .foreground{background:linear-gradient(to right,var(--theme-color-70),var(--theme-color))}`; onlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/download-video.min.html"] = `

下载视频

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

直接下载

{{speed}}
{{progressPercent}}%

选集

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

导出

{{showRpcSettings ? '取消' : 'aria2 RPC'}}

aria2 RPC

配置

主机
端口
密钥
限速
默认路径
路径
最终路径: {{rpcSettings.baseDir + rpcSettings.dir}}
方法
开始下载
{{saveRpcSettingsText}}
`; onlineData["https://raw.githubusercontent.com/the1812/Bilibili-Evolved/master/min/download-video.min.js"] = (()=>{return(t,e)=>{const{getFriendlyTitle:s}=e.import("title");const{VideoInfo:a,DanmakuInfo:i}=e.import("video-info");const{DownloadVideoPackage:n}=e.import("download-video-package");class o{async getApiGenerator(t=false){function e(e,s,a){if(t){if(a){return`https://api.bilibili.com/x/player/playurl?avid=${e}&cid=${s}&qn=${a}&otype=json&fnver=0&fnval=16`}else{return`https://api.bilibili.com/x/player/playurl?avid=${e}&cid=${s}&otype=json&fnver=0&fnval=16`}}else{if(a){return`https://api.bilibili.com/x/player/playurl?avid=${e}&cid=${s}&qn=${a}&otype=json`}else{return`https://api.bilibili.com/x/player/playurl?avid=${e}&cid=${s}&otype=json`}}}return e.bind(this)}async getDashUrl(t){return(await this.getApiGenerator(true))(c.aid,c.cid,t)}async getUrl(t){return(await this.getApiGenerator())(c.aid,c.cid,t)}}class r extends o{async getApiGenerator(t=false){function e(e,s,a){if(t){if(a){return`https://api.bilibili.com/pgc/player/web/playurl?avid=${e}&cid=${s}&qn=${a}&otype=json&fourk=1&fnval=16`}else{return`https://api.bilibili.com/pgc/player/web/playurl?avid=${e}&cid=${s}&otype=json&fourk=1&fnval=16`}}else{if(a){return`https://api.bilibili.com/pgc/player/web/playurl?avid=${e}&cid=${s}&qn=${a}&otype=json`}else{return`https://api.bilibili.com/pgc/player/web/playurl?avid=${e}&cid=${s}&qn=&otype=json`}}}return e.bind(this)}}class l extends o{constructor(t){super();this.ep=t}async getApiGenerator(t=false){function e(e,s,a){if(t){if(a){return`https://api.bilibili.com/pugv/player/web/playurl?avid=${e}&cid=${s}&qn=${a}&otype=json&ep_id=${this.ep}&fnver=0&fnval=16`}else{return`https://api.bilibili.com/pugv/player/web/playurl?avid=${e}&cid=${s}&otype=json&ep_id=${this.ep}&fnver=0&fnval=16`}}else{if(a){return`https://api.bilibili.com/pugv/player/web/playurl?avid=${e}&cid=${s}&qn=${a}&otype=json&ep_id=${this.ep}`}else{return`https://api.bilibili.com/pugv/player/web/playurl?avid=${e}&cid=${s}&otype=json&ep_id=${this.ep}`}}}return e.bind(this)}}const c={entity:new o,aid:"",cid:""};let d=[];let p=null;class h{constructor(t,e,s){this.quality=t;this.internalName=e;this.displayName=s}async downloadInfo(t=false){const e=new u(this);await e.fetchVideoInfo(t);return e}static parseFormats(t){const e=t.accept_quality;const s=t.accept_format.split(",");const a=t.accept_description;const i=e.map((t,e)=>{return new h(t,s[e],a[e])});return i}static async getAvailableDashFormats(){const t=await c.entity.getDashUrl();const e=await Ajax.getJsonWithCredentials(t);if(e.code!==0){throw new Error("获取清晰度信息失败.")}return h.parseFormats(e.data||e.result||e)}static async getAvailableFormats(){const t=await c.entity.getUrl();const e=await Ajax.getJsonWithCredentials(t);if(e.code!==0){throw new Error("获取清晰度信息失败.")}const s=e.data||e.result||e;return h.parseFormats(s)}}class u{constructor(t,e){this.fragmentSplitFactor=6*2;this.workingXhr=null;this.progressMap=new Map;this.format=t;this.fragments=e||[];this.videoSpeed=new f(this)}get danmakuOption(){return t.downloadVideoDefaultDanmaku}get isDash(){return this.fragments.some(t=>t.url.includes(".m4s"))}get totalSize(){return this.fragments.map(t=>t.size).reduce((t,e)=>t+e)}async fetchVideoInfo(t=false){if(!t){const t=await c.entity.getUrl(this.format.quality);const e=await Ajax.getTextWithCredentials(t);const s=JSON.parse(e.replace(/http:/g,"https:"));const a=s.data||s.result||s;if(a.quality!==this.format.quality){throw new Error("获取下载链接失败, 请确认当前账号有下载权限后重试.")}const i=a.durl;this.fragments=i.map(t=>{return{length:t.length,size:t.size,url:t.url,backupUrls:t.backup_url}})}else{const{dashToFragments:t,getDashInfo:s}=await e.importAsync("video-dash");const a=await s(await c.entity.getDashUrl(this.format.quality),this.format.quality);this.fragments=t(a)}return this.fragments}updateProgress(){const t=this.progressMap?[...this.progressMap.values()].reduce((t,e)=>t+e,0)/this.totalSize:0;if(t>1||t<0){console.error(`[下载视频] 进度异常: ${t}`,this.progressMap.values())}this.progress&&this.progress(t)}cancelDownload(){this.videoSpeed.stopMeasure();if(this.workingXhr!==null){this.workingXhr.forEach(t=>t.abort())}else{logError("Cancel Download Failed: forEach in this.workingXhr not found.")}}downloadFragment(t){const e=[];const s=this.isDash?4*1024*1024:16*1024*1024;let a;if(t.size<=s*6){a=t.size/this.fragmentSplitFactor}else{a=s}let i=0;const n=t=>[...this.progressMap.keys()].indexOf(t)+1;while(i{const a=new XMLHttpRequest;a.open("GET",t.url);a.responseType="arraybuffer";a.withCredentials=false;a.addEventListener("progress",t=>{console.log(`[下载视频] 视频片段${n(a)}下载进度: ${t.loaded}/${r} bytes loaded, ${o}`);this.progressMap.set(a,t.loaded);this.updateProgress()});a.addEventListener("load",()=>{if((""+a.status)[0]==="2"){console.log(`[下载视频] 视频片段${n(a)}下载完成`);e(a.response)}else{s(`视频片段${n(a)}请求失败, response = ${a.status}`)}});a.addEventListener("abort",()=>s("canceled"));a.addEventListener("error",()=>{console.error(`[下载视频] 视频片段${n(a)}下载失败: ${o}`);this.progressMap.set(a,0);this.updateProgress();a.open("GET",t.url);a.setRequestHeader("Range",o);a.send()});a.setRequestHeader("Range",o);this.progressMap.set(a,0);a.send();this.workingXhr.push(a)}));i=Math.round(i+a)+1}return Promise.all(e)}async copyUrl(){const t=this.fragments.map(t=>t.url).reduce((t,e)=>t+"\r\n"+e);GM.setClipboard(t,"text")}async showUrl(){const t=this.fragments.map(t=>`\n${t.url}\n`).reduce((t,e)=>t+"\r\n"+e);Toast.success(t+`复制全部`,"显示链接");const e=await SpinQuery.select("#copy-link");e.addEventListener("click",async()=>{await this.copyUrl()})}async exportData(t=false){const e=JSON.stringify([{fragments:this.fragments,title:s(),totalSize:this.fragments.map(t=>t.size).reduce((t,e)=>t+e),referer:document.URL.replace(window.location.search,"")}]);if(t){GM.setClipboard(e,"text")}else{const t=new Blob([e],{type:"text/json"});const a=await this.downloadDanmaku();const i=new n;i.add(`${s()}.json`,t);i.add(s()+"."+this.danmakuOption.toLowerCase(),a);await i.emit(`${s()}.zip`)}}async exportAria2(a=false){if(a){const a=await this.downloadDanmaku();const i=new n;i.add(`${s()}.${this.danmakuOption==="ASS"?"ass":"xml"}`,a);await i.emit();const o=t.aria2RpcOption;const r=this.fragments.map((t,e)=>{let a="";if(this.fragments.length>1&&!this.isDash){a=" - "+(e+1)}const i=[];if(o.secretKey!==""){i.push(`token:${o.secretKey}`)}i.push([t.url]);i.push({referer:document.URL.replace(window.location.search,""),"user-agent":UserAgent,out:`${s()}${a}${this.extension(t)}`,split:this.fragmentSplitFactor,dir:o.baseDir+o.dir||undefined,"max-download-limit":o.maxDownloadLimit||undefined});const n=encodeURIComponent(`${s()}${a}`);return{params:i,id:n}});const{sendRpc:l}=await e.importAsync("aria2-rpc");await l(r)}else{const t=`\n# Generated by Bilibili Evolved Video Export\n# https://github.com/the1812/Bilibili-Evolved/\n${this.fragments.map((t,e)=>{let a="";if(this.fragments.length>1&&!this.isDash){a=" - "+(e+1)}return`\n${t.url}\n referer=${document.URL.replace(window.location.search,"")}\n user-agent=${UserAgent}\n out=${s()}${a}${this.extension(t)}\n split=${this.fragmentSplitFactor}\n`.trim()}).join("\n")}\n`.trim();const e=new Blob([t],{type:"text/plain"});const a=await this.downloadDanmaku();const i=new n;i.add(`${s()}.txt`,e);i.add(s()+"."+this.danmakuOption.toLowerCase(),a);await i.emit(`${s()}.zip`)}}extension(t){const e=t||this.fragments[0];const s=[".flv",".mp4"].find(t=>e.url.includes(t));if(s){return s}else if(e.url.includes(".m4s")){return this.fragments.indexOf(e)===0?".mp4":".m4a"}else{console.warn("No extension detected.");return".flv"}}async downloadDanmaku(){if(this.danmakuOption!=="无"){const t=new i(c.cid);await t.fetchInfo();if(this.danmakuOption==="XML"){return t.rawXML}else{const{convertToAss:s}=await e.importAsync("download-danmaku");return s(t.rawXML)}}else{return null}}async download(){this.workingXhr=[];this.progressMap=new Map;this.updateProgress();const t=[];this.videoSpeed.startMeasure();for(const e of this.fragments){const s=await this.downloadFragment(e);t.push(s)}if(t.length<1){throw new Error("下载失败.")}const e=s();const a=new n;t.forEach((s,i)=>{let n;const o=this.fragments[i];if(t.length>1&&!this.isDash){n=`${e} - ${i+1}${this.extension(o)}`}else{n=`${e}${this.extension(o)}`}a.add(n,new Blob(Array.isArray(s)?s:[s]))});const i=await this.downloadDanmaku();a.add(`${s()}.${this.danmakuOption==="ASS"?"ass":"xml"}`,i);await a.emit(e+".zip");this.progress&&this.progress(0);this.videoSpeed.stopMeasure()}}class f{constructor(t){this.lastProgress=0;this.measureInterval=1e3;this.workingDownloader=t}startMeasure(){this.intervalTimer=setInterval(()=>{const t=this.workingDownloader.progressMap?[...this.workingDownloader.progressMap.values()].reduce((t,e)=>t+e,0):0;const e=t-this.lastProgress;if(this.speedUpdate!==undefined){this.speedUpdate(formatFileSize(e)+"/s")}this.lastProgress=t},this.measureInterval)}stopMeasure(){clearInterval(this.intervalTimer)}}async function w(){const t=await SpinQuery.select(()=>(unsafeWindow||window).aid);const e=await SpinQuery.select(()=>(unsafeWindow||window).cid);if(!(t&&e)){return false}c.aid=t;c.cid=e;if(document.URL.includes("bangumi")){c.entity=new r}else if(document.URL.includes("cheese")){const t=document.URL.match(/cheese\/play\/ep([\d]+)/);c.entity=new l(t[1])}else{c.entity=new o}try{d=await h.getAvailableFormats()}catch(t){return false}return true}async function m(){p=d[0];e.applyStyle("downloadVideoStyle");const t=dq("#download-video");t.addEventListener("click",()=>{const t=dq(".download-video");t.classList.toggle("opened");window.scroll(0,0);dq(".gui-settings-mask").click()});document.body.insertAdjacentHTML("beforeend",e.import("downloadVideoHtml"));g()}async function g(){let o;const r=new Vue({el:".download-video",components:{VDropdown:()=>e.importAsync("v-dropdown.vue"),VCheckbox:()=>e.importAsync("v-checkbox.vue"),RpcProfiles:()=>e.importAsync("aria2-rpc-profiles.vue")},data:{downloadSingle:true,coverUrl:EmptyImageUrl,aid:c.aid,cid:c.cid,dashModel:{value:t.downloadVideoFormat,items:["flv","dash"]},qualityModel:{value:p.displayName,items:d.map(t=>t.displayName)},danmakuModel:{value:t.downloadVideoDefaultDanmaku,items:["无","XML","ASS"]},codecModel:{value:t.downloadVideoDashCodec,items:["AVC/H.264","HEVC/H.265"]},progressPercent:0,size:"获取大小中",blobUrl:"",episodeList:[],downloading:false,speed:"",batch:false,rpcSettings:t.aria2RpcOption,showRpcSettings:false,busy:false,saveRpcSettingsText:"保存配置",enableDash:t.enableDashDownload,lastDirectDownloadLink:""},computed:{displaySize(){if(typeof this.size==="string"){return this.size}return formatFileSize(this.size)},sizeWarning(){if(typeof this.size==="string"){return false}return this.size>1073741824},selectedEpisodeCount(){return this.episodeList.filter(t=>t.checked).length},dash(){return this.dashModel.value==="dash"}},methods:{close(){this.$el.classList.remove("opened")},danmakuOptionChange(){t.downloadVideoDefaultDanmaku=this.danmakuModel.value},async codecChange(){t.downloadVideoDashCodec=this.codecModel.value;await this.formatChange()},async dashChange(){console.log("dash change");t.downloadVideoFormat=this.dashModel.value;const e=this.dashModel.value;let s=[];if(e==="flv"){s=await h.getAvailableFormats()}else{s=await h.getAvailableDashFormats()}d=s;[p]=e;this.qualityModel.items=s.map(t=>t.displayName);[this.qualityModel.value]=this.qualityModel.items;await this.formatChange()},async formatChange(){console.log("format change");const t=this.getFormat();try{this.size="获取大小中";const e=await t.downloadInfo(this.dash);this.size=e.totalSize}catch(t){this.size="获取大小失败";throw t}},getFormat(){const t=d.find(t=>t.displayName===this.qualityModel.value);if(!t){console.error(`No format found. model value = ${this.qualityModel.value}`);return null}return t},async exportData(t){if(this.busy===true){return}try{this.busy=true;if(!this.downloadSingle){await this.exportBatchData(t);return}const a=this.getFormat();const i=await a.downloadInfo(this.dash);switch(t){case"copyLink":await i.copyUrl();Toast.success("已复制链接到剪贴板.","下载视频",3e3);break;case"showLink":await i.showUrl();break;case"aria2":await i.exportAria2(false);break;case"aria2RPC":await i.exportAria2(true);break;case"copyVLD":await i.exportData(true);Toast.success("已复制VLD数据到剪贴板.","下载视频",3e3);break;case"exportVLD":await i.exportData(false);break;case"ffmpegFragments":if(i.fragments.length<2){Toast.info("当前视频没有分段.","分段列表",3e3)}else{const{getFragmentsList:t}=await e.importAsync("ffmpeg-support");const a=new n;a.add("ffmpeg-files.txt",t(i.fragments.length,s(),i.fragments.map(t=>i.extension(t))));await a.emit()}break;default:break}}catch(t){logError(t)}finally{this.busy=false}},async exportBatchData(t){const a=this.episodeList;if(a.every(t=>t.checked===false)){Toast.info("请至少选择1集或以上的数量!","批量导出",3e3);return}const o=t=>{const e=a.find(e=>e.cid===t.cid);if(e===undefined){return false}return e.checked};const r=this.getFormat();if(this.danmakuModel.value!=="无"){const t=Toast.info("下载弹幕中...","批量导出");const s=new n;try{if(this.danmakuModel.value==="XML"){for(const t of a.filter(o)){const e=new i(t.cid);await e.fetchInfo();s.add(t.title+".xml",e.rawXML)}}else{const{convertToAss:t}=await e.importAsync("download-danmaku");for(const e of a.filter(o)){const a=new i(e.cid);await a.fetchInfo();s.add(e.title+".ass",await t(a.rawXML))}}await s.emit(this.cid+".danmakus.zip")}catch(t){logError(`弹幕下载失败`);throw t}finally{t.dismiss()}}const l=Toast.info("获取链接中...","批量导出");const d=this.batchExtractor;d.config.itemFilter=o;d.config.api=await c.entity.getApiGenerator(this.dash);let p;try{switch(t){case"aria2":p=await d.collectAria2(r,l,false);await n.single(s(false)+".txt",new Blob([p],{type:"text/plain"}),{ffmpeg:this.ffmpegOption});return;case"aria2RPC":await d.collectAria2(r,l,true);Toast.success(`成功发送了批量请求.`,"aria2 RPC",3e3);return;case"copyVLD":GM.setClipboard(await d.collectData(r,l),{mimetype:"text/plain"});Toast.success("已复制批量vld数据到剪贴板.","批量导出",3e3);return;case"exportVLD":p=await d.collectData(r,l);await n.single(s(false)+".json",new Blob([p],{type:"text/json"}),{ffmpeg:this.ffmpegOption});return;case"ffmpegFragments":{const t=await d.getRawItems(r);const a=new u(r,t[0].fragments);const{getBatchFragmentsList:i}=await e.importAsync("ffmpeg-support");const o=i(t,this.dash||a.extension());if(!o){Toast.info("所有选择的分P都没有分段.","分段列表",3e3)}else{const t=new n;for(const[e,s]of o.entries()){t.add(e,s)}await t.emit(escapeFilename(`${s(false)}.zip`))}}break;case"ffmpegEpisodes":{const t=await d.getRawItems(r);const s=new u(r,t[0].fragments);const{getBatchEpisodesList:a}=await e.importAsync("ffmpeg-support");const i=a(t,this.dash||s.extension());const o=new n;o.add("ffmpeg-files.txt",i);await o.emit()}break;default:return}}catch(t){logError(t)}finally{l.dismiss()}},async checkBatch(){const t=["/www.bilibili.com/bangumi","/www.bilibili.com/video/av"];if(!t.some(t=>document.URL.includes(t))){this.batch=false;this.episodeList=[];return}const{BatchExtractor:s}=await e.importAsync("batch-download");if(await s.test()!==true){this.batch=false;this.episodeList=[];return}const a=this.batchExtractor=new s;this.batch=true;this.episodeList=(await a.getItemList()).map((t,e)=>{return{aid:t.aid,cid:t.cid,title:t.title,index:e,checked:true}})},cancelDownload(){if(o){o.cancelDownload()}},async startDownload(){const t=this.getFormat();try{this.downloading=true;const e=await t.downloadInfo(this.dash);e.videoSpeed.speedUpdate=(t=>this.speed=t);e.progress=(t=>{this.progressPercent=Math.trunc(t*100)});o=e;await e.download();this.lastDirectDownloadLink=n.lastPackageUrl}catch(t){if(t!=="canceled"){logError(t)}this.progressPercent=0}finally{this.downloading=false;this.speed=""}},selectAllEpisodes(){this.episodeList.forEach(t=>t.checked=true)},unselectAllEpisodes(){this.episodeList.forEach(t=>t.checked=false)},inverseAllEpisodes(){this.episodeList.forEach(t=>t.checked=!t.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"}t.aria2RpcOption=this.rpcSettings;const e=t.aria2RpcOptionProfiles.find(e=>e.name===t.aria2RpcOptionSelectedProfile);if(e){Object.assign(e,this.rpcSettings);t.aria2RpcOptionProfiles=t.aria2RpcOptionProfiles}this.saveRpcSettingsText="已保存";setTimeout(()=>this.saveRpcSettingsText="保存配置",2e3)},updateProfile(e){t.aria2RpcOption=this.rpcSettings=_.omit(e,"name")}},async mounted(){}});Observer.videoChange(async()=>{r.close();r.batch=false;r.downloadSingle=true;const t=dq("#download-video");const e=await w();t.style.display=e?"flex":"none";if(!e){return}r.aid=c.aid;r.cid=c.cid;try{const t=new a(c.aid);await t.fetchInfo();r.coverUrl=t.coverUrl.replace("http:","https:")}catch(t){r.coverUrl=EmptyImageUrl}r.dashChange();await r.checkBatch()})}return{widget:{content:`\n`,condition:w,success:m}}}})(); diff --git a/min/bundle.json b/min/bundle.json index ba1dcc1a4..e2e5d6a04 100644 --- a/min/bundle.json +++ b/min/bundle.json @@ -47,7 +47,7 @@ "default-video-speed.min.js": "34E3D2BC8BD5BBC2534EDE6D7B02DE6D5F4A01879641A9E128B4C24124759D77", "double-click-fullscreen.min.js": "09C035FC7E281ABB042A4200F69757AB093079DBCC9939BE8C53C23EE2EDE41C", "download-audio.min.js": "1F4536DE4FF302BFD026CA17E028AF8EB037FB6D0CB355692549DECAEAE0E8C9", - "download-danmaku.min.js": "B254644525ABF064DB770FE986D2AB88063406783EC0538004EFBE0E2B2ACD62", + "download-danmaku.min.js": "E3B7DAC039E0E300EAE310AFD5C88476DA1A6228CBBDD99D290336C77EEA0AF8", "download-video.min.css": "9E3DC9F6245E47D828E6098E9E9D8C93312FCC3E8915DD500512C9D6D9EB865E", "download-video.min.html": "0DD24CECA30EFA2E6BEEC08523A39D98D80DE5F379EF16864012BDE1117A1ECB", "download-video.min.js": "400F1182B7849852B4ECCA9065F4FD4652DE7827FBAB4A68B352C6B6B854316B", diff --git a/min/bundle.zip b/min/bundle.zip index c6b39d0d338dad1e512a05b13fd06dc573ecc633..16fdb9ce530a06c5f1800a96cc42af02e459738d 100644 GIT binary patch delta 2151 zcmZ8h4^Y$h70>UNR7m(EBfno>2qpunLP8P<@+S#~5JLH9b#`l=JES(^4`GGCl7L|6 zp;vCL*Xb0EA8u}E?e(;+t5WC2x~(ENz1t?&!n)n9D~GtddCZ;8w)1M+ySW!*9oz5n z?&bS^?|t8UpZDhrw9SmQ?HLh9#1Zv~X5^8PWg{sgspqwu_h;-mw{qi?Qy9M zu-1^>>a41;JNZ{uVK23pwzVn`{Y;!4)lLaQ1m8KLE$~E~JCv{z3B{B^G+Jcc9f}Tx z+w(g5!|e$Vd6A-+U9mow3_Rou7g--95yA8ktyPXVJCs;^XLGot_o1j8y12GV8*xTL zJ2$U?+=}72mJo_-4eWF9 zsaAbus}36#orI2Z(&KtDnS>W1*r{H9tmA=Xi=FJ6c#lqn;jm7|wgy%_8P-YMZeM;M z;e9p{{t2Ulg6bW8I+XNrh&Sz=?udgd>O09R!mk}<=MetxU|3#!jXk`kGvI@K*87^1 zEMh*P*GYa+ZO1rs;S_E=sYwXIQ$o$D&XP1$XV-QGx2h-?S^1>F>m?lV7%r8tQHu+Y zlu|%kRfeY0`)KSd<%B0OonV)-+(nJzS1YmEMGeA99CvZ76P`2-d(sS;ws8z8Wn7w% zvAT?Egndw$rH=h1P1WUchtcMz99&|B)Hz#v^6Hv}B>X#J^9;;u$Su}Cfp4xMU+Si( zSc6*^Q#K;J?BPKF5lYX}e~Fh$Rkkgu5ykySZmnUE7Eh#O{6xADLrok@<*9VZ_+Nv) zr`Vt;v_o+WbSXQL-$(}ZmosE7Zz5h!0qu|8VukQ_We_v@B;#K!)4hEzUG=Oo)D!B% zH4~R@kBcKYeIY$-N$ozyh6<_?b7pa%f-2REZav1`dKq&SWD|aaluE|#7+NYB&|`S1 zlFK}fnMztGz7fW3C7I!^BD?x-AMcVry#d2j+?K{DPFImnTswdp%++@XSUR9LV!xX+ z+u&xzZlT9bE$ZMdJ<@jRP05@W5|VSc=VmNZ4#DGL+s}^ZF?B?ro2(FHX%Wq5aM45c z;@R;8Cz!ot7vK3A4tg1s&PO@X&A-$y&G9&X;N^MbR`{cryQ&pZHIKkc*u+dc@LMcY zlM&Y~v>X?!`F-DX;-+4G`8_@Mzo#eEtmUyZ&g!u+!$}w|l!ewm{EvrMaAqx43-9B` zTJA*QE{c6TmM78WV{9`s@H!twArp%}c6=VT8qR$%TS9HNL^x2x&mT2Pc-koCAh&=q zTBuRmEEES1g4t4Y2R z-okuA0U7iCa!yixzK&lg8j^8)kYCOTvcg}!cmG6a z3v!{}J%rgHSFP~TB;Fe2j>=1`wGA^tM*q{pGA0kp4+>vX&r$TCt)ASe6?bG+G&aM@``MKjGOlYUS*bg!ER8+x?Gl^oDRP$dC53MDwd=g9^n}+~eo@sJ*l?q0ryniHrg=;SS#kHy|}~ zMR#FSBm1}nG;*Iwr!m(^4Z6vnvcXP8i9ML|+9tM`#MUMrqFKD!M0KL~9V|9+6Xst= zaWn74&*lx7nl}*k6>{B1o5_;dc-5d9;H}r|*dB^@CI*@Cr)DyVjo0x}Gd(UGM@w^R2vGE!x{QDmGV;;4gwRd;_dqb&Oamt~aQVNeJ0vM24jx6GV* zlJlPTyytz+bKcB6)pY}1L&IWN8rBcz4c|1JKU^?e_^N#8=x_wSHhb6bn{V!W8kM86O-Va9B?mTciDx!t|Gm_QyGP}fa@yIK z*m39Tb{jstB&&FBR3^@PW>gM}zNz8^T#`snErEQCB+|QE$7D7Gn~|-Et(dKZZ64cv zwgqep*-UI^Hf5@HO#RjWk%!NIN^3RTLH>$ko(l z+-)}Kx_eWORL^FF?L_EZN_iNpCW}a5e>F8pZ&^@bqeWO-N%Ica$SQt;avR0;-~GgZ z?9B!XHk45jp5PVfPi1(~Mt)I%&utVEQ8?@r7x~y>rzT;*F*|QNe1`#*odzq~?YwRF zG5ne83(BdI>;fO zMvsF77vd!c#l*8YSOi;`N>J|P!aDo#h?7h>bqmeI$U%dd753w&7DG;IDmbkgb(^=P zaA+~zjElTU|6+|16`Iiu%QCWy+Yntwt%7g5j1NEO#JOb@6cH?PQBeBQg>^0pOEYea zyJl~G-o=$}MWvge7u{}Zkxs3^3vRA%4X(Ml)_dVu&Wq!?e>nw29ggK7g6j;0yX{4~ zl-rZRno2U`_FA$Q7^AZ;RC?L-OZG^A@4#d&vn_DBmKxV=Dt)nPLwlGCs*)^Z_n^TcWTaa zgFT$iQcq!hCThZks7b|63%78no>yX+sONjfaG{=>_3L{~IMZV)$6b{i@M^~N-+XuC zzLnG_euptph34Eed7HJJ8OKzh9h-}6stk|#94x$nlq z0j6XLP6b#PVUz?ZsxPQ8W3a+(#o6V#y9PO11QS7O)BDHGI6Q7HhcUzheSHEChInv) z79xjq`8T;A5uT9~A&xxrjTylk<}%cTS;Eg_ZI~i?>QY6AK#iheVyR-pG%x9=T?$-o zr3|ZEbA-p4*wQ8@d_$vxvyDm>HZ*a9ZP?w!J$t1e?>A9MIfahR>VHtM4|exKB~% z9vgH-xsyMb(Hmvr`E5BGWr?M5ogpu!sXCO0xf7i+*6Pc3s%{{gz&|3){9g75I}XRl zo3|;>aYHMq3~~$4bhbmqUpiDX0xf)>QKVX!{-rq7LLq(jAg>)%3Fn;5!Gcyk{P^>5 zxAMqt#m-jp>9-zH@yQXj6lYtRvj>i{OJ%;JMM-{6%tvX(6Q;$J>TI@Lcg_ZEM}3*1U&6{~SO zI#*GkINw0J9SQ!cNhb!9c%+;kgQ|sOF8c8`)9Kz@fIqI{DV;PEtO_kgLp#mSpIk&7 F@=ppfN)!M9 diff --git a/min/download-danmaku.min.js b/min/download-danmaku.min.js index f8cb808a9..a1bb22061 100644 --- a/min/download-danmaku.min.js +++ b/min/download-danmaku.min.js @@ -1 +1 @@ -(()=>{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)}})}}}}})(); \ No newline at end of file +(()=>{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"));return e*4/188};const e=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-3*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 n=1.4-.2*t(".bilibili-player-setting-fontsize .bui-thumb");i.resolution={x:1920*n,y:1080*n};i.bottomMarginPercent=[.75,.5,.25,0,0][e(".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 r=o.convertToAssDocument(t);return r.generateAss()}async function r(t,e){const a=n();const r=new i((unsafeWindow||window).cid);await r.fetchInfo();const l=await(async()=>{if(t===true){return new Blob([await o(r.rawXML)],{type:"text/plain"})}else{return new Blob([r.rawXML],{type:"text/plain"})}})();const s=URL.createObjectURL(l);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:r,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);r(e.shiftKey,t)}})}}}}})(); \ No newline at end of file diff --git a/src/video/download-danmaku.ts b/src/video/download-danmaku.ts index 21aa52fcd..76ed19522 100644 --- a/src/video/download-danmaku.ts +++ b/src/video/download-danmaku.ts @@ -7,6 +7,10 @@ export async function convertToAss(xml: string) { let config: any = { title } try { await loadDanmakuSettingsPanel() + const getSliderFactor = (selector: string) => { + const transform = parseFloat((dq(selector) as HTMLElement).style.transform!.replace(/translateX\(([\d\.]+)/, '$1')) + return transform * 4 / 188 + } const getSliderIndex = (selector: string) => { const transform = parseFloat((dq(selector) as HTMLElement).style.transform!.replace(/translateX\(([\d\.]+)/, '$1')) as 0 | 44 | 94 | 144 | 188 const index = { @@ -21,7 +25,7 @@ export async function convertToAss(xml: string) { config.font = (dq('.bilibili-player-video-danmaku-setting-right-font .bui-select-result') as HTMLElement).innerText config.alpha = parseFloat((dq('.bilibili-player-setting-opacity .bui-bar') as HTMLElement).style.transform!.replace(/scaleX\(([\d\.]+)\)/, '$1')) config.duration = (() => { - const scrollDuration = [18, 14, 10, 8, 6][getSliderIndex('.bilibili-player-setting-speedplus .bui-thumb')] + const scrollDuration = 18 - 3 * getSliderFactor('.bilibili-player-setting-speedplus .bui-thumb') return (danmaku: { type: number }) => { switch (danmaku.type) { case 4: @@ -49,7 +53,7 @@ export async function convertToAss(xml: string) { } return result.concat(7, 8) })() - const resolutionFactor = [1.4, 1.2, 1, 0.8, 0.6][getSliderIndex('.bilibili-player-setting-fontsize .bui-thumb')] // 改变分辨率来调整字体大小 + const resolutionFactor = 1.4 - 0.2 * getSliderFactor('.bilibili-player-setting-fontsize .bui-thumb') // 改变分辨率来调整字体大小 config.resolution = { x: 1920 * resolutionFactor, y: 1080 * resolutionFactor