Skip to content

Commit

Permalink
improvement: set proxy rules
Browse files Browse the repository at this point in the history
  • Loading branch information
zhanglun committed May 28, 2024
1 parent 403628d commit 1e420f9
Show file tree
Hide file tree
Showing 7 changed files with 385 additions and 125 deletions.
30 changes: 27 additions & 3 deletions src-tauri/src/core/config.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
use chrono::{TimeZone, Utc};
use dotenv::dotenv;
use serde::{Deserialize, Serialize};
use std::{env, fs, path, path::PathBuf};
use std::{
collections::HashSet,
env, fs,
path::{self, PathBuf},
};
use toml;

#[derive(Debug, Serialize, Deserialize)]
Expand Down Expand Up @@ -67,10 +71,11 @@ pub struct UserConfig {
pub last_sync_time: String,

pub proxy: Option<Vec<Proxy>>,
pub proxy_rules: Vec<String>,

pub customize_style: CustomizeStyle,
pub purge_on_days: u64,
pub purge_unread_articles: bool,
pub proxy_rules: Vec<String>,
}

impl Default for UserConfig {
Expand Down Expand Up @@ -226,10 +231,15 @@ pub fn add_proxy(proxy_cfg: Proxy) -> Result<Option<Vec<Proxy>>, String> {
}
}

