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

37 lines
1.1 KiB
TypeScript
Raw Normal View History

2022-02-23 02:00:45 +08:00
import dayjs from "dayjs";
2022-11-23 17:44:40 +08:00
import { useEffect } from "react";
2022-09-24 19:03:14 +08:00
import { useRecoilValue, useSetRecoilState } from "recoil";
2022-09-05 20:30:39 +08:00
import { getClashLogs } from "@/services/cmds";
2022-11-23 17:44:40 +08:00
import { useClashInfo } from "@/hooks/use-clash";
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
2022-11-23 17:44:40 +08:00
export const useLogSetup = () => {
const { clashInfo } = useClashInfo();
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-11-23 17:44:40 +08:00
if (!enableLog || !clashInfo) return;
2022-09-20 22:15:28 +08:00
2022-09-05 20:30:39 +08:00
getClashLogs().then(setLogData);
2022-11-23 17:44:40 +08:00
const { server = "", secret = "" } = clashInfo;
const ws = new WebSocket(`ws://${server}/logs?token=${secret}`);
ws.addEventListener("message", (event) => {
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-02-23 02:00:45 +08:00
2022-11-23 17:44:40 +08:00
return () => ws?.close();
}, [clashInfo, enableLog]);
};