refactor: connect mihomo websocket

This commit is contained in:
oomeow
2025-10-04 10:53:44 +08:00
Unverified
parent f92b3527de
commit 04bbe7f544
15 changed files with 153 additions and 245 deletions

View File

@@ -1,4 +1,3 @@
import { listen } from "@tauri-apps/api/event";
import { useLocalStorage } from "foxact/use-local-storage";
import { useEffect, useRef } from "react";
import { mutate } from "swr";
@@ -17,28 +16,28 @@ export const useConnectionData = () => {
const ws = useRef<MihomoWebSocket | null>(null);
const wsFirstConnection = useRef<boolean>(true);
const listenerRef = useRef<() => void | null>(null);
const timeoutRef = useRef<ReturnType<typeof setTimeout>>(null);
const response = useSWRSubscription<IConnections, any, string | null>(
subscriptKey,
(_key, { next }) => {
const reconnect = async () => {
await ws.current?.close();
ws.current = null;
timeoutRef.current = setTimeout(async () => await connect(), 500);
};
const connect = () =>
MihomoWebSocket.connect_connections()
.then((ws_) => {
ws.current = ws_;
if (timeoutRef.current) clearTimeout(timeoutRef.current);
listenerRef.current = ws_.addListener(async (msg) => {
ws_.addListener(async (msg) => {
if (msg.type === "Text") {
if (msg.data.startsWith("Websocket error")) {
next(msg.data);
await ws.current?.close();
ws.current = null;
timeoutRef.current = setTimeout(
async () => await connect(),
500,
);
await reconnect();
} else {
const data = JSON.parse(msg.data) as IConnections;
next(null, (old = initConnData) => {
@@ -89,8 +88,6 @@ export const useConnectionData = () => {
return () => {
ws.current?.close();
listenerRef.current?.();
listenerRef.current = null;
};
},
{
@@ -99,20 +96,6 @@ export const useConnectionData = () => {
},
);
useEffect(() => {
const unlistenRefreshWebsocket = listen(
"verge://refresh-websocket",
async () => {
await ws.current?.close();
setDate(Date.now());
},
);
return () => {
unlistenRefreshWebsocket.then((fn) => fn());
};
}, [setDate]);
useEffect(() => {
mutate(`$sub$${subscriptKey}`);
}, [date, subscriptKey]);