Skip to content

A full-featured download manager.

refactor: replace forever with child process

Dr_rOot8656fa086272
diff --git a/src/main/core/Engine.js b/src/main/core/Engine.js
index 2e6a0814..2dc1f2f0 100644
--- a/src/main/core/Engine.js
+++ b/src/main/core/Engine.js
@@ -1,18 +1,22 @@
import { app } from 'electron'
import is from 'electron-is'
-import { existsSync } from 'fs'
+import { existsSync, writeFile, unlink } from 'fs'
import { resolve, join } from 'path'
-import forever from 'forever-monitor'
+import { spawn } from 'child_process'
import logger from './Logger'
import { getI18n } from '../ui/Locale'
import {
getEngineBin,
+ getEnginePidPath,
getSessionPath,
transformConfig
} from '../utils/index'
+const { platform } = process
+
export default class Engine {
+ // ChildProcess | null
static instance = null
constructor (options = {}) {
@@ -21,84 +25,103 @@ export default class Engine {
this.i18n = getI18n()
this.systemConfig = options.systemConfig
this.userConfig = options.userConfig
+ this.basePath = this.getBasePath()
}
- getStartSh () {
- const { platform } = process
- let basePath = resolve(app.getAppPath(), '..')
+ start () {
+ const pidPath = getEnginePidPath()
+ logger.info('[Motrix] Engie pid path:', pidPath)
- if (is.dev()) {
- basePath = resolve(__dirname, `../../../extra/${platform}`)
+ if (this.instance) {
+ return
+ }
+
+ const binPath = this.getBinPath()
+ const args = this.getStartArgs()
+ this.instance = spawn(binPath, args)
+ const pid = this.instance.pid.toString()
+ this.writePidFile(pidPath, pid)
+
+ this.instance.once('close', function () {
+ try {
+ unlink(pidPath, function (err) {
+ if (err) {
+ logger.warn(`[Motrix] Unlink engine process pid file failed: ${err}`)
+ }
+ })
+ } catch (err) {
+ logger.warn(`[Motrix] Unlink engine process pid file failed: ${err}`)
+ }
+ })
+ }
+
+ stop () {
+ if (this.instance) {
+ this.instance.kill()
+ this.instance = null
}
+ }
+
+ writePidFile (pidPath, pid) {
+ writeFile(pidPath, pid, (err) => {
+ if (err) {
+ logger.error(`[Motrix] Write engine process pid failed: ${err}`)
+ }
+ })
+ }
+ getBinPath () {
const binName = getEngineBin(platform)
if (!binName) {
throw new Error(this.i18n.t('app.engine-damaged-message'))
}
- const binPath = join(basePath, `/engine/${binName}`)
- const binIsExist = existsSync(binPath)
+ const result = join(this.basePath, `/engine/${binName}`)
+ const binIsExist = existsSync(result)
if (!binIsExist) {
- logger.error('[Motrix] engine bin is not exist:', binPath)
+ logger.error('[Motrix] engine bin is not exist:', result)
throw new Error(this.i18n.t('app.engine-missing-message'))
}
- const confPath = join(basePath, '/engine/aria2.conf')
+ return result
+ }
- const sessionPath = this.userConfig['session-path'] || getSessionPath()
- const sessionIsExist = existsSync(sessionPath)
+ getBasePath () {
+ let result = resolve(app.getAppPath(), '..')
- let result = [`${binPath}`, `--conf-path=${confPath}`, `--save-session=${sessionPath}`]
- if (sessionIsExist) {
- result = [...result, `--input-file=${sessionPath}`]
+ if (is.dev()) {
+ result = resolve(__dirname, `../../../extra/${platform}`)
}
- const extraConfig = transformConfig(this.systemConfig)
- result = [...result, ...extraConfig]
-
return result
}
- start () {
- const sh = this.getStartSh()
- logger.info('[Motrix] Engine start sh:', sh)
- this.instance = forever.start(sh, {
- max: is.dev() ? 0 : 100,
- parser: function (command, args) {
- return {
- command: command,
- args: args
- }
- },
- silent: !is.dev()
- })
-
- const { child } = this.instance
- logger.info('[Motrix] Engine pid:', child.pid)
-
- this.instance.on('error', (err) => {
- logger.info(`[Motrix] Engine error: ${err}`)
- })
+ getStartArgs () {
+ const confPath = join(this.basePath, '/engine/aria2.conf')
- this.instance.on('start', function (process, data) {
- logger.info('[Motrix] Engine started')
- })
+ const sessionPath = this.userConfig['session-path'] || getSessionPath()
+ const sessionIsExist = existsSync(sessionPath)
- this.instance.on('stop', function (process) {
- logger.info('[Motrix] Engine stopped')
- })
+ let result = [`--conf-path=${confPath}`, `--save-session=${sessionPath}`]
+ if (sessionIsExist) {
+ result = [...result, `--input-file=${sessionPath}`]
+ }
- // this.instance.on('restart', function (forever) {
- // logger.info(`[Motrix] Engine exit:`)
- // })
+ const extraConfig = {
+ ...this.systemConfig
+ }
+ const keepSeeding = this.userConfig['keep-seeding']
+ const seedRatio = this.systemConfig['seed-ratio']
+ if (keepSeeding || seedRatio === 0) {
+ extraConfig['seed-ratio'] = 0
+ delete extraConfig['seed-time']
+ }
+ console.log('extraConfig===>', extraConfig)
- // this.instance.on('exit:code', function (code) {
- // logger.info(`[Motrix] Engine exit: ${code}`)
- // })
+ const extra = transformConfig(extraConfig)
+ result = [...result, ...extra]
- // this.instance.on('stderr', (data) => {
- // logger.info(`[Motrix] Engine stderr: ${data}`)
- // })
+ return result
}
isRunning (pid) {
@@ -109,31 +132,6 @@ export default class Engine {
}
}
- stop () {
- const { pid } = this.instance.child
- try {
- logger.info('[Motrix] Engine stopping')
- this.instance.stop()
- } catch (err) {
- logger.error('[Motrix] Engine stop fail:', err.message)
- this.forceStop(pid)
- } finally {
- this.instance.removeAllListeners('start')
- this.instance.removeAllListeners('error')
- this.instance.removeAllListeners('stop')
- }
- }
-
- forceStop (pid) {
- try {
- if (pid && this.isRunning(pid)) {
- process.kill(pid)
- }
- } catch (err) {
- logger.warn('[Motrix] Engine force stop fail:', err)
- }
- }
-
restart () {
this.stop()
this.start()
diff --git a/src/main/utils/index.js b/src/main/utils/index.js
index 177f4a5b..2e8738f0 100644
--- a/src/main/utils/index.js
+++ b/src/main/utils/index.js
@@ -25,6 +25,10 @@ export function getSessionPath () {
return resolve(app.getPath('userData'), './download.session')
}
+export function getEnginePidPath () {
+ return resolve(app.getPath('userData'), './engine.pid')
+}
+
export function getUserDataPath () {
return app.getPath('userData')
}