Files
clash-proxy/src/components/layout/use-log-setup.ts

49 lines
1.4 KiB
TypeScript
Raw Normal View History

2022-02-23 02:00:45 +08:00
import dayjs from "dayjs";
import { useEffect, useState } from "react";
2022-09-24 19:03:14 +08:00
import { useRecoilValue, useSetRecoilState } from "recoil";
2022-02-23 02:00:45 +08:00
import { listen } from "@tauri-apps/api/event";
2022-08-06 02:35:11 +08:00
import { getInformation } from "@/services/api";
2022-09-05 20:30:39 +08:00
import { getClashLogs } from "@/services/cmds";
2022-09-24 19:03:14 +08:00
import { atomEnableLog, atomLogData } from "@/services/states";
2022-02-23 02:00:45 +08:00
const MAX_LOG_NUM = 1000;
// setup the log websocket
export default function useLogSetup() {
const [refresh, setRefresh] = useState({});
2022-09-20 22:15:28 +08:00
2022-09-24 19:03:14 +08:00
const enableLog = useRecoilValue(atomEnableLog);
2022-02-23 02:00:45 +08:00
const setLogData = useSetRecoilState(atomLogData);
useEffect(() => {
2022-09-20 22:15:28 +08:00
if (!enableLog) return;
2022-09-05 20:30:39 +08:00
getClashLogs().then(setLogData);
2022-02-23 02:00:45 +08:00
const handler = (event: MessageEvent<any>) => {
2022-11-19 17:22:29 +08:00
const data = JSON.parse(event.data) as ILogItem;
2022-02-23 02:00:45 +08:00
const time = dayjs().format("MM-DD HH:mm:ss");
setLogData((l) => {
if (l.length >= MAX_LOG_NUM) l.shift();
return [...l, { ...data, time }];
});
};
2022-09-24 19:03:14 +08:00
const ws = getInformation().then((info) => {
const { server = "", secret = "" } = info;
2022-09-24 19:03:14 +08:00
const ws = new WebSocket(`ws://${server}/logs?token=${secret}`);
2022-02-23 02:00:45 +08:00
ws.addEventListener("message", handler);
2022-09-24 19:03:14 +08:00
return ws;
});
2022-02-23 02:00:45 +08:00
const unlisten = listen("verge://refresh-clash-config", () =>
setRefresh({})
);
2022-02-23 02:00:45 +08:00
return () => {
2022-09-24 19:03:14 +08:00
ws.then((ws) => ws?.close());
unlisten.then((fn) => fn());
2022-02-23 02:00:45 +08:00
};
2022-09-20 22:15:28 +08:00
}, [refresh, enableLog]);
2022-02-23 02:00:45 +08:00
}