feat: 完成登录与栅格下载桌面端

This commit is contained in:
2026-10-25 02:09:12 +08:00
commit 5ca491834e
76 changed files with 10637 additions and 0 deletions
+24
View File
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
+7
View File
@@ -0,0 +1,7 @@
# Tauri + Vue + TypeScript
This template should help get you started developing with Vue 3 and TypeScript in Vite. The template uses Vue 3 `<script setup>` SFCs, check out the [script setup docs](https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup) to learn more.
## Recommended IDE Setup
- [VS Code](https://code.visualstudio.com/) + [Vue - Official](https://marketplace.visualstudio.com/items?itemName=Vue.volar) + [Tauri](https://marketplace.visualstudio.com/items?itemName=tauri-apps.tauri-vscode) + [rust-analyzer](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer)
+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>NqiTools</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
+1626
View File
File diff suppressed because it is too large Load Diff
+29
View File
@@ -0,0 +1,29 @@
{
"name": "nqi-tools",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vue-tsc --noEmit && vite build",
"preview": "vite preview",
"tauri": "tauri",
"tauri:dev": "tauri dev",
"exe": "tauri build -- --bundles none"
},
"dependencies": {
"@tauri-apps/api": "^2",
"@tauri-apps/plugin-dialog": "^2",
"@tauri-apps/plugin-opener": "^2",
"@vicons/ionicons5": "^0.13.0",
"naive-ui": "^2.43.2",
"vue": "^3.5.13"
},
"devDependencies": {
"@vitejs/plugin-vue": "^6.0.7",
"typescript": "~6.0.3",
"vite": "^8.0.16",
"vue-tsc": "^3.3.5",
"@tauri-apps/cli": "^2"
}
}
+6
View File
@@ -0,0 +1,6 @@
<svg width="206" height="231" viewBox="0 0 206 231" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M143.143 84C143.143 96.1503 133.293 106 121.143 106C108.992 106 99.1426 96.1503 99.1426 84C99.1426 71.8497 108.992 62 121.143 62C133.293 62 143.143 71.8497 143.143 84Z" fill="#FFC131"/>
<ellipse cx="84.1426" cy="147" rx="22" ry="22" transform="rotate(180 84.1426 147)" fill="#24C8DB"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M166.738 154.548C157.86 160.286 148.023 164.269 137.757 166.341C139.858 160.282 141 153.774 141 147C141 144.543 140.85 142.121 140.558 139.743C144.975 138.204 149.215 136.139 153.183 133.575C162.73 127.404 170.292 118.608 174.961 108.244C179.63 97.8797 181.207 86.3876 179.502 75.1487C177.798 63.9098 172.884 53.4021 165.352 44.8883C157.82 36.3744 147.99 30.2165 137.042 27.1546C126.095 24.0926 114.496 24.2568 103.64 27.6274C92.7839 30.998 83.1319 37.4317 75.8437 46.1553C74.9102 47.2727 74.0206 48.4216 73.176 49.5993C61.9292 50.8488 51.0363 54.0318 40.9629 58.9556C44.2417 48.4586 49.5653 38.6591 56.679 30.1442C67.0505 17.7298 80.7861 8.57426 96.2354 3.77762C111.685 -1.01901 128.19 -1.25267 143.769 3.10474C159.348 7.46215 173.337 16.2252 184.056 28.3411C194.775 40.457 201.767 55.4101 204.193 71.404C206.619 87.3978 204.374 103.752 197.73 118.501C191.086 133.25 180.324 145.767 166.738 154.548ZM41.9631 74.275L62.5557 76.8042C63.0459 72.813 63.9401 68.9018 65.2138 65.1274C57.0465 67.0016 49.2088 70.087 41.9631 74.275Z" fill="#FFC131"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M38.4045 76.4519C47.3493 70.6709 57.2677 66.6712 67.6171 64.6132C65.2774 70.9669 64 77.8343 64 85.0001C64 87.1434 64.1143 89.26 64.3371 91.3442C60.0093 92.8732 55.8533 94.9092 51.9599 97.4256C42.4128 103.596 34.8505 112.392 30.1816 122.756C25.5126 133.12 23.9357 144.612 25.6403 155.851C27.3449 167.09 32.2584 177.598 39.7906 186.112C47.3227 194.626 57.153 200.784 68.1003 203.846C79.0476 206.907 90.6462 206.743 101.502 203.373C112.359 200.002 122.011 193.568 129.299 184.845C130.237 183.722 131.131 182.567 131.979 181.383C143.235 180.114 154.132 176.91 164.205 171.962C160.929 182.49 155.596 192.319 148.464 200.856C138.092 213.27 124.357 222.426 108.907 227.222C93.458 232.019 76.9524 232.253 61.3736 227.895C45.7948 223.538 31.8055 214.775 21.0867 202.659C10.3679 190.543 3.37557 175.59 0.949823 159.596C-1.47592 143.602 0.768139 127.248 7.41237 112.499C14.0566 97.7497 24.8183 85.2327 38.4045 76.4519ZM163.062 156.711L163.062 156.711C162.954 156.773 162.846 156.835 162.738 156.897C162.846 156.835 162.954 156.773 163.062 156.711Z" fill="#24C8DB"/>
</svg>

