@@ -7,6 +7,7 @@ let axiosIns: AxiosInstance = null!
7
7
let mihomoTrafficWs : WebSocket | null = null
8
8
let mihomoMemoryWs : WebSocket | null = null
9
9
let mihomoLogsWs : WebSocket | null = null
10
+ let mihomoConnectionsWs : WebSocket | null = null
10
11
11
12
export const getAxios = async ( force : boolean = false ) : Promise < AxiosInstance > => {
12
13
if ( axiosIns && ! force ) return axiosIns
@@ -46,13 +47,6 @@ export const patchMihomoConfig = async (patch: Partial<IMihomoConfig>): Promise<
46
47
} ) ) as Promise < void >
47
48
}
48
49
49
- export const mihomoConnections = async ( ) : Promise < IMihomoConnectionsInfo > => {
50
- const instance = await getAxios ( )
51
- return ( await instance . get ( '/connections' ) . catch ( ( ) => {
52
- return { downloadTotal : 0 , uploadTotal : 0 , connections : [ ] , memory : 0 }
53
- } ) ) as IMihomoConnectionsInfo
54
- }
55
-
56
50
export const mihomoCloseConnection = async ( id : string ) : Promise < void > => {
57
51
const instance = await getAxios ( )
58
52
return ( await instance . delete ( `/connections/${ encodeURIComponent ( id ) } ` ) . catch ( ( e ) => {
@@ -230,3 +224,44 @@ const mihomoLogs = (): void => {
230
224
}
231
225
}
232
226
}
227
+
228
+ export const startMihomoConnections = ( ) : void => {
229
+ mihomoConnections ( )
230
+ }
231
+
232
+ export const stopMihomoConnections = ( ) : void => {
233
+ if ( mihomoConnectionsWs ) {
234
+ mihomoConnectionsWs . removeAllListeners ( )
235
+ if ( mihomoConnectionsWs . readyState === WebSocket . OPEN ) {
236
+ mihomoConnectionsWs . close ( )
237
+ }
238
+ mihomoConnectionsWs = null
239
+ }
240
+ }
241
+
242
+ const mihomoConnections = ( ) : void => {
243
+ let server = getControledMihomoConfig ( ) [ 'external-controller' ]
244
+ const secret = getControledMihomoConfig ( ) . secret ?? ''
245
+ if ( server ?. startsWith ( ':' ) ) server = `127.0.0.1${ server } `
246
+ stopMihomoConnections ( )
247
+
248
+ mihomoConnectionsWs = new WebSocket (
249
+ `ws://${ server } /connections?token=${ encodeURIComponent ( secret ) } `
250
+ )
251
+
252
+ mihomoConnectionsWs . onmessage = ( e ) : void => {
253
+ const data = e . data as string
254
+ window ?. webContents . send ( 'mihomoConnections' , JSON . parse ( data ) as IMihomoConnectionsInfo )
255
+ }
256
+
257
+ mihomoConnectionsWs . onclose = ( ) : void => {
258
+ mihomoConnections ( )
259
+ }
260
+
261
+ mihomoConnectionsWs . onerror = ( ) : void => {
262
+ if ( mihomoConnectionsWs ) {
263
+ mihomoConnectionsWs . close ( )
264
+ mihomoConnectionsWs = null
265
+ }
266
+ }
267
+ }
0 commit comments