Skip to content

Commit

Permalink
fix proxy
Browse files Browse the repository at this point in the history
  • Loading branch information
jlvihv committed Jun 17, 2024
1 parent 5dcb0fa commit 3d88795
Show file tree
Hide file tree
Showing 12 changed files with 141 additions and 23 deletions.
33 changes: 33 additions & 0 deletions src-tauri/src/kv.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::config::config_dir;
use crate::model::AppConfig;
use crate::model::LiveInfo;
use crate::model::QueryHistory;
use crate::model::RecordingHistory;
use crate::model::RecordingPlan;
use anyhow::Result;
Expand Down Expand Up @@ -385,6 +386,38 @@ pub mod live {
}
}

pub mod query_history {
use std::collections::VecDeque;

use super::*;

pub fn add(history: &QueryHistory) -> Result<()> {
let write_txn = db().begin_write()?;
{
let mut table = write_txn.open_table(TABLE)?;
let now = chrono::Utc::now().timestamp_millis();
let key = format!("query_history:{}:{}", history.url, now);
let history = serde_json::to_vec(history)?;
table.insert(key.as_str(), &*history)?;
}
write_txn.commit()?;
Ok(())
}

pub fn get_all() -> Result<Vec<QueryHistory>> {
let mut histories = VecDeque::new();
let read_txn = db().begin_read()?;
let table = read_txn.open_table(TABLE)?;
let iter = table.range("query_history:".."query_history")?;
for kv in iter {
let (_, history) = kv?;
let history: QueryHistory = serde_json::from_slice(&history.value())?;
histories.push_front(history);
}
Ok(histories.into())
}
}

