mirror of
https://github.com/cap153/LANChat.git
synced 2026-12-06 08:01:41 +00:00
桌面端增加cli参数、端口配置保存到配置文件
This commit is contained in:
1 parent
954236c6cd
commit
46292157c4
8 files changed
+69
-71
No files matched your search
@@ -1,5 +1,4 @@
|
||||
- [x] dns手动添加设备
|
||||
- [ ] 手动接收(验证安卓端作为发送端是否有能力发给手动接收)
|
||||
|
||||
设置面板文字`下载路径:`的左边增加文字`自动下载`和开关,默认开启,和整体主题保持一致的样式;
|
||||
关闭了自动下载的情况下,收到文件`file-pending`的textContent显示`未下载`;
|
||||
|
||||
@@ -380,7 +380,9 @@ pub async fn get_my_id(state: State<'_, DbState>) -> Result<String, String> {
|
||||
#[tauri::command]
|
||||
pub async fn get_settings(state: State<'_, DbState>) -> Result<serde_json::Value, String> {
|
||||
let download_path = crate::db::get_download_path(&state.pool).await?;
|
||||
let port = crate::db::get_port(&state.pool).await?;
|
||||
let port = crate::config_file::get_port_from_config()
|
||||
.map(|p| p.to_string())
|
||||
.unwrap_or_else(|| "8888".to_string());
|
||||
let cfg = crate::config_file::read_config();
|
||||
let db_path = cfg.db_path.unwrap_or_else(crate::config_file::get_default_db_path);
|
||||
let auto_download = crate::db::get_auto_download(&state.pool).await;
|
||||
@@ -405,7 +407,8 @@ pub async fn update_settings(
|
||||
crate::db::update_download_path(&state.pool, path).await?;
|
||||
}
|
||||
if let Some(ref p) = port {
|
||||
crate::db::update_port(&state.pool, p).await?;
|
||||
let port_num: u16 = p.parse().map_err(|_| "端口格式无效".to_string())?;
|
||||
crate::config_file::save_port_to_config(port_num)?;
|
||||
}
|
||||
if let Some(path) = db_path {
|
||||
if !cfg!(target_os = "android") {
|
||||
|
||||
@@ -5,19 +5,24 @@ use std::path::PathBuf;
|
||||
pub struct Config {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub db_path: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub port: Option<u16>,
|
||||
}
|
||||
|
||||
impl Default for Config {
|
||||
fn default() -> Self {
|
||||
Config { db_path: None }
|
||||
Config { db_path: None, port: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// 配置文件路径 ~/.config/lanchat/config.json
|
||||
/// 配置文件路径(平台标准配置目录下)
|
||||
/// Linux: ~/.config/lanchat/config.json
|
||||
/// macOS: ~/Library/Application Support/lanchat/config.json
|
||||
/// Windows: %APPDATA%\lanchat\config.json
|
||||
/// Android: /data/data/com.lanchat.app/.config/lanchat/config.json
|
||||
fn config_path() -> PathBuf {
|
||||
dirs::home_dir()
|
||||
.unwrap_or_else(|| PathBuf::from("."))
|
||||
.join(".config")
|
||||
dirs::config_dir()
|
||||
.unwrap_or_else(|| dirs::home_dir().unwrap_or_else(|| PathBuf::from(".")).join(".config"))
|
||||
.join("lanchat")
|
||||
.join("config.json")
|
||||
}
|
||||
@@ -87,3 +92,20 @@ pub fn get_default_db_path() -> String {
|
||||
.to_string_lossy()
|
||||
.to_string()
|
||||
}
|
||||
|
||||
/// 从配置读取端口,不存在返回 None
|
||||
pub fn get_port_from_config() -> Option<u16> {
|
||||
read_config().port
|
||||
}
|
||||
|
||||
/// 保存端口到配置
|
||||
pub fn save_port_to_config(port: u16) -> Result<(), String> {
|
||||
if port == 0 {
|
||||
return Err("端口不能为 0".to_string());
|
||||
}
|
||||
let mut cfg = read_config();
|
||||
cfg.port = Some(port);
|
||||
write_config(&cfg)?;
|
||||
println!("[Config] 端口配置已保存: {}", port);
|
||||
Ok(())
|
||||
}
|
||||
@@ -124,40 +124,6 @@ pub async fn update_download_path(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 获取端口配置,默认返回 "8888"
|
||||
pub async fn get_port(pool: &sqlx::Pool<sqlx::Sqlite>) -> Result<String, String> {
|
||||
let res: Result<(String,), _> =
|
||||
sqlx::query_as("SELECT value FROM settings WHERE key = 'port'")
|
||||
.fetch_one(pool)
|
||||
.await;
|
||||
|
||||
match res {
|
||||
Ok((port,)) => Ok(port),
|
||||
Err(_) => Ok("8888".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// 更新端口配置
|
||||
pub async fn update_port(
|
||||
pool: &sqlx::Pool<sqlx::Sqlite>,
|
||||
port: &str,
|
||||
) -> Result<(), String> {
|
||||
// 验证端口格式
|
||||
let port_num: u16 = port.parse().map_err(|_| "端口格式无效".to_string())?;
|
||||
if port_num == 0 {
|
||||
return Err("端口不能为 0".to_string());
|
||||
}
|
||||
|
||||
sqlx::query("INSERT OR REPLACE INTO settings (key, value) VALUES ('port', ?)")
|
||||
.bind(port.to_string())
|
||||
.execute(pool)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
println!("[DB] 端口配置已保存: {}", port);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// 为 Tauri 桌面端初始化数据库
|
||||
#[cfg(feature = "desktop")]
|
||||
pub async fn init_db(app_handle: &AppHandle) -> Result<Pool<Sqlite>, sqlx::Error> {
|
||||
|
||||
@@ -91,11 +91,8 @@ pub fn run() {
|
||||
|
||||
let my_id = db::get_user_id(&pool).await.expect("无法获取或生成用户 ID");
|
||||
|
||||
// 读 DB 取 port
|
||||
let port: u16 = {
|
||||
let port_str = db::get_port(&pool).await.unwrap_or_else(|_| "8888".to_string());
|
||||
port_str.parse().unwrap_or(8888)
|
||||
};
|
||||
// 读配置文件取 port
|
||||
let port: u16 = crate::config_file::get_port_from_config().unwrap_or(8888);
|
||||
println!("[Lib] 服务端口: {}", port);
|
||||
|
||||
handle.manage(db::DbState { pool: pool.clone() });
|
||||
|
||||
+23
-13
@@ -1,6 +1,7 @@
|
||||
// src/main.rs
|
||||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||
|
||||
use clap::Parser;
|
||||
use lanchat::db;
|
||||
use lanchat::peers::PeerManager;
|
||||
use std::sync::Arc;
|
||||
@@ -10,7 +11,20 @@ use tauri::{
|
||||
Emitter, Manager,
|
||||
};
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
struct Args {
|
||||
#[arg(short, long)]
|
||||
port: Option<u16>,
|
||||
#[arg(long)]
|
||||
db_path: Option<String>,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let args = Args::parse();
|
||||
|
||||
let cli_port = args.port;
|
||||
let cli_db_path = args.db_path;
|
||||
|
||||
let builder = tauri::Builder::default()
|
||||
.plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {
|
||||
// 当尝试启动第二个实例时,显示已存在的窗口
|
||||
@@ -30,7 +44,6 @@ fn main() {
|
||||
let builder = builder.plugin(tauri_plugin_notification::init());
|
||||
|
||||
builder
|
||||
// --- 重点:添加下面这段代码 ---
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
lanchat::commands::close_android_fd,
|
||||
lanchat::commands::get_my_name,
|
||||
@@ -73,8 +86,7 @@ fn main() {
|
||||
lanchat::commands::start_tray_flash,
|
||||
lanchat::commands::stop_tray_flash,
|
||||
])
|
||||
// --------------------------
|
||||
.setup(|app| {
|
||||
.setup(move |app| {
|
||||
let handle = app.handle().clone();
|
||||
|
||||
// 获取主窗口并设置关闭事件处理
|
||||
@@ -91,15 +103,16 @@ fn main() {
|
||||
}
|
||||
|
||||
// 先初始化 DB,再创建托盘(托盘菜单需要读 DB)
|
||||
let pool = tauri::async_runtime::block_on(async {
|
||||
// Step 6: 读 config.json 取 db_path
|
||||
let db_dir = cli_db_path.or_else(|| {
|
||||
let cfg = lanchat::config_file::read_config();
|
||||
let db_dir = cfg.db_path
|
||||
cfg.db_path
|
||||
.as_ref()
|
||||
.map(|p| lanchat::config_file::resolve_db_dir(p));
|
||||
.map(|p| lanchat::config_file::resolve_db_dir(p).to_string_lossy().to_string())
|
||||
});
|
||||
|
||||
let pool = tauri::async_runtime::block_on(async {
|
||||
if let Some(dir) = db_dir {
|
||||
lanchat::db::init_db_standalone(Some(dir)).await.expect("DB error")
|
||||
lanchat::db::init_db_standalone(Some(std::path::PathBuf::from(dir))).await.expect("DB error")
|
||||
} else {
|
||||
db::init_db(&handle).await.expect("DB error")
|
||||
}
|
||||
@@ -113,10 +126,7 @@ fn main() {
|
||||
db::get_user_id(&pool).await.expect("无法获取或生成用户 ID")
|
||||
});
|
||||
|
||||
let port: u16 = tauri::async_runtime::block_on(async {
|
||||
let port_str = db::get_port(&pool).await.unwrap_or_else(|_| "8888".to_string());
|
||||
port_str.parse().unwrap_or(8888)
|
||||
});
|
||||
let port: u16 = cli_port.unwrap_or_else(|| lanchat::config_file::get_port_from_config().unwrap_or(8888));
|
||||
|
||||
let notif_enabled = tauri::async_runtime::block_on(async {
|
||||
lanchat::db::get_notifications_enabled(&pool).await
|
||||
@@ -195,7 +205,7 @@ fn main() {
|
||||
})
|
||||
.build(app)?;
|
||||
|
||||
// 创建 PeerManager 并启动服务(DB 已就绪,无需再次 block_on)
|
||||
// 创建 PeerManager 并启动服务(DB 已就绪,无需再次 block_on)
|
||||
let peer_manager = Arc::new(PeerManager::new());
|
||||
let _ = tauri::async_runtime::block_on(async {
|
||||
if let Err(e) = peer_manager.load_from_db(&pool).await {
|
||||
|
||||
@@ -46,13 +46,8 @@ async fn main() {
|
||||
println!("[Server Main] 我的用户名: {}", my_name);
|
||||
println!("[Server Main] 我的 ID: {}", my_id);
|
||||
|
||||
// Step 4: 若 --port 没传,读 DB 取 port
|
||||
let port: u16 = if let Some(p) = args.port {
|
||||
p
|
||||
} else {
|
||||
let port_str = lanchat::db::get_port(&pool).await.unwrap_or_else(|_| "8888".to_string());
|
||||
port_str.parse().unwrap_or(8888)
|
||||
};
|
||||
// Step 4: 若 --port 没传,读配置文件取 port
|
||||
let port: u16 = args.port.unwrap_or_else(|| lanchat::config_file::get_port_from_config().unwrap_or(8888));
|
||||
|
||||
// 创建全局用户管理器
|
||||
let peer_manager = Arc::new(PeerManager::new());
|
||||
|
||||
@@ -187,9 +187,9 @@ async fn get_settings_http(State(state): State<Arc<AppState>>) -> impl IntoRespo
|
||||
.to_string()
|
||||
});
|
||||
|
||||
let port = crate::db::get_port(&state.pool)
|
||||
.await
|
||||
.unwrap_or_else(|_| "8888".to_string());
|
||||
let port = crate::config_file::get_port_from_config()
|
||||
.map(|p| p.to_string())
|
||||
.unwrap_or_else(|| "8888".to_string());
|
||||
|
||||
let cfg = crate::config_file::read_config();
|
||||
let db_path = cfg.db_path.unwrap_or_else(crate::config_file::get_default_db_path);
|
||||
@@ -225,7 +225,13 @@ async fn update_settings_http(
|
||||
}
|
||||
}
|
||||
if let Some(ref p) = payload.port {
|
||||
if let Err(e) = crate::db::update_port(&state.pool, p).await {
|
||||
let port_num: u16 = match p.parse() {
|
||||
Ok(n) if n > 0 => n,
|
||||
_ => {
|
||||
return (StatusCode::BAD_REQUEST, Json(ErrorResponse { error: "端口格式无效".to_string() })).into_response();
|
||||
}
|
||||
};
|
||||
if let Err(e) = crate::config_file::save_port_to_config(port_num) {
|
||||
return (StatusCode::BAD_REQUEST, Json(ErrorResponse { error: e })).into_response();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user