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 all commits
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
12 changes: 12 additions & 0 deletions src-tauri/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
anyhow = "1.0"
tokio = "1.4"
tokio-stream = { version = "0.1", features = ["net"] }
log = "0.4"
infer = "0.16"
warp = "0.3"
Expand Down
42 changes: 42 additions & 0 deletions src-tauri/src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -288,3 +288,45 @@ pub async fn copy_file(source: PathBuf, target: PathBuf,) -> Result<(), String,>
.map_err(|err| format!("复制文件失败: {}", err),)?;
Ok((),)
}

use tauri::State;
use tokio::{net::TcpListener, sync::Mutex};
use tokio_stream::wrappers::TcpListenerStream;
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 cache_dir = get_cache_file_path(app_handle,);

let cors = warp::cors().allow_any_origin().allow_methods(vec!["GET"],);

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

let mut state = state.lock().await;

state.stop_server();

let addr = format!("{}:{}", host, port);
match TcpListener::bind(&addr,).await {
Ok(listener,) => {
let new_handle = tauri::async_runtime::spawn(async move {
let stream = TcpListenerStream::new(listener,);
warp::serve(route,).run_incoming(stream,).await;
},);

state.set_handle(new_handle,);
Ok((),)
}
Err(e,) => Err(e.to_string(),),
}
}
54 changes: 28 additions & 26 deletions src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,43 +1,44 @@
use tauri::{Manager, WebviewUrl, WebviewWindowBuilder};

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

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
.setup(|app| {
let win_builder = WebviewWindowBuilder::new(app, "main", WebviewUrl::default(),)
.title("Matcha",)
.min_inner_size(620.0, 540.0,)
.inner_size(1080.0, 720.0,)
.center();
let mut builder = tauri::Builder::default().setup(|app| {
let win_builder = WebviewWindowBuilder::new(app, "main", WebviewUrl::default(),)
.title("Matcha",)
.min_inner_size(620.0, 540.0,)
.inner_size(1080.0, 720.0,)
.center();

#[cfg(not(target_os = "macos"))]
let win_builder = win_builder.decorations(false,).transparent(true,);
#[cfg(not(target_os = "macos"))]
let win_builder = win_builder.decorations(false,).transparent(true,);

#[cfg(target_os = "macos")]
let win_builder = win_builder
.decorations(true,)
.hidden_title(true,)
.title_bar_style(tauri::TitleBarStyle::Overlay,);
#[cfg(target_os = "macos")]
let win_builder = win_builder
.decorations(true,)
.hidden_title(true,)
.title_bar_style(tauri::TitleBarStyle::Overlay,);

let window = win_builder.build().unwrap();
let window = win_builder.build().unwrap();

#[cfg(dev)]
if tauri::is_dev() {
window.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 @@ -66,6 +67,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
}
2 changes: 2 additions & 0 deletions src/layouts/default.vue
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ onMounted(async () => {

const general = useGeneralSettingsStore()

await general.startAssetsServer(general.assetsServerAddress)

if (isRelease && general.autoUpdate) {
try {
const update = await check()
Expand Down
20 changes: 20 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,26 @@ 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(':')
try {
await invoke('start_assets_server', { host, port: Number.parseInt(port) })
toast.success('资源服务器已启动', { description: `地址: ${address}` })
} catch (error) {
toast.error('资源服务器错误', { description: error as string })
}
}

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

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

return $$({
theme,
autoUpdate,
Expand All @@ -34,6 +52,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