| 1 | import log from 'electron-log/main.js' |
| 2 | import type Dispatcher from 'undici/types/dispatcher' |
| 3 | import { ProxyAgent, Socks5ProxyAgent, getGlobalDispatcher, setGlobalDispatcher } from 'undici' |
| 4 | |
| 5 | let originalDispatcher: Dispatcher | null = null |
| 6 | let currentProxyDispatcher: Dispatcher | null = null |
| 7 | |
| 8 | function isSocksUrl(url: string): boolean { |
| 9 | return url.startsWith('socks5://') || url.startsWith('socks://') |
| 10 | } |
| 11 | |
| 12 | export function applyProxy(proxyUrl: string | undefined): void { |
| 13 | if (!originalDispatcher) { |
| 14 | originalDispatcher = getGlobalDispatcher() |
| 15 | } |
| 16 | |
| 17 | if (!proxyUrl || !proxyUrl.trim()) { |
| 18 | clearProxy() |
| 19 | return |
| 20 | } |
| 21 | |
| 22 | const url = proxyUrl.trim() |
| 23 | const dispatcher = isSocksUrl(url) ? new Socks5ProxyAgent(url) : new ProxyAgent(url) |
| 24 | |
| 25 | closeCurrentProxy() |
| 26 | currentProxyDispatcher = dispatcher |
| 27 | setGlobalDispatcher(dispatcher) |
| 28 | log.info('[proxy] applied', url) |
| 29 | } |
| 30 | |
| 31 | export function clearProxy(): void { |
| 32 | if (!originalDispatcher) return |
| 33 | closeCurrentProxy() |
| 34 | setGlobalDispatcher(originalDispatcher) |
| 35 | log.info('[proxy] cleared, restored default dispatcher') |
| 36 | } |
| 37 | |
| 38 | function closeCurrentProxy(): void { |
| 39 | if (currentProxyDispatcher && typeof currentProxyDispatcher.close === 'function') { |
| 40 | void currentProxyDispatcher.close().catch(() => {}) |
| 41 | } |
| 42 | currentProxyDispatcher = null |
| 43 | } |
| 44 |