Skip to content

A full-featured download manager.

feat: setup proxy with scopes

Dr_rOotecbe7f40c36c
diff --git a/src/main/Application.js b/src/main/Application.js
index 174ba40d..d15932d1 100644
--- a/src/main/Application.js
+++ b/src/main/Application.js
@@ -8,7 +8,8 @@ import { isEmpty, isEqual } from 'lodash'
import {
APP_RUN_MODE,
AUTO_SYNC_TRACKER_INTERVAL,
- AUTO_CHECK_UPDATE_INTERVAL
+ AUTO_CHECK_UPDATE_INTERVAL,
+ PROXY_SCOPES
} from '@shared/constants'
import { checkIsNeedRun } from '@shared/utils'
import {
@@ -61,22 +62,22 @@ export default class Application extends EventEmitter {
this.initEngineClient()
- this.initTouchBarManager()
-
this.initThemeManager()
this.initTrayManager()
+ this.initTouchBarManager()
+
this.initDockManager()
this.initAutoLaunchManager()
this.initEnergyManager()
- this.initUpdaterManager()
-
this.initProtocolManager()
+ this.initUpdaterManager()
+
this.handleCommands()
this.handleEvents()
@@ -288,6 +289,49 @@ export default class Application extends EventEmitter {
})
}
+ watchProxyChange () {
+ const { userConfig } = this.configManager
+ const key = 'proxy'
+ this.configListeners[key] = userConfig.onDidChange(key, async (newValue, oldValue) => {
+ logger.info(`[Motrix] detected ${key} value change event:`, newValue, oldValue)
+ this.updateManager.setupProxy(newValue)
+
+ const { enable, server, bypass, scope = [] } = newValue
+ const system = enable && server && scope.includes(PROXY_SCOPES.DOWNLOAD)
+ ? {
+ 'all-proxy': server,
+ 'no-proxy': bypass
+ }
+ : {}
+ this.configManager.setSystemConfig(system)
+ this.engineClient.call('changeGlobalOption', system)
+ })
+ }
+
+ watchLocaleChange () {
+ const { userConfig } = this.configManager
+ const key = 'locale'
+ this.configListeners[key] = userConfig.onDidChange(key, async (newValue, oldValue) => {
+ logger.info(`[Motrix] detected ${key} value change event:`, newValue, oldValue)
+ this.localeManager.changeLanguageByLocale(newValue)
+ .then(() => {
+ this.menuManager.handleLocaleChange(newValue)
+ this.trayManager.handleLocaleChange(newValue)
+ })
+ this.sendCommandToAll('application:update-locale', { locale: newValue })
+ })
+ }
+
+ watchThemeChange () {
+ const { userConfig } = this.configManager
+ const key = 'theme'
+ this.configListeners[key] = userConfig.onDidChange(key, async (newValue, oldValue) => {
+ logger.info(`[Motrix] detected ${key} value change event:`, newValue, oldValue)
+ this.themeManager.updateSystemTheme(newValue)
+ this.sendCommandToAll('application:update-theme', { theme: newValue })
+ })
+ }
+
watchShowProgressBarChange () {
const { userConfig } = this.configManager
const key = 'show-progress-bar'
@@ -395,22 +439,13 @@ export default class Application extends EventEmitter {
this.upnp.closeClient()
}
- autoSyncTracker () {
- const enable = this.configManager.getUserConfig('auto-sync-tracker')
- const lastTime = this.configManager.getUserConfig('last-sync-tracker-time')
- const result = checkIsNeedRun(enable, lastTime, AUTO_SYNC_TRACKER_INTERVAL)
- logger.info('[Motrix] auto sync tracker checkIsNeedRun:', result)
- if (!result) {
- return
- }
-
- const source = this.configManager.getUserConfig('tracker-source')
+ syncTrackers (source, proxy) {
if (isEmpty(source)) {
return
}
setTimeout(() => {
- fetchBtTrackerFromSource(source).then((data) => {
+ fetchBtTrackerFromSource(source, proxy).then((data) => {
logger.warn('[Motrix] auto sync tracker data:', data)
if (!data || data.length === 0) {
return
@@ -432,6 +467,21 @@ export default class Application extends EventEmitter {
}, 500)
}
+ autoSyncTrackers () {
+ const enable = this.configManager.getUserConfig('auto-sync-tracker')
+ const lastTime = this.configManager.getUserConfig('last-sync-tracker-time')
+ const result = checkIsNeedRun(enable, lastTime, AUTO_SYNC_TRACKER_INTERVAL)
+ logger.info('[Motrix] auto sync tracker checkIsNeedRun:', result)
+ if (!result) {
+ return
+ }
+
+ const source = this.configManager.getUserConfig('tracker-source')
+ const proxy = this.configManager.getUserConfig('proxy', { enable: false })
+
+ this.syncTrackers(source, proxy)
+ }
+
autoResumeTask () {
const enabled = this.configManager.getUserConfig('resume-all-when-app-launched')
if (!enabled) {
@@ -633,9 +683,12 @@ export default class Application extends EventEmitter {
}
const enabled = this.configManager.getUserConfig('auto-check-update')
+ const proxy = this.configManager.getSystemConfig('all-proxy')
const lastTime = this.configManager.getUserConfig('last-check-update-time')
+ const autoCheck = checkIsNeedRun(enabled, lastTime, AUTO_CHECK_UPDATE_INTERVAL)
this.updateManager = new UpdateManager({
- autoCheck: checkIsNeedRun(enabled, lastTime, AUTO_CHECK_UPDATE_INTERVAL)
+ autoCheck,
+ proxy
})
this.handleUpdaterEvents()
}
@@ -870,7 +923,7 @@ export default class Application extends EventEmitter {
handleEvents () {
this.once('application:initialized', () => {
- this.autoSyncTracker()
+ this.autoSyncTrackers()
this.autoResumeTask()
@@ -884,6 +937,9 @@ export default class Application extends EventEmitter {
this.watchProtocolsChange()
this.watchRunModeChange()
this.watchShowProgressBarChange()
+ this.watchProxyChange()
+ this.watchLocaleChange()
+ this.watchThemeChange()
this.on('download-status-change', (downloading) => {
this.trayManager.handleDownloadStatusChange(downloading)
diff --git a/src/main/core/ConfigManager.js b/src/main/core/ConfigManager.js
index bb572afe..509410e6 100644
--- a/src/main/core/ConfigManager.js
+++ b/src/main/core/ConfigManager.js
@@ -16,7 +16,9 @@ import {
IP_VERSION,
LOGIN_SETTING_OPTIONS,
NGOSANG_TRACKERS_BEST_IP_URL_CDN,
- NGOSANG_TRACKERS_BEST_URL_CDN
+ NGOSANG_TRACKERS_BEST_URL_CDN,
+ PROXY_SCOPES,
+ PROXY_SCOPE_OPTIONS
} from '@shared/constants'
import { CHROME_UA } from '@shared/ua'
import { separateConfig } from '@shared/utils'
@@ -98,7 +100,6 @@ export default class ConfigManager {
// },
/* eslint-disable quote-props */
defaults: {
- 'all-proxy-backup': EMPTY_STRING,
'auto-check-update': is.macOS(),
'auto-hide-window': false,
'auto-sync-tracker': true,
@@ -117,6 +118,12 @@ export default class ConfigManager {
'no-confirm-before-delete-task': false,
'open-at-login': false,
'protocols': { 'magnet': true, 'thunder': false },
+ 'proxy': {
+ 'enable': false,
+ 'server': EMPTY_STRING,
+ 'bypass': EMPTY_STRING,
+ 'scope': PROXY_SCOPE_OPTIONS
+ },
'resume-all-when-app-launched': false,
'run-mode': APP_RUN_MODE.STANDARD,
'show-progress-bar': true,
@@ -129,7 +136,6 @@ export default class ConfigManager {
'tray-theme': APP_THEME.AUTO,
'tray-speedometer': is.macOS(),
'update-channel': 'latest',
- 'use-proxy': false,
'window-state': {}
}
/* eslint-enable quote-props */
@@ -146,6 +152,12 @@ export default class ConfigManager {
})
}
+ const proxy = this.getUserConfig('proxy', { enable: false })
+ const { enable, server, bypass, scope = [] } = proxy
+ if (enable && server && scope.includes(PROXY_SCOPES.DOWNLOAD)) {
+ this.setSystemConfig('all-proxy', server)
+ this.setSystemConfig('no-proxy', bypass)
+ }
// Fix spawn ENAMETOOLONG on Windows
const tracker = reduceTrackerString(this.systemConfig.get('bt-tracker'))
diff --git a/src/main/core/UpdateManager.js b/src/main/core/UpdateManager.js
index d5960d56..c81ed88e 100644
--- a/src/main/core/UpdateManager.js
+++ b/src/main/core/UpdateManager.js
@@ -4,6 +4,7 @@ import { dialog } from 'electron'
import is from 'electron-is'
import { autoUpdater } from 'electron-updater'
+import { PROXY_SCOPES } from '@shared/constants'
import logger from './Logger'
import { getI18n } from '../ui/Locale'
@@ -22,6 +23,9 @@ export default class UpdateManager extends EventEmitter {
this.updater.autoDownload = false
this.updater.autoInstallOnAppQuit = false
this.updater.logger = logger
+ logger.info('[Motrix] setup proxy:', this.options.proxy)
+ this.setupProxy(this.options.proxy)
+
this.autoCheckData = {
checkEnable: this.options.autoCheck,
userCheck: false
@@ -29,6 +33,31 @@ export default class UpdateManager extends EventEmitter {
this.init()
}
+ setupProxy (proxy) {
+ const { enable, server, scope = [] } = proxy
+ if (!enable || !server || !scope.includes(PROXY_SCOPES.UPDATE_APP)) {
+ this.updater.netSession.setProxy({
+ proxyRules: undefined
+ })
+ return
+ }
+
+ const url = new URL(server)
+ const { username, password, protocol = 'http:', host, port } = url
+ const proxyRules = `${protocol}//${host}`
+
+ logger.info(`[Motrix] setup proxy: ${proxyRules}`, username, password, protocol, host, port)
+ this.updater.netSession.setProxy({
+ proxyRules
+ })
+
+ if (server.includes('@')) {
+ this.updater.signals.login((_authInfo, callback) => {
+ callback(username, password)
+ })
+ }
+ }
+
init () {
// Event: error
// Event: checking-for-update
diff --git a/src/renderer/components/Preference/Advanced.vue b/src/renderer/components/Preference/Advanced.vue
index 8a276997..2432ceb6 100644
--- a/src/renderer/components/Preference/Advanced.vue
+++ b/src/renderer/components/Preference/Advanced.vue
@@ -49,15 +49,15 @@
:label-width="formLabelWidth"
>
<el-switch
- v-model="form.useProxy"
- :active-text="$t('preferences.use-proxy')"
- @change="onUseProxyChange"
+ v-model="form.proxy.enable"
+ :active-text="$t('preferences.enable-proxy')"
+ @change="onProxyEnableChange"
>
</el-switch>
</el-form-item>
<el-form-item
:label-width="formLabelWidth"
- v-if="form.useProxy"
+ v-if="form.proxy.enable"
style="margin-top: -16px;"
>
<el-col
@@ -69,8 +69,8 @@
>
<el-input
placeholder="[http://][USER:PASSWORD@]HOST[:PORT]"
- @change="onAllProxyBackupChange"
- v-model="form.allProxyBackup">
+ @change="onProxyServerChange"
+ v-model="form.proxy.server">
</el-input>
</el-col>
<el-col
@@ -84,9 +84,30 @@
type="textarea"
rows="2"
auto-complete="off"
- :placeholder="`${$t('preferences.no-proxy-input-tips')}`"
- v-model="form.noProxy">
+ @change="handleProxyBypassChange"
+ :placeholder="`${$t('preferences.proxy-bypass-input-tips')}`"
+ v-model="form.proxy.bypass">
</el-input>
+ </el-col>
+ <el-col
+ class="form-item-sub"
+ :xs="24"
+ :sm="24"
+ :md="20"
+ :lg="20"
+ >
+ <el-select
+ class="proxy-scope"
+ v-model="form.proxy.scope"
+ multiple
+ >
+ <el-option
+ v-for="item in proxyScopeOptions"
+ :key="item"
+ :label="$t(`preferences.proxy-scope-${item}`)"
+ :value="item"
+ />
+ </el-select>
<div class="el-form-item__info" style="margin-top: 8px;">
<a target="_blank" href="https://github.com/agalwood/Motrix/wiki/Proxy" rel="noopener noreferrer">
{{ $t('preferences.proxy-tips') }}
@@ -433,9 +454,9 @@
ENGINE_RPC_PORT,
LOG_LEVELS,
TRACKER_SOURCE_OPTIONS,
+ PROXY_SCOPE_OPTIONS
} from '@shared/constants'
import {
- backupConfig,
buildRpcUrl,
calcFormLabelWidth,
changedConfig,
@@ -454,8 +475,6 @@
const initForm = (config) => {
const {
- allProxy,
- allProxyBackup,
autoCheckUpdate,
autoSyncTracker,
btTracker,
@@ -466,8 +485,8 @@
lastSyncTrackerTime,
listenPort,
logLevel,
- noProxy,
protocols,
+ proxy,
rpcListenPort,
rpcSecret,
trackerSource,
@@ -475,8 +494,6 @@
userAgent
} = config
const result = {
- allProxy,
- allProxyBackup,
autoCheckUpdate,
autoSyncTracker,
btTracker: convertCommaToLine(btTracker),
@@ -487,7 +504,7 @@
lastSyncTrackerTime,
listenPort,
logLevel,
- noProxy: convertCommaToLine(noProxy),
+ proxy: cloneDeep(proxy),
protocols: { ...protocols },
rpcListenPort,
rpcSecret,
@@ -515,6 +532,7 @@
formLabelWidth: calcFormLabelWidth(locale),
formOriginal,
hideRpcSecret: true,
+ proxyScopeOptions: PROXY_SCOPE_OPTIONS,
rules: {},
trackerSourceOptions: TRACKER_SOURCE_OPTIONS,
trackerSyncing: false
@@ -577,8 +595,6 @@
handleLocaleChange (locale) {
const lng = getLanguage(locale)
getLocaleManager().changeLanguage(lng)
- this.$electron.ipcRenderer.send('command',
- 'application:change-locale', lng)
},
onCheckUpdateClick () {
this.$electron.ipcRenderer.send('command', 'application:check-for-updates')
@@ -610,11 +626,29 @@
[protocol]: enabled
}
},
- onUseProxyChange (flag) {
- this.form.allProxy = flag ? this.form.allProxyBackup : ''
+ onProxyEnableChange (enable) {
+ this.form.proxy = {
+ ...this.form.proxy,
+ enable
+ }
},
- onAllProxyBackupChange (value) {
- this.form.allProxy = value
+ onProxyServerChange (server) {
+ this.form.proxy = {
+ ...this.form.proxy,
+ server
+ }
+ },
+ handleProxyBypassChange (bypass) {
+ this.form.proxy = {
+ ...this.form.proxy,
+ bypass: convertLineToComma(bypass)
+ }
+ },
+ onProxyScopeChange (scope) {
+ this.form.proxy = {
+ ...this.form.proxy,
+ scope: [...scope]
+ }
},
changeUA (type) {
const ua = userAgentMap[type]
@@ -685,10 +719,6 @@
.then((config) => {
this.form = initForm(config)
this.formOriginal = cloneDeep(this.form)
- if (changedConfig.basic.theme !== undefined) {
- this.$electron.ipcRenderer.send('command',
- 'application:change-theme', changedConfig.basic.theme)
- }
})
},
submitForm (formName) {
@@ -704,10 +734,9 @@
}
const {
- btAutoDownloadContent,
autoHideWindow,
+ btAutoDownloadContent,
btTracker,
- noProxy,
rpcListenPort
} = data
@@ -721,10 +750,6 @@
data.btTracker = reduceTrackerString(convertLineToComma(btTracker))
}
- if (noProxy) {
- data.noProxy = convertLineToComma(noProxy)
- }
-
if (rpcListenPort === EMPTY_STRING) {
data.rpcListenPort = this.rpcDefaultPort
}
@@ -776,17 +801,8 @@
cancelId: 1
}).then(({ response }) => {
if (response === 0) {
- if (changedConfig.basic.theme !== undefined) {
- this.$electron.ipcRenderer.send('command',
- 'application:change-theme',
- backupConfig.theme)
- }
- if (changedConfig.basic.locale !== undefined) {
- this.handleLocaleChange(backupConfig.locale)
- }
changedConfig.basic = {}
changedConfig.advanced = {}
- backupConfig.theme = undefined
next()
}
})
@@ -797,6 +813,9 @@
</script>
<style lang="scss">
+.proxy-scope {
+ width: 100%;
+}
.bt-tracker {
position: relative;
.sync-tracker-btn {
diff --git a/src/renderer/components/Preference/Basic.vue b/src/renderer/components/Preference/Basic.vue
index 9db1b4dc..092528cf 100644
--- a/src/renderer/components/Preference/Basic.vue
+++ b/src/renderer/components/Preference/Basic.vue
@@ -72,7 +72,6 @@
<el-col class="form-item-sub" :span="16">
<el-select
v-model="form.locale"
- @change="handleLocaleChange"
:placeholder="$t('preferences.change-language')">
<el-option
v-for="item in locales"
@@ -308,7 +307,6 @@
import { availableLanguages, getLanguage } from '@shared/locales'
import { getLocaleManager } from '@/components/Locale'
import {
- backupConfig,
calcFormLabelWidth,
changedConfig,
checkIsNeedRestart,
@@ -319,7 +317,8 @@
import {
APP_RUN_MODE,
EMPTY_STRING,
- ENGINE_MAX_CONCURRENT_DOWNLOADS
+ ENGINE_MAX_CONCURRENT_DOWNLOADS,
+ ENGINE_RPC_PORT
} from '@shared/constants'
import { reduceTrackerString } from '@shared/utils/tracker'
@@ -406,13 +405,6 @@
let form = {}
form = initForm(extend(form, formOriginal, changedConfig.basic))
- if (backupConfig.theme === undefined) {
- backupConfig.theme = formOriginal.theme
- } else {
- formOriginal.theme = backupConfig.theme
- }
- backupConfig.locale = formOriginal.locale
-
return {
form,
formLabelWidth: calcFormLabelWidth(locale),
@@ -526,6 +518,9 @@
showHideAppMenuOption () {
return is.windows() || is.linux()
},
+ rpcDefaultPort () {
+ return ENGINE_RPC_PORT
+ },
...mapState('preference', {
config: state => state.config
})
@@ -534,22 +529,18 @@
handleLocaleChange (locale) {
const lng = getLanguage(locale)
getLocaleManager().changeLanguage(lng)
- this.$electron.ipcRenderer.send('command',
- 'application:change-locale', lng)
},
handleThemeChange (theme) {
this.form.theme = theme
- this.$electron.ipcRenderer.send('command',
- 'application:change-theme', theme)
},
handleDownloadChange (value) {
- const speedLimit = parseInt(this.form.maxOverallDownloadLimit)
+ const speedLimit = parseInt(this.form.maxOverallDownloadLimit, 10)
this.downloadUnit = value
const limit = speedLimit > 0 ? `${speedLimit}${value}` : 0
this.form.maxOverallDownloadLimit = limit
},
handleUploadChange (value) {
- const speedLimit = parseInt(this.form.maxOverallUploadLimit)
+ const speedLimit = parseInt(this.form.maxOverallUploadLimit, 10)
this.uploadUnit = value
const limit = speedLimit > 0 ? `${speedLimit}${value}` : 0
this.form.maxOverallUploadLimit = limit
@@ -588,10 +579,9 @@
}
const {
- btAutoDownloadContent,
autoHideWindow,
+ btAutoDownloadContent,
btTracker,
- noProxy,
rpcListenPort
} = data
@@ -605,10 +595,6 @@
data.btTracker = reduceTrackerString(convertLineToComma(btTracker))
}
- if (noProxy) {
- data.noProxy = convertLineToComma(noProxy)
- }
-
if (rpcListenPort === EMPTY_STRING) {
data.rpcListenPort = this.rpcDefaultPort
}
@@ -641,8 +627,6 @@
})
},
resetForm (formName) {
- this.$refs.themeSwitcher.currentValue = backupConfig.theme
- this.handleLocaleChange(this.formOriginal.locale)
this.syncFormConfig()
}
},
@@ -662,17 +646,8 @@
cancelId: 1
}).then(({ response }) => {
if (response === 0) {
- if (changedConfig.basic.theme !== undefined) {
- this.$electron.ipcRenderer.send('command',
- 'application:change-theme',
- backupConfig.theme)
- }
- if (changedConfig.basic.locale !== undefined) {
- this.handleLocaleChange(this.formOriginal.locale)
- }
changedConfig.basic = {}
changedConfig.advanced = {}
- backupConfig.theme = undefined
next()
}
})
diff --git a/src/renderer/pages/index/App.vue b/src/renderer/pages/index/App.vue
index 4511a10d..64482fa2 100644
--- a/src/renderer/pages/index/App.vue
+++ b/src/renderer/pages/index/App.vue
@@ -21,6 +21,8 @@
import EngineClient from '@/components/Native/EngineClient'
import Ipc from '@/components/Native/Ipc'
import TitleBar from '@/components/Native/TitleBar'
+ import { getLanguage } from '@shared/locales'
+ import { getLocaleManager } from '@/components/Locale'
export default {
name: 'motrix-app',
@@ -78,6 +80,10 @@
this.updateRootClassName()
},
watch: {
+ locale (val) {
+ const lng = getLanguage(val)
+ getLocaleManager().changeLanguage(lng)
+ },
themeClass () {
this.updateRootClassName()
},
diff --git a/src/renderer/pages/index/commands.js b/src/renderer/pages/index/commands.js
index ade68020..7614bab4 100644
--- a/src/renderer/pages/index/commands.js
+++ b/src/renderer/pages/index/commands.js
@@ -25,6 +25,11 @@ const updateTheme = (payload = {}) => {
store.dispatch('preference/updateAppTheme', theme)
}
+const updateLocale = (payload = {}) => {
+ const { locale } = payload
+ store.dispatch('preference/updateAppLocale', locale)
+}
+
const updateTrayFocused = (payload = {}) => {
const { focused } = payload
store.dispatch('app/updateTrayFocused', focused)
@@ -192,4 +197,5 @@ commands.register('application:show-task-detail', showTaskDetail)
commands.register('application:update-preference-config', fetchPreference)
commands.register('application:update-system-theme', updateSystemTheme)
commands.register('application:update-theme', updateTheme)
+commands.register('application:update-locale', updateLocale)
commands.register('application:update-tray-focused', updateTrayFocused)
diff --git a/src/renderer/store/modules/preference.js b/src/renderer/store/modules/preference.js
index b6851923..1d95470a 100644
--- a/src/renderer/store/modules/preference.js
+++ b/src/renderer/store/modules/preference.js
@@ -117,11 +117,16 @@ const actions = {
updateAppTheme ({ dispatch }, theme) {
dispatch('updatePreference', { theme })
},
+ updateAppLocale ({ dispatch }, locale) {
+ dispatch('updatePreference', { locale })
+ },
updatePreference ({ commit }, config) {
commit('UPDATE_PREFERENCE_DATA', config)
},
fetchBtTracker (_, trackerSource = []) {
- return fetchBtTrackerFromSource(trackerSource)
+ const { proxy = { enable: false } } = state.config
+ console.log('fetchBtTracker', trackerSource, proxy)
+ return fetchBtTrackerFromSource(trackerSource, proxy)
},
toggleEngineMode () {
diff --git a/src/shared/configKeys.js b/src/shared/configKeys.js
index 172403b9..94258773 100644
--- a/src/shared/configKeys.js
+++ b/src/shared/configKeys.js
@@ -1,5 +1,4 @@
const userKeys = [
- 'all-proxy-backup',
'auto-check-update',
'auto-hide-window',
'auto-sync-tracker',
@@ -20,14 +19,14 @@ const userKeys = [
'no-confirm-before-delete-task',
'open-at-login',
'protocols',
+ 'proxy',
'resume-all-when-app-launched',
'run-mode',
'show-progress-bar',
'task-notification',
'theme',
'tracker-source',
- 'tray-speedometer',
- 'use-proxy'
+ 'tray-speedometer'
]
const systemKeys = [
diff --git a/src/shared/constants.js b/src/shared/constants.js
index ff1f402a..cb561540 100644
--- a/src/shared/constants.js
+++ b/src/shared/constants.js
@@ -172,6 +172,18 @@ export const TRACKER_SOURCE_OPTIONS = [
}
]
+export const PROXY_SCOPES = {
+ DOWNLOAD: 'download',
+ UPDATE_APP: 'update-app',
+ UPDATE_TRACKERS: 'update-trackers'
+}
+
+export const PROXY_SCOPE_OPTIONS = [
+ PROXY_SCOPES.DOWNLOAD,
+ PROXY_SCOPES.UPDATE_APP,
+ PROXY_SCOPES.UPDATE_TRACKERS
+]
+
export const NONE_SELECTED_FILES = 'none'
export const SELECTED_ALL_FILES = 'all'
diff --git a/src/shared/utils/tracker.js b/src/shared/utils/tracker.js
index eb48d922..3e6acc70 100644
--- a/src/shared/utils/tracker.js
+++ b/src/shared/utils/tracker.js
@@ -1,15 +1,57 @@
import { isEmpty } from 'lodash'
import axios from 'axios'
-import { MAX_BT_TRACKER_LENGTH } from '@shared/constants'
+import { MAX_BT_TRACKER_LENGTH, ONE_SECOND, PROXY_SCOPES } from '@shared/constants'
-export const fetchBtTrackerFromSource = async (source) => {
+export const convertToAxiosProxy = (proxyServer = '') => {
+ if (!proxyServer) {
+ return
+ }
+
+ const url = new URL(proxyServer)
+ const { username, password, protocol = 'http:', host, hostname, port } = url
+ console.log(username, password, protocol, host, hostname, port)
+
+ let result = {
+ protocol: protocol.replace(':', ''),
+ host: hostname,
+ port
+ }
+
+ const auth = username || password
+ ? {
+ username,
+ password
+ }
+ : undefined
+
+ if (auth) {
+ result = {
+ ...result,
+ auth
+ }
+ }
+
+ return result
+}
+
+export const fetchBtTrackerFromSource = async (source, proxyConfig = {}) => {
if (isEmpty(source)) {
return []
}
const now = Date.now()
- const promises = source.map((url) => {
- return axios.get(`${url}?t=${now}`).then((value) => value.data)
+ const { enable, server, scope = [] } = proxyConfig
+ const proxy = enable && server && scope.includes(PROXY_SCOPES.UPDATE_TRACKERS)
+ ? convertToAxiosProxy(server)
+ : undefined
+
+ console.log('fetchBtTrackerFromSource===>', source, proxy)
+ // Axios's config.proxy is Node.js only
+ const promises = source.map(async (url) => {
+ return axios.get(`${url}?t=${now}`, {
+ timeout: 30 * ONE_SECOND,
+ proxy
+ }).then((value) => value.data)
})
const results = await Promise.allSettled(promises)