feat: 改为安装包分发并使用动态端口
@@ -7,9 +7,8 @@
|
||||
"dev": "vite",
|
||||
"build": "vue-tsc --noEmit && vite build",
|
||||
"preview": "vite preview",
|
||||
"tauri": "tauri",
|
||||
"tauri:dev": "tauri dev",
|
||||
"exe": "tauri build -- --bundles none"
|
||||
"tauri": "node scripts/tauri.mjs",
|
||||
"backend:freeze": "..\\backend\\.venv\\Scripts\\python.exe ..\\backend\\scripts\\freeze.py"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tauri-apps/api": "^2",
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const desktop = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const cli = path.join(desktop, "node_modules", "@tauri-apps", "cli", "tauri.js");
|
||||
const args = process.argv.slice(2);
|
||||
|
||||
if (args[0] === "build" || args[0] === "bundle") {
|
||||
if (args[0] === "build") {
|
||||
const freeze = spawnSync("npm", ["run", "backend:freeze"], {
|
||||
cwd: desktop,
|
||||
stdio: "inherit",
|
||||
shell: true,
|
||||
});
|
||||
if ((freeze.status ?? 1) !== 0) process.exit(freeze.status ?? 1);
|
||||
}
|
||||
args.push("--config", path.join("src-tauri", "tauri.release.conf.json"));
|
||||
}
|
||||
|
||||
const result = spawnSync(process.execPath, [cli, ...args], {
|
||||
cwd: desktop,
|
||||
stdio: "inherit",
|
||||
});
|
||||
process.exit(result.status ?? 1);
|
||||
@@ -1,3 +1,12 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn main() {
|
||||
if std::env::var("PROFILE").ok().as_deref() == Some("release") {
|
||||
let backend = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../backend/build/nqi-backend/nqi-backend.exe");
|
||||
if !backend.is_file() {
|
||||
panic!("缺少打包后端 {}", backend.display());
|
||||
}
|
||||
}
|
||||
tauri_build::build()
|
||||
}
|
||||
|
||||
|
Before Width: | Height: | Size: 1.6 KiB After Width: | Height: | Size: 4.9 KiB |
|
Before Width: | Height: | Size: 2.8 KiB After Width: | Height: | Size: 9.6 KiB |
|
Before Width: | Height: | Size: 567 B After Width: | Height: | Size: 1.1 KiB |
|
After Width: | Height: | Size: 2.4 KiB |
|
Before Width: | Height: | Size: 1.3 KiB After Width: | Height: | Size: 4.2 KiB |
|
Before Width: | Height: | Size: 1.7 KiB After Width: | Height: | Size: 5.5 KiB |
|
Before Width: | Height: | Size: 1.7 KiB After Width: | Height: | Size: 5.6 KiB |
|
Before Width: | Height: | Size: 3.0 KiB After Width: | Height: | Size: 11 KiB |
|
Before Width: | Height: | Size: 536 B After Width: | Height: | Size: 1.0 KiB |
|
Before Width: | Height: | Size: 3.4 KiB After Width: | Height: | Size: 12 KiB |
|
Before Width: | Height: | Size: 777 B After Width: | Height: | Size: 1.6 KiB |
|
Before Width: | Height: | Size: 1020 B After Width: | Height: | Size: 2.6 KiB |
|
Before Width: | Height: | Size: 1.2 KiB After Width: | Height: | Size: 3.3 KiB |
|
Before Width: | Height: | Size: 848 B After Width: | Height: | Size: 1.8 KiB |
|
Before Width: | Height: | Size: 37 KiB After Width: | Height: | Size: 17 KiB |
|
Before Width: | Height: | Size: 5.5 KiB After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 22 KiB |
@@ -1,54 +1,128 @@
|
||||
use std::net::{SocketAddr, TcpStream};
|
||||
use std::path::PathBuf;
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::sync::atomic::{AtomicU16, Ordering};
|
||||
use std::sync::Mutex;
|
||||
use std::time::Duration;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use tauri::Manager;
|
||||
|
||||
static BACKEND: Mutex<Option<Child>> = Mutex::new(None);
|
||||
static PORT: AtomicU16 = AtomicU16::new(0);
|
||||
|
||||
fn backend_up() -> bool {
|
||||
let address: SocketAddr = "127.0.0.1:8765".parse().expect("address");
|
||||
TcpStream::connect_timeout(&address, Duration::from_millis(200)).is_ok()
|
||||
struct Launch {
|
||||
program: PathBuf,
|
||||
args: Vec<String>,
|
||||
cwd: PathBuf,
|
||||
data_dir: PathBuf,
|
||||
}
|
||||
|
||||
fn start_backend() {
|
||||
if backend_up() {
|
||||
return;
|
||||
fn pick_port() -> u16 {
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind local port");
|
||||
listener.local_addr().expect("local address").port()
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn backend_port() -> u16 {
|
||||
PORT.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
fn repo_root() -> Option<PathBuf> {
|
||||
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.parent()
|
||||
.and_then(|path| path.parent())
|
||||
.map(PathBuf::from)
|
||||
}
|
||||
|
||||
fn bundled_backend(app: &tauri::App) -> Option<PathBuf> {
|
||||
let mut roots = Vec::new();
|
||||
if let Ok(dir) = app.path().resource_dir() {
|
||||
roots.push(dir);
|
||||
}
|
||||
let manifest = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
let Some(repo) = manifest.parent().and_then(|path| path.parent()) else {
|
||||
return;
|
||||
};
|
||||
let python = repo
|
||||
if let Ok(dir) = app.path().executable_dir() {
|
||||
roots.push(dir);
|
||||
}
|
||||
for root in roots {
|
||||
for candidate in [
|
||||
root.join("nqi-backend").join("nqi-backend.exe"),
|
||||
root.join("resources").join("nqi-backend").join("nqi-backend.exe"),
|
||||
] {
|
||||
if candidate.is_file() {
|
||||
return Some(candidate);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn installed_data_dir(app: &tauri::App) -> PathBuf {
|
||||
let folder = app.config().identifier.clone();
|
||||
if let Ok(appdata) = std::env::var("APPDATA") {
|
||||
if !appdata.is_empty() {
|
||||
return PathBuf::from(appdata).join(folder);
|
||||
}
|
||||
}
|
||||
PathBuf::from(".").join(folder)
|
||||
}
|
||||
|
||||
fn launch_plan(app: &tauri::App, port: u16) -> Option<Launch> {
|
||||
if !cfg!(debug_assertions) {
|
||||
if let Some(program) = bundled_backend(app) {
|
||||
let cwd = program.parent()?.to_path_buf();
|
||||
return Some(Launch {
|
||||
program,
|
||||
args: Vec::new(),
|
||||
cwd,
|
||||
data_dir: installed_data_dir(app),
|
||||
});
|
||||
}
|
||||
}
|
||||
let repo = repo_root()?;
|
||||
let program = repo
|
||||
.join("backend")
|
||||
.join(".venv")
|
||||
.join("Scripts")
|
||||
.join("python.exe");
|
||||
if !python.exists() {
|
||||
return;
|
||||
if !program.is_file() {
|
||||
return None;
|
||||
}
|
||||
let log_dir = repo.join("data");
|
||||
let _ = std::fs::create_dir_all(&log_dir);
|
||||
let mut command = Command::new(python);
|
||||
Some(Launch {
|
||||
program,
|
||||
args: vec![
|
||||
"-m".into(),
|
||||
"uvicorn".into(),
|
||||
"app.main:app".into(),
|
||||
"--host".into(),
|
||||
"127.0.0.1".into(),
|
||||
"--port".into(),
|
||||
port.to_string(),
|
||||
],
|
||||
cwd: repo.join("backend"),
|
||||
data_dir: repo.join("data"),
|
||||
})
|
||||
}
|
||||
|
||||
fn start_backend(app: &tauri::App) {
|
||||
let port = pick_port();
|
||||
PORT.store(port, Ordering::SeqCst);
|
||||
let Some(plan) = launch_plan(app, port) else {
|
||||
return;
|
||||
};
|
||||
let _ = std::fs::create_dir_all(&plan.data_dir);
|
||||
let mut command = Command::new(&plan.program);
|
||||
command
|
||||
.args([
|
||||
"-m",
|
||||
"uvicorn",
|
||||
"app.main:app",
|
||||
"--host",
|
||||
"127.0.0.1",
|
||||
"--port",
|
||||
"8765",
|
||||
])
|
||||
.current_dir(repo.join("backend"))
|
||||
.args(&plan.args)
|
||||
.current_dir(&plan.cwd)
|
||||
.env("NQI_PORT", port.to_string())
|
||||
.env("NQI_DATA_DIR", &plan.data_dir)
|
||||
.stdin(Stdio::null());
|
||||
if let Ok(log) = std::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(log_dir.join("backend.log"))
|
||||
.open(plan.data_dir.join("backend.log"))
|
||||
{
|
||||
if let Ok(error_log) = log.try_clone() {
|
||||
command.stdout(log).stderr(error_log);
|
||||
command.stdout(Stdio::from(log)).stderr(Stdio::from(error_log));
|
||||
}
|
||||
}
|
||||
#[cfg(windows)]
|
||||
@@ -59,6 +133,26 @@ fn start_backend() {
|
||||
if let Ok(child) = command.spawn() {
|
||||
*BACKEND.lock().expect("backend lock") = Some(child);
|
||||
}
|
||||
wait_until_ready(port);
|
||||
}
|
||||
|
||||
fn wait_until_ready(port: u16) {
|
||||
let address = SocketAddr::from(([127, 0, 0, 1], port));
|
||||
let deadline = Instant::now() + Duration::from_secs(20);
|
||||
while Instant::now() < deadline {
|
||||
if TcpStream::connect_timeout(&address, Duration::from_millis(200)).is_ok() {
|
||||
return;
|
||||
}
|
||||
let exited = BACKEND
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|mut slot| slot.as_mut().and_then(|child| child.try_wait().ok().flatten()))
|
||||
.is_some();
|
||||
if exited {
|
||||
return;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
}
|
||||
|
||||
fn stop_backend() {
|
||||
@@ -73,10 +167,14 @@ fn stop_backend() {
|
||||
|
||||
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||||
pub fn run() {
|
||||
start_backend();
|
||||
tauri::Builder::default()
|
||||
.plugin(tauri_plugin_opener::init())
|
||||
.plugin(tauri_plugin_dialog::init())
|
||||
.invoke_handler(tauri::generate_handler![backend_port])
|
||||
.setup(|app| {
|
||||
start_backend(app);
|
||||
Ok(())
|
||||
})
|
||||
.build(tauri::generate_context!())
|
||||
.expect("error while building tauri application")
|
||||
.run(|_app, event| {
|
||||
|
||||
@@ -24,13 +24,25 @@
|
||||
}
|
||||
},
|
||||
"bundle": {
|
||||
"active": false,
|
||||
"active": true,
|
||||
"targets": ["nsis"],
|
||||
"publisher": "NqiTools",
|
||||
"icon": [
|
||||
"icons/32x32.png",
|
||||
"icons/128x128.png",
|
||||
"icons/128x128@2x.png",
|
||||
"icons/icon.icns",
|
||||
"icons/icon.ico"
|
||||
]
|
||||
],
|
||||
"windows": {
|
||||
"webviewInstallMode": {
|
||||
"type": "skip"
|
||||
},
|
||||
"nsis": {
|
||||
"installMode": "currentUser",
|
||||
"languages": ["SimpChinese"],
|
||||
"displayLanguageSelector": false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"bundle": {
|
||||
"resources": {
|
||||
"../../backend/build/nqi-backend/": "nqi-backend/"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -31,7 +31,7 @@ onMounted(() => {
|
||||
async function connect() {
|
||||
offline.value = "";
|
||||
ready.value = false;
|
||||
for (let attempt = 0; attempt < 20; attempt += 1) {
|
||||
for (let attempt = 0; attempt < 40; attempt += 1) {
|
||||
try {
|
||||
const result = await loadCaptcha();
|
||||
sessionId.value = result.sessionId;
|
||||
|
||||
@@ -1,4 +1,27 @@
|
||||
export const API_BASE = import.meta.env.DEV ? "" : "http://127.0.0.1:8765";
|
||||
let apiBase = "";
|
||||
let preparing: Promise<void> | null = null;
|
||||
|
||||
export function initApi(): Promise<void> {
|
||||
preparing ??= resolveApiBase();
|
||||
return preparing;
|
||||
}
|
||||
|
||||
async function resolveApiBase(): Promise<void> {
|
||||
if (!("__TAURI_INTERNALS__" in window)) return;
|
||||
const { invoke } = await import("@tauri-apps/api/core");
|
||||
for (let attempt = 0; attempt < 50; attempt += 1) {
|
||||
try {
|
||||
const port = await invoke<number>("backend_port");
|
||||
if (port > 0) {
|
||||
apiBase = `http://127.0.0.1:${port}`;
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
// 窗口可能比端口命令更早就绪。
|
||||
}
|
||||
await new Promise((resolve) => window.setTimeout(resolve, 100));
|
||||
}
|
||||
}
|
||||
|
||||
export class ApiError extends Error {
|
||||
status: number;
|
||||
@@ -10,13 +33,14 @@ export class ApiError extends Error {
|
||||
}
|
||||
|
||||
export async function api<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
await initApi();
|
||||
let response: Response;
|
||||
try {
|
||||
const headers = new Headers(init?.headers);
|
||||
if (init?.body && !(init.body instanceof FormData) && !headers.has("Content-Type")) {
|
||||
headers.set("Content-Type", "application/json");
|
||||
}
|
||||
response = await fetch(`${API_BASE}${path}`, { ...init, headers });
|
||||
response = await fetch(`${apiBase}${path}`, { ...init, headers });
|
||||
} catch {
|
||||
throw new ApiError(0, "连接失败");
|
||||
}
|
||||
|
||||
@@ -17,12 +17,6 @@ export default defineConfig(() => ({
|
||||
port: 1420,
|
||||
strictPort: true,
|
||||
host: host || false,
|
||||
proxy: {
|
||||
"/api": {
|
||||
target: "http://127.0.0.1:8765",
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
hmr: host
|
||||
? {
|
||||
protocol: "ws",
|
||||
|
||||