Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✨ 支持自定义资源服务器地址 #213

Merged
merged 5 commits into from
Dec 3, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions src-tauri/src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -288,3 +288,51 @@ pub async fn copy_file(source: PathBuf, target: PathBuf,) -> Result<(), String,>
.map_err(|err| format!("复制文件失败: {}", err),)?;
Ok((),)
}

use std::{
net::{IpAddr, Ipv4Addr, TcpListener},
sync::Mutex,
};

use tauri::State;
use warp::Filter;

use crate::state::AppState;

#[tauri::command]
pub async fn start_assets_server(
app_handle: AppHandle,
state: State<'_, Mutex<AppState,>,>,
host: String,
port: u16,
) -> Result<(), String,> {
let cors = warp::cors().allow_any_origin().allow_methods(vec!["GET"],);

let cache_dir = get_cache_file_path(app_handle,);

let route = warp::path("matcha",)
.and(warp::path("cache",),)
.and(warp::fs::dir(cache_dir,),)
.with(cors,);

let ip_addr: IpAddr = host
.parse()
.unwrap_or(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1,),),);

let mut state = state.lock().unwrap();
A-kirami marked this conversation as resolved.
Show resolved Hide resolved

state.stop_server();

let addr = format!("{}:{}", ip_addr, port);
match TcpListener::bind(&addr,) {
A-kirami marked this conversation as resolved.
Show resolved Hide resolved
Ok(_,) => {
let new_handle = tauri::async_runtime::spawn(async move {
warp::serve(route,).run((ip_addr, port,),).await;
},);

state.set_handle(new_handle,);
Ok((),)
}
Err(e,) => Err(e.to_string(),),
}
}
29 changes: 15 additions & 14 deletions src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,26 +1,26 @@
use tauri::Manager;

mod command;
mod server;
mod state;
mod utils;
use std::sync::Mutex;

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
.setup(|app| {
#[cfg(dev)]
app.get_webview_window("main",).unwrap().open_devtools();
let mut builder = tauri::Builder::default().setup(|app| {
#[cfg(dev)]
app.get_webview_window("main",).unwrap().open_devtools();

app.manage(Mutex::new(state::AppState::default(),),);

let cache_path = app.handle().path().app_cache_dir().unwrap();
let port: u16 = 8720;
server::start_static_file_server(cache_path, port,);
Ok((),)
},);

#[cfg(desktop)]
app.handle()
.plugin(tauri_plugin_updater::Builder::new().build(),)?;
#[cfg(desktop)]
{
builder = builder.plugin(tauri_plugin_updater::Builder::new().build(),)
}

Ok((),)
},)
builder
.plugin(tauri_plugin_os::init(),)
.plugin(tauri_plugin_fs::init(),)
.plugin(tauri_plugin_websocket::init(),)
Expand Down Expand Up @@ -49,6 +49,7 @@ pub fn run() {
command::merge_file_fragment,
command::write_file,
command::copy_file,
command::start_assets_server,
],)
.run(tauri::generate_context!(),)
.expect("error while running tauri application",);
Expand Down
38 changes: 0 additions & 38 deletions src-tauri/src/server.rs

This file was deleted.

16 changes: 16 additions & 0 deletions src-tauri/src/state.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
#[derive(Default,)]
pub struct AppState {
server_handle: Option<tauri::async_runtime::JoinHandle<(),>,>,
}

impl AppState {
pub(crate) fn set_handle(&mut self, handle: tauri::async_runtime::JoinHandle<(),>,) {
self.server_handle = Some(handle,);
}

pub(crate) fn stop_server(&mut self,) {
if let Some(handle,) = self.server_handle.take() {
handle.abort();
}
}
}
9 changes: 1 addition & 8 deletions src-tauri/src/utils.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{collections::HashMap, error::Error, fs, net::TcpListener, path::PathBuf, str};
use std::{collections::HashMap, error::Error, fs, path::PathBuf, str};

use base64::{engine::general_purpose, Engine as _};
use regex::Regex;
Expand Down Expand Up @@ -117,10 +117,3 @@ pub fn validate_file(
}
Ok((),)
}

