Bilibili-Evolved/min/aria2-rpc.min.js
2019-10-12 12:13:15 +08:00

1 line
1.7 KiB
JavaScript

(()=>{return(t,e)=>{function o(){const e=t.aria2RpcOption;const o=e.host.match(/^http[s]?:\/\//)?e.host:"http://"+e.host;const r="aria2.addUri";return{option:e,host:o,methodName:r}}async function r(t,e=false){try{let o=await t();if(typeof o==="string"){o=JSON.parse(o)}if(o.error!==undefined){if(o.error.code===1){logError(`请求遭到拒绝, 请检查您的密钥相关设置.`)}else{logError(`请求发生错误, code = ${o.error.code}, message = ${o.error.message}`)}return false}if(!e){Toast.success(`成功发送了请求, GID = ${o.result}`,"aria2 RPC",5e3)}return true}catch(t){logError(`无法连接到RPC主机.`);return false}}async function s(t,e=false){const{option:s,host:n,methodName:a}=o();return await r(async()=>{const e=window.btoa(unescape(encodeURIComponent(JSON.stringify(t.params))));const o=`${n}:${s.port}/jsonrpc?method=${a}&id=${t.id}&params=${e}`;console.log(`RPC request:`,o);if(o.startsWith("http:")){return await new Promise((t,e)=>{GM.xmlHttpRequest({method:"GET",url:o,responseType:"json",onload:e=>t(e.response),onerror:t=>e(t)})})}else{return await Ajax.getJson(o)}},e)}async function n(t,e=false){const{option:s,host:n,methodName:a}=o();return await r(async()=>{const e=`${n}:${s.port}/jsonrpc`;const o={method:a,id:t.id,params:t.params};if(e.startsWith("http:")){return await new Promise((t,r)=>{GM.xmlHttpRequest({method:"POST",url:e,responseType:"json",data:JSON.stringify(o),onload:e=>t(e.response),onerror:t=>r(t)})})}else{return await Ajax.postJson(e,o)}},e)}async function a(e,o=false){const r=t.aria2RpcOption;for(const t of e){let e;if(r.method==="get"){e=await s(t,o)}else{e=await n(t,o)}if(o===true&&e===false){logError(`${decodeURIComponent(t.id)} 导出失败`)}}}return{export:{sendRpc:a}}}})();