Skip to content

Commit

Permalink
fix(updater): should use nyanpasu proxy or system proxy when performi…
Browse files Browse the repository at this point in the history
…ng request (#273)

* fix(updater): core updater should use nyanpasu proxy or system proxy when preforming request

* fix: lint
  • Loading branch information
greenhat616 authored Jan 16, 2024
1 parent 04cb5c4 commit dc582b4
Show file tree
Hide file tree
Showing 21 changed files with 173 additions and 81 deletions.
7 changes: 5 additions & 2 deletions backend/sysproxy-rs/src/macos.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
use crate::{Error, Result, Sysproxy};
use std::net::{SocketAddr, UdpSocket};
use std::{process::Command, str::from_utf8};
use std::{
net::{SocketAddr, UdpSocket},
process::Command,
str::from_utf8,
};

impl Sysproxy {
pub fn get_system_proxy() -> Result<Sysproxy> {
Expand Down
17 changes: 10 additions & 7 deletions backend/sysproxy-rs/src/windows.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
use crate::{Error, Result, Sysproxy};
use iptools::iprange::IpRange;
use iptools::ipv4::validate_cidr;
use std::ffi::c_void;
use std::{mem::size_of, mem::ManuallyDrop, net::SocketAddr, str::FromStr};
use windows::core::PWSTR;
use windows::Win32::NetworkManagement::Rras::{
RasEnumEntriesW, ERROR_BUFFER_TOO_SMALL, RASENTRYNAMEW,
use iptools::{iprange::IpRange, ipv4::validate_cidr};
use std::{
ffi::c_void,
mem::{size_of, ManuallyDrop},
net::SocketAddr,
str::FromStr,
};
use windows::{
core::PWSTR,
Win32::NetworkManagement::Rras::{RasEnumEntriesW, ERROR_BUFFER_TOO_SMALL, RASENTRYNAMEW},
};

use windows::Win32::Networking::WinInet::{
Expand Down
4 changes: 2 additions & 2 deletions backend/tauri/src/cmds.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
use crate::{
config::*,
core::{tasks::jobs::ProfilesJobGuard, updater::ManifestVersionLatest, *},
feat,
feat, ret_err,
utils::{
candy, dirs, help,
resolve::{self, save_window_state},
},
wrap_err,
};
use crate::{ret_err, wrap_err};
use anyhow::{Context, Result};
use chrono::Local;
use log::debug;
Expand Down
8 changes: 1 addition & 7 deletions backend/tauri/src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,4 @@ mod profiles;
mod runtime;
mod verge;

pub use self::clash::*;
pub use self::config::*;
pub use self::draft::*;
pub use self::prfitem::*;
pub use self::profiles::*;
pub use self::runtime::*;
pub use self::verge::*;
pub use self::{clash::*, config::*, draft::*, prfitem::*, profiles::*, runtime::*, verge::*};
2 changes: 1 addition & 1 deletion backend/tauri/src/config/prfitem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ impl PrfItem {
builder = builder.proxy(proxy);
}
}
_ => {}
_ => todo!(),
};
}

Expand Down
3 changes: 1 addition & 2 deletions backend/tauri/src/core/core.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use super::{clash_api, logger::Logger};
use crate::log_err;
use crate::{config::*, utils::dirs};
use crate::{config::*, log_err, utils::dirs};
use anyhow::{bail, Context, Result};
use once_cell::sync::OnceCell;
use parking_lot::Mutex;
Expand Down
14 changes: 9 additions & 5 deletions backend/tauri/src/core/tasks/events.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
use chrono::Utc;
use serde::{Deserialize, Serialize};

use super::storage::EventsGuard;
use super::task::{TaskEventID, TaskID, TaskRunResult, Timestamp};
use super::utils::Result;
use std::collections::HashMap;
use std::sync::{Arc, OnceLock};
use super::{
storage::EventsGuard,
task::{TaskEventID, TaskID, TaskRunResult, Timestamp},
utils::Result,
};
use std::{
collections::HashMap,
sync::{Arc, OnceLock},
};
pub struct TaskEvents;

pub trait TaskEventsDispatcher {
Expand Down
20 changes: 13 additions & 7 deletions backend/tauri/src/core/tasks/jobs/logger.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,20 @@
use super::JobExt;
use crate::config::Config;
use crate::core::tasks::executor::{AsyncJobExecutor, TaskExecutor};
use crate::core::tasks::task::TaskSchedule;
use crate::utils::dirs;
use crate::{
config::Config,
core::tasks::{
executor::{AsyncJobExecutor, TaskExecutor},
task::TaskSchedule,
},
utils::dirs,
};
use anyhow::Result;
use async_trait::async_trait;
use chrono::{DateTime, Local, TimeZone};
use std::fs::{self, DirEntry};
use std::str::FromStr;
use std::time::Duration;
use std::{
fs::{self, DirEntry},
str::FromStr,
time::Duration,
};

const CLEAR_LOG_TASK_NAME: &str = "clear_logs";

Expand Down
7 changes: 3 additions & 4 deletions backend/tauri/src/core/tasks/jobs/profiles.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
use super::super::{
executor::AsyncJobExecutor,
executor::TaskExecutor,
executor::{AsyncJobExecutor, TaskExecutor},
task::{Task, TaskID, TaskManager, TaskSchedule},
};
use crate::{config::Config, feat};
use anyhow::Result;
use async_trait::async_trait;
use parking_lot::Mutex;
use std::hash::{Hash, Hasher};
use std::sync::{Arc, OnceLock};
use std::{
collections::{hash_map::DefaultHasher, HashMap},
hash::{Hash, Hasher},
sync::{Arc, OnceLock},
time::Duration,
};

Expand Down
17 changes: 10 additions & 7 deletions backend/tauri/src/core/tasks/storage.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
// store is a interface to save and restore task states
use super::task::{TaskEventID, TaskManager};
use super::utils::Result;
use super::{events::TaskEvent, task::TaskID};
use crate::core::storage::Storage;
use crate::core::tasks::task::Task;
use super::{
events::TaskEvent,
task::{TaskEventID, TaskID, TaskManager},
utils::Result,
};
use crate::core::{storage::Storage, tasks::task::Task};
use log::debug;
use std::str;
use std::sync::{Arc, OnceLock};
use std::{
str,
sync::{Arc, OnceLock},
};

pub struct EventsGuard;

Expand Down
9 changes: 6 additions & 3 deletions backend/tauri/src/core/tasks/task.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use super::storage::TaskGuard;
use super::{
events::{TaskEventState, TaskEvents, TaskEventsDispatcher},
executor::{AsyncJob, Job, TaskExecutor},
storage::TaskGuard,
utils::{Error, Result, TaskCreationError},
};
use crate::error;
Expand All @@ -14,8 +14,11 @@ use delay_timer::{
use parking_lot::{Mutex, RwLock as RW};
use serde::{Deserialize, Serialize};
use snowflake::SnowflakeIdGenerator;
use std::sync::OnceLock;
use std::{collections::HashMap, sync::Arc, time::Duration};
use std::{
collections::HashMap,
sync::{Arc, OnceLock},
time::Duration,
};

pub type TaskID = u64;
pub type TaskEventID = i64; // 任务事件 ID,适用于任务并发执行,区分不同的执行事件
Expand Down
6 changes: 3 additions & 3 deletions backend/tauri/src/core/updater.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ impl Updater {
}

async fn get_mihomo_alpha_version(&self) -> Result<String> {
let client = reqwest::Client::new();
let client = crate::utils::candy::get_reqwest_client()?;
let url = format!(
"{}/{}",
self.mirror.as_str(),
Expand Down Expand Up @@ -272,7 +272,7 @@ impl Updater {
debug!("file path: {:?}", file_path);
let mut dst = std::fs::File::create(&file_path)?;

let client = reqwest::Client::new();
let client = crate::utils::candy::get_reqwest_client()?;
let res = client.get(url).send().await?;
let status_code = res.status();
if !status_code.is_success() {
Expand Down Expand Up @@ -345,7 +345,7 @@ pub async fn get_latest_version_manifest(mirror: &str) -> Result<ManifestVersion
mirror
);
log::debug!("{}", url);
let client = reqwest::Client::new();
let client = crate::utils::candy::get_reqwest_client()?;
let res = client.get(url).send().await?;
let status_code = res.status();
if !status_code.is_success() {
Expand Down
15 changes: 8 additions & 7 deletions backend/tauri/src/core/win_service.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
#![cfg(target_os = "windows")]

use crate::config::{ClashCore, Config};
use crate::utils::dirs;
use crate::{
config::{ClashCore, Config},
utils::dirs,
};
use anyhow::{bail, Context, Result};
use deelevate::{PrivilegeLevel, Token};
use runas::Command as RunasCommand;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::os::windows::process::CommandExt;
use std::path::PathBuf;
use std::time::Duration;
use std::{env::current_exe, process::Command as StdCommand};
use std::{
collections::HashMap, env::current_exe, os::windows::process::CommandExt, path::PathBuf,
process::Command as StdCommand, time::Duration,
};
use tokio::time::sleep;

const SERVICE_URL: &str = "http://127.0.0.1:33211";
Expand Down
8 changes: 2 additions & 6 deletions backend/tauri/src/enhance/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,10 @@ mod tun;

pub(self) use self::field::*;

use self::chain::*;
use self::merge::*;
use self::script::*;
use self::tun::*;
use self::{chain::*, merge::*, script::*, tun::*};
use crate::config::Config;
use serde_yaml::Mapping;
use std::collections::HashMap;
use std::collections::HashSet;
use std::collections::{HashMap, HashSet};

type ResultLog = Vec<(String, String)>;

Expand Down
5 changes: 1 addition & 4 deletions backend/tauri/src/feat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,7 @@
//! - timer 定时器
//! - cmds 页面调用
//!
use crate::config::*;
use crate::core::*;
use crate::log_err;
use crate::utils::resolve;
use crate::{config::*, core::*, log_err, utils::resolve};
use anyhow::{bail, Result};
use serde_yaml::{Mapping, Value};
use wry::application::clipboard::Clipboard;
Expand Down
14 changes: 13 additions & 1 deletion backend/tauri/src/utils/candy.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
use super::dirs::app_logs_dir;
use super::{config::NyanpasuReqwestProxyExt, dirs::app_logs_dir};
use anyhow::Result;
use chrono::Local;
use glob::glob;
use std::path::Path;
use zip::ZipWriter;

pub fn collect_logs(target_path: &Path) -> Result<()> {
let logs_dir = app_logs_dir()?;
let now = Local::now().format("%Y-%m-%d");
Expand All @@ -26,3 +27,14 @@ pub fn collect_logs(target_path: &Path) -> Result<()> {
zip.finish()?;
Ok(())
}

// TODO: 添加自定义 User-Agent 等配置,说白了就是重构一下 prfitem 的那坨代码
pub fn get_reqwest_client() -> Result<reqwest::Client> {
let builder = reqwest::ClientBuilder::new();
let app_version = super::dirs::get_app_version();
let client = builder
.swift_set_nyanpasu_proxy()
.user_agent(format!("clash-nyanpasu/{}", app_version))
.build()?;
Ok(client)
}
60 changes: 60 additions & 0 deletions backend/tauri/src/utils/config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
use anyhow::Result;
use sysproxy::Sysproxy;

use crate::config::Config;

pub fn get_self_proxy() -> Result<String> {
let port = Config::verge()
.latest()
.verge_mixed_port
.unwrap_or(Config::clash().data().get_mixed_port());

let proxy_scheme = format!("http://127.0.0.1:{port}");
Ok(proxy_scheme)
}

pub fn get_system_proxy() -> Result<Option<String>> {
let p = Sysproxy::get_system_proxy()?;
if p.enable {
let proxy_scheme = format!("http://{}:{}", p.host, p.port);
return Ok(Some(proxy_scheme));
}

Ok(None)
}

pub trait NyanpasuReqwestProxyExt {
fn swift_set_proxy(self, url: &str) -> Self;

fn swift_set_nyanpasu_proxy(self) -> Self;
}

impl NyanpasuReqwestProxyExt for reqwest::ClientBuilder {
fn swift_set_proxy(self, url: &str) -> Self {
let mut builder = self;
if let Ok(proxy) = reqwest::Proxy::http(url) {
builder = builder.proxy(proxy);
}
if let Ok(proxy) = reqwest::Proxy::https(url) {
builder = builder.proxy(proxy);
}
if let Ok(proxy) = reqwest::Proxy::all(url) {
builder = builder.proxy(proxy);
}
builder
}

// TODO: 修改成按枚举配置
fn swift_set_nyanpasu_proxy(self) -> Self {
let mut builder = self;
if let Ok(proxy) = get_self_proxy() {
builder = builder.swift_set_proxy(&proxy);
}
if let Ok(proxy) = get_system_proxy() {
if let Some(proxy) = proxy {
builder = builder.swift_set_proxy(&proxy);
}
}
builder
}
}
6 changes: 5 additions & 1 deletion backend/tauri/src/utils/dirs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,11 @@ static mut RESOURCE_DIR: Option<PathBuf> = None;
#[allow(unused)]
static mut PORTABLE_FLAG: bool = false;

pub static mut APP_VERSION: &str = env!("NYANPASU_VERSION");
pub static APP_VERSION: &str = env!("NYANPASU_VERSION");

pub fn get_app_version() -> &'static str {
APP_VERSION
}

/// initialize portable flag
#[cfg(target_os = "windows")]
Expand Down
15 changes: 9 additions & 6 deletions backend/tauri/src/utils/init.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
use crate::config::*;
use crate::utils::{dirs, help};
use crate::{
config::*,
utils::{dirs, help},
};
use anyhow::Result;
use chrono::Local;
use log::LevelFilter;
use log4rs::append::console::ConsoleAppender;
use log4rs::append::file::FileAppender;
use log4rs::config::{Appender, Logger, Root};
use log4rs::encode::pattern::PatternEncoder;
use log4rs::{
append::{console::ConsoleAppender, file::FileAppender},
config::{Appender, Logger, Root},
encode::pattern::PatternEncoder,
};
use std::fs;
use tauri::PackageInfo;

Expand Down
Loading

0 comments on commit dc582b4

Please sign in to comment.