pub fn get_unused_port() -> u16 {
let listener = TcpListener::bind("127.0.0.1:0",).unwrap();
let port = listener.local_addr().unwrap().port();
drop(listener,);
port
}
6 changes: 6 additions & 0 deletions src/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,12 @@ onBeforeMount(async () => {
await setWindowEffect()
await setAcrylicWindowEffect(general.applyAcrylicWindowEffects)
})

onMounted(async () => {
setTimeout(async () => {
await general.startAssetsServer(general.assetsServerAddress)
}, 500)
A-kirami marked this conversation as resolved.
Show resolved Hide resolved
})
</script>

<template>
Expand Down
17 changes: 17 additions & 0 deletions src/stores/general-settings.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { invoke } from '@tauri-apps/api/core'
import { defineStore } from 'pinia'
import { toast } from 'vue-sonner'

export interface GeneralSettings {
theme: 'light' | 'dark' | 'auto'
Expand All @@ -8,6 +10,7 @@ export interface GeneralSettings {
showRecallMessage: boolean
applyAcrylicWindowEffects: boolean
enableLinkPreview: boolean
assetsServerAddress: string
}

export const useGeneralSettingsStore = defineStore(
Expand All @@ -21,11 +24,23 @@ export const useGeneralSettingsStore = defineStore(
const showRecallMessage = $ref<GeneralSettings['showRecallMessage']>(true)
const applyAcrylicWindowEffects = $ref<GeneralSettings['applyAcrylicWindowEffects']>(false)
const enableLinkPreview = $ref<GeneralSettings['enableLinkPreview']>(true)
const assetsServerAddress = $ref<GeneralSettings['assetsServerAddress']>('127.0.0.1:8720')

async function startAssetsServer(address: string): Promise<void> {
const [host, port] = address.split(':')
await invoke('start_assets_server', { host, port: Number.parseInt(port) }).catch((error) => {
toast.error('资源服务器错误', { description: error })
})
}
A-kirami marked this conversation as resolved.
Show resolved Hide resolved

watch($$(applyAcrylicWindowEffects), async (enable) => {
await setAcrylicWindowEffect(enable)
})

watch($$(assetsServerAddress), async (address) => {
await startAssetsServer(address)
})

return $$({
theme,
autoUpdate,
Expand All @@ -34,6 +49,8 @@ export const useGeneralSettingsStore = defineStore(
showRecallMessage,
applyAcrylicWindowEffects,
enableLinkPreview,
assetsServerAddress,
startAssetsServer,
})
},

Expand Down
4 changes: 3 additions & 1 deletion src/utils/file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { invoke } from '@tauri-apps/api/core'
import { appCacheDir, join } from '@tauri-apps/api/path'
import { exists, BaseDirectory } from '@tauri-apps/plugin-fs'

const general = useGeneralSettingsStore()

interface FileSource {
str?: string
binary?: number[]
Expand Down Expand Up @@ -82,7 +84,7 @@ export async function getFile(type: GetType, fileId: string): Promise<string | U
}
switch (type) {
case GetType.URL: {
return `http://127.0.0.1:8720/matcha/cache/${file.sha256}`
return `http://${general.assetsServerAddress}/matcha/cache/${file.sha256}`
}
case GetType.PATH:
case GetType.DATA: {
Expand Down
11 changes: 11 additions & 0 deletions src/views/settings/general.vue
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ const generalSettingsSchema = toTypedSchema(
showRecallMessage: z.boolean(),
applyAcrylicWindowEffects: z.boolean(),
enableLinkPreview: z.boolean(),
assetsServerAddress: z.string().regex(/^(?:[0-9]{1,3}\.){3}[0-9]{1,3}:[0-9]{1,5}$/, '服务器地址格式不正确'),
}),
)

Expand Down Expand Up @@ -165,5 +166,15 @@ const osType = getOsType()
</FormControl>
</FormItem>
</FormField>
<FormField v-slot="{ componentField }" name="assetsServerAddress">
<FormItem v-auto-animate>
<FormLabel>资源服务器地址</FormLabel>
<FormControl>
<Input type="text" v-bind="componentField" class="h-9 max-w-100" />
</FormControl>
<FormDescription>指定用于提供资源文件的服务器地址</FormDescription>
<FormMessage />
</FormItem>
</FormField>
</form>
</template>
Loading