feat: event emit when clash config update

This commit is contained in:
GyDi 2022-03-13 01:37:41 +08:00
parent e1793f57ef
commit c1eb539a5c
No known key found for this signature in database
GPG Key ID: 1C95E0D3467B3084
5 changed files with 31 additions and 34 deletions

View File

@ -264,7 +264,7 @@ impl Clash {
/// activate the profile /// activate the profile
/// generate a new profile to the temp_dir /// generate a new profile to the temp_dir
/// then put the path to the clash core /// then put the path to the clash core
fn _activate(info: ClashInfo, config: Mapping) -> Result<()> { fn _activate(info: ClashInfo, config: Mapping, window: Option<Window>) -> Result<()> {
let temp_path = dirs::profiles_temp_path(); let temp_path = dirs::profiles_temp_path();
config::save_yaml(temp_path.clone(), &config, Some("# Clash Verge Temp File"))?; config::save_yaml(temp_path.clone(), &config, Some("# Clash Verge Temp File"))?;
@ -294,6 +294,12 @@ impl Clash {
if resp.status() != 204 { if resp.status() != 204 {
log::error!("failed to activate clash for status \"{}\"", resp.status()); log::error!("failed to activate clash for status \"{}\"", resp.status());
} }
// emit the window to update something
if let Some(window) = window {
window.emit("verge://refresh-clash-config", "yes").unwrap();
}
// do not retry // do not retry
break; break;
} }
@ -325,6 +331,7 @@ impl Clash {
// generate the payload // generate the payload
let payload = profiles.gen_enhanced(event_name.clone())?; let payload = profiles.gen_enhanced(event_name.clone())?;
let window = self.window.clone();
win.once(&event_name, move |event| { win.once(&event_name, move |event| {
if let Some(result) = event.payload() { if let Some(result) = event.payload() {
@ -359,7 +366,7 @@ impl Clash {
log::info!("profile enhanced status {}", result.status); log::info!("profile enhanced status {}", result.status);
Self::_activate(info, config).unwrap(); Self::_activate(info, config, window).unwrap();
} }
if let Some(error) = result.error { if let Some(error) = result.error {
@ -390,7 +397,7 @@ impl Clash {
config.insert(key, value); config.insert(key, value);
} }
Self::_activate(info, config)?; Self::_activate(info, config, self.window.clone())?;
self.activate_enhanced(profiles, delay) self.activate_enhanced(profiles, delay)
} }
} }

View File

@ -45,13 +45,8 @@ fn main() -> std::io::Result<()> {
let profiles_state = app_handle.state::<states::ProfilesState>(); let profiles_state = app_handle.state::<states::ProfilesState>();
let mut clash = clash_state.0.lock().unwrap(); let mut clash = clash_state.0.lock().unwrap();
let mut profiles = profiles_state.0.lock().unwrap(); let mut profiles = profiles_state.0.lock().unwrap();
match clash.restart_sidecar(&mut profiles) {
Ok(_) => { crate::log_if_err!(clash.restart_sidecar(&mut profiles));
let window = app_handle.get_window("main").unwrap();
window.emit("restart_clash", "yes").unwrap();
}
Err(err) => log::error!("{}", err),
}
} }
"quit" => { "quit" => {
resolve::resolve_reset(app_handle); resolve::resolve_reset(app_handle);

View File

@ -12,6 +12,7 @@ import useLogSetup from "./use-log-setup";
import useTrafficGraph from "./use-traffic-graph"; import useTrafficGraph from "./use-traffic-graph";
import parseTraffic from "../../utils/parse-traffic"; import parseTraffic from "../../utils/parse-traffic";
// setup the traffic
const LayoutTraffic = () => { const LayoutTraffic = () => {
const portValue = useRecoilValue(atomClashPort); const portValue = useRecoilValue(atomClashPort);
const [traffic, setTraffic] = useState({ up: 0, down: 0 }); const [traffic, setTraffic] = useState({ up: 0, down: 0 });
@ -26,12 +27,14 @@ const LayoutTraffic = () => {
useLogSetup(); useLogSetup();
useEffect(() => { useEffect(() => {
let unlisten: () => void = null!;
// should reconnect the traffic ws // should reconnect the traffic ws
listen("restart_clash", () => setRefresh({})).then((fn) => (unlisten = fn)); const unlisten = listen("verge://refresh-clash-config", () =>
setRefresh({})
);
return () => unlisten?.(); return () => {
unlisten.then((fn) => fn());
};
}, []); }, []);
useEffect(() => { useEffect(() => {

View File

@ -1,5 +1,5 @@
import dayjs from "dayjs"; import dayjs from "dayjs";
import { useEffect } from "react"; import { useEffect, useState } from "react";
import { useSetRecoilState } from "recoil"; import { useSetRecoilState } from "recoil";
import { listen } from "@tauri-apps/api/event"; import { listen } from "@tauri-apps/api/event";
import { ApiType } from "../../services/types"; import { ApiType } from "../../services/types";
@ -10,11 +10,11 @@ const MAX_LOG_NUM = 1000;
// setup the log websocket // setup the log websocket
export default function useLogSetup() { export default function useLogSetup() {
const [refresh, setRefresh] = useState({});
const setLogData = useSetRecoilState(atomLogData); const setLogData = useSetRecoilState(atomLogData);
useEffect(() => { useEffect(() => {
let ws: WebSocket = null!; let ws: WebSocket = null!;
let unlisten: () => void = null!;
const handler = (event: MessageEvent<any>) => { const handler = (event: MessageEvent<any>) => {
const data = JSON.parse(event.data) as ApiType.LogItem; const data = JSON.parse(event.data) as ApiType.LogItem;
@ -25,25 +25,19 @@ export default function useLogSetup() {
}); });
}; };
(async () => { getInfomation().then((info) => {
const { server = "", secret = "" } = await getInfomation(); const { server = "", secret = "" } = info;
ws = new WebSocket(`ws://${server}/logs?token=${secret}`); ws = new WebSocket(`ws://${server}/logs?token=${secret}`);
ws.addEventListener("message", handler); ws.addEventListener("message", handler);
});
// reconnect the websocket const unlisten = listen("verge://refresh-clash-config", () =>
unlisten = await listen("restart_clash", async () => { setRefresh({})
const { server = "", secret = "" } = await getInfomation(); );
ws?.close();
ws = new WebSocket(`ws://${server}/logs?token=${secret}`);
ws.addEventListener("message", handler);
});
})();
return () => { return () => {
ws?.close(); ws?.close();
unlisten?.(); unlisten?.then((fn) => fn());
}; };
}, []); }, [refresh]);
} }

View File

@ -30,12 +30,10 @@ const Layout = () => {
if (e.key === "Escape") appWindow.hide(); if (e.key === "Escape") appWindow.hide();
}); });
listen("restart_clash", async () => { listen("verge://refresh-clash-config", async () => {
// the clash info may be updated // the clash info may be updated
await getAxios(true); await getAxios(true);
// make sure that the clash is ok mutate("getProxies");
setTimeout(() => mutate("getProxies"), 1000);
setTimeout(() => mutate("getProxies"), 2000);
mutate("getClashConfig"); mutate("getClashConfig");
}); });
}, []); }, []);