pub fn update_proxy(id: String, proxy_cfg: Proxy) -> Result<Option<Vec<Proxy>>, String> {
pub fn update_proxy(
id: String,
proxy_cfg: Proxy,
allow_list: Vec<String>,
) -> Result<Option<Vec<Proxy>>, String> {
let mut data = get_user_config();
let user_config_path = get_user_config_path();
let mut proxies = data.proxy.unwrap_or_default();
let mut rules: Vec<String> = vec![];

if let Some(proxy) = proxies
.iter_mut()
Expand All @@ -240,9 +250,23 @@ pub fn update_proxy(id: String, proxy_cfg: Proxy) -> Result<Option<Vec<Proxy>>,
proxy.enable = proxy_cfg.enable;
proxy.username = proxy_cfg.username;
proxy.password = proxy_cfg.password;

rules = allow_list
.into_iter()
.map(|l| format!("{}:{},{}", proxy.server, proxy.port, l))
.collect();
}

let set: HashSet<String> = data
.proxy_rules
.into_iter()
.chain(rules.into_iter())
.collect();

rules = set.into_iter().collect();

data.proxy = Some(proxies);
data.proxy_rules = rules;

let content = toml::to_string(&data).unwrap();

Expand Down
36 changes: 36 additions & 0 deletions src-tauri/src/feed/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,38 @@ pub fn create_client() -> reqwest::Client {
client_builder.build().unwrap()
}

pub fn find_proxy(url: &str) -> Option<config::Proxy>{
let user_config = config::get_user_config();
let proxies = user_config.proxy;
let rules = user_config.proxy_rules;

let mut server_port = "";

for elem in rules.iter() {
let parts: Vec<_> = elem.split(",").collect();

if parts.len() >= 2 && parts[1] == url {
server_port = parts[0].clone();
}
}

match proxies {
Some(proxies) => {
for proxy in proxies.into_iter() {
let key = format!("{}:{}", proxy.server, proxy.port);

if key == server_port && proxy.enable {
return Some(proxy);
}
}
None
},
None => {
None
}
}
}

/// request feed, parse Feeds
///
/// # Examples
Expand All @@ -46,6 +78,10 @@ pub async fn parse_feed(url: &str) -> Result<feed_rs::model::Feed, String> {
let client = create_client();
let result = client.get(url).send().await;

let proxy = find_proxy(url);

println!("proxy !!!==>{:?}", proxy);

let a = match result {
Ok(response) => match response.status() {
reqwest::StatusCode::OK => {
Expand Down
7 changes: 4 additions & 3 deletions src-tauri/src/server/handlers/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,13 +50,14 @@ pub async fn handle_add_proxy(proxy_cfg: web::Json<config::Proxy>) -> Result<imp
#[derive(Debug, Serialize, Deserialize)]
pub struct UpdateProxyBody {
id: String,
data: config::Proxy,
proxy: config::Proxy,
rules: Vec<String>,
}

#[post("/api/proxy")]
pub async fn handle_update_proxy(body: web::Json<UpdateProxyBody>) -> Result<impl Responder> {
let body = body.into_inner();
let result = config::update_proxy(body.id, body.data);
let result = config::update_proxy(body.id, body.proxy, body.rules);

let response = match result {
Ok(proxies) => HttpResponse::Ok().json(proxies),
Expand All @@ -69,7 +70,7 @@ pub async fn handle_update_proxy(body: web::Json<UpdateProxyBody>) -> Result<imp
#[delete("/api/proxy")]
pub async fn handle_delete_proxy(body: web::Json<UpdateProxyBody>) -> Result<impl Responder> {
let body = body.into_inner();
let result = config::delete_proxy(body.id, body.data);
let result = config::delete_proxy(body.id, body.proxy);


println!("--->{:?}", result);
Expand Down
2 changes: 1 addition & 1 deletion src/components/ArticleView/Detail.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ export const ArticleDetail = (props: ArticleDetailProps) => {
<div className="flex items-center gap-2 rounded-full bg-[var(--gray-4)] pr-3">
<Avatar
radius="full"
className="w-8 h-8"
className="w-6 h-6"
src={store.feed?.logo || ico}
fallback={article.feed_title?.slice(0, 1)}
></Avatar>
Expand Down
118 changes: 118 additions & 0 deletions src/layout/Setting/Proxy/AddProxyRuleModal.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
import { request } from "@/helpers/request";
import { Avatar, Badge, Button, Checkbox, Dialog, Popover, Separator, TextField } from "@radix-ui/themes";
import { ChangeEvent, useCallback, useEffect, useState } from "react";
import { toast } from "sonner";
import { PlusCircle } from "lucide-react";
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
CommandSeparator,
} from "@/components/ui/command";
import { FeedResItem } from "@/db";
import { getChannelFavicon } from "@/helpers/parseXML";

export interface AddProxyRuleModalProps {
feedList: FeedResItem[];
value: FeedResItem[];
onValueChange: (values: FeedResItem[]) => void;
}

export const AddProxyRuleModal = (props: AddProxyRuleModalProps) => {
const { feedList, value, onValueChange } = props;
const [selectedValues, setSelectValues] = useState<FeedResItem[]>([]);

// const handleSave = () => {
// const params = {
//
// };
//
// console.log("%c Line:15 🍅 params", "color:#ea7e5c", params);
// let fn = proxy
// ? request.post("proxy", {
// id: `socks5://${proxy.server}:${proxy.port}`,
// data: {
// ...params,
// enable: proxy.enable,
// },
// })
// : request.put("proxy", {
// ...params,
// enable: false,
// });
//
// fn.then(({ data }) => {
// console.log(data);
// if (data.error) {
// toast.error(data.error);
// } else {
// }
// });
// };

function handleChange(values: FeedResItem[]) {
onValueChange(values);
}

return (
<Popover.Root>
<Popover.Trigger>
<Button variant="outline">
<PlusCircle size={16} />
</Button>
</Popover.Trigger>
<Popover.Content className="w-[462px] p-0" align="start">
<Command>
<CommandInput placeholder="Searching" />
<CommandList>
<CommandEmpty>No results found.</CommandEmpty>
<CommandGroup>
{feedList.map((option) => {
const isSelected = selectedValues.some((s) => s.link === option.link);
return (
<CommandItem
key={option.id}
onSelect={() => {
let values = [];

if (isSelected) {
values = selectedValues.filter((s) => s.link !== option.link);
} else {
values = [...selectedValues, option];
}

setSelectValues(values);
handleChange(values);
}}
>
<Checkbox checked={isSelected} className="mr-2" />
<Avatar
src={getChannelFavicon(option.link)}
fallback={option.title.slice(0, 1)}
alt={option.title}
size="1"
/>
<span>{option.title}</span>
</CommandItem>
);
})}
</CommandGroup>
{selectedValues.length > 0 && (
<>
<CommandSeparator />
<CommandGroup>
<CommandItem onSelect={() => {}} className="justify-center text-center">
Clear filters
</CommandItem>
</CommandGroup>
</>
)}
</CommandList>
</Command>
</Popover.Content>
</Popover.Root>
);
};
Loading

0 comments on commit 1e420f9

Please sign in to comment.