After

Width:  |  Height:  |  Size: 2.5 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

+7
View File
@@ -0,0 +1,7 @@
# Generated by Cargo
# will have compiled files and executables
/target/
# Generated by Tauri
# will have schema files for capabilities auto-completion
/gen/schemas
+4952
View File
File diff suppressed because it is too large Load Diff
+39
View File
@@ -0,0 +1,39 @@
[package]
name = "desktop"
version = "0.1.0"
description = "A Tauri App"
authors = ["you"]
edition = "2024"
autobins = false
[[bin]]
name = "NqiTools"
path = "src/main.rs"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
# The `_lib` suffix may seem redundant but it is necessary
# to make the lib name unique and wouldn't conflict with the bin name.
# This seems to be only an issue on Windows, see https://github.com/rust-lang/cargo/issues/8519
name = "desktop_lib"
crate-type = ["staticlib", "cdylib", "rlib"]
[build-dependencies]
tauri-build = { version = "2", features = [] }
[dependencies]
tauri = { version = "2", features = [] }
tauri-plugin-opener = "2"
tauri-plugin-dialog = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
# Read the optimization guideline for more details: https://tauri.app/concept/size/#cargo-configuration
[profile.release]
codegen-units = 1
lto = true
opt-level = 3
panic = "abort"
strip = true
+3
View File
@@ -0,0 +1,3 @@
fn main() {
tauri_build::build()
}
@@ -0,0 +1,11 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Capability for the main window",
"windows": ["main"],
"permissions": [
"core:default",
"opener:default",
"dialog:default"
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 567 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 536 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 777 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1020 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 848 B

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

+87
View File
@@ -0,0 +1,87 @@
use std::net::{SocketAddr, TcpStream};
use std::path::PathBuf;
use std::process::{Child, Command, Stdio};
use std::sync::Mutex;
use std::time::Duration;
static BACKEND: Mutex<Option<Child>> = Mutex::new(None);
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()
}
fn start_backend() {
if backend_up() {
return;
}
let manifest = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let Some(repo) = manifest.parent().and_then(|path| path.parent()) else {
return;
};
let python = repo
.join("backend")
.join(".venv")
.join("Scripts")
.join("python.exe");
if !python.exists() {
return;
}
let log_dir = repo.join("data");
let _ = std::fs::create_dir_all(&log_dir);
let mut command = Command::new(python);
command
.args([
"-m",
"uvicorn",
"app.main:app",
"--host",
"127.0.0.1",
"--port",
"8765",
])
.current_dir(repo.join("backend"))
.stdin(Stdio::null());
if let Ok(log) = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(log_dir.join("backend.log"))
{
if let Ok(error_log) = log.try_clone() {
command.stdout(log).stderr(error_log);
}
}
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
command.creation_flags(0x0800_0000);
}
if let Ok(child) = command.spawn() {
*BACKEND.lock().expect("backend lock") = Some(child);
}
}
fn stop_backend() {
if let Ok(mut slot) = BACKEND.lock() {
if let Some(child) = slot.as_mut() {
let _ = child.kill();
let _ = child.wait();
}
*slot = None;
}
}
#[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())
.build(tauri::generate_context!())
.expect("error while building tauri application")
.run(|_app, event| {
if matches!(event, tauri::RunEvent::Exit) {
stop_backend();
}
});
}
+6
View File
@@ -0,0 +1,6 @@
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
fn main() {
desktop_lib::run()
}
+36
View File
@@ -0,0 +1,36 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "NqiTools",
"version": "0.1.0",
"identifier": "com.nqitools.app",
"build": {
"beforeDevCommand": "npm run dev",
"devUrl": "http://localhost:1420",
"beforeBuildCommand": "npm run build",
"frontendDist": "../dist"
},
"app": {
"windows": [
{
"title": "NqiTools",
"width": 1180,
"height": 780,
"minWidth": 980,
"minHeight": 640
}
],
"security": {
"csp": null
}
},
"bundle": {
"active": false,
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
]
}
}
+19
View File
@@ -0,0 +1,19 @@
<script setup lang="ts">
import { ref } from "vue";
import { darkTheme, NConfigProvider, NMessageProvider, zhCN, dateZhCN } from "naive-ui";
import LoginView from "./features/auth/LoginView.vue";
import Shell from "./shell/Shell.vue";
import type { UserInfo } from "./features/auth/api";
import { isDark, themeOverrides } from "./shared/theme";
const user = ref<UserInfo | null>(null);
</script>
<template>
<n-config-provider :locale="zhCN" :date-locale="dateZhCN" :theme="isDark ? darkTheme : null" :theme-overrides="themeOverrides">
<n-message-provider>
<LoginView v-if="!user" @success="user = $event" />
<Shell v-else :user="user" @logout="user = null" />
</n-message-provider>
</n-config-provider>
</template>
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="37.07" height="36" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 198"><path fill="#41B883" d="M204.8 0H256L128 220.8L0 0h97.92L128 51.2L157.44 0h47.36Z"></path><path fill="#41B883" d="m0 0l128 220.8L256 0h-51.2L128 132.48L50.56 0H0Z"></path><path fill="#35495E" d="M50.56 0L128 133.12L204.8 0h-47.36L128 51.2L97.92 0H50.56Z"></path></svg>