mod tests {
#[test]
fn test_kv() {
Expand Down
2 changes: 1 addition & 1 deletion src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ pub fn run() {
manager::request_api::try_request_get_status,
manager::request_api::request_post,
manager::my_utils::get_youtube_info,
manager::my_utils::get_system_proxy_info,
manager::my_utils::get_system_proxy_config,
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
Expand Down
33 changes: 29 additions & 4 deletions src-tauri/src/manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -489,13 +489,35 @@ pub mod request_api {
}

pub mod my_utils {
use rusty_ytdl::{Video, VideoInfo};
use rusty_ytdl::{Video, VideoInfo, VideoOptions};

use crate::model::ProxyConfig;

use super::*;

#[tauri::command]
pub async fn get_youtube_info(url: String) -> Result<VideoInfo, String> {
let video = Video::new(&url).map_err(|e| format!("Could not get video info: {}", e))?;
let mut video_options = VideoOptions::default();
match get_system_proxy_config().await {
Ok(proxy) => {
video_options.request_options.proxy = if proxy.enabled {
match reqwest::Proxy::all(proxy.address) {
Ok(p) => Some(p),
Err(e) => {
println!("can not set system http proxy: {}", e);
None
}
}
} else {
None
};
}
Err(e) => {
println!("can not get system http proxy: {}", e);
}
}
let video = Video::new_with_options(&url, video_options)
.map_err(|e| format!("Could not get video info: {}", e))?;
let video_info = video
.get_info()
.await
Expand All @@ -504,10 +526,13 @@ pub mod my_utils {
}

#[tauri::command]
pub async fn get_system_proxy_info() -> Result<String, String> {
pub async fn get_system_proxy_config() -> Result<ProxyConfig, String> {
// 读取环境变量中的 http_proxy 或 HTTP_PROXY 或 all_proxy 或 ALL_PROXY
let proxy = sysproxy::Sysproxy::get_system_proxy()
.map_err(|e| format!("can not get system http proxy: {}", e.to_string()))?;
Ok(format!("http://{}:{}", proxy.host, proxy.port))
Ok(ProxyConfig {
enabled: proxy.enable,
address: format!("http://{}:{}", proxy.host, proxy.port),
})
}
}
15 changes: 15 additions & 0 deletions src-tauri/src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -310,3 +310,18 @@ pub mod platform {
}
}
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProxyConfig {
pub enabled: bool,
pub address: String,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct QueryHistory {
pub url: String,
pub anchor_name: String,
pub platform_kind: PlatformKind,
}
5 changes: 5 additions & 0 deletions src/lib/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,8 @@ export interface Stream {
resolution: string;
protocol: StreamingProtocol;
}

export interface ProxyConfig {
enabled: boolean;
address: string;
}
7 changes: 4 additions & 3 deletions src/lib/platform/douyin.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { LiveStatus, PlatformKind, StreamingProtocol, type LiveInfo } from '@/model';
import { getProxyForFetch } from '@/proxy';
// import { invoke } from '@tauri-apps/api/core';
import { fetch } from '@tauri-apps/plugin-http';

Expand All @@ -20,9 +21,11 @@ export async function getLiveInfoForDouyin(url: string): Promise<LiveInfo> {
method: 'GET',
headers: getHeaders(),
connectTimeout: 10000,
proxy: {
all: await getProxyForFetch()
}
});
let html = await resp.text();
console.log('douyin html', html);
// 解析 html,填充 LiveInfo
parseHtmlAndFillLiveInfo(html, info);
} catch (e) {
Expand Down Expand Up @@ -67,7 +70,6 @@ function parseHtmlAndFillLiveInfo(html: string, info: LiveInfo) {
}
let roomStore = roomStoreJsonStr.split(',"has_commerce_goods"')[0] + '}}}';
let jsonData = JSON.parse(roomStore);
console.log('jsonData', jsonData);
let room = jsonData.roomInfo.room;

// 2: 直播中,4: 未直播
Expand Down Expand Up @@ -98,7 +100,6 @@ function parseHtmlAndFillLiveInfo(html: string, info: LiveInfo) {
});
}
info.status = LiveStatus.Live;
console.log('info', info);
}

function getHeaders() {
Expand Down
7 changes: 5 additions & 2 deletions src/lib/platform/tiktok.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { LiveStatus, PlatformKind, StreamingProtocol, type LiveInfo, type Stream } from '@/model';
import { getProxyForFetch } from '@/proxy';
import { fetch } from '@tauri-apps/plugin-http';

export async function getLiveInfoForTiktok(url: string): Promise<LiveInfo> {
Expand All @@ -19,7 +20,10 @@ export async function getLiveInfoForTiktok(url: string): Promise<LiveInfo> {
let resp = await fetch(url, {
method: 'GET',
headers: getHeaders(),
connectTimeout: 10000
connectTimeout: 10000,
proxy: {
all: await getProxyForFetch()
}
});
let html = await resp.text();
// 解析 html,填充 LiveInfo
Expand All @@ -39,7 +43,6 @@ function parseHtmlAndFillLiveInfo(html: string, info: LiveInfo) {
throw new Error('can not match json string');
}
let json = JSON.parse(jsonStr[1]);
console.log('tiktok', json);
let liveRoom = json.LiveRoom.liveRoomUserInfo;
info.roomCover = liveRoom.liveRoom.coverUrl || '';
info.viewerCount = liveRoom.liveRoom.liveRoomStats.userCount.toString() || '';
Expand Down
4 changes: 4 additions & 0 deletions src/lib/platform/twitch.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { LiveStatus, PlatformKind, StreamingProtocol, type LiveInfo, type Stream } from '@/model';
import { getProxyForFetch } from '@/proxy';
import { fetch } from '@tauri-apps/plugin-http';

export async function getLiveInfoForTwitch(url: string): Promise<LiveInfo> {
Expand All @@ -20,6 +21,9 @@ export async function getLiveInfoForTwitch(url: string): Promise<LiveInfo> {
method: 'POST',
headers: getHeadersForStream(),
connectTimeout: 10000,
proxy: {
all: await getProxyForFetch()
},
body: JSON.stringify({
operationName: 'PlaybackAccessToken_Template',
query:
Expand Down
6 changes: 5 additions & 1 deletion src/lib/platform/xiaohongshu.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { LiveStatus, PlatformKind, StreamingProtocol, type LiveInfo } from '@/model';
import { getProxyForFetch } from '@/proxy';
import { invoke } from '@tauri-apps/api/core';
import { fetch } from '@tauri-apps/plugin-http';

Expand All @@ -23,7 +24,10 @@ export async function getLiveInfoForXiaohongshu(url: string): Promise<LiveInfo>
let resp = await fetch(appApi, {
method: 'GET',
headers: getHeaders(),
connectTimeout: 10000
connectTimeout: 10000,
proxy: {
all: await getProxyForFetch()
}
});
let json = JSON.parse(await resp.text());
if (json.code != 0) {
Expand Down
1 change: 0 additions & 1 deletion src/lib/platform/youtube.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ export async function getLiveInfoForYoutube(url: string): Promise<LiveInfo> {
};
try {
let youtubeInfo: any = await invoke('get_youtube_info', { url });
console.log('youtube info', youtubeInfo);
info.status = youtubeInfo.videoDetails.isLiveContent ? LiveStatus.Live : LiveStatus.NotLive;
info.viewerCount = youtubeInfo.videoDetails.viewCount;
info.title = youtubeInfo.videoDetails.title;
Expand Down
30 changes: 30 additions & 0 deletions src/lib/proxy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { invoke } from '@tauri-apps/api/core';
import type { ProxyConfig } from './model';

let proxyConfig: ProxyConfig | null = null;

export async function getProxyConfig(): Promise<ProxyConfig | null> {
if (proxyConfig === null) {
try {
proxyConfig = await invoke('get_system_proxy_config');
return proxyConfig;
} catch (e) {
console.error('get proxy info failed: ', e);
return null;
}
} else {
return proxyConfig;
}
}

export async function getProxyForFetch(): Promise<string | undefined> {
let config = await getProxyConfig();
if (config === null) {
return undefined;
}
if (config.enabled) {
return config.address;
} else {
return undefined;
}
}
21 changes: 10 additions & 11 deletions src/routes/record/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import { scale } from 'svelte/transition';
import { backOut } from 'svelte/easing';
import CollapsiblePanel from '@/components/CollapsiblePanel.svelte';
import { getProxyConfig } from '@/proxy';
// 关键信息变量
Expand Down Expand Up @@ -76,14 +77,6 @@
if (history) {
queryHistory = JSON.parse(history);
}
// 获取系统代理
try {
let proxy = await invoke('get_system_proxy_info');
console.log('proxy: ', proxy);
} catch (e) {
console.error('get system proxy error: ', e);
}
});
// 防抖调用 api, 500ms 内只调用一次
Expand Down Expand Up @@ -148,7 +141,10 @@
}
const checked = (event.target as HTMLInputElement).checked;
if (checked) {
recordingOption.useProxy = await invoke('get_system_proxy_info');
const proxyConfig = await getProxyConfig();
if (proxyConfig && recordingOption.useProxy === null) {
recordingOption.useProxy = proxyConfig.address;
}
} else {
recordingOption.useProxy = null;
}
Expand Down Expand Up @@ -332,7 +328,7 @@
liveInfo = undefined;
errorMessage = '';
useProxy = false;
recordingOption = {useProxy:null}
recordingOption.useProxy = null;
}}
>
<span
Expand Down Expand Up @@ -456,7 +452,10 @@
{#if recordStatus === RecordingStatus.NotRecording}
<CollapsiblePanel isOpen={advancedOptions} className="pt-12">
<div class="grid grid-cols-2 gap-4 pt-8">
<label for="useProxy" class="flex w-full cursor-pointer items-center gap-4">
<label
for="useProxy"
class="flex w-full cursor-pointer items-center gap-4 py-4"
>
<input
id="useProxy"
class="checkbox"
Expand Down

0 comments on commit 3d88795

Please sign in to comment.