A full-featured download manager.
fix: engine failed to quit
Shatyuka0f5398b10699
diff --git a/package.json b/package.jsonindex 2a5b4c30..6d77e3ac 100644--- a/package.json+++ b/package.json@@ -196,7 +196,6 @@"@babel/runtime": "^7.12.5","@motrix/nat-api": "^0.3.1","@panter/vue-i18next": "^0.15.2",- "aria2": "^4.1.1","axios": "^0.21.1","blob-util": "^2.0.2","clipboard-polyfill": "^3.0.1",diff --git a/src/main/core/EngineClient.js b/src/main/core/EngineClient.jsindex 2329cd07..663f08ab 100644--- a/src/main/core/EngineClient.js+++ b/src/main/core/EngineClient.js@@ -1,6 +1,6 @@'use strict'-import Aria2 from 'aria2'+import { Aria2 } from '@shared/aria2'import logger from './Logger'import {diff --git a/src/renderer/api/Api.js b/src/renderer/api/Api.jsindex 3ac8d8be..bd2e4655 100644--- a/src/renderer/api/Api.js+++ b/src/renderer/api/Api.js@@ -1,7 +1,7 @@import { ipcRenderer } from 'electron'import is from 'electron-is'import { isEmpty, clone } from 'lodash'-import Aria2 from 'aria2'+import { Aria2 } from '@shared/aria2'import {separateConfig,compactUndefined,diff --git a/src/shared/aria2/index.js b/src/shared/aria2/index.jsnew file mode 100644index 00000000..1d1250ed--- /dev/null+++ b/src/shared/aria2/index.js@@ -0,0 +1,5 @@+'use strict'++const Aria2 = require('./lib/Aria2')++module.exports = Aria2diff --git a/src/shared/aria2/lib/Aria2.js b/src/shared/aria2/lib/Aria2.jsnew file mode 100644index 00000000..30c54258--- /dev/null+++ b/src/shared/aria2/lib/Aria2.js@@ -0,0 +1,72 @@+'use strict'++import { JSONRPCClient } from './JSONRPCClient'++export class Aria2 extends JSONRPCClient {+ prefix (str) {+ if (!str.startsWith('system.') && !str.startsWith('aria2.')) {+ str = 'aria2.' + str+ }+ return str+ }++ unprefix (str) {+ const suffix = str.split('aria2.')[1]+ return suffix || str+ }++ addSecret (parameters) {+ let params = this.secret ? ['token:' + this.secret] : []+ if (Array.isArray(parameters)) {+ params = params.concat(parameters)+ }+ return params+ }++ _onnotification (notification) {+ const { method, params } = notification+ const event = this.unprefix(method)+ if (event !== method) this.emit(event, params)+ return super._onnotification(notification)+ }++ async call (method, ...params) {+ return super.call(this.prefix(method), this.addSecret(params))+ }++ async multicall (calls) {+ const multi = [+ calls.map(([method, ...params]) => {+ return { methodName: this.prefix(method), params: this.addSecret(params) }+ })+ ]+ return super.call('system.multicall', multi)+ }++ async batch (calls) {+ return super.batch(+ calls.map(([method, ...params]) => [+ this.prefix(method),+ this.addSecret(params)+ ])+ )+ }++ async listNotifications () {+ const events = await this.call('system.listNotifications')+ return events.map((event) => this.unprefix(event))+ }++ async listMethods () {+ const methods = await this.call('system.listMethods')+ return methods.map((method) => this.unprefix(method))+ }++ defaultOptions = Object.assign({}, JSONRPCClient.defaultOptions, {+ secure: false,+ host: 'localhost',+ port: 6800,+ secret: '',+ path: '/jsonrpc'+ })+}diff --git a/src/shared/aria2/lib/Deferred.js b/src/shared/aria2/lib/Deferred.jsnew file mode 100644index 00000000..a1c4b155--- /dev/null+++ b/src/shared/aria2/lib/Deferred.js@@ -0,0 +1,8 @@+'use strict'++module.exports = function Deferred () {+ this.promise = new Promise((resolve, reject) => {+ this.resolve = resolve+ this.reject = reject+ })+}diff --git a/src/shared/aria2/lib/JSONRPCClient.js b/src/shared/aria2/lib/JSONRPCClient.jsnew file mode 100644index 00000000..31da884e--- /dev/null+++ b/src/shared/aria2/lib/JSONRPCClient.js@@ -0,0 +1,191 @@+'use strict'++const Deferred = require('./Deferred')+const promiseEvent = require('./promiseEvent')+const JSONRPCError = require('./JSONRPCError')++const _WebSocket = require('ws')+const _fetch = require('node-fetch')+const EventEmitter = require('events')++const WebSocket = global.WebSocket || _WebSocket+const fetch = global.fetch ? global.fetch.bind(global) : _fetch++export class JSONRPCClient extends EventEmitter {+ constructor (options) {+ super()+ this.deferreds = Object.create(null)+ this.lastId = 0++ Object.assign(this, this.defaultOptions, options)+ }++ id () {+ return this.lastId+++ }++ url (protocol) {+ return (+ protocol ++ (this.secure ? 's' : '') ++ '://' ++ this.host ++ ':' ++ this.port ++ this.path+ )+ }++ websocket (message) {+ return new Promise((resolve, reject) => {+ const cb = (err) => {+ if (err) reject(err)+ else resolve()+ }+ this.socket.send(JSON.stringify(message), cb)+ if (global.WebSocket && this.socket instanceof global.WebSocket) cb()+ })+ }++ async http (message) {+ const response = await fetch(this.url('http'), {+ method: 'POST',+ body: JSON.stringify(message),+ headers: {+ Accept: 'application/json',+ 'Content-Type': 'application/json'+ }+ })++ response+ .json()+ .then(this._onmessage)+ .catch((err) => {+ this.emit('error', err)+ })++ return response+ }++ _buildMessage (method, params) {+ if (typeof method !== 'string') {+ throw new TypeError(method + ' is not a string')+ }++ const message = {+ method,+ 'json-rpc': '2.0',+ id: this.id()+ }++ if (params) Object.assign(message, { params })+ return message+ }++ async batch (calls) {+ const message = calls.map(([method, params]) => {+ return this._buildMessage(method, params)+ })++ await this._send(message)++ return message.map(({ id }) => {+ const { promise } = (this.deferreds[id] = new Deferred())+ return promise+ })+ }++ async call (method, parameters) {+ const message = this._buildMessage(method, parameters)+ await this._send(message)++ const { promise } = (this.deferreds[message.id] = new Deferred())++ return promise+ }++ async _send (message) {+ this.emit('output', message)++ const { socket } = this+ return socket && socket.readyState === 1+ ? this.websocket(message)+ : this.http(message)+ }++ _onresponse ({ id, error, result }) {+ const deferred = this.deferreds[id]+ if (!deferred) return+ if (error) deferred.reject(new JSONRPCError(error))+ else deferred.resolve(result)+ delete this.deferreds[id]+ }++ _onrequest ({ method, params }) {+ return this.onrequest(method, params)+ }++ _onnotification = ({ method, params }) => {+ this.emit(method, params)+ }++ _onmessage = (message) => {+ this.emit('input', message)++ if (Array.isArray(message)) {+ for (const object of message) {+ this._onobject(object)+ }+ } else {+ this._onobject(message)+ }+ }++ _onobject (message) {+ if (message.method === undefined) this._onresponse(message)+ else if (message.id === undefined) this._onnotification(message)+ else this._onrequest(message)+ }++ async open () {+ const socket = (this.socket = new WebSocket(this.url('ws')))++ socket.onclose = (...args) => {+ this.emit('close', ...args)+ }+ socket.onmessage = (event) => {+ let message+ try {+ message = JSON.parse(event.data)+ } catch (err) {+ this.emit('error', err)+ return+ }+ this._onmessage(message)+ }+ socket.onopen = (...args) => {+ this.emit('open', ...args)+ }+ socket.onerror = (...args) => {+ this.emit('error', ...args)+ }++ return promiseEvent(this, 'open')+ }++ async close () {+ const { socket } = this+ socket.close()+ return promiseEvent(this, 'close')+ }++ defaultOptions = {+ secure: false,+ host: 'localhost',+ port: 80,+ secret: '',+ path: '/jsonrpc',+ fetch,+ WebSocket+ }+}diff --git a/src/shared/aria2/lib/JSONRPCError.js b/src/shared/aria2/lib/JSONRPCError.jsnew file mode 100644index 00000000..59a8a6e5--- /dev/null+++ b/src/shared/aria2/lib/JSONRPCError.js@@ -0,0 +1,10 @@+'use strict'++export class JSONRPCError extends Error {+ constructor ({ message, code, data }) {+ super(message)+ this.code = code+ if (data) this.data = data+ this.name = this.constructor.name+ }+}diff --git a/src/shared/aria2/lib/debug.js b/src/shared/aria2/lib/debug.jsnew file mode 100644index 00000000..fc8f8e78--- /dev/null+++ b/src/shared/aria2/lib/debug.js@@ -0,0 +1,23 @@+'use strict'++const { inspect } = require('util')++module.exports = (aria2) => {+ aria2.on('open', () => {+ console.log('aria2', 'OPEN')+ })++ aria2.on('close', () => {+ console.log('aria2', 'CLOSE')+ })++ aria2.on('input', (m) => {+ console.log('aria2', 'IN')+ console.log(inspect(m, { depth: null, colors: true }))+ })++ aria2.on('output', (m) => {+ console.log('aria2', 'OUT')+ console.log(inspect(m, { depth: null, colors: true }))+ })+}diff --git a/src/shared/aria2/lib/promiseEvent.js b/src/shared/aria2/lib/promiseEvent.jsnew file mode 100644index 00000000..f5638cba--- /dev/null+++ b/src/shared/aria2/lib/promiseEvent.js@@ -0,0 +1,20 @@+'use strict'++module.exports = function promiseEvent (target, event) {+ return new Promise((resolve, reject) => {+ function cleanup () {+ target.removeListener(event, onEvent)+ target.removeListener('error', onError)+ }+ function onEvent (data) {+ resolve(data)+ cleanup()+ }+ function onError (err) {+ reject(err)+ cleanup()+ }+ target.addListener(event, onEvent)+ target.addListener('error', onError)+ })+}