import axios, { AxiosInstance } from 'axios' import { controledMihomoConfig } from '../config' import WebSocket from 'ws' import { window } from '..' let axiosIns: AxiosInstance = null! let mihomoTrafficWs: WebSocket = null! export const getAxios = async (force: boolean = false): Promise => { if (axiosIns && !force) return axiosIns let server = controledMihomoConfig['external-controller'] const secret = controledMihomoConfig.secret ?? '' if (server?.startsWith(':')) server = `127.0.0.1${server}` axiosIns = axios.create({ baseURL: `http://${server}`, proxy: false, headers: secret ? { Authorization: `Bearer ${secret}` } : {}, timeout: 15000 }) axiosIns.interceptors.response.use((r) => r.data) return axiosIns } export async function mihomoVersion(): Promise { const instance = await getAxios() return instance.get('/version') as Promise } export const mihomoConfig = async (): Promise => { const instance = await getAxios() return instance.get('/configs') as Promise } export const patchMihomoConfig = async (patch: Partial): Promise => { const instance = await getAxios() return instance.patch('/configs', patch) } export const mihomoConnections = async (): Promise => { const instance = await getAxios() return instance.get('/connections') as Promise } export const mihomoRules = async (): Promise => { const instance = await getAxios() return instance.get('/rules') as Promise } export const mihomoTraffic = (): void => { let server = controledMihomoConfig['external-controller'] const secret = controledMihomoConfig.secret ?? '' if (server?.startsWith(':')) server = `127.0.0.1${server}` mihomoTrafficWs = new WebSocket(`ws://${server}/traffic?secret=${secret}`) mihomoTrafficWs.onmessage = (e): void => { const data = e.data as string window?.webContents.send('mihomoTraffic', JSON.parse(data) as IMihomoTrafficInfo) } mihomoTrafficWs.onclose = (): void => { mihomoTraffic() } mihomoTrafficWs.onerror = (): void => { if (mihomoTrafficWs) { mihomoTrafficWs.close() mihomoTrafficWs = null! } } }