Aria2 RPC Edit

Aria2 RPC Library 重写,参考自 https://gf.qytechs.cn/scripts/5672-aria2-rpc

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.gf.qytechs.cn/scripts/402652/971052/Aria2%20RPC%20Edit.js

  1. // ==UserScript==
  2. // @name Aria2 RPC Edit
  3. // @namespace Sonic853
  4. // @version 0.3.3
  5. // @description Aria2 RPC Library 重写,参考自 https://gf.qytechs.cn/scripts/5672-aria2-rpc
  6. // @author Sonic853
  7. // @original-author moe.jixun
  8. // @original-license MIT
  9. // @original-script https://gf.qytechs.cn/scripts/5672-aria2-rpc
  10. // @license MIT
  11. // @grant GM_xmlhttpRequest
  12. // ==/UserScript==
  13. // Source code: https://github.com/Sonic853/Static_library/blob/master/aria2.ts
  14. // tsc .\aria2.ts --target esnext
  15. // Public Class Aria2 ( options )
  16. var Aria2AUTH;
  17. (function (Aria2AUTH) {
  18. Aria2AUTH[Aria2AUTH["noAuth"] = 0] = "noAuth";
  19. Aria2AUTH[Aria2AUTH["basic"] = 1] = "basic";
  20. Aria2AUTH[Aria2AUTH["secret"] = 2] = "secret";
  21. })(Aria2AUTH || (Aria2AUTH = {}));
  22. class Aria2BATCH {
  23. parent;
  24. data = [];
  25. onSuccess;
  26. onFail;
  27. addRaw(fn, params) {
  28. this.data.push({
  29. method: `aria2.${fn}`,
  30. params
  31. });
  32. }
  33. add(fn, ...args) {
  34. if (this.parent[fn] === undefined)
  35. throw new Error(`Unknown function: ${fn}, please check if you had a typo.`);
  36. return this.addRaw(fn, args);
  37. }
  38. async send() {
  39. let ret = await this.parent.send(true, this.data, this.onSuccess, this.onFail);
  40. this.reset();
  41. return ret;
  42. }
  43. getActions() {
  44. return this.data.slice();
  45. }
  46. setActions(actions) {
  47. if (!actions || !actions.map)
  48. return;
  49. this.data = actions;
  50. }
  51. reset() {
  52. this.onSuccess = this.onFail = null;
  53. this.data = [];
  54. }
  55. constructor(obj, cbSuccess, cbFail) {
  56. this.parent = obj;
  57. this.onSuccess = cbSuccess;
  58. this.onFail = cbFail;
  59. }
  60. }
  61. // var GM_fetch = async (input: RequestInfo, init?: RequestInit): Promise<any> => {
  62. // // Promise<Response>
  63. // if (typeof GM_xmlhttpRequest !== 'undefined') {
  64. // return new Promise((resolve, reject)=>{
  65. // if (typeof input === 'string') {
  66. // }
  67. // else {
  68. // }
  69. // })
  70. // }else{
  71. // console.warn([
  72. // 'Warning: You are now using an simple implementation of GM_xmlhttpRequest',
  73. // 'Cross-domain request are not avilible unless configured correctly @ target server.',
  74. // '',
  75. // 'Some of its features are not avilible, such as `username` and `password` field.'
  76. // ].join('\n'))
  77. // return fetch(input, init)
  78. // }
  79. // }
  80. var Aria2 = class AriaBase {
  81. jsonrpc_ver = '2.0';
  82. id;
  83. options;
  84. doRequest;
  85. getBasicAuth() {
  86. return btoa(`${this.options.auth.user}:${this.options.auth.pass}`);
  87. }
  88. async send(bIsDataBatch, data, cbSuccess, cbError) {
  89. this.id = (+new Date());
  90. let srcTaskObj = { jsonrpc: this.jsonrpc_ver, id: this.id };
  91. let payload = {
  92. method: 'POST',
  93. url: `http://${this.options.host}:${this.options.post}/jsonrpc`,
  94. headers: {
  95. 'Content-Type': 'application/json; charset=UTF-8'
  96. },
  97. data: bIsDataBatch
  98. ? data.map(e => { return this.merge({}, srcTaskObj, e); })
  99. : this.merge({}, srcTaskObj, data),
  100. onload: r => {
  101. if (r.readyState !== 4) {
  102. cbError && cbError(null, false);
  103. }
  104. else {
  105. let repData;
  106. try {
  107. repData = JSON.parse(r.responseText);
  108. }
  109. catch (error) {
  110. repData = r.responseText;
  111. }
  112. cbSuccess && cbSuccess(repData);
  113. }
  114. },
  115. onerror: cbError ? cbError(null, false) : null
  116. };
  117. switch (this.options.auth.type) {
  118. case Aria2AUTH.basic: {
  119. payload.headers.Authorization = 'Basic ' + this.getBasicAuth();
  120. break;
  121. }
  122. case Aria2AUTH.secret: {
  123. let sToken = `token:${this.options.auth.pass}`;
  124. if (bIsDataBatch) {
  125. for (let i = 0; i < payload.data.length; i++) {
  126. payload.data[i].params.splice(0, 0, sToken);
  127. }
  128. }
  129. else {
  130. if (!payload.data.params)
  131. payload.data.params = [];
  132. payload.data.params.splice(0, 0, sToken);
  133. }
  134. break;
  135. }
  136. case Aria2AUTH.noAuth:
  137. default: {
  138. break;
  139. }
  140. }
  141. return await this.doRequest.send(payload);
  142. }
  143. BATCH = new Aria2BATCH(this);
  144. merge(...args) {
  145. let base = args[0];
  146. let _isObject = function (obj) {
  147. return obj instanceof Object;
  148. };
  149. let _merge = function (...args) {
  150. let argL = args.length;
  151. for (let i = 1; i < argL; i++) {
  152. Object.keys(args[i]).forEach(function (key) {
  153. if (_isObject(args[i][key]) && _isObject(base[key])) {
  154. base[key] = _merge(base[key], args[i][key]);
  155. }
  156. else {
  157. base[key] = args[i][key];
  158. }
  159. });
  160. }
  161. return base;
  162. };
  163. return _merge(...args);
  164. }
  165. constructor(options) {
  166. if (options) {
  167. if (!options.auth)
  168. options.auth = { type: Aria2AUTH.noAuth };
  169. if (typeof options.host !== 'string')
  170. options.host = 'localhost';
  171. if (typeof options.post !== 'number')
  172. options.post = 6800;
  173. this.options = options;
  174. }
  175. else
  176. this.options = {
  177. auth: {
  178. type: Aria2AUTH.noAuth
  179. },
  180. host: 'localhost',
  181. post: 6800
  182. };
  183. let isFunction = (obj) => {
  184. return typeof obj === 'function';
  185. };
  186. this.id = (+new Date());
  187. if (typeof GM_xmlhttpRequest !== 'undefined') {
  188. this.doRequest = new class {
  189. parent;
  190. async send({ url, method, data, headers, onload, onerror }) {
  191. return new Promise((resolve, reject) => {
  192. GM_xmlhttpRequest({
  193. url,
  194. method,
  195. data: typeof data === 'string' ? data : JSON.stringify(data),
  196. headers,
  197. onload(r) {
  198. onload && onload(r);
  199. resolve(r);
  200. },
  201. onerror() {
  202. onerror && onerror();
  203. reject();
  204. }
  205. });
  206. });
  207. }
  208. constructor(obj) {
  209. this.parent = obj;
  210. }
  211. }(this);
  212. }
  213. else {
  214. console.warn([
  215. 'Warning: You are now using an simple implementation of GM_xmlhttpRequest',
  216. 'Cross-domain request are not avilible unless configured correctly @ target server.',
  217. '',
  218. 'Some of its features are not avilible, such as `username` and `password` field.'
  219. ].join('\n'));
  220. this.doRequest = new class {
  221. parent;
  222. async send({ url, method, data, headers, onload, onerror }) {
  223. try {
  224. let response = await fetch(url, {
  225. method,
  226. body: typeof data === 'string' ? data : JSON.stringify(data),
  227. headers
  228. });
  229. let responseText = await response.text();
  230. onload && onload(responseText);
  231. return {
  232. readyState: 4,
  233. responseHeaders: response.headers,
  234. status: response.status,
  235. statusText: response.statusText,
  236. response,
  237. responseText,
  238. finalUrl: response.url
  239. };
  240. }
  241. catch (error) {
  242. onerror && onerror(error);
  243. return;
  244. }
  245. }
  246. constructor(obj) {
  247. this.parent = obj;
  248. }
  249. }(this);
  250. }
  251. {
  252. [
  253. "addUri", "addTorrent", "addMetalink", "remove", "forceRemove",
  254. "pause", "pauseAll", "forcePause", "forcePauseAll", "unpause",
  255. "unpauseAll", "tellStatus", "getUris", "getFiles", "getPeers",
  256. "getServers", "tellActive", "tellWaiting", "tellStopped",
  257. "changePosition", "changeUri", "getOption", "changeOption",
  258. "getGlobalOption", "changeGlobalOption", "getGlobalStat",
  259. "purgeDownloadResult", "removeDownloadResult", "getVersion",
  260. "getSessionInfo", "shutdown", "forceShutdown", "saveSession"
  261. ].forEach(sMethod => {
  262. this[sMethod] = async (...args) => {
  263. let cbSuccess, cbError;
  264. if (args.length && isFunction(args[args.length - 1])) {
  265. cbSuccess = args[args.length - 1];
  266. args.splice(-1, 1);
  267. if (args.length && isFunction(args[args.length - 1])) {
  268. cbError = cbSuccess;
  269. cbSuccess = args[args.length - 1];
  270. args.splice(-1, 1);
  271. }
  272. }
  273. return await this.send(false, {
  274. method: `aria2.${sMethod}`,
  275. params: args
  276. }, cbSuccess, cbError);
  277. };
  278. });
  279. }
  280. }
  281. };

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址