Skip to content

A full-featured download manager.

refactor: convert to arrow function

Dr_rOotcc27cb345912
diff --git a/src/main/Application.js b/src/main/Application.js
index c5cf276e..757921f1 100644
--- a/src/main/Application.js
+++ b/src/main/Application.js
@@ -1,8 +1,8 @@
import { EventEmitter } from 'node:events'
-import { app, shell, dialog, ipcMain } from 'electron'
-import is from 'electron-is'
import { readFile, unlink } from 'node:fs'
import { extname, basename } from 'node:path'
+import { app, shell, dialog, ipcMain } from 'electron'
+import is from 'electron-is'
import { isEmpty, isEqual } from 'lodash'
import {
@@ -695,7 +695,7 @@ export default class Application extends EventEmitter {
const sessionPath = this.context.get('session-path')
setTimeout(() => {
- unlink(sessionPath, function (err) {
+ unlink(sessionPath, (err) => {
logger.info('[Motrix] Removed the download seesion file:', err)
})
diff --git a/src/main/core/Engine.js b/src/main/core/Engine.js
index 8532f4c2..1bf37724 100644
--- a/src/main/core/Engine.js
+++ b/src/main/core/Engine.js
@@ -43,9 +43,9 @@ export default class Engine {
const pid = this.instance.pid.toString()
this.writePidFile(pidPath, pid)
- this.instance.once('close', function () {
+ this.instance.once('close', () => {
try {
- unlink(pidPath, function (err) {
+ unlink(pidPath, (err) => {
if (err) {
logger.warn(`[Motrix] Unlink engine process pid file failed: ${err}`)
}
@@ -56,11 +56,11 @@ export default class Engine {
})
if (is.dev()) {
- this.instance.stdout.on('data', function (data) {
+ this.instance.stdout.on('data', (data) => {
logger.log('[Motrix] engine stdout===>', data.toString())
})
- this.instance.stderr.on('data', function (data) {
+ this.instance.stderr.on('data', (data) => {
logger.log('[Motrix] engine stderr===>', data.toString())
})
}
diff --git a/src/main/ui/Locale.js b/src/main/ui/Locale.js
index 9e77f025..e5831759 100644
--- a/src/main/ui/Locale.js
+++ b/src/main/ui/Locale.js
@@ -5,20 +5,20 @@ const localeManager = new LocaleManager({
resources
})
-export function getLocaleManager () {
+export const getLocaleManager = () => {
return localeManager
}
-export function setupLocaleManager (locale) {
+export const setupLocaleManager = (locale) => {
localeManager.changeLanguageByLocale(locale)
return localeManager
}
-export function getI18n () {
+export const getI18n = () => {
return localeManager.getI18n()
}
-export function getI18nTranslator () {
+export const getI18nTranslator = () => {
return localeManager.getI18n().t
}
diff --git a/src/main/utils/index.js b/src/main/utils/index.js
index 5494faa5..a155aebb 100644
--- a/src/main/utils/index.js
+++ b/src/main/utils/index.js
@@ -43,12 +43,12 @@ export const getDhtPath = (protocol) => {
return resolve(getUserDataPath(), `./${name}`)
}
-export function getEngineBin (platform) {
+export const getEngineBin = (platform) => {
const result = engineBinMap[platform] || ''
return result
}
-export function getEngineArch (platform, arch) {
+export const getEngineArch = (platform, arch) => {
if (!['darwin', 'win32', 'linux'].includes(platform)) {
return ''
}
@@ -84,7 +84,7 @@ export const getAria2ConfPath = (platform, arch) => {
return resolve(base, './aria2.conf')
}
-export function transformConfig (config) {
+export const transformConfig = (config) => {
const result = []
for (const [k, v] of Object.entries(config)) {
if (v !== '') {
@@ -94,7 +94,7 @@ export function transformConfig (config) {
return result
}
-export function isRunningInDmg () {
+export const isRunningInDmg = () => {
if (!is.macOS() || is.dev()) {
return false
}
@@ -103,7 +103,7 @@ export function isRunningInDmg () {
return result
}
-export function moveAppToApplicationsFolder (errorMsg = '') {
+export const moveAppToApplicationsFolder = (errorMsg = '') => {
return new Promise((resolve, reject) => {
try {
const result = app.moveToApplicationsFolder()
@@ -118,7 +118,7 @@ export function moveAppToApplicationsFolder (errorMsg = '') {
})
}
-export function splitArgv (argv) {
+export const splitArgv = (argv) => {
const args = []
const extra = {}
for (const arg of argv) {
@@ -134,7 +134,7 @@ export function splitArgv (argv) {
return { args, extra }
}
-export function parseArgvAsUrl (argv) {
+export const parseArgvAsUrl = (argv) => {
const arg = argv[1]
if (!arg) {
return
@@ -145,7 +145,7 @@ export function parseArgvAsUrl (argv) {
}
}
-export function checkIsSupportedSchema (url = '') {
+export const checkIsSupportedSchema = (url = '') => {
const str = url.toLowerCase()
if (
str.startsWith('ftp:') ||
@@ -162,11 +162,11 @@ export function checkIsSupportedSchema (url = '') {
}
}
-export function isDirectory (path) {
+export const isDirectory = (path) => {
return existsSync(path) && lstatSync(path).isDirectory()
}
-export function parseArgvAsFile (argv) {
+export const parseArgvAsFile = (argv) => {
let arg = argv[1]
if (!arg || isDirectory(arg)) {
return
@@ -197,7 +197,7 @@ export const convertArrayBufferToBuffer = (arrayBuffer) => {
return buffer
}
-export function showItemInFolder (fullPath) {
+export const showItemInFolder = (fullPath) => {
if (!fullPath) {
return
}
diff --git a/src/main/utils/menu.js b/src/main/utils/menu.js
index 01f33bae..25dbf94e 100644
--- a/src/main/utils/menu.js
+++ b/src/main/utils/menu.js
@@ -1,6 +1,6 @@
import { parse } from 'querystring'
-export function concat (template, submenu, submenuToAdd) {
+export const concat = (template, submenu, submenuToAdd) => {
submenuToAdd.forEach(sub => {
let relativeItem = null
if (sub.position) {
@@ -37,7 +37,7 @@ export function concat (template, submenu, submenuToAdd) {
})
}
-export function merge (template, item) {
+export const merge = (template, item) => {
if (item.id) {
const matched = findById(template, item.id)
if (matched) {
@@ -73,7 +73,7 @@ function findById (template, id) {
return null
}
-export function translateTemplate (template, keystrokesByCommand, i18n) {
+export const translateTemplate = (template, keystrokesByCommand, i18n) => {
for (const i in template) {
const item = template[i]
if (item.command) {
@@ -101,7 +101,7 @@ export function translateTemplate (template, keystrokesByCommand, i18n) {
return template
}
-export function handleCommand (item) {
+export const handleCommand = (item) => {
handleCommandBefore(item)
const args = item['command-arg']
@@ -158,7 +158,7 @@ function acceleratorForCommand (command, keystrokesByCommand) {
return null
}
-export function flattenMenuItems (menu) {
+export const flattenMenuItems = (menu) => {
const flattenItems = {}
menu.items.forEach(item => {
if (item.id) {
@@ -171,7 +171,7 @@ export function flattenMenuItems (menu) {
return flattenItems
}
-export function updateStates (itemsById, visibleStates, enabledStates, checkedStates) {
+export const updateStates = (itemsById, visibleStates, enabledStates, checkedStates) => {
if (visibleStates) {
for (const command in visibleStates) {
const item = itemsById[command]
diff --git a/src/renderer/utils/native.js b/src/renderer/utils/native.js
index 5e17f3fa..0594a916 100644
--- a/src/renderer/utils/native.js
+++ b/src/renderer/utils/native.js
@@ -1,6 +1,6 @@
-import { shell, nativeTheme } from '@electron/remote'
import { access, constants } from 'node:fs'
import { resolve } from 'node:path'
+import { shell, nativeTheme } from '@electron/remote'
import { Message } from 'element-ui'
import {
@@ -9,7 +9,7 @@ import {
} from '@shared/utils'
import { APP_THEME, TASK_STATUS } from '@shared/constants'
-export function showItemInFolder (fullPath, { errorMsg }) {
+export const showItemInFolder = (fullPath, { errorMsg }) => {
if (!fullPath) {
return
}
@@ -35,7 +35,7 @@ export const openItem = async (fullPath) => {
return result
}
-export function getTaskFullPath (task) {
+export const getTaskFullPath = (task) => {
const { dir, files, bittorrent } = task
let result = resolve(dir)
@@ -109,7 +109,7 @@ export const moveTaskFilesToTrash = (task) => {
return deleteResult1 && deleteResult2
}
-export function getSystemTheme () {
+export const getSystemTheme = () => {
return nativeTheme.shouldUseDarkColors ? APP_THEME.DARK : APP_THEME.LIGHT
}
diff --git a/src/shared/locales/index.js b/src/shared/locales/index.js
index 72d09f3f..ae6d799b 100644
--- a/src/shared/locales/index.js
+++ b/src/shared/locales/index.js
@@ -112,7 +112,7 @@ export const availableLanguages = [
}
]
-function checkLngIsAvailable (locale) {
+const checkLngIsAvailable = (locale) => {
return availableLanguages.some(lng => lng.value === locale)
}
@@ -133,7 +133,7 @@ function checkLngIsAvailable (locale) {
* pt, pt-BR, pt-PT
* zh, zh-CN, zh-HK, zh-TW
*/
-export function getLanguage (locale = 'en-US') {
+export const getLanguage = (locale = 'en-US') => {
if (checkLngIsAvailable(locale)) {
return locale
}
diff --git a/src/shared/utils/index.js b/src/shared/utils/index.js
index f4b8a75d..8d552073 100644
--- a/src/shared/utils/index.js
+++ b/src/shared/utils/index.js
@@ -31,7 +31,7 @@ import {
UNKNOWN_PEERID_NAME
} from '@shared/constants'
-export function bytesToSize (bytes, precision = 1) {
+export const bytesToSize = (bytes, precision = 1) => {
const b = parseInt(bytes, 10)
const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
if (b === 0) { return '0 KB' }
@@ -55,7 +55,7 @@ export const extractSpeedUnit = (speed = '') => {
return match[2]
}
-export function bitfieldToPercent (text) {
+export const bitfieldToPercent = (text) => {
const len = text.length - 1
let p
let one = 0
@@ -69,7 +69,7 @@ export function bitfieldToPercent (text) {
return Math.floor(one / (4 * len) * 100).toString()
}
-export function bitfieldToGraphic (text) {
+export const bitfieldToGraphic = (text) => {
const len = text.length
let result = ''
for (let i = 0; i < len; i++) {
@@ -78,7 +78,7 @@ export function bitfieldToGraphic (text) {
return result
}
-export function peerIdParser (str) {
+export const peerIdParser = (str) => {
if (!str || str === UNKNOWN_PEERID) {
return UNKNOWN_PEERID_NAME
}
@@ -101,7 +101,7 @@ export function peerIdParser (str) {
return result
}
-export function calcProgress (totalLength, completedLength, decimal = 2) {
+export const calcProgress = (totalLength, completedLength, decimal = 2) => {
const total = parseInt(totalLength, 10)
const completed = parseInt(completedLength, 10)
if (total === 0 || completed === 0) {
@@ -112,7 +112,7 @@ export function calcProgress (totalLength, completedLength, decimal = 2) {
return result
}
-export function calcRatio (totalLength, uploadLength) {
+export const calcRatio = (totalLength, uploadLength) => {
const total = parseInt(totalLength, 10)
const upload = parseInt(uploadLength, 10)
if (total === 0 || upload === 0) {
@@ -124,7 +124,7 @@ export function calcRatio (totalLength, uploadLength) {
return result
}
-export function timeRemaining (totalLength, completedLength, downloadSpeed) {
+export const timeRemaining = (totalLength, completedLength, downloadSpeed) => {
const remainingLength = totalLength - completedLength
return Math.ceil(remainingLength / downloadSpeed)
}
@@ -142,7 +142,7 @@ export function timeRemaining (totalLength, completedLength, downloadSpeed) {
* second: 's'
* }
*/
-export function timeFormat (seconds, { prefix = '', suffix = '', i18n }) {
+export const timeFormat = (seconds, { prefix = '', suffix = '', i18n }) => {
let result = ''
let hours = ''
let minutes = ''
@@ -174,7 +174,7 @@ export function timeFormat (seconds, { prefix = '', suffix = '', i18n }) {
return result ? `${prefix} ${result} ${suffix}` : result
}
-export function localeDateTimeFormat (timestamp, locale) {
+export const localeDateTimeFormat = (timestamp, locale) => {
if (!timestamp) {
return ''
}
@@ -193,7 +193,7 @@ export function localeDateTimeFormat (timestamp, locale) {
})
}
-export function ellipsis (str = '', maxLen = 64) {
+export const ellipsis = (str = '', maxLen = 64) => {
const len = str.length
let result = str
if (len < maxLen) {
@@ -207,7 +207,7 @@ export function ellipsis (str = '', maxLen = 64) {
return result
}
-export function getFileSelection (files = []) {
+export const getFileSelection = (files = []) => {
console.log('getFileSelection===>', files)
const selectedFiles = files.filter((file) => file.selected)
if (files.length === 0 || selectedFiles.length === 0) {
@@ -226,7 +226,7 @@ export function getFileSelection (files = []) {
return result
}
-export function getTaskName (task, options = {}) {
+export const getTaskName = (task, options = {}) => {
const o = {
defaultName: '',
maxLen: 64, // -1: No limit length
@@ -251,7 +251,7 @@ export function getTaskName (task, options = {}) {
return result
}
-export function getFileNameFromFile (file) {
+export const getFileNameFromFile = (file) => {
if (!file) {
return ''
}
@@ -270,17 +270,17 @@ export function getFileNameFromFile (file) {
return path.substring(index + 1)
}
-export function isMagnetTask (task) {
+export const isMagnetTask = (task) => {
const { bittorrent } = task
return bittorrent && !bittorrent.info
}
-export function checkTaskIsSeeder (task) {
+export const checkTaskIsSeeder = (task) => {
const { bittorrent, seeder } = task
return !!bittorrent && seeder === 'true'
}
-export function getTaskUri (task, withTracker = false) {
+export const getTaskUri = (task, withTracker = false) => {
const { files } = task
let result = ''
if (checkTaskIsBT(task)) {
@@ -296,7 +296,7 @@ export function getTaskUri (task, withTracker = false) {
return result
}
-export function buildMagnetLink (task, withTracker = false, btTracker = []) {
+export const buildMagnetLink = (task, withTracker = false, btTracker = []) => {
const { bittorrent, infoHash } = task
const { info } = bittorrent
@@ -319,7 +319,7 @@ export function buildMagnetLink (task, withTracker = false, btTracker = []) {
return result
}
-export function checkTaskTitleIsEmpty (task) {
+export const checkTaskTitleIsEmpty = (task) => {
const { files, bittorrent } = task
const [file] = files
const { path } = file
@@ -330,17 +330,17 @@ export function checkTaskTitleIsEmpty (task) {
return result === ''
}
-export function checkTaskIsBT (task = {}) {
+export const checkTaskIsBT = (task = {}) => {
const { bittorrent } = task
return !!bittorrent
}
-export function isTorrent (file) {
+export const isTorrent = (file) => {
const { name, type } = file
return name.endsWith('.torrent') || type === 'application/x-bittorrent'
}
-export function getAsBase64 (file, callback) {
+export const getAsBase64 = (file, callback) => {
const reader = new FileReader()
reader.addEventListener('load', () => {
// https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
@@ -350,7 +350,7 @@ export function getAsBase64 (file, callback) {
reader.readAsDataURL(file)
}
-export function mergeTaskResult (response = []) {
+export const mergeTaskResult = (response = []) => {
let result = []
for (const res of response) {
result = result.concat(...res)
@@ -358,7 +358,7 @@ export function mergeTaskResult (response = []) {
return result
}
-export function changeKeysCase (obj, caseConverter) {
+export const changeKeysCase = (obj, caseConverter) => {
const result = {}
if (isEmpty(obj) || !isFunction(caseConverter)) {
return result
@@ -372,19 +372,19 @@ export function changeKeysCase (obj, caseConverter) {
return result
}
-export function changeKeysToCamelCase (obj = {}) {
+export const changeKeysToCamelCase = (obj = {}) => {
return changeKeysCase(obj, camelCase)
}
-export function changeKeysToKebabCase (obj = {}) {
+export const changeKeysToKebabCase = (obj = {}) => {
return changeKeysCase(obj, kebabCase)
}
-export function validateNumber (n) {
+export const validateNumber = (n) => {
return !isNaN(parseFloat(n)) && isFinite(n) && Number(n) === n
}
-export function fixValue (obj = {}) {
+export const fixValue = (obj = {}) => {
const result = {}
for (const [k, v] of Object.entries(obj)) {
if (v === 'true') {
@@ -400,7 +400,7 @@ export function fixValue (obj = {}) {
return result
}
-export function separateConfig (options) {
+export const separateConfig = (options) => {
// user
const user = {}
// system
@@ -422,13 +422,13 @@ export function separateConfig (options) {
}
}
-export function compactUndefined (arr = []) {
+export const compactUndefined = (arr = []) => {
return arr.filter((item) => {
return item !== undefined
})
}
-export function splitTextRows (text = '') {
+export const splitTextRows = (text = '') => {
let result = text
.replace(/(?:\\\r\\\n|\\\r|\\\n)/g, ' ')
.replace(/(?:\r\n|\r|\n)/g, '\n')
@@ -437,38 +437,38 @@ export function splitTextRows (text = '') {
return result
}
-export function convertCommaToLine (text = '') {
+export const convertCommaToLine = (text = '') => {
let arr = text.split(',')
arr = arr.map((row) => row.trim())
const result = arr.join('\n').trim()
return result
}
-export function convertLineToComma (text = '') {
+export const convertLineToComma = (text = '') => {
const result = text.trim().replace(/(?:\r\n|\r|\n)/g, ',')
return result
}
-export function filterVideoFiles (files = []) {
+export const filterVideoFiles = (files = []) => {
const suffix = [...VIDEO_SUFFIXES, ...SUB_SUFFIXES]
return files.filter((item) => {
return suffix.includes(item.extension)
})
}
-export function filterAudioFiles (files = []) {
+export const filterAudioFiles = (files = []) => {
return files.filter((item) => {
return AUDIO_SUFFIXES.includes(item.extension)
})
}
-export function filterImageFiles (files = []) {
+export const filterImageFiles = (files = []) => {
return files.filter((item) => {
return IMAGE_SUFFIXES.includes(item.extension)
})
}
-export function isAudioOrVideo (uri = '') {
+export const isAudioOrVideo = (uri = '') => {
const suffixs = [...AUDIO_SUFFIXES, ...VIDEO_SUFFIXES]
const result = suffixs.some((suffix) => {
return uri.includes(suffix)
@@ -476,7 +476,7 @@ export function isAudioOrVideo (uri = '') {
return result
}
-export function needCheckCopyright (links = '') {
+export const needCheckCopyright = (links = '') => {
const uris = splitTaskLinks(links)
const avs = uris.filter(uri => {
return isAudioOrVideo(uri)
@@ -486,7 +486,7 @@ export function needCheckCopyright (links = '') {
return result
}
-export function decodeThunderLink (url = '') {
+export const decodeThunderLink = (url = '') => {
if (!url.startsWith('thunder://')) {
return url
}
@@ -498,7 +498,7 @@ export function decodeThunderLink (url = '') {
return result
}
-export function splitTaskLinks (links = '') {
+export const splitTaskLinks = (links = '') => {
const temp = compact(splitTextRows(links))
const result = temp.map((item) => {
return decodeThunderLink(item)
@@ -506,13 +506,13 @@ export function splitTaskLinks (links = '') {
return result
}
-export function detectResource (content) {
+export const detectResource = (content) => {
return RESOURCE_TAGS.some((type) => {
return content.includes(type)
})
}
-export function buildFileList (rawFile) {
+export const buildFileList = (rawFile) => {
rawFile.uid = Date.now()
const file = {
status: 'ready',
@@ -526,15 +526,15 @@ export function buildFileList (rawFile) {
return fileList
}
-export function isRTL (locale = 'en-US') {
+export const isRTL = (locale = 'en-US') => {
return SUPPORT_RTL_LOCALES.includes(locale)
}
-export function getLangDirection (locale = 'en-US') {
+export const getLangDirection = (locale = 'en-US') => {
return isRTL(locale) ? 'rtl' : 'ltr'
}
-export function listTorrentFiles (files) {
+export const listTorrentFiles = (files) => {
const result = files.map((file, index) => {
const extension = getFileExtension(file.path)
const item = {
@@ -549,20 +549,20 @@ export function listTorrentFiles (files) {
return result
}
-export function getFileName (fullPath) {
+export const getFileName = (fullPath) => {
// eslint-disable-next-line
return fullPath.replace(/^.*[\\\/]/, '')
}
-export function getFileExtension (filename) {
+export const getFileExtension = (filename) => {
return filename.slice((filename.lastIndexOf('.') - 1 >>> 0) + 2)
}
-export function removeExtensionDot (extension = '') {
+export const removeExtensionDot = (extension = '') => {
return extension.replace('.', '')
}
-export function diffConfig (current = {}, next = {}) {
+export const diffConfig = (current = {}, next = {}) => {
const curr = pick(current, Object.keys(next))
const result = omitBy(next, (val, key) => {
if (isArray(val) || isPlainObject(val)) {
@@ -573,11 +573,11 @@ export function diffConfig (current = {}, next = {}) {
return result
}
-export function calcFormLabelWidth (locale) {
+export const calcFormLabelWidth = (locale) => {
return locale.startsWith('de') ? '28%' : '25%'
}
-export function parseHeader (header = '') {
+export const parseHeader = (header = '') => {
header = header.trim()
let result = {}
if (!header) {
@@ -596,7 +596,7 @@ export function parseHeader (header = '') {
return result
}
-export function formatOptionsForEngine (options = {}) {
+export const formatOptionsForEngine = (options = {}) => {
const result = {}
Object.keys(options).forEach((key) => {
@@ -611,7 +611,7 @@ export function formatOptionsForEngine (options = {}) {
return result
}
-export function buildRpcUrl (options = {}) {
+export const buildRpcUrl = (options = {}) => {
const { port, secret } = options
let result = `${ENGINE_RPC_HOST}:${port}/jsonrpc`
if (secret) {
@@ -622,7 +622,7 @@ export function buildRpcUrl (options = {}) {
return result
}
-export function checkIsNeedRestart (changed = {}) {
+export const checkIsNeedRestart = (changed = {}) => {
let result = false
if (isEmpty(changed)) {