refactor: update MihomoManager to handle traffic WebSocket URL and authorization

This commit is contained in:
Tunglies
2025-03-09 14:43:58 +08:00
parent e1905aced4
commit 48f1da963a
7 changed files with 35 additions and 23 deletions

View File

@@ -1,16 +0,0 @@
use anyhow::Result;
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Rate {
pub up: u64,
pub down: u64,
}
#[cfg(target_os = "macos")]
pub fn get_traffic_ws_url() -> Result<String> {
use crate::module::mihomo::MihomoManager;
let (url, _) = MihomoManager::get_clash_client_info().unwrap();
let ws_url = url.replace("http://", "ws://") + "/traffic";
Ok(ws_url)
}

View File

@@ -1,5 +1,4 @@
pub mod backup;
pub mod clash_api;
#[allow(clippy::module_inception)]
mod core;
pub mod handle;

View File

@@ -1,7 +1,7 @@
use once_cell::sync::OnceCell;
#[cfg(target_os = "macos")]
pub mod speed_rate;
use crate::core::clash_api::Rate;
use crate::module::mihomo::Rate;
use crate::{
cmd,
config::Config,

View File

@@ -1,4 +1,5 @@
use crate::core::clash_api::{get_traffic_ws_url, Rate};
use crate::module::mihomo::Rate;
use crate::module::mihomo::MihomoManager;
use crate::utils::help::format_bytes_speed;
use ab_glyph::FontArc;
use anyhow::Result;
@@ -8,8 +9,9 @@ use imageproc::drawing::draw_text_mut;
use parking_lot::Mutex;
use std::io::Cursor;
use std::sync::Arc;
use tokio_tungstenite::tungstenite::http;
use tokio_tungstenite::tungstenite::Message;
use tungstenite::client::IntoClientRequest;
#[derive(Debug, Clone)]
pub struct SpeedRate {
rate: Arc<Mutex<(Rate, Rate)>>,
@@ -198,9 +200,13 @@ impl Traffic {
let stream = Box::pin(
stream::unfold((), |_| async {
loop {
let ws_url = get_traffic_ws_url().unwrap();
let (url, token) = MihomoManager::get_traffic_ws_url();
let mut request = url.into_client_request().unwrap();
request
.headers_mut()
.insert(http::header::AUTHORIZATION, token);
match tokio_tungstenite::connect_async(&ws_url).await {
match tokio_tungstenite::connect_async(request).await {
Ok((ws_stream, _)) => {
log::info!(target: "app", "traffic ws connection established");
return Some((