After

Width:  |  Height:  |  Size: 496 B

+178
View File
@@ -0,0 +1,178 @@
<script setup lang="ts">
import { onMounted, ref } from "vue";
import { NAlert, NButton, NIcon, NInput, NSpin, NTooltip } from "naive-ui";
import { HelpCircleOutline, MoonOutline, SunnyOutline } from "@vicons/ionicons5";
import { ApiError } from "../../shared/http";
import { loadCaptcha, login, refreshCaptcha, sendSms, type UserInfo } from "./api";
import { isDark, toggleTheme } from "../../shared/theme";
const emit = defineEmits<{ success: [user: UserInfo] }>();
const ready = ref(false);
const offline = ref("");
const sessionId = ref("");
const captchaUrl = ref("");
const username = ref("");
const password = ref("");
const captcha = ref("");
const smsCode = ref("");
const smsRequired = ref(false);
const sending = ref(false);
const submitting = ref(false);
const errorText = ref("");
const smsHint = ref("");
const countdown = ref(0);
let timer = 0;
onMounted(() => {
void connect();
});
async function connect() {
offline.value = "";
ready.value = false;
for (let attempt = 0; attempt < 20; attempt += 1) {
try {
const result = await loadCaptcha();
sessionId.value = result.sessionId;
captchaUrl.value = result.captcha;
ready.value = true;
return;
} catch (error) {
const failedLocally = !(error instanceof ApiError) || error.status === 0;
offline.value = error instanceof ApiError ? error.message : "连接失败";
if (!failedLocally) {
ready.value = true;
return;
}
await new Promise((resolve) => window.setTimeout(resolve, 500));
}
}
}
async function reloadCaptcha() {
errorText.value = "";
try {
if (!sessionId.value) {
await connect();
return;
}
const result = await refreshCaptcha(sessionId.value);
captchaUrl.value = result.captcha;
captcha.value = "";
} catch (error) {
errorText.value = error instanceof ApiError ? error.message : "验证码刷新失败";
await connect();
}
}
async function requestSms() {
if (!sessionId.value || countdown.value > 0) return;
sending.value = true;
smsHint.value = "";
try {
const result = await sendSms(sessionId.value);
smsHint.value = result.message || "短信已发送";
countdown.value = 60;
timer = window.setInterval(() => {
countdown.value -= 1;
if (countdown.value <= 0) window.clearInterval(timer);
}, 1000);
} catch (error) {
errorText.value = error instanceof ApiError ? error.message : "短信发送失败";
} finally {
sending.value = false;
}
}
async function submit() {
errorText.value = "";
submitting.value = true;
try {
const result = await login({
sessionId: sessionId.value,
username: username.value.trim(),
password: password.value,
captcha: captcha.value.trim(),
smsCode: smsCode.value.trim(),
});
if (result.status === "sms_required") {
smsRequired.value = true;
smsHint.value = result.message || "请获取并填写短信验证码";
return;
}
if (result.user) emit("success", result.user);
} catch (error) {
errorText.value = error instanceof ApiError ? error.message : "登录失败";
smsRequired.value = false;
await reloadCaptcha();
} finally {
submitting.value = false;
}
}
</script>
<template>
<div class="gate">
<n-button class="theme-switch" quaternary circle :aria-label="isDark ? '切换到日间' : '切换到夜间'" @click="toggleTheme">
<template #icon><n-icon><MoonOutline v-if="!isDark" /><SunnyOutline v-else /></n-icon></template>
</n-button>
<section class="gate-card">
<div class="brand">
<div class="brand-mark" aria-hidden="true">
<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
<path d="M4 16.5 12 4l8 12.5" stroke="currentColor" stroke-width="1.8" />
<path d="M7.2 16.5h9.6M9.2 13.2h5.6" stroke="currentColor" stroke-width="1.8" />
</svg>
</div>
<div>
<h1>NqiTools</h1>
</div>
</div>
<n-spin :show="!ready && !offline">
<n-alert v-if="!ready" type="warning" style="margin-bottom: 12px">连接失败,正在重试。</n-alert>
<n-alert v-else-if="offline" type="warning" style="margin-bottom: 12px">{{ offline }}</n-alert>
<n-alert v-if="errorText" type="error" style="margin-bottom: 12px">{{ errorText }}</n-alert>
<form @submit.prevent="submit">
<div class="form-row">
<label for="username">账号</label>
<n-input id="username" v-model:value="username" placeholder="账号" autocomplete="username" />
</div>
<div class="form-row">
<label for="password">密码</label>
<n-input id="password" v-model:value="password" type="password" show-password-on="click" placeholder="密码" autocomplete="current-password" />
</div>
<div class="form-row">
<label for="captcha">
验证码
<n-tooltip>
<template #trigger>
<n-icon class="hint" :size="15"><HelpCircleOutline /></n-icon>
</template>
点击图片刷新。
</n-tooltip>
</label>
<div class="captcha-line">
<n-input id="captcha" v-model:value="captcha" placeholder="验证码" />
<img v-if="captchaUrl" :src="captchaUrl" alt="验证码" title="点击刷新" @click="reloadCaptcha" />
</div>
</div>
<div v-if="smsRequired" class="form-row">
<label for="sms">短信</label>
<div class="captcha-line">
<n-input id="sms" v-model:value="smsCode" placeholder="短信验证码" />
<n-button :disabled="sending || countdown > 0" @click="requestSms">
{{ countdown > 0 ? `${countdown}s` : "获取短信" }}
</n-button>
</div>
</div>
<p v-if="smsHint" class="file-name" style="margin: 0 0 8px 96px">{{ smsHint }}</p>
<div class="gate-actions">
<n-button type="primary" attr-type="submit" :loading="submitting" :disabled="!ready">登录</n-button>
</div>
</form>
</n-spin>
</section>
</div>
</template>
+43
View File
@@ -0,0 +1,43 @@
import { api } from "../../shared/http";
export interface UserInfo {
loginId: string;
userName: string;
cityName: string;
orgName: string;
}
export function loadCaptcha() {
return api<{ sessionId: string; captcha: string }>("/api/auth/captcha", { method: "POST" });
}
export function refreshCaptcha(sessionId: string) {
return api<{ sessionId: string; captcha: string }>("/api/auth/captcha/refresh", {
method: "POST",
body: JSON.stringify({ sessionId }),
});
}
export function sendSms(sessionId: string) {
return api<{ message: string }>("/api/auth/sms", {
method: "POST",
body: JSON.stringify({ sessionId }),
});
}
export function login(body: {
sessionId: string;
username: string;
password: string;
captcha: string;
smsCode?: string;
}) {
return api<{ status: string; message?: string; user?: UserInfo }>("/api/auth/login", {
method: "POST",
body: JSON.stringify(body),
});
}
export function logout() {
return api<{ ok: boolean }>("/api/auth/logout", { method: "POST" });
}
@@ -0,0 +1,142 @@
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from "vue";
import { NButton, NEmpty, NIcon, NProgress, NTag, useMessage } from "naive-ui";
import { FolderOpenOutline, PlayOutline, StopCircleOutline } from "@vicons/ionicons5";
import { ApiError, openLocal } from "../../shared/http";
import { cancelJob, loadJobs, resumeJob, type DownloadJob } from "./api";
const props = defineProps<{ focusId: string }>();
const message = useMessage();
const jobs = ref<DownloadJob[]>([]);
const tab = ref<"active" | "done">("active");
let timer = 0;
const activeJobs = computed(() => jobs.value.filter((job) => job.status !== "done"));
const doneJobs = computed(() => jobs.value.filter((job) => job.status === "done"));
const visible = computed(() => (tab.value === "active" ? activeJobs.value : doneJobs.value));
const statusText: Record<string, string> = {
queued: "等待中",
running: "下载中",
cancelled: "已停止",
error: "出错",
done_with_errors: "部分失败",
done: "已完成",
};
onMounted(() => {
void refresh();
timer = window.setInterval(() => void refresh(), 1000);
});
onUnmounted(() => window.clearInterval(timer));
async function refresh() {
try {
const result = await loadJobs();
jobs.value = result.jobs;
} catch (error) {
if (error instanceof ApiError && error.status !== 0) message.error(error.message);
}
}
function percent(job: DownloadJob) {
if (!job.total) return 0;
return Math.min(100, Math.round((job.completed / job.total) * 100));
}
async function stop(job: DownloadJob) {
try {
await cancelJob(job.id);
await refresh();
} catch (error) {
message.error(error instanceof ApiError ? error.message : "停止失败");
}
}
async function resume(job: DownloadJob) {
try {
await resumeJob(job.id);
tab.value = "active";
await refresh();
} catch (error) {
message.error(error instanceof ApiError ? error.message : "继续失败");
}
}
async function openFile(job: DownloadJob) {
const opened = await openLocal(job.csvPath).catch(() => false);
if (!opened) message.info(job.csvPath);
}
async function openDir(job: DownloadJob) {
const index = Math.max(job.csvPath.lastIndexOf("\\"), job.csvPath.lastIndexOf("/"));
const folder = index > 0 ? job.csvPath.slice(0, index) : job.csvPath;
const opened = await openLocal(folder).catch(() => false);
if (!opened) message.info(folder);
}
</script>
<template>
<section class="page">
<header class="page-head">
<div>
<h2>下载管理</h2>
</div>
</header>
<div class="tabs">
<button class="tab" :class="{ on: tab === 'active' }" type="button" @click="tab = 'active'">
正在下载<em>{{ activeJobs.length }}</em>
</button>
<button class="tab" :class="{ on: tab === 'done' }" type="button" @click="tab = 'done'">
已完成<em>{{ doneJobs.length }}</em>
</button>
</div>
<div class="task-list">
<article
v-for="job in visible"
:key="job.id"
class="task"
:class="{ focus: job.id === props.focusId }"
>
<div class="task-top">
<div>
<h3>{{ job.name }}</h3>
<div class="sub">{{ job.completed }}/{{ job.total }} 个栅格 · 已写入 {{ job.writtenRows }} 行</div>
</div>
<div class="task-actions">
<n-tag size="small" :type="job.status === 'running' ? 'info' : job.status === 'done' ? 'success' : 'warning'">
{{ statusText[job.status] || job.status }}
</n-tag>
<n-button v-if="job.status === 'running' || job.status === 'queued'" size="small" @click="stop(job)">
<template #icon><n-icon><StopCircleOutline /></n-icon></template>
停止
</n-button>
<n-button v-else-if="job.status !== 'done'" size="small" type="primary" secondary @click="resume(job)">
<template #icon><n-icon><PlayOutline /></n-icon></template>
继续
</n-button>
<n-button size="small" quaternary @click="openFile(job)">打开</n-button>
<n-button size="small" quaternary @click="openDir(job)">
<template #icon><n-icon><FolderOpenOutline /></n-icon></template>
</n-button>
</div>
</div>
<n-progress
style="margin-top: 10px"
:percentage="percent(job)"
:show-indicator="true"
:processing="job.status === 'running'"
/>
<div class="task-foot">
<span class="sub">{{ job.message }}</span>
<span class="sub">失败 {{ job.failed }}</span>
</div>
<ul v-if="job.failures?.length" class="fail-list">
<li v-for="item in job.failures.slice(0, 3)" :key="item.id">{{ item.id }}:{{ item.message }}</li>
</ul>
</article>
<n-empty v-if="visible.length === 0" class="empty" :description="tab === 'active' ? '没有正在下载的任务' : '还没有完成的任务'" />
</div>
</section>
</template>
@@ -0,0 +1,197 @@
<script setup lang="ts">
import { onMounted, ref, watch } from "vue";
import {
NButton,
NCheckbox,
NCheckboxGroup,
NIcon,
NInput,
NInputNumber,
NSelect,
NTooltip,
useMessage,
} from "naive-ui";
import { FolderOpenOutline, HelpCircleOutline } from "@vicons/ionicons5";
import { ApiError, chooseDirectory } from "../../shared/http";
import { createJob, loadMeta, type Meta } from "./api";
const emit = defineEmits<{ started: [id: string] }>();
const message = useMessage();
const meta = ref<Meta | null>(null);
const network = ref("NR");
const cityCode = ref("JM");
const month = ref(previousMonth());
const concurrency = ref(8);
const groups = ref<string[]>([]);
const outputDir = ref("");
const file = ref<File | null>(null);
const submitting = ref(false);
const networkOptions = [
{ label: "5G", value: "NR" },
{ label: "4G", value: "LTE" },
];
function previousMonth() {
const date = new Date();
date.setDate(1);
date.setMonth(date.getMonth() - 1);
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}`;
}
onMounted(async () => {
try {
meta.value = await loadMeta();
syncGroups();
} catch (error) {
message.error(error instanceof ApiError ? error.message : "读取下载项目失败");
}
});
watch(network, syncGroups);
function syncGroups() {
groups.value = (meta.value?.groups[network.value] || []).map((item) => item.id);
}
function onFile(event: Event) {
const input = event.target as HTMLInputElement;
file.value = input.files?.[0] ?? null;
}
async function pickDir() {
const selected = await chooseDirectory();
if (selected) outputDir.value = selected;
}
async function start() {
if (!file.value) {
message.warning("请先选择栅格 ID 表");
return;
}
if (!/^\d{4}-(0[1-9]|1[0-2])$/.test(month.value)) {
message.warning("月份格式应为 YYYY-MM");
return;
}
const form = new FormData();
form.append("file", file.value);
form.append("network", network.value);
form.append("city_code", cityCode.value);
form.append("month", month.value);
form.append("groups", JSON.stringify(groups.value));
form.append("concurrency", String(concurrency.value || 8));
form.append("output_dir", outputDir.value.trim());
submitting.value = true;
try {
const job = await createJob(form);
message.success("已开始下载");
emit("started", job.id);
} catch (error) {
message.error(error instanceof ApiError ? error.message : "创建下载失败");
} finally {
submitting.value = false;
}
}
</script>
<template>
<section class="page">
<div class="page-scroll">
<header class="page-head">
<div>
<h2>栅格下载</h2>
</div>
<div class="head-actions">
<n-button type="primary" :loading="submitting" @click="start">开始下载</n-button>
</div>
</header>
<div class="panel">
<div class="form-row">
<label>网络</label>
<n-select v-model:value="network" :options="networkOptions" />
</div>
<div class="form-row">
<label>地市</label>
<n-select
v-model:value="cityCode"
:options="(meta?.cities || []).map((city) => ({ label: city.name, value: city.code }))"
/>
</div>
<div class="form-row">
<label>
月份
<n-tooltip>
<template #trigger>
<n-icon class="hint" :size="15"><HelpCircleOutline /></n-icon>
</template>
例如 2026-09。
</n-tooltip>
</label>
<n-input v-model:value="month" placeholder="YYYY-MM" />
</div>
<div class="form-row">
<label>
并发
<n-tooltip>
<template #trigger>
<n-icon class="hint" :size="15"><HelpCircleOutline /></n-icon>
</template>
同时下载的栅格数量。
</n-tooltip>
</label>
<n-input-number v-model:value="concurrency" :min="1" :max="32" />
</div>
<div class="form-row" style="align-items: start">
<label>
项目
<n-tooltip>
<template #trigger>
<n-icon class="hint" :size="15"><HelpCircleOutline /></n-icon>
</template>
选择要导出的指标。
</n-tooltip>
</label>
<n-checkbox-group v-model:value="groups">
<div v-for="item in meta?.groups[network] || []" :key="item.id" style="margin-bottom: 6px">
<n-checkbox :value="item.id">{{ item.label }}</n-checkbox>
<n-tooltip>
<template #trigger>
<n-icon class="hint" :size="14" style="margin-left: 4px"><HelpCircleOutline /></n-icon>
</template>
{{ item.columns.join("、") }}
</n-tooltip>
</div>
</n-checkbox-group>
</div>
<div class="form-row">
<label>
区域表
<n-tooltip>
<template #trigger>
<n-icon class="hint" :size="15"><HelpCircleOutline /></n-icon>
</template>
支持 CSV、TXT、XLSX。
</n-tooltip>
</label>
<div class="captcha-line">
<label class="n-button n-button--default-type" style="padding: 0 12px; line-height: 32px; border: 1px solid #d5e0ea; border-radius: 6px; cursor: pointer">
选择文件
<input type="file" accept=".csv,.txt,.xlsx" hidden @change="onFile" />
</label>
<span class="file-name">{{ file?.name || "尚未选择" }}</span>
</div>
</div>
<div class="form-row">
<label>保存到</label>
<div class="captcha-line">
<n-input v-model:value="outputDir" placeholder="默认目录" />
<n-button @click="pickDir">
<template #icon><n-icon><FolderOpenOutline /></n-icon></template>
</n-button>
</div>
</div>
</div>
</div>
</section>
</template>
+51
View File
@@ -0,0 +1,51 @@
import { api } from "../../shared/http";
export interface GroupOption {
id: string;
label: string;
columns: string[];
}
export interface Meta {
networks: { value: string; label: string }[];
cities: { name: string; code: string }[];
groups: Record<string, GroupOption[]>;
fixed: { grid: string[]; cell: Record<string, string[]> };
}
export interface DownloadJob {
id: string;
name: string;
status: string;
message: string;
network: string;
cityName: string;
month: string;
total: number;
completed: number;
failed: number;
writtenRows: number;
csvPath: string;
failures: { id: string; message: string }[];
createdAt: string;
}
export function loadMeta() {
return api<Meta>("/api/download/meta");
}
export function loadJobs() {
return api<{ jobs: DownloadJob[] }>("/api/download/jobs");
}
export function createJob(form: FormData) {
return api<DownloadJob>("/api/download/jobs", { method: "POST", body: form });
}
export function cancelJob(id: string) {
return api<DownloadJob>(`/api/download/jobs/${id}/cancel`, { method: "POST" });
}
export function resumeJob(id: string) {
return api<DownloadJob>(`/api/download/jobs/${id}/resume`, { method: "POST" });
}
View File
+5
View File
@@ -0,0 +1,5 @@
import { createApp } from "vue";
import App from "./App.vue";
import "./styles.css";
createApp(App).mount("#app");
+49
View File
@@ -0,0 +1,49 @@
export const API_BASE = import.meta.env.DEV ? "" : "http://127.0.0.1:8765";
export class ApiError extends Error {
status: number;
constructor(status: number, message: string) {
super(message);
this.status = status;
}
}
export async function api<T>(path: string, init?: RequestInit): Promise<T> {
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 });
} catch {
throw new ApiError(0, "连接失败");
}
const text = await response.text();
const data = text ? JSON.parse(text) : null;
if (!response.ok) {
const detail = data?.detail;
const message = typeof detail === "string" ? detail : "请求失败";
throw new ApiError(response.status, message);
}
return data as T;
}
export function health() {
return api<{ ok: boolean }>("/api/health");
}
export async function openLocal(path: string) {
if (!("__TAURI_INTERNALS__" in window)) return false;
const { openPath } = await import("@tauri-apps/plugin-opener");
await openPath(path);
return true;
}
export async function chooseDirectory() {
if (!("__TAURI_INTERNALS__" in window)) return null;
const { open } = await import("@tauri-apps/plugin-dialog");
const selected = await open({ directory: true, multiple: false });
return typeof selected === "string" ? selected : null;
}
+24
View File
@@ -0,0 +1,24 @@
import { ref, watch } from "vue";
const stored = localStorage.getItem("nqi-theme");
export const isDark = ref(stored === "dark");
watch(isDark, (value) => {
localStorage.setItem("nqi-theme", value ? "dark" : "light");
document.documentElement.dataset.theme = value ? "dark" : "light";
}, { immediate: true });
export function toggleTheme() {
isDark.value = !isDark.value;
}
export const themeOverrides = {
common: {
primaryColor: "#2563eb",
primaryColorHover: "#1d4ed8",
primaryColorPressed: "#1e40af",
primaryColorSuppl: "#2563eb",
borderRadius: "6px",
fontFamily: '"Segoe UI", "Microsoft YaHei", sans-serif',
},
};
+61
View File
@@ -0,0 +1,61 @@
<script setup lang="ts">
import { ref } from "vue";
import { NButton, NIcon, NLayoutSider, NMenu } from "naive-ui";
import { LogOutOutline, MoonOutline, PersonOutline, SunnyOutline } from "@vicons/ionicons5";
import { logout, type UserInfo } from "../features/auth/api";
import { isDark, toggleTheme } from "../shared/theme";
import { navGroups, type PageKey } from "./navigation";
import GridDownloadView from "../features/download/GridDownloadView.vue";
import DownloadManagerView from "../features/download/DownloadManagerView.vue";
const props = defineProps<{ user: UserInfo }>();
const emit = defineEmits<{ logout: [] }>();
const page = ref<PageKey>("grid");
const focusId = ref("");
function onMenu(key: string) {
if (key === "grid" || key === "tasks") page.value = key;
}
function onStarted(id: string) {
focusId.value = id;
page.value = "tasks";
}
async function signOut() {
try {
await logout();
} finally {
emit("logout");
}
}
</script>
<template>
<div class="shell">
<aside class="sider">
<div class="sider-title">NqiTools</div>
<n-layout-sider :native-scrollbar="false" :width="220" style="background: transparent; flex: 1">
<n-menu :value="page" :options="navGroups" @update:value="onMenu" />
</n-layout-sider>
<div class="sider-user">
<n-icon :size="18"><PersonOutline /></n-icon>
<div class="who">
<strong>{{ props.user.userName || props.user.loginId }}</strong>
<span>{{ props.user.cityName || "已登录" }}</span>
</div>
<n-button quaternary circle size="small" :aria-label="isDark ? '切换到日间' : '切换到夜间'" @click="toggleTheme">
<template #icon><n-icon><MoonOutline v-if="!isDark" /><SunnyOutline v-else /></n-icon></template>
</n-button>
<n-button quaternary circle size="small" aria-label="退出" @click="signOut">
<template #icon><n-icon><LogOutOutline /></n-icon></template>
</n-button>
</div>
</aside>
<main class="content">
<GridDownloadView v-if="page === 'grid'" @started="onStarted" />
<DownloadManagerView v-else :focus-id="focusId" />
</main>
</div>
</template>
+22
View File
@@ -0,0 +1,22 @@
import type { Component } from "vue";
import { h } from "vue";
import { NIcon } from "naive-ui";
import { CloudDownloadOutline, ListOutline } from "@vicons/ionicons5";
function renderIcon(icon: Component) {
return () => h(NIcon, null, { default: () => h(icon) });
}
export type PageKey = "grid" | "tasks";
export const navGroups = [
{
type: "group" as const,
label: "下载",
key: "download",
children: [
{ label: "栅格下载", key: "grid" as const, icon: renderIcon(CloudDownloadOutline) },
{ label: "下载管理", key: "tasks" as const, icon: renderIcon(ListOutline) },
],
},
];
+357
View File
@@ -0,0 +1,357 @@
:root {
color: var(--ink);
background: var(--bg);
font-family: "Segoe UI", "Microsoft YaHei", sans-serif;
font-size: 14px;
--bg: #f3f4f6;
--panel: #ffffff;
--ink: #111827;
--muted: #6b7280;
--line: #e5e7eb;
--accent: #2563eb;
--accent-soft: #eff6ff;
--sidebar: #ffffff;
}
:root[data-theme="dark"] {
--bg: #0f172a;
--panel: #1e293b;
--ink: #f8fafc;
--muted: #94a3b8;
--line: #334155;
--accent: #60a5fa;
--accent-soft: #1e3a8a;
--sidebar: #111827;
}
::selection {
background: var(--accent-soft);
color: var(--ink);
}
html,
body,
#app {
margin: 0;
height: 100%;
}
button,
input,
select {
font-family: inherit;
}
.gate {
position: relative;
min-height: 100%;
display: grid;
place-items: center;
padding: 32px 16px;
background: var(--bg);
}
.theme-switch {
position: absolute;
top: 16px;
right: 16px;
}
.gate-card {
width: min(440px, 100%);
background: var(--panel);
border: 1px solid var(--line);
border-radius: 12px;
box-shadow: 0 10px 28px rgba(17, 24, 39, 0.08);
padding: 28px 28px 22px;
}
.brand {
display: flex;
gap: 14px;
align-items: center;
margin-bottom: 22px;
}
.brand-mark {
width: 44px;
height: 44px;
border-radius: 10px;
background: var(--accent);
color: #fff;
display: grid;
place-items: center;
flex: none;
}
.brand h1 {
margin: 0;
font-size: 20px;
line-height: 1.3;
}
.brand p,
.file-name,
.hint,
.task .sub,
.empty {
color: var(--muted);
}
.form-row {
display: grid;
grid-template-columns: 84px minmax(0, 1fr);
gap: 8px 12px;
align-items: center;
margin-bottom: 12px;
}
.brand p {
margin: 2px 0 0;
font-size: 13px;
}
.captcha-line {
display: flex;
gap: 8px;
align-items: center;
}
.form-row label {
display: flex;
align-items: center;
gap: 4px;
color: var(--ink);
}
.captcha-line img {
width: 112px;
height: 36px;
border: 1px solid var(--line);
border-radius: 6px;
background: var(--bg);
cursor: pointer;
object-fit: cover;
}
.gate-actions {
display: flex;
justify-content: flex-end;
gap: 8px;
margin-top: 8px;
}
.shell {
height: 100%;
display: grid;
grid-template-columns: 220px minmax(0, 1fr);
background: var(--bg);
color: var(--ink);
}
.sider {
display: flex;
flex-direction: column;
background: var(--sidebar);
border-right: 1px solid var(--line);
min-height: 0;
}
.sider-title {
padding: 18px 16px 8px;
font-weight: 650;
font-size: 16px;
}
.sider-user {
margin-top: auto;
padding: 12px;
border-top: 1px solid var(--line);
display: flex;
align-items: center;
gap: 8px;
}
.sider-user .who {
min-width: 0;
flex: 1;
}
.sider-user strong,
.sider-user span {
display: block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.sider-user span {
color: var(--muted);
font-size: 12px;
}
.content {
min-width: 0;
min-height: 0;
display: flex;
flex-direction: column;
}
.page {
min-height: 0;
flex: 1;
display: flex;
flex-direction: column;
}
.page-scroll {
min-height: 0;
flex: 1;
overflow: auto;
}
.page-head {
position: sticky;
top: 0;
z-index: 2;
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
padding: 14px 20px;
background: var(--bg);
border-bottom: 1px solid var(--line);
}
.page-head h2 {
margin: 0;
font-size: 18px;
}
.page-head p {
margin: 2px 0 0;
color: var(--muted);
font-size: 12px;
}
.head-actions {
display: flex;
gap: 8px;
align-items: center;
}
.panel,
.task {
background: var(--panel);
border: 1px solid var(--line);
}
.panel {
margin: 16px 20px 24px;
border-radius: 10px;
padding: 16px 16px 8px;
}
.hint {
cursor: help;
}
.tabs {
display: flex;
gap: 8px;
padding: 12px 20px 0;
}
.file-name {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.tab {
border: 0;
background: transparent;
color: var(--muted);
border-bottom: 2px solid transparent;
padding: 8px 2px;
margin-right: 16px;
cursor: pointer;
font-size: 14px;
}
.tab.on {
color: var(--accent);
border-bottom-color: var(--accent);
font-weight: 650;
}
.tab em {
font-style: normal;
margin-left: 6px;
color: var(--accent);
background: var(--accent-soft);
border-radius: 99px;
padding: 0 7px;
font-size: 12px;
}
.task-list {
flex: 1;
min-height: 0;
overflow: auto;
padding: 12px 20px 24px;
display: flex;
flex-direction: column;
gap: 10px;
}
.task {
border-radius: 10px;
padding: 12px 14px;
}
.task.focus {
border-color: var(--accent);
box-shadow: 0 0 0 2px color-mix(in srgb, var(--accent) 20%, transparent);
}
.task-top,
.task-foot {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.task h3 {
margin: 0;
font-size: 15px;
}
.empty {
margin: 48px auto;
text-align: center;
}
.task-actions {
display: flex;
gap: 6px;
flex: none;
}
.fail-list {
margin: 8px 0 0;
padding-left: 18px;
color: #9a4d16;
font-size: 12px;
}
.task .sub {
margin-top: 2px;
font-size: 12px;
}
.empty {
margin: 48px auto;
text-align: center;
}
+7
View File
@@ -0,0 +1,7 @@
/// <reference types="vite/client" />
declare module "*.vue" {
import type { DefineComponent } from "vue";
const component: DefineComponent<{}, {}, any>;
export default component;
}
+25
View File
@@ -0,0 +1,25 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"module": "ESNext",
"lib": ["ES2020", "DOM"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "preserve",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"],
"references": [{ "path": "./tsconfig.node.json" }]
}
+10
View File
@@ -0,0 +1,10 @@
{
"compilerOptions": {
"composite": true,
"skipLibCheck": true,
"module": "ESNext",
"moduleResolution": "bundler",
"allowSyntheticDefaultImports": true
},
"include": ["vite.config.ts"]
}
+38
View File
@@ -0,0 +1,38 @@
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
// @ts-expect-error type error without @types/node package
import process from "node:process";
const host = process.env.TAURI_DEV_HOST;
// https://vite.dev/config/
export default defineConfig(() => ({
plugins: [vue()],
// Vite options tailored for Tauri development and only applied in `tauri dev` or `tauri build`
//
// 1. prevent Vite from obscuring rust errors
clearScreen: false,
// 2. tauri expects a fixed port, fail if that port is not available
server: {
port: 1420,
strictPort: true,
host: host || false,
proxy: {
"/api": {
target: "http://127.0.0.1:8765",
changeOrigin: true,
},
},
hmr: host
? {
protocol: "ws",
host,
port: 1421,
}
: undefined,
watch: {
// 3. tell Vite to ignore watching `src-tauri`
ignored: ["**/src-tauri/**"],
},
},
}));