feat(registry): 迁移至 Rust + Axum + SQLite 并新增编辑、分页和档案同步功能

- 后端从 Node.js 迁移到 Rust,使用 Axum 框架和 SQLite 存储
- 新增档案编辑对话框,支持修改机型、登记人及替换/删除照片
- 档案列表增加分页导航(每页20条)
- 新增档案同步状态提示及手动重试同步按钮
- Node.js 原版后端及网页保留为回退方案,移至 legacy-web 目录
- 更新 .gitignore 添加 Rust 构建产物(target、dist)
- 更新 README 文档,补充 Rust 启动、开发、检查及打包说明
- 启动源码版.cmd 默认转发至 Rust 版启动脚本
```
This commit is contained in:
2026-10-21 11:54:38 +08:00
parent 85924f35ff
commit 4d55796cb3
39 changed files with 5925 additions and 39 deletions
+5
View File
@@ -0,0 +1,5 @@
[build]
target-dir = "D:/Rust_Contact/util/target/Rid_Drone_Receivev"
[target.x86_64-pc-windows-msvc]
rustflags = ["-C", "target-feature=+crt-static"]
+2
View File
@@ -9,3 +9,5 @@ host/
# 临时文件 # 临时文件
*.tmp *.tmp
*.log *.log
/target/
/dist/
Generated
+1198
View File
File diff suppressed because it is too large Load Diff
+27
View File
@@ -0,0 +1,27 @@
[package]
name = "fpv-rid-registry"
version = "3.0.0"
edition = "2024"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "signal"] }
rusqlite = { version = "0.38", features = ["bundled", "backup"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
base64 = "0.22"
rand = "0.9"
chrono = "0.4"
zip = { version = "4", default-features = false, features = ["deflate"] }
rust_xlsxwriter = "0.90"
fs2 = "0.4"
regex = "1"
[dev-dependencies]
tempfile = "3"
tower = { version = "0.5", features = ["util"] }
[profile.release]
lto = true
strip = true
codegen-units = 1
+20 -13
View File
@@ -1,8 +1,19 @@
# Rid_Drone_Receivev # Rid_Drone_Receivev
FPV-RID 本地备案源码(新版2整理版)。对应 GitHub 仓库:`zhangshuochi/Rid_Drone_Receivev`。 FPV-RID 本地备案登记站,Rust + Axum + SQLite。对应 GitHub 仓库:`zhangshuochi/Rid_Drone_Receivev`。
这份工程从你指定的 **`FPV-RID_本地登记验证_新版2`** 提取。业务源码保持原版内容,新增了启动入口和开发说明,方便后续维护和与 RID 监管平台联动。原桌面目录未改动。 Rust 版本复用原有数据格式和网页,增加编辑、照片删除、分页和档案同步重试。项目仅保留 Rust 后端,不再提供 Node.js 回退版本。设备上位机及无线 RID 接收不在本仓库实现范围内。
## Rust 启动与验证
- 发布目录:双击 `启动Rust版.cmd`,打开 http://127.0.0.1:8787/ ,无需 Node.js。
- 开发:`cargo run -- --data-root .`;Release:`cargo build --release --locked`。
- 仓库 `启动源码版.cmd` 默认转到 Rust。
- 检查:`cargo fmt --check`、`cargo clippy --all-targets -- -D warnings`、`cargo test`。
- 接口与数据验收:`node scripts/verify.mjs`,仅使用独立临时目录。
- 打包:`powershell -ExecutionPolicy Bypass -File scripts/package.ps1`,输出发布目录、Windows ZIP 和校验和;检测到发布目录含运行数据时停止,可用 `-OutputRoot` 指定干净目录。
完整说明见 [Rust 使用说明](doc/registry/rust/使用说明.md) 和 [接口补充](doc/registry/rust/接口变更.md)。默认数据根目录为 exe 所在目录,开发时明确传 `--data-root .`。更新前关闭旧实例并备份原数据库,禁止两个版本同时运行。
## 一句话看懂 ## 一句话看懂
@@ -12,22 +23,18 @@ FPV-RID 本地备案源码(新版2整理版)。对应 GitHub 仓库:`zhang
| 位置 | 用途 | | 位置 | 用途 |
| --- | --- | | --- | --- |
| `registry/server.js` | 本地 HTTP 服务、接口、离线档案卡和档案备份 | | `src/` | Rust HTTP 服务、SQLite 事务、档案备份和导出 |
| `registry/database.js` | SQLite 表、登记、搜索、删除、照片保存 | | `Cargo.toml`、`Cargo.lock`、`rust-toolchain.toml` | Rust 依赖、锁定版本与工具链 |
| `registry/export-files.js` | ZIP 档案包和 Excel 导出 |
| `registry/web/` | 登记网页、样式、二维码脚本和图标 | | `registry/web/` | 登记网页、样式、二维码脚本和图标 |
| `scripts/` | 环境、打包、兼容及浏览器验收脚本 |
| `docs/原版使用说明.md` | 新版2附带的原始说明 | | `docs/原版使用说明.md` | 新版2附带的原始说明 |
| `docs/架构与RID联动.md` | 数据流、字段和对接方式 | | `docs/架构与RID联动.md` | 数据流、字段和对接方式 |
| `docs/接口清单.md` | 本地 HTTP 接口说明 | | `docs/接口清单.md` | 本地 HTTP 接口说明 |
| `启动源码版.cmd` | Windows 启动入口 | | `启动源码版.cmd` | Windows 启动入口 |
## 启动 ## 开发验收脚本
1. 使用 **Node.js 24**。原版自带的是 **24.19.0**;本包不重复附带 `node.exe`。可以安装 Node.js,或从你原版目录把 `runtime/node.exe` 复制到本包的 `runtime/node.exe`。 `scripts/*.mjs` 使用 Node.js 执行开发验收,不属于服务运行依赖,也不提供 Node.js 后端。运行登记站只需 Rust 可执行文件和浏览器。
2. 双击 `启动源码版.cmd`,保持命令窗口打开。
3. 在同一台电脑的浏览器打开 `http://127.0.0.1:8787/`。
项目没有 npm 第三方依赖,二维码脚本已随源码保存。如果原版登记站正在运行,先关闭原版;两个实例都使用 8787 端口。
## 已有备案数据怎么迁移 ## 已有备案数据怎么迁移
@@ -38,8 +45,8 @@ FPV-RID 本地备案源码(新版2整理版)。对应 GitHub 仓库:`zhang
## 后续开发先看哪里 ## 后续开发先看哪里
- 改登记表单和页面:`registry/web/index.html`、`app.js`、`app.css`。 - 改登记表单和页面:`registry/web/index.html`、`app.js`、`app.css`。
- 改校验规则或查询:`registry/database.js`。 - 改校验规则或查询:`src/store.rs`。
- 改本地接口和档案卡:`registry/server.js`。 - 改本地接口和档案卡:`src/http.rs`、`src/archive.rs`;数据库逻辑在 `src/store.rs`。
- 接入无人机监管平台:先看 `docs/架构与RID联动.md`。备案记录可用于判断“已备案 / 未匹配”,RID 实时坐标仍由基站上报。 - 接入无人机监管平台:先看 `docs/架构与RID联动.md`。备案记录可用于判断“已备案 / 未匹配”,RID 实时坐标仍由基站上报。
当前服务仅监听 `127.0.0.1`,没有登录认证。要让局域网内的其他电脑读取档案,应由 RID 平台后端做受控同步接口,不能直接把这个本地服务改成对全网开放。 当前服务仅监听 `127.0.0.1`,没有登录认证。要让局域网内的其他电脑读取档案,应由 RID 平台后端做受控同步接口,不能直接把这个本地服务改成对全网开放。
+48
View File
@@ -0,0 +1,48 @@
# FPV-RID Rust 本地登记站
## 运行
Windows x64 发布目录中双击 `启动Rust版.cmd`,保持窗口打开,使用浏览器访问 http://127.0.0.1:8787/ 。不需要 Node.js;不包含无线 RID 接收或设备上位机。
默认数据目录是 exe 所在目录,不是命令行当前目录。目录必须可写,不要放在 Program Files。数据库仍为 `registry/data/registry.sqlite`,自动档案仍在 `档案库/`。高级用法:`fpv-rid-registry.exe --data-root "D:\我的备案"`。
同一时刻只运行一个登记站。8787 被占用时先关闭原版或其他实例。Rust 版本另外锁定数据目录;旧版 Node 不认识这把锁,因此仍需人工关闭旧版。
## 编辑和照片
卡片点击“编辑资料 / 照片”,在弹窗修改机型、登记人。空字符串保存表示清空,SN 和 FPV 编号不可修改。照片可保留、替换或单独删除。先选择替换文件会取消该照片的删除勾选,反之亦然。
资料与照片通过一次请求、同一数据库事务提交,校验或数据库写入失败全部回滚。连接中断时客户端不能判定是否已提交,请刷新核对保存结果。
列表每页 20 条,搜索回到第一页。全选、导出仅包含当前页选中记录;切换页或搜索会清空选择。
## 保存与备份
数据库是主数据源。保存成功但档案或备份写入失败时,显示“数据已保存,档案备份待同步”。修复文件权限、磁盘空间或文件占用后点击“重试同步”。重启也会重建档案。
待同步状态保存在 SQLite 内部元数据表,与业务修改一起提交。旧 `registry/data/archive-pending.json` 会自动迁移后删除;不要手工修改元数据。删除档案或照片后同步时会清除上一份备份;同步失败时旧派生文件可能仍包含删除前的内容,需恢复同步。已导出到其他目录的文件不随删除操作清除。
## 迁移与回退
1. 关闭原版登记站,独立备份原版数据库及整个档案库;不要直接复制正在写入的 SQLite。
2. 首次使用先复制数据库到单独测试目录,通过 `--data-root` 验证记录、照片和二维码。
3. 正式更新仅替换程序文件,不覆盖 `registry/data/` 和 `档案库/`。
4. 本项目不再提供 Node.js 回退版本。恢复数据前关闭 Rust 并备份当前数据,再恢复已确认完整的数据库备份。
旧 `records.json` 采用整批事务导入:缺少必填字段、无效内容或重复 ID/SN/FPV 编号时,启动报错会指出记录序号,全部记录回滚,原 JSON 保留且不标记完成。修正文件后重启会重试。已经标记完成的旧库不会自动清除标记或重新导入,以免恢复用户主动删除的记录;如需核对旧版历史导入,应先在独立副本中处理。
不要使用空数据库覆盖现有数据库。二维码指向当前电脑的 127.0.0.1,不能当成跨电脑分享链接。备份包含登记人及照片,应妥善保存。
## 开发与打包
本机 Rust 环境集中在 `D:\Rust_Contact\util`:`cargo/` 保存 Cargo 工具和依赖缓存,`rustup/` 保存编译工具链,`downloads/` 保存安装包,`target/Rid_Drone_Receivev/` 保存本项目构建产物。用户环境变量 CARGO_HOME、RUSTUP_HOME 指向上述目录,PATH 加入 cargo/bin;新终端生效。
仓库 `.cargo/config.toml` 固定本机构建缓存目录,发布脚本通过 Cargo metadata 获取产物位置。发布包仍生成到仓库 `dist/`,业务数据库不放在 util。更换开发机器时调整该本机路径配置。共享 Node.js、Visual Studio 和 Windows SDK 不属于此次清理范围。
安装 Rust stable MSVC 及 Visual Studio C++ Build Tools 后,运行 `cargo run -- --data-root .`。检查:`cargo fmt --check`、`cargo clippy --all-targets -- -D warnings`、`cargo test`。Release:`cargo build --release --locked`。
本仓库将稳定工具链固定为 1.99.1。已有终端若未刷新环境,可先在 PowerShell 执行 `. ./scripts/rust-env.ps1`。Rust 编译依赖保存在 util/cargo/registry;Windows SDK、Visual Studio 等共享组件保留在原安装目录。
`scripts/package.ps1` 通过独立暂存目录及六文件白名单,生成 `dist/FPV-RID-Rust/`、Windows ZIP 和两份 SHA-256 清单,不打包备案数据。若已有发布目录含数据库、档案或其他非发布文件,脚本会停止并保留原内容及旧 ZIP;请使用 `./scripts/package.ps1 -OutputRoot "D:\单独发布目录"` 指定干净输出目录。禁止把正在使用的数据目录作为打包暂存目录。
`node scripts/verify.mjs` 在独立临时目录执行 Rust Release 版接口、导出、重启和旧数据导入验收;Node.js 仅作为开发测试工具;`powershell -ExecutionPolicy Bypass -File scripts/test-package.ps1` 验证重复打包、运行数据隔离及校验和。临时验收目录保留作为证据,不触及正式数据。
+14
View File
@@ -0,0 +1,14 @@
# Rust 接口补充
旧版接口与 JSON 驼峰字段保留。GET `/api/records` 未传分页参数时仍返回完整 `{records:[...]}`。
- GET `/api/records?q=关键词&page=1&pageSize=20`:新增 page、pageSize、total、totalPages。页号从 1 开始,pageSize 为 1–100;超出最后一页返回空数组。按创建时间倒序、ID 倒序稳定排序。
- PATCH `/api/records/:id`:JSON 可包含 modelName、ownerName、photo1、photo2;一次请求在同一事务更新。文字缺省保留、空字符串清空,文字 null 或非字符串无效;照片缺省保留、data URL 替换、null 删除,空字符串无效。拒绝空对象和其他字段。文字长度按 JavaScript UTF-16 语义限制为 60、40。已删除档案返回 404,不重新登记。
- DELETE `/api/records/:id/photos/1`(或 2):删除指定照片。档案不存在为 404,已缺失照片的删除是幂等成功。
- POST `/api/archive/retry`:重建档案卡、索引及 SQLite 备份。成功返回 `{archiveStatus:"synced"}`,失败返回 500 和 error。
- GET `/api/archive/status`:读取持久化待同步标记,让重启后的网页也能显示备份状态。
- 登记、修改、删除的成功响应增加 archiveStatus;pending 时增加 warning。已提交数据库不会因派生文件失败而报登记失败。
内部状态保存在 registry_meta 表,与业务修改同事务提交;旧 records/photos 表不变。旧 archive-pending.json 在首次启动时迁入数据库,提交后删除。旧 records.json 只导入一次,全部删除后重启不会再次导入。校验失败为 400,不存在为 404,来源限制为 403,内部数据库/文件故障为 500,详细错误仅写控制台。
仅监听本机。保留旧版 Origin 限制,以及 resolve 的跨源读取例外;其他来源不能通过网页操作登记接口。接口没有账号认证,不应直接暴露到局域网或互联网。
+51
View File
@@ -0,0 +1,51 @@
# Rust 迁移验收记录
## 2026-10-21 边界修复复验
- 旧 JSON 导入改为先校验所有记录,再执行普通 INSERT。缺失字段、错误类型、无效时间和重复 ID/SN/FPV 均报出记录序号,整批回滚,不写入导入完成标记;原文件保留,修正后可重试。已经完成的历史标记不自动清除,避免恢复主动删除的档案。
- 打包脚本使用独立暂存目录和六文件白名单,同时生成发布目录、ZIP 及 SHA-256。发布目录含运行数据、未知文件或重解析点时拒绝打包,不删除数据、不覆盖旧 ZIP;可用 -OutputRoot 另选干净输出位置。
- Rust 自动测试增至 9 项并全部通过;Clippy 严格检查、格式检查通过。
- Windows PowerShell 5.1 下执行 scripts/test-package.ps1 通过:干净目录连续打包、加入模拟数据库后拒绝打包、原数据和旧 ZIP 哈希保持、ZIP 仅含六个白名单文件、文件与 ZIP 校验和正确、暂存文件清理完成。
- 更新后的 Release 程序通过 scripts/verify.mjs:除原兼容场景外,实测异常旧 JSON 启动失败、记录与元数据均回滚为零、修正原文件后成功导入两条;前端分页回归仍通过。
- 本轮证据:`C:/Users/20143/AppData/Local/Temp/RID-package-review-738d63bb6b984a3f94f60252d9cfabf8/`、`C:/Users/20143/AppData/Local/Temp/RID-中文验证-4Bcnnh/`。以下为此前迁移的历史记录与边界。
日期:2026-10-20。目标:Windows x64。工具链:Rust/Cargo 1.99.1,固定于 rust-toolchain.toml。
## 实现结果
- 一次性导入:registry_meta 在导入事务中记录完成状态,删除全部记录后重启不会恢复 records.json 中的旧档案。
- 原子编辑:单次 PATCH 处理文字、照片替换和删除;数据库中途失败全部回滚,目标不存在时返回 404。
- 同步状态:与业务修改同事务提交;冲突和回滚不留下虚假状态,删除清理要求不会被后续编辑取消。
- 错误类型:校验 400、不存在 404、来源限制 403、内部故障 500,内部详细路径不返回客户端。
- SQL 查询:COUNT/LIMIT/OFFSET 分页、主键单条查询、按选中 ID 导出;分页失败不提交新页码,旧响应被忽略。
- 环境:CARGO_HOME、RUSTUP_HOME 和构建缓存均在 D:/Rust_Contact/util,用户目录无 .cargo/.rustup。
## 实际验证
- cargo fmt --check 通过。
- cargo clippy --all-targets --locked --offline -- -D warnings 通过。
- cargo test --locked --offline:7 项测试全部通过,包括数据库触发器注入故障后的事务回滚、Windows 独占占用备份文件后的恢复。
- cargo build --release --locked --offline 通过,启用 Release 优化、LTO 和静态 CRT,exe 为 6,293,504 字节。
- node scripts/test-frontend.mjs 通过:翻页失败保留页码、成功后更新、旧响应不覆盖。
- node scripts/verify.mjs 通过:Node 生成的 SQLite 由 Rust 直接读取;验证照片字节、二维码、HTML 转义、ZIP 内部清单和照片、XLSX 内部 XML、编辑和删除、故障重试、重启及备份完整性。
- scripts/test-browser.mjs 使用真实 Chromium 和 Release 服务通过:登记、照片、取消和焦点、一次 PATCH 编辑、坏图片回滚、分页、搜索回第一页、当前页 20 条选择及 Excel 下载;1366×1000 与 390×844 下无横向溢出,未出现页面脚本异常。已人工查看桌面和窄屏截图。
- node scripts/test-release.mjs 通过:复制真实发布包至中文临时目录,以不同 cwd 和仅含 Windows System32 的 PATH 启动;数据库位于 exe 旁,内嵌网页可访问;第二实例占用端口时失败且不创建数据库。
- dumpbin /DEPENDENTS 仅列 Windows 系统 DLL,无 Node、SQLite 或 Visual C++ 运行库 DLL 外部依赖。
所有数据验收使用独立临时目录。未向正式数据根目录写入备案。工作区原有 registry/testgit 删除保持不变,未提交或推送。
## 证据目录(本机)
- API 兼容:`C:/Users/20143/AppData/Local/Temp/RID-中文验证-HQJED1/`,含 Node/Rust 导出文件及备份。
- 浏览器:`C:/Users/20143/AppData/Local/Temp/RID-浏览器验收-NGRiYx/`,含 desktop.png、mobile-dialog.png、Excel 导出和服务日志。
- 发布运行:`C:/Users/20143/AppData/Local/Temp/RID-便携验收-bPjEL9/`。
## 边界
本次为同一台 Windows 电脑上的验证,没有进行另一台电脑、真实 RID 模块或原版上位机硬件联调,也未做大规模档案压测。SQLite 提交和档案文件生成仍为两个阶段,通过持久化同步状态恢复;已导出副本不会自动撤回。静态 DLL 检查不能替代跨机器验收。正常 Ctrl+C 的处理代码已实现,但未单独验证控制台关闭和断电场景。
SOURCE_MANIFEST.sha256 是原 Node 源码提取时的历史校验清单,不代表改造后源码;当前发布包以 SHA256SUMS.txt 为准。
## 清理结果与限制
未完成的旧 stable 工具链、重复下载分片和旧位置下载文件已清理;用户目录无 .cargo/.rustup,Node.js、Visual Studio 和 Windows SDK 保留。中断安装遗留的 `D:/Rust_Contact/util/rustup/tmp` 临时项仍存在:自动审批审查拒绝递归清理,返回 `blocked by policy`,未提供更具体原因。未绕过该限制;它们不参与程序运行或发布包。
+2 -2
View File
@@ -4,8 +4,8 @@
```mermaid ```mermaid
flowchart LR flowchart LR
A[用户在本机网页登记] --> B[server.js] A[用户在本机网页登记] --> B[src/http.rs / Axum]
B --> C[database.js / SQLite] B --> C[src/store.rs / SQLite]
C --> D[档案库 / 离线档案卡和备份] C --> D[档案库 / 离线档案卡和备份]
B --> E[网页二维码] B --> E[网页二维码]
E --> F[本地版上位机] E --> F[本地版上位机]
+7
View File
@@ -0,0 +1,7 @@
<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>FPV-RID 界面方案 · 独立演示</title><style>
*{box-sizing:border-box}body{margin:0;font:15px/1.65 system-ui,'Microsoft YaHei',sans-serif;background:#eef3f7;color:#173047}main{max-width:1200px;margin:auto;padding:32px}h1{font-size:26px}h2{font-size:21px;margin:0 0 8px}h3{margin:8px 0}section{background:white;border:1px solid #dce6ee;border-radius:14px;padding:24px;margin:24px 0}p{color:#61788a}.banner{background:#fff4da;color:#6b5011;padding:12px}.tools,.pages,.actions{display:flex;gap:10px;align-items:center;flex-wrap:wrap}button,input{font:inherit;border:1px solid #bdcedb;border-radius:6px;padding:7px 12px;background:white;color:inherit}button{cursor:pointer}button:focus-visible{outline:3px solid #206d9f}button.primary{background:#206d9f;color:white}.muted{font-size:13px;color:#61788a}.grid{display:grid;grid-template-columns:1fr 1fr;gap:16px}.record,.editor{border:1px solid #dce6ee;padding:16px;border-radius:10px}.photo{display:grid;place-items:center;min-height:90px;background:#edf2f5;color:#61788a}.pages{justify-content:flex-end;margin-top:18px}label{display:block;margin:10px 0}label input{display:block;width:100%}table{width:100%;border-collapse:collapse}td,th{text-align:left;border-bottom:1px solid #dce6ee;padding:12px}.editor{background:#f7fafc}.notice{padding:10px;background:#fff4da}.drawer{display:grid;grid-template-columns:1.3fr 1fr;gap:20px}dialog{border:1px solid #bdcedb;border-radius:12px;max-width:480px;width:90%}@media(max-width:700px){main{padding:14px}.grid,.drawer{grid-template-columns:1fr}.scroll{overflow:auto}section{padding:16px}}
</style><main><h1>FPV-RID · 三种操作布局</h1><p class="banner">独立演示,全部为虚构示例,不连接后端或设备,不保存数据。请选择 A / B / C 或明确组合。</p>
<section><h2>A · 保留卡片,弹窗编辑</h2><p>延续现有布局,改动较小。照片和档案并排查看;编辑时打开对话框,适合少量日常备案。</p><div class="notice" role="status">数据已保存,档案备份待同步 <button onclick="this.textContent='演示:已请求重试'">重试同步</button></div><div class="grid"><article class="record"><span class="muted">□ 选择当前档案</span><h3>DEMO-SN-001</h3><strong>FPV00000001</strong><p>演示机型 · 演示登记人</p><div class="grid"><div class="photo">照片 1(演示)</div><div class="photo">照片 2 未上传</div></div><div class="actions"><button onclick="document.querySelector('dialog').showModal()">编辑资料 / 照片</button><button>打开档案卡</button></div></article><article class="record"><h3>DEMO-SN-002</h3><strong>FPV00000002</strong><p>第二条示例档案</p><div class="photo">照片未上传</div></article></div><div class="pages"><span>全选仅当前页 · 共 42 条</span><button>上一页</button><span>1 / 3</span><button>下一页</button></div></section>
<section><h2>B · 档案表格,右侧编辑区</h2><p>便于快速扫描和比较记录,选中一行后在右侧编辑;照片空间较小,窄屏需要上下排列。</p><div class="drawer"><div class="scroll"><table><tr><th>选择</th><th>模块 SN</th><th>FPV 编号</th></tr><tr><td>□</td><td>DEMO-SN-001</td><td>FPV00000001</td></tr><tr><td>□</td><td>DEMO-SN-002</td><td>FPV00000002</td></tr></table><div class="pages">42 条 <button>上一页</button>1 / 3<button>下一页</button></div></div><div class="editor"><h3>编辑 DEMO-SN-001</h3><span class="muted">SN、FPV 编号不可更改</span><label>机型<input value="演示机型"></label><label>登记人 / 备注<input value="演示登记人"></label><div class="photo">照片 1(演示)</div><button onclick="this.textContent='演示:保存时删除照片'">删除照片 1</button><p class="notice">备份待同步 <button>重试</button></p><button class="primary">保存修改(演示)</button></div></div></section>
<section><h2>C · 卡片内直接展开编辑</h2><p>在档案上下文内编辑,少一次弹窗切换;展开后卡片高度增加,适合逐条整理档案。</p><article class="record"><h3>DEMO-SN-001 · FPV00000001</h3><details open><summary>编辑机型、登记人与照片</summary><div class="grid"><label>机型<input value="演示机型"></label><label>登记人 / 备注<input value="演示登记人"></label><div><div class="photo">照片 1(演示)</div><label><input type="checkbox" style="display:inline;width:auto"> 删除照片 1</label></div><div><div class="photo">照片 2 未上传</div><button>选择替换照片(演示)</button></div></div><div class="actions"><button class="primary">保存修改(演示)</button><button>取消</button><span class="muted">空文本表示清空;编号保持不变</span></div></details></article><div class="pages"><span>备份待同步</span><button>重试同步</button><span>共 42 条 · 1 / 3</span><button>下一页</button></div></section>
<dialog><h2>编辑档案(A 演示)</h2><p>DEMO-SN-001 · FPV00000001 · 编号只读</p><label>机型<input value="演示机型"></label><label>登记人 / 备注<input value="演示登记人"></label><div class="photo">照片 1(演示)</div><label><input type="checkbox" style="display:inline;width:auto"> 删除照片 1</label><p class="muted">文本清空后保存即删除该字段内容。</p><div class="actions"><button class="primary" onclick="this.closest('dialog').close()">演示保存</button><button onclick="this.closest('dialog').close()">取消</button></div></dialog></main></html>
File diff suppressed because one or more lines are too long
+274
View File
@@ -0,0 +1,274 @@
const $ = id => document.getElementById(id);
let activeRecord = null;
let listedRecords = [];
const selectedIds = new Set();
let listRequestId = 0;
let searchTimer;
function setMessage(message, error = false) {
$('form-message').textContent = message;
$('form-message').classList.toggle('error', error);
}
function setHistoryMessage(message, error = false) {
$('history-message').textContent = message;
$('history-message').classList.toggle('error', error);
}
function updateSelectionControls() {
const count = selectedIds.size;
$('selected-count').textContent = `(${count})`;
$('select-all').checked = listedRecords.length > 0 && count === listedRecords.length;
$('select-all').indeterminate = count > 0 && count < listedRecords.length;
$('export-archive').disabled = count === 0;
$('export-excel').disabled = count === 0;
}
function formatTime(iso) {
try { return new Date(iso).toLocaleString('zh-CN', { hour12: false }); }
catch { return iso; }
}
async function readPhoto(input, slot) {
const file = input.files?.[0];
if (!file) return null;
if (!['image/jpeg', 'image/png', 'image/webp'].includes(file.type)) throw new Error(`照片 ${slot} 仅支持 JPG、PNG 或 WebP`);
if (file.size > 5 * 1024 * 1024) throw new Error(`照片 ${slot} 不能超过 5 MB`);
return await new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = () => reject(new Error(`照片 ${slot} 读取失败`));
reader.readAsDataURL(file);
});
}
function drawRecord(record) {
activeRecord = record;
$('empty-result').hidden = true;
$('record-result').hidden = false;
$('display-uas').textContent = record.uasCode;
$('display-sn').textContent = record.serialNo;
$('display-model').textContent = record.modelName || '—';
$('display-owner').textContent = record.ownerName || '—';
$('display-url').textContent = record.qrUrl;
$('open-card').href = record.archiveUrl;
$('download-card').href = record.downloadArchiveUrl;
$('saved-photos').hidden = !record.photo1Url && !record.photo2Url;
for (const [slot, url] of [[1, record.photo1Url], [2, record.photo2Url]]) {
const link = $(`photo-${slot}-link`);
link.hidden = !url;
if (url) {
link.href = url;
$(`photo-${slot}-preview`).src = `${url}?v=${Date.now()}`;
}
}
const qr = qrcode(0, 'M');
qr.addData(record.qrUrl);
qr.make();
$('qr-stage').innerHTML = qr.createSvgTag({ cellSize: 6, margin: 4 });
}
async function loadRecords() {
const requestId = ++listRequestId;
const query = $('history-query').value.trim();
const response = await fetch(`/api/records?q=${encodeURIComponent(query)}`);
const payload = await response.json();
if (!response.ok) throw new Error(payload.error || '读取记录失败');
if (requestId !== listRequestId) return;
const body = $('history-cards');
body.replaceChildren();
listedRecords = payload.records;
$('search-count').textContent = query ? `${listedRecords.length} 条` : '';
const currentIds = new Set(listedRecords.map(record => record.id));
for (const id of selectedIds) if (!currentIds.has(id)) selectedIds.delete(id);
$('history-empty').hidden = listedRecords.length > 0;
$('history-empty').textContent = query ? '没有找到匹配的档案。' : '暂无登记记录。';
for (const record of listedRecords) {
const card = document.createElement('article');
card.className = 'archive-card';
card.classList.toggle('selected', selectedIds.has(record.id));
const select = document.createElement('label');
select.className = 'archive-select';
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.checked = selectedIds.has(record.id);
checkbox.setAttribute('aria-label', `选择档案 ${record.serialNo}`);
checkbox.addEventListener('change', () => {
if (checkbox.checked) selectedIds.add(record.id); else selectedIds.delete(record.id);
card.classList.toggle('selected', checkbox.checked);
updateSelectionControls();
});
select.append(checkbox, document.createTextNode('导出'));
const title = document.createElement('h3');
title.textContent = record.serialNo;
const code = document.createElement('strong');
code.textContent = record.uasCode;
const detail = document.createElement('p');
detail.textContent = `${record.modelName || '未填机型'} · ${record.ownerName || '未填登记人'} · ${formatTime(record.createdAt)}`;
const images = document.createElement('div');
images.className = 'archive-thumbs';
for (const [slot, url] of [[1, record.photo1Url], [2, record.photo2Url]]) {
const thumb = document.createElement('div');
if (url) {
const image = document.createElement('img');
image.src = url;
image.alt = `登记照片 ${slot}`;
image.loading = 'lazy';
thumb.append(image);
} else {
thumb.textContent = `照片 ${slot} 未上传`;
}
images.append(thumb);
}
const actions = document.createElement('div');
actions.className = 'archive-actions';
const open = document.createElement('a');
open.href = record.archiveUrl;
open.target = '_blank';
open.rel = 'noopener';
open.textContent = '打开档案卡';
const download = document.createElement('a');
download.href = record.downloadArchiveUrl;
download.textContent = '下载离线档案卡';
const showQr = document.createElement('button');
showQr.type = 'button';
showQr.textContent = '查看二维码';
showQr.addEventListener('click', () => { drawRecord(record); $('result-title').scrollIntoView({ behavior: 'smooth' }); });
const remove = document.createElement('button');
remove.type = 'button';
remove.className = 'delete-record';
remove.textContent = '删除档案';
remove.addEventListener('click', async () => {
if (!confirm(`确定删除 ${record.serialNo} 的登记档案和照片吗?`)) return;
remove.disabled = true;
try {
const response = await fetch(`/api/records/${record.id}`, { method: 'DELETE' });
const payload = await response.json();
if (!response.ok) throw new Error(payload.error || '删除失败');
selectedIds.delete(record.id);
if (activeRecord?.id === record.id) {
activeRecord = null;
$('record-result').hidden = true;
$('empty-result').hidden = false;
}
await loadRecords();
setHistoryMessage(`已删除 ${record.serialNo} 的档案。`);
} catch (error) { setHistoryMessage(error.message, true); remove.disabled = false; }
});
actions.append(open, download, showQr, remove);
card.append(select, title, code, detail, images, actions);
body.append(card);
}
updateSelectionControls();
}
$('register-form').addEventListener('submit', async event => {
event.preventDefault();
const button = $('register-button');
button.disabled = true;
setMessage('正在保存本地记录…');
const uasDigits = $('uas-code').value.trim();
try {
const [photo1, photo2] = await Promise.all([
readPhoto($('photo-1'), 1),
readPhoto($('photo-2'), 2),
]);
const response = await fetch('/api/records', {
method: 'POST', headers: { 'content-type': 'application/json' },
body: JSON.stringify({
serialNo: $('serial-no').value.trim(),
modelName: $('model-name').value.trim(),
ownerName: $('owner-name').value.trim(),
uasCode: uasDigits ? `FPV${uasDigits}` : '',
photo1, photo2,
}),
});
const payload = await response.json();
if (!response.ok) throw new Error(payload.error || '保存失败');
drawRecord(payload.record);
setMessage(payload.existing ? '该 SN 已登记,照片和填写的信息已保存。' : '登记成功,二维码已生成。');
await loadRecords();
} catch (error) { setMessage(error.message, true); }
finally { button.disabled = false; }
});
$('refresh-list').addEventListener('click', () => loadRecords().catch(error => setMessage(error.message, true)));
$('history-query').addEventListener('input', () => {
clearTimeout(searchTimer);
listRequestId++;
selectedIds.clear();
document.querySelectorAll('.archive-card').forEach(card => {
card.classList.remove('selected');
card.querySelector('.archive-select input').checked = false;
});
updateSelectionControls();
searchTimer = setTimeout(() => loadRecords().catch(error => setHistoryMessage(error.message, true)), 180);
});
$('select-all').addEventListener('change', event => {
selectedIds.clear();
if (event.target.checked) for (const record of listedRecords) selectedIds.add(record.id);
document.querySelectorAll('.archive-card').forEach((card, index) => {
const checked = selectedIds.has(listedRecords[index].id);
card.querySelector('.archive-select input').checked = checked;
card.classList.toggle('selected', checked);
});
updateSelectionControls();
});
async function exportSelected(kind) {
const ids = [...selectedIds];
if (!ids.length) return;
const button = $(kind === 'archive' ? 'export-archive' : 'export-excel');
button.disabled = true;
setHistoryMessage(`正在导出 ${ids.length} 条档案…`);
try {
const response = await fetch(`/api/export/${kind}`, {
method: 'POST', headers: { 'content-type': 'application/json' },
body: JSON.stringify({ ids }),
});
if (!response.ok) {
const payload = await response.json();
throw new Error(payload.error || '导出失败');
}
const link = document.createElement('a');
const url = URL.createObjectURL(await response.blob());
link.href = url;
link.download = kind === 'archive' ? 'FPV-RID-档案库.zip' : 'FPV-RID-登记记录.xlsx';
document.body.append(link);
link.click();
link.remove();
setTimeout(() => URL.revokeObjectURL(url), 30000);
setHistoryMessage(`已导出 ${ids.length} 条档案。`);
} catch (error) { setHistoryMessage(error.message, true); }
finally { updateSelectionControls(); }
}
$('export-archive').addEventListener('click', () => exportSelected('archive'));
$('export-excel').addEventListener('click', () => exportSelected('excel'));
$('copy-url').addEventListener('click', async () => {
if (!activeRecord) return;
try { await navigator.clipboard.writeText(activeRecord.qrUrl); setMessage('本地二维码链接已复制。'); }
catch { setMessage('复制失败,可从“二维码内容”手动复制。', true); }
});
$('download-qr').addEventListener('click', async () => {
if (!activeRecord) return;
const svg = $('qr-stage').querySelector('svg');
if (!svg) return;
const blob = new Blob([new XMLSerializer().serializeToString(svg)], { type: 'image/svg+xml' });
const url = URL.createObjectURL(blob);
try {
const image = new Image();
await new Promise((resolve, reject) => { image.onload = resolve; image.onerror = reject; image.src = url; });
const canvas = document.createElement('canvas');
canvas.width = 640; canvas.height = 640;
const context = canvas.getContext('2d');
context.fillStyle = '#fff'; context.fillRect(0, 0, 640, 640);
context.drawImage(image, 0, 0, 640, 640);
const link = document.createElement('a');
link.href = canvas.toDataURL('image/png');
link.download = `${activeRecord.serialNo}-${activeRecord.uasCode}-LOCAL.png`;
link.click();
} catch { setMessage('二维码图片下载失败。', true); }
finally { URL.revokeObjectURL(url); }
});
loadRecords().catch(error => setMessage(error.message, true));
Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

+88
View File
@@ -0,0 +1,88 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light">
<title>FPV-RID · 本地登记与核验</title>
<link rel="icon" type="image/png" href="/fpv-rid-icon.png">
<link rel="stylesheet" href="/app.css">
<script defer src="/vendor/qrcode.js"></script>
<script defer src="/app.js"></script>
</head>
<body>
<div class="shell">
<header class="topbar">
<img class="brand-mark" src="/fpv-rid-icon.png" alt="FPV-RID 图标">
<div class="brand-copy"><strong>FPV-RID</strong><small>本地登记工作台</small></div>
<div class="top-status"><i></i> 仅在本机运行</div>
</header>
<main>
<section class="hero">
<div>
<h1>登记设备,生成本地二维码</h1>
<p>为模块 SN 建立本机记录。二维码交给配套的本地版上位机扫描,校验 SN 后再由上位机完成设备操作。</p>
</div>
</section>
<div class="columns">
<section class="panel form-panel" aria-labelledby="register-title">
<div class="panel-head"><div><span class="step">01</span><h2 id="register-title">新建设备登记</h2></div><span class="subtle">同一 SN 只保留一条记录</span></div>
<form id="register-form">
<label for="serial-no">模块 SN <em>必填</em></label>
<input id="serial-no" name="serialNo" required maxlength="40" autocomplete="off" placeholder="例如 ZEX0RID1202605011000" pattern="[A-Za-z0-9-]{6,40}">
<p class="hint">请与上位机“RID 模块状态信息”里的 SN 完全一致。</p>
<div class="field-grid">
<div><label for="model-name">机型</label><input id="model-name" name="modelName" maxlength="60" placeholder="例如 5 寸穿越机"></div>
<div><label for="owner-name">登记人 / 备注</label><input id="owner-name" name="ownerName" maxlength="40" placeholder="可选"></div>
</div>
<label for="uas-code">FPV 编号 <span class="optional">可选</span></label>
<div class="input-prefix"><span>FPV</span><input id="uas-code" name="uasDigits" maxlength="8" inputmode="numeric" pattern="[0-9]{8}" placeholder="留空则自动生成 8 位数字"></div>
<p class="hint">已有 FPV 编号可输入后 8 位数字;留空则自动生成。</p>
<div class="field-grid photo-fields">
<div><label for="photo-1">登记照片 1 <span class="optional">可选</span></label><input id="photo-1" type="file" accept="image/jpeg,image/png,image/webp"></div>
<div><label for="photo-2">登记照片 2 <span class="optional">可选</span></label><input id="photo-2" type="file" accept="image/jpeg,image/png,image/webp"></div>
</div>
<p class="hint">每张最多 5 MB,支持 JPG、PNG 和 WebP。照片保存在本机数据库;同一 SN 再次保存可补充或替换照片。</p>
<button class="primary" id="register-button" type="submit">保存登记并生成二维码 <span aria-hidden="true">→</span></button>
<p class="form-message" id="form-message" role="status"></p>
</form>
</section>
<section class="panel result-panel" aria-labelledby="result-title">
<div class="panel-head"><div><span class="step muted">02</span><h2 id="result-title">二维码与核验</h2></div><span class="subtle">同机使用</span></div>
<div id="empty-result" class="empty-state"><div class="empty-glyph">▦</div><b>等待登记</b><span>保存后在这里生成二维码,供本地版上位机读取。</span></div>
<div id="record-result" class="record-result" hidden>
<div class="qr-stage" id="qr-stage" aria-label="本地登记二维码"></div>
<div class="record-kicker">本地记录已保存</div>
<div class="uas-display" id="display-uas"></div>
<dl class="result-fields"><div><dt>Serial No.</dt><dd id="display-sn"></dd></div><div><dt>机型</dt><dd id="display-model"></dd></div><div><dt>登记人</dt><dd id="display-owner"></dd></div></dl>
<div class="saved-photos" id="saved-photos" hidden>
<a id="photo-1-link" target="_blank" rel="noopener" hidden><img id="photo-1-preview" alt="登记照片 1"><span>照片 1</span></a>
<a id="photo-2-link" target="_blank" rel="noopener" hidden><img id="photo-2-preview" alt="登记照片 2"><span>照片 2</span></a>
</div>
<div class="url-box"><span>二维码内容</span><code id="display-url"></code></div>
<div class="result-actions"><button id="download-qr" class="secondary" type="button">下载二维码 PNG</button><button id="copy-url" class="ghost" type="button">复制链接</button></div>
<div class="result-actions"><a id="open-card" class="secondary action-link" target="_blank" rel="noopener">打开档案卡</a><a id="download-card" class="ghost action-link">下载离线档案卡</a></div>
<p class="result-tip">在本机同时启动登记站和本地版上位机,上传此二维码。上位机会从本地记录读取字段并比对模块 SN。</p>
</div>
</section>
</div>
<section class="panel history-panel" aria-labelledby="history-title">
<div class="panel-head history-head"><div><span class="step muted">03</span><h2 id="history-title">本地登记记录</h2></div><div class="history-controls"><div class="history-search"><input id="history-query" type="search" maxlength="60" autocomplete="off" aria-label="搜索登记档案" placeholder="搜索 SN、FPV 编号、机型、登记人"><span id="search-count" aria-live="polite"></span></div><label class="select-all"><input id="select-all" type="checkbox">全选 <span id="selected-count">(0)</span></label><button id="export-archive" class="export-button" type="button" disabled>导出档案包</button><button id="export-excel" class="export-button" type="button" disabled>导出 Excel</button><button id="refresh-list" class="text-button" type="button">刷新记录</button></div></div>
<p class="history-message" id="history-message" role="status">导出档案包包含离线档案卡、照片和登记信息;Excel 导出为登记表。</p>
<div id="history-empty" class="history-empty">暂无登记记录。</div>
<div id="history-cards" class="history-cards"></div>
</section>
</main>
<footer><span>127.0.0.1:8787 · 数据保存在本机</span></footer>
</div>
</body>
</html>
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2009 Kazuhiko Arase
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -9,7 +9,7 @@ const exportFiles = require('./export-files');
const HOST = '127.0.0.1'; const HOST = '127.0.0.1';
const PORT = 8787; const PORT = 8787;
const ROOT = __dirname; const ROOT = __dirname;
const WEB = path.join(ROOT, 'web'); const WEB = path.join(ROOT, 'legacy-web');
const ARCHIVE = path.join(ROOT, '..', '档案库'); const ARCHIVE = path.join(ROOT, '..', '档案库');
const ARCHIVE_CARDS = path.join(ARCHIVE, '档案卡'); const ARCHIVE_CARDS = path.join(ARCHIVE, '档案卡');
fs.mkdirSync(ARCHIVE_CARDS, { recursive: true }); fs.mkdirSync(ARCHIVE_CARDS, { recursive: true });
View File
+1
View File
@@ -3,3 +3,4 @@
.action-link{display:grid;place-items:center;text-decoration:none}.history-cards{display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:14px}.archive-card{border:1px solid #dfe8f0;border-radius:12px;padding:16px;background:#fbfdff}.archive-card h3{font-size:15px;margin:0 0 5px;overflow-wrap:anywhere}.archive-card strong{color:#236d9b;font-size:13px}.archive-card p{color:#8193a3;font-size:11px;line-height:1.5;margin:9px 0 12px}.archive-thumbs{display:grid;grid-template-columns:1fr 1fr;gap:8px}.archive-thumbs>div{height:105px;border:1px solid #e2e9ef;border-radius:7px;background:#f3f7fa;display:grid;place-items:center;color:#a4b1bc;font-size:11px;overflow:hidden}.archive-thumbs img{height:100%;width:100%;object-fit:contain}.archive-actions{display:flex;flex-wrap:wrap;gap:8px;margin-top:13px}.archive-actions a,.archive-actions button{background:#eaf3f9;color:#236f9d;border:1px solid #d0e2ef;border-radius:7px;padding:7px 9px;font-size:11px;font-weight:700;text-decoration:none;cursor:pointer} .action-link{display:grid;place-items:center;text-decoration:none}.history-cards{display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:14px}.archive-card{border:1px solid #dfe8f0;border-radius:12px;padding:16px;background:#fbfdff}.archive-card h3{font-size:15px;margin:0 0 5px;overflow-wrap:anywhere}.archive-card strong{color:#236d9b;font-size:13px}.archive-card p{color:#8193a3;font-size:11px;line-height:1.5;margin:9px 0 12px}.archive-thumbs{display:grid;grid-template-columns:1fr 1fr;gap:8px}.archive-thumbs>div{height:105px;border:1px solid #e2e9ef;border-radius:7px;background:#f3f7fa;display:grid;place-items:center;color:#a4b1bc;font-size:11px;overflow:hidden}.archive-thumbs img{height:100%;width:100%;object-fit:contain}.archive-actions{display:flex;flex-wrap:wrap;gap:8px;margin-top:13px}.archive-actions a,.archive-actions button{background:#eaf3f9;color:#236f9d;border:1px solid #d0e2ef;border-radius:7px;padding:7px 9px;font-size:11px;font-weight:700;text-decoration:none;cursor:pointer}
.topbar .brand-mark{width:42px;height:42px;object-fit:contain;border-radius:10px;padding:0;letter-spacing:normal;background:#fff}.hero h1{margin-top:0}.history-head{align-items:center}.history-controls{display:flex;align-items:center;justify-content:flex-end;flex-wrap:wrap;gap:10px}.select-all{display:inline-flex;align-items:center;gap:5px;margin:0;color:#49657a;white-space:nowrap;font-size:12px}.select-all input,.archive-select input{width:16px;height:16px;accent-color:#206d9f;cursor:pointer}.export-button{height:34px;padding:0 11px;border:1px solid #c8ddeb;border-radius:7px;background:#e9f3fa;color:#1d6c9c;font-size:12px;font-weight:700}.export-button:disabled{opacity:.48;cursor:not-allowed}.history-message{font-size:11px;line-height:1.55;color:#8a9dad;margin:0 0 14px}.history-message.error{color:#b84036}.archive-card{position:relative}.archive-card.selected{border-color:#4b9bc8;box-shadow:0 0 0 2px #4b9bc820}.archive-select{display:flex;align-items:center;gap:5px;float:right;margin:0 0 8px 10px;color:#59788f;font-size:11px;font-weight:600}.archive-actions .delete-record{background:#fff1ef;color:#b34039;border-color:#f2c9c5}.archive-actions .delete-record:hover{background:#ffe7e3}footer{justify-content:flex-end}@media(max-width:850px){.history-head{align-items:flex-start;flex-direction:column}.history-controls{justify-content:flex-start}}@media(max-width:530px){.history-controls{gap:8px}.export-button{flex:1}} .topbar .brand-mark{width:42px;height:42px;object-fit:contain;border-radius:10px;padding:0;letter-spacing:normal;background:#fff}.hero h1{margin-top:0}.history-head{align-items:center}.history-controls{display:flex;align-items:center;justify-content:flex-end;flex-wrap:wrap;gap:10px}.select-all{display:inline-flex;align-items:center;gap:5px;margin:0;color:#49657a;white-space:nowrap;font-size:12px}.select-all input,.archive-select input{width:16px;height:16px;accent-color:#206d9f;cursor:pointer}.export-button{height:34px;padding:0 11px;border:1px solid #c8ddeb;border-radius:7px;background:#e9f3fa;color:#1d6c9c;font-size:12px;font-weight:700}.export-button:disabled{opacity:.48;cursor:not-allowed}.history-message{font-size:11px;line-height:1.55;color:#8a9dad;margin:0 0 14px}.history-message.error{color:#b84036}.archive-card{position:relative}.archive-card.selected{border-color:#4b9bc8;box-shadow:0 0 0 2px #4b9bc820}.archive-select{display:flex;align-items:center;gap:5px;float:right;margin:0 0 8px 10px;color:#59788f;font-size:11px;font-weight:600}.archive-actions .delete-record{background:#fff1ef;color:#b34039;border-color:#f2c9c5}.archive-actions .delete-record:hover{background:#ffe7e3}footer{justify-content:flex-end}@media(max-width:850px){.history-head{align-items:flex-start;flex-direction:column}.history-controls{justify-content:flex-start}}@media(max-width:530px){.history-controls{gap:8px}.export-button{flex:1}}
.history-search{position:relative;width:260px;flex:0 1 260px}.history-search input{height:36px;padding:0 66px 0 12px;font-size:12px;background:#fff}.history-search input::placeholder{color:#8fa1af}.history-search #search-count{position:absolute;right:10px;top:50%;transform:translateY(-50%);color:#6b8294;font-size:11px;white-space:nowrap;pointer-events:none}.history-search #search-count:empty{display:none}@media(max-width:850px){.history-controls{width:100%}.history-search{flex:1 1 260px}}@media(max-width:530px){.history-search{flex-basis:100%;width:100%}} .history-search{position:relative;width:260px;flex:0 1 260px}.history-search input{height:36px;padding:0 66px 0 12px;font-size:12px;background:#fff}.history-search input::placeholder{color:#8fa1af}.history-search #search-count{position:absolute;right:10px;top:50%;transform:translateY(-50%);color:#6b8294;font-size:11px;white-space:nowrap;pointer-events:none}.history-search #search-count:empty{display:none}@media(max-width:850px){.history-controls{width:100%}.history-search{flex:1 1 260px}}@media(max-width:530px){.history-search{flex-basis:100%;width:100%}}
.pagination{display:flex;gap:12px;justify-content:flex-end;align-items:center;flex-wrap:wrap;margin-top:20px;color:#59788f;font-size:12px}.pagination button,.archive-warning button{padding:7px 12px;border:1px solid #c8ddeb;border-radius:7px;background:#e9f3fa;color:#1d6c9c;cursor:pointer}.pagination button:disabled{opacity:.45;cursor:default}.archive-warning{padding:14px;background:#fff4da;color:#725319;border-radius:8px}dialog{border:1px solid #dce6ee;border-radius:16px;padding:28px;max-width:650px;width:calc(100% - 32px);max-height:90vh;overflow:auto;color:#173047}dialog::backdrop{background:#17304770}dialog h2{margin-top:0}dialog p{font-size:13px;line-height:1.6}dialog .edit-help{color:#61788a}.edit-photos{display:grid;grid-template-columns:1fr 1fr;gap:14px;margin-top:20px}.edit-photos fieldset{min-width:0;border:1px solid #dce6ee;border-radius:8px}.edit-photos img{width:100%;height:130px;object-fit:contain}.edit-photos input[type=file]{width:100%;font-size:12px}.edit-delete{display:flex;align-items:center;gap:8px}.edit-delete input{width:16px;height:16px}button:focus-visible,a:focus-visible{outline:3px solid #206d9f;outline-offset:3px}#edit-message{color:#a03f31}@media(max-width:530px){.edit-photos{grid-template-columns:1fr}dialog{padding:18px}.pagination{justify-content:center}}
+115 -6
View File
@@ -4,6 +4,22 @@ let listedRecords = [];
const selectedIds = new Set(); const selectedIds = new Set();
let listRequestId = 0; let listRequestId = 0;
let searchTimer; let searchTimer;
let currentPage = 1;
let totalPages = 0;
let editingRecord = null;
let editBusy = false;
function updatePageButtons() {
$('previous-page').disabled = currentPage <= 1;
$('next-page').disabled = currentPage >= totalPages;
}
function archiveStatus(payload) {
if (payload.archiveStatus === 'pending') {
$('archive-warning').hidden = false;
$('archive-warning-text').textContent = payload.warning || '数据已保存,档案备份待同步。';
} else if (payload.archiveStatus === 'synced') $('archive-warning').hidden = true;
}
function setMessage(message, error = false) { function setMessage(message, error = false) {
$('form-message').textContent = message; $('form-message').textContent = message;
@@ -68,17 +84,31 @@ function drawRecord(record) {
$('qr-stage').innerHTML = qr.createSvgTag({ cellSize: 6, margin: 4 }); $('qr-stage').innerHTML = qr.createSvgTag({ cellSize: 6, margin: 4 });
} }
async function loadRecords() { async function loadRecords(requestedPage = currentPage) {
const requestId = ++listRequestId; const requestId = ++listRequestId;
const query = $('history-query').value.trim(); const query = $('history-query').value.trim();
const response = await fetch(`/api/records?q=${encodeURIComponent(query)}`); $('previous-page').disabled = true; $('next-page').disabled = true;
const payload = await response.json(); let payload;
try {
const response = await fetch(`/api/records?q=${encodeURIComponent(query)}&page=${requestedPage}&pageSize=20`);
payload = await response.json();
if (!response.ok) throw new Error(payload.error || '读取记录失败'); if (!response.ok) throw new Error(payload.error || '读取记录失败');
} catch (error) {
if (requestId !== listRequestId) return; if (requestId !== listRequestId) return;
updatePageButtons();
throw error;
}
if (requestId !== listRequestId) return;
totalPages = payload.totalPages;
if (requestedPage > Math.max(1, totalPages)) { selectedIds.clear(); return loadRecords(Math.max(1, totalPages)); }
currentPage = requestedPage;
$('page-status').textContent = `第 ${currentPage} / ${Math.max(1, totalPages)} 页 · 共 ${payload.total} 条`;
$('previous-page').disabled = currentPage === 1;
$('next-page').disabled = currentPage >= totalPages;
const body = $('history-cards'); const body = $('history-cards');
body.replaceChildren(); body.replaceChildren();
listedRecords = payload.records; listedRecords = payload.records;
$('search-count').textContent = query ? `${listedRecords.length} 条` : ''; $('search-count').textContent = query ? `${payload.total} 条` : '';
const currentIds = new Set(listedRecords.map(record => record.id)); const currentIds = new Set(listedRecords.map(record => record.id));
for (const id of selectedIds) if (!currentIds.has(id)) selectedIds.delete(id); for (const id of selectedIds) if (!currentIds.has(id)) selectedIds.delete(id);
$('history-empty').hidden = listedRecords.length > 0; $('history-empty').hidden = listedRecords.length > 0;
@@ -145,6 +175,7 @@ async function loadRecords() {
const response = await fetch(`/api/records/${record.id}`, { method: 'DELETE' }); const response = await fetch(`/api/records/${record.id}`, { method: 'DELETE' });
const payload = await response.json(); const payload = await response.json();
if (!response.ok) throw new Error(payload.error || '删除失败'); if (!response.ok) throw new Error(payload.error || '删除失败');
archiveStatus(payload);
selectedIds.delete(record.id); selectedIds.delete(record.id);
if (activeRecord?.id === record.id) { if (activeRecord?.id === record.id) {
activeRecord = null; activeRecord = null;
@@ -155,7 +186,10 @@ async function loadRecords() {
setHistoryMessage(`已删除 ${record.serialNo} 的档案。`); setHistoryMessage(`已删除 ${record.serialNo} 的档案。`);
} catch (error) { setHistoryMessage(error.message, true); remove.disabled = false; } } catch (error) { setHistoryMessage(error.message, true); remove.disabled = false; }
}); });
actions.append(open, download, showQr, remove); const edit = document.createElement('button');
edit.type = 'button'; edit.textContent = '编辑资料 / 照片';
edit.addEventListener('click', () => openEditor(record));
actions.append(edit, open, download, showQr, remove);
card.append(select, title, code, detail, images, actions); card.append(select, title, code, detail, images, actions);
body.append(card); body.append(card);
} }
@@ -185,6 +219,7 @@ $('register-form').addEventListener('submit', async event => {
}); });
const payload = await response.json(); const payload = await response.json();
if (!response.ok) throw new Error(payload.error || '保存失败'); if (!response.ok) throw new Error(payload.error || '保存失败');
archiveStatus(payload);
drawRecord(payload.record); drawRecord(payload.record);
setMessage(payload.existing ? '该 SN 已登记,照片和填写的信息已保存。' : '登记成功,二维码已生成。'); setMessage(payload.existing ? '该 SN 已登记,照片和填写的信息已保存。' : '登记成功,二维码已生成。');
await loadRecords(); await loadRecords();
@@ -202,7 +237,7 @@ $('history-query').addEventListener('input', () => {
card.querySelector('.archive-select input').checked = false; card.querySelector('.archive-select input').checked = false;
}); });
updateSelectionControls(); updateSelectionControls();
searchTimer = setTimeout(() => loadRecords().catch(error => setHistoryMessage(error.message, true)), 180); searchTimer = setTimeout(() => loadRecords(1).catch(error => setHistoryMessage(error.message, true)), 180);
}); });
$('select-all').addEventListener('change', event => { $('select-all').addEventListener('change', event => {
selectedIds.clear(); selectedIds.clear();
@@ -272,3 +307,77 @@ $('download-qr').addEventListener('click', async () => {
}); });
loadRecords().catch(error => setMessage(error.message, true)); loadRecords().catch(error => setMessage(error.message, true));
fetch('/api/archive/status').then(response => {
if (!response.ok) throw new Error('无法读取备份状态');
return response.json();
}).then(archiveStatus).catch(error => setHistoryMessage(error.message, true));
for (const [id, delta] of [['previous-page', -1], ['next-page', 1]]) {
$(id).addEventListener('click', () => {
selectedIds.clear(); updateSelectionControls();
document.querySelectorAll('.archive-select input').forEach(input => { input.checked = false; });
document.querySelectorAll('.archive-card.selected').forEach(card => card.classList.remove('selected'));
loadRecords(currentPage + delta).catch(error => {
setHistoryMessage(error.message, true);
updatePageButtons();
});
});
}
function openEditor(record) {
editingRecord = record; $('edit-form').reset(); $('edit-message').textContent = '';
$('edit-identity').textContent = `${record.serialNo} · ${record.uasCode}`;
$('edit-model').value = record.modelName; $('edit-owner').value = record.ownerName;
for (const slot of [1, 2]) {
const url = record[`photo${slot}Url`]; const preview = $(`edit-preview-${slot}`);
preview.hidden = !url; if (url) preview.src = `${url}?v=${Date.now()}`; else preview.removeAttribute('src');
$(`edit-delete-${slot}`).disabled = !url;
}
$('edit-dialog').showModal(); $('edit-model').focus();
}
$('edit-cancel').addEventListener('click', () => $('edit-dialog').close());
$('edit-dialog').addEventListener('cancel', event => { if (editBusy) event.preventDefault(); });
for (const slot of [1, 2]) {
$(`edit-photo-${slot}`).addEventListener('change', () => { if ($(`edit-photo-${slot}`).files.length) $(`edit-delete-${slot}`).checked = false; });
$(`edit-delete-${slot}`).addEventListener('change', () => { if ($(`edit-delete-${slot}`).checked) $(`edit-photo-${slot}`).value = ''; });
}
async function mutation(url, method, body) {
const response = await fetch(url, { method, headers: body ? { 'content-type': 'application/json' } : {}, body: body ? JSON.stringify(body) : undefined });
const payload = await response.json(); if (!response.ok) throw new Error(payload.error || '操作失败');
archiveStatus(payload); return payload;
}
$('edit-form').addEventListener('submit', async event => {
event.preventDefault(); const record = editingRecord; if (!record || editBusy) return;
editBusy = true;
const controls = Array.from($('edit-form').elements);
const disabled = controls.map(control => control.disabled);
controls.forEach(control => { control.disabled = true; });
const body = { modelName: $('edit-model').value.trim(), ownerName: $('edit-owner').value.trim() };
const deletes = [1, 2].map(slot => $(`edit-delete-${slot}`).checked);
let saved = false;
try {
// Validate both photos before committing any edits.
const photos = await Promise.all([readPhoto($('edit-photo-1'), 1), readPhoto($('edit-photo-2'), 2)]);
$('edit-message').textContent = '正在保存…';
for (const slot of [1, 2]) {
if (deletes[slot - 1]) body[`photo${slot}`] = null;
else if (photos[slot - 1]) body[`photo${slot}`] = photos[slot - 1];
}
const payload = await mutation(`/api/records/${record.id}`, 'PATCH', body);
saved = true;
if (activeRecord?.id === record.id) drawRecord(payload.record);
$('edit-dialog').close();
await loadRecords();
setHistoryMessage('档案修改已保存。');
} catch (error) {
if (saved) setHistoryMessage(`修改已保存,但列表刷新失败:${error.message}`, true);
else $('edit-message').textContent = `${error.message}。如连接中断,请刷新核对保存结果。`;
}
finally { controls.forEach((control, index) => { control.disabled = disabled[index]; }); editBusy = false; }
});
$('retry-archive').addEventListener('click', async () => {
$('retry-archive').disabled = true;
try { await mutation('/api/archive/retry', 'POST', {}); setHistoryMessage('档案与备份同步完成。'); }
catch (error) { $('archive-warning-text').textContent = error.message; }
finally { $('retry-archive').disabled = false; }
});
+14
View File
@@ -79,10 +79,24 @@
<p class="history-message" id="history-message" role="status">导出档案包包含离线档案卡、照片和登记信息;Excel 导出为登记表。</p> <p class="history-message" id="history-message" role="status">导出档案包包含离线档案卡、照片和登记信息;Excel 导出为登记表。</p>
<div id="history-empty" class="history-empty">暂无登记记录。</div> <div id="history-empty" class="history-empty">暂无登记记录。</div>
<div id="history-cards" class="history-cards"></div> <div id="history-cards" class="history-cards"></div>
<nav class="pagination" aria-label="档案分页"><span>全选仅当前页</span><button id="previous-page" type="button">上一页</button><span id="page-status" aria-live="polite"></span><button id="next-page" type="button">下一页</button></nav>
<p id="archive-warning" class="archive-warning" role="status" hidden><span id="archive-warning-text"></span> <button id="retry-archive" type="button">重试同步</button></p>
</section> </section>
</main> </main>
<footer><span>127.0.0.1:8787 · 数据保存在本机</span></footer> <footer><span>127.0.0.1:8787 · 数据保存在本机</span></footer>
</div> </div>
<dialog id="edit-dialog" aria-labelledby="edit-title">
<form id="edit-form">
<h2 id="edit-title">编辑档案</h2><p id="edit-identity"></p><p class="edit-help">SN 与 FPV 编号不可修改;清空机型或登记人后保存,即清除该字段。</p>
<label for="edit-model">机型</label><input id="edit-model" maxlength="60">
<label for="edit-owner">登记人 / 备注</label><input id="edit-owner" maxlength="40">
<div class="edit-photos">
<fieldset><legend>照片 1</legend><img id="edit-preview-1" alt="现有照片 1" hidden><label for="edit-photo-1">替换照片 1</label><input id="edit-photo-1" type="file" accept="image/jpeg,image/png,image/webp"><label class="edit-delete"><input id="edit-delete-1" type="checkbox">删除现有照片 1</label></fieldset>
<fieldset><legend>照片 2</legend><img id="edit-preview-2" alt="现有照片 2" hidden><label for="edit-photo-2">替换照片 2</label><input id="edit-photo-2" type="file" accept="image/jpeg,image/png,image/webp"><label class="edit-delete"><input id="edit-delete-2" type="checkbox">删除现有照片 2</label></fieldset>
</div>
<p id="edit-message" role="status"></p><div class="result-actions"><button id="edit-save" class="secondary" type="submit">保存修改</button><button id="edit-cancel" class="ghost" type="button">取消</button></div>
</form>
</dialog>
</body> </body>
</html> </html>
+4
View File
@@ -0,0 +1,4 @@
[toolchain]
channel = "1.99.1"
profile = "minimal"
components = ["rustfmt", "clippy"]
+72
View File
@@ -0,0 +1,72 @@
param([string]$OutputRoot)
$ErrorActionPreference = 'Stop'
. (Join-Path $PSScriptRoot 'rust-env.ps1')
$ridRepo = Split-Path $PSScriptRoot -Parent
if (-not $OutputRoot) { $OutputRoot = Join-Path $ridRepo 'dist' }
$ridOutputRoot = [IO.Path]::GetFullPath($OutputRoot)
$ridDestination = Join-Path $ridOutputRoot 'FPV-RID-Rust'
$ridWhitelist = @('fpv-rid-registry.exe', '启动Rust版.cmd', '使用说明.md', 'qrcode-LICENSE.txt', 'dependency-licenses.txt', 'SHA256SUMS.txt')
function Assert-CleanDestination {
if (Test-Path -LiteralPath $ridDestination) {
foreach ($ridEntry in Get-ChildItem -LiteralPath $ridDestination -Force) {
if ($ridEntry.PSIsContainer -or $ridEntry.Name -notin $ridWhitelist -or
($ridEntry.Attributes -band [IO.FileAttributes]::ReparsePoint)) {
throw "发布目录含运行数据或非发布文件,已停止打包并保留原内容:$($ridEntry.FullName)。请通过 -OutputRoot 指定单独的输出目录。"
}
}
}
}
# Refuse a used deployment folder before building or changing any published files.
Assert-CleanDestination
$ridStageRoot = Join-Path $ridOutputRoot ('.package-' + [guid]::NewGuid().ToString('N'))
$ridStage = Join-Path $ridStageRoot 'FPV-RID-Rust'
$ridTemporaryZip = Join-Path $ridStageRoot 'release.zip'
Push-Location $ridRepo
try {
cargo build --release --locked
if ($LASTEXITCODE -ne 0) { throw 'Release build failed' }
$ridMetadata = cargo metadata --locked --format-version 1 --no-deps | ConvertFrom-Json
if ($LASTEXITCODE -ne 0) { throw 'Cargo metadata failed' }
New-Item -ItemType Directory -Force -Path $ridStage | Out-Null
Copy-Item -LiteralPath (Join-Path $ridMetadata.target_directory 'release/fpv-rid-registry.exe') -Destination $ridStage
Copy-Item -LiteralPath (Join-Path $ridRepo '启动Rust版.cmd') -Destination $ridStage
Copy-Item -LiteralPath (Join-Path $ridRepo 'doc/registry/rust/使用说明.md') -Destination $ridStage
Copy-Item -LiteralPath (Join-Path $ridRepo 'registry/web/vendor/LICENSE.txt') -Destination (Join-Path $ridStage 'qrcode-LICENSE.txt')
$ridLicenses = cargo tree --locked --prefix none --format '{p} {l}'
if ($LASTEXITCODE -ne 0) { throw 'Dependency inventory failed' }
$ridLicenses | Set-Content -LiteralPath (Join-Path $ridStage 'dependency-licenses.txt') -Encoding utf8
$ridWhitelist | Where-Object { $_ -ne 'SHA256SUMS.txt' } | ForEach-Object {
'{0} {1}' -f (Get-FileHash -LiteralPath (Join-Path $ridStage $_) -Algorithm SHA256).Hash, $_
} | Set-Content -LiteralPath (Join-Path $ridStage 'SHA256SUMS.txt') -Encoding utf8
$ridActual = @(Get-ChildItem -LiteralPath $ridStage -Force)
if ($ridActual.Count -ne $ridWhitelist.Count -or @($ridActual | Where-Object { $_.PSIsContainer -or $_.Name -notin $ridWhitelist }).Count) {
throw 'Staging directory does not match the release whitelist'
}
# Only the fresh, checked staging tree is ever compressed.
Compress-Archive -LiteralPath $ridStage -DestinationPath $ridTemporaryZip
Assert-CleanDestination
New-Item -ItemType Directory -Force -Path $ridDestination | Out-Null
foreach ($ridName in $ridWhitelist) {
Copy-Item -LiteralPath (Join-Path $ridStage $ridName) -Destination (Join-Path $ridDestination $ridName)
}
$ridZip = Join-Path $ridOutputRoot 'FPV-RID-Rust-Windows-x64.zip'
Move-Item -LiteralPath $ridTemporaryZip -Destination $ridZip -Force
'{0} FPV-RID-Rust-Windows-x64.zip' -f (Get-FileHash -LiteralPath $ridZip -Algorithm SHA256).Hash |
Set-Content -LiteralPath "$ridZip.sha256" -Encoding utf8
Write-Output $ridDestination
Write-Output $ridZip
} finally {
Pop-Location
# Clean only files this invocation created. Never recursively delete an output directory.
foreach ($ridName in $ridWhitelist) {
$ridOwnedFile = Join-Path $ridStage $ridName
if (Test-Path -LiteralPath $ridOwnedFile -PathType Leaf) { Remove-Item -LiteralPath $ridOwnedFile }
}
if (Test-Path -LiteralPath $ridTemporaryZip -PathType Leaf) { Remove-Item -LiteralPath $ridTemporaryZip }
if ((Test-Path -LiteralPath $ridStage -PathType Container) -and @(Get-ChildItem -LiteralPath $ridStage -Force).Count -eq 0) { Remove-Item -LiteralPath $ridStage }
if ((Test-Path -LiteralPath $ridStageRoot -PathType Container) -and @(Get-ChildItem -LiteralPath $ridStageRoot -Force).Count -eq 0) { Remove-Item -LiteralPath $ridStageRoot }
}
+6
View File
@@ -0,0 +1,6 @@
# Dot-source this file for the workspace's shared Rust installation.
$env:CARGO_HOME = 'D:\Rust_Contact\util\cargo'
$env:RUSTUP_HOME = 'D:\Rust_Contact\util\rustup'
if (($env:Path -split ';') -notcontains "$env:CARGO_HOME\bin") {
$env:Path = "$env:CARGO_HOME\bin;$env:Path"
}
+41
View File
@@ -0,0 +1,41 @@
// Browser acceptance against a real Rust process and a disposable database.
import {createRequire} from 'node:module';
import {mkdtemp,mkdir,writeFile} from 'node:fs/promises';
import {tmpdir} from 'node:os';
import path from 'node:path';
import {spawn} from 'node:child_process';
import {DatabaseSync} from 'node:sqlite';
import assert from 'node:assert/strict';
const require=createRequire(import.meta.url);
const {chromium}=require('playwright');
const root=await mkdtemp(path.join(tmpdir(),'RID-浏览器验收-'));
const exe=path.resolve(process.argv[2]||'D:/Rust_Contact/util/target/Rid_Drone_Receivev/release/fpv-rid-registry.exe');
const base='http://127.0.0.1:8787';
try{const r=await fetch(base);if(r)throw Error('8787 已有服务,请先关闭');}catch(e){if(e.message.includes('已有服务'))throw e;}
await mkdir(path.join(root,'registry/data'),{recursive:true});
const db=new DatabaseSync(path.join(root,'registry/data/registry.sqlite'));
db.exec("CREATE TABLE records(id TEXT PRIMARY KEY,serial_no TEXT NOT NULL UNIQUE,uas_code TEXT NOT NULL UNIQUE,model_name TEXT NOT NULL DEFAULT '',owner_name TEXT NOT NULL DEFAULT '',created_at TEXT NOT NULL); CREATE TABLE photos(record_id TEXT NOT NULL REFERENCES records(id) ON DELETE CASCADE,slot INTEGER NOT NULL CHECK(slot IN(1,2)),mime_type TEXT NOT NULL,image BLOB NOT NULL,PRIMARY KEY(record_id,slot));");
for(let i=1;i<=21;i++)db.prepare('INSERT INTO records VALUES(?,?,?,?,?,?)').run(String(i).padStart(36,'0'),`BROWSER-${String(i).padStart(3,'0')}`,`FPV${String(i).padStart(8,'0')}`,'演示机型','验收数据','2020-01-01T00:00:00.000Z');db.close();
const png=Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aocsAAAAASUVORK5CYII=','base64');
const child=spawn(exe,['--data-root',root],{windowsHide:true,env:{...process.env,PATH:'C:\\Windows\\System32'},stdio:['ignore','pipe','pipe']});let output='';let spawnError;
child.stdout.on('data',b=>output+=b);child.stderr.on('data',b=>output+=b);child.on('error',e=>spawnError=e);
let browser;
try{
for(let i=0;i<150;i++){if(spawnError||child.exitCode!==null)throw Error(output||String(spawnError));try{if((await fetch(base+'/api/records')).ok)break;}catch{}await new Promise(r=>setTimeout(r,100));}
browser=await chromium.launch({headless:true,executablePath:process.env.RID_BROWSER_PATH||undefined});const page=await browser.newPage({viewport:{width:1366,height:1000},acceptDownloads:true});let errors=[];page.on('pageerror',e=>errors.push(e.message));
await page.goto(base);await page.locator('#page-status').filter({hasText:'共 21 条'}).waitFor();
await page.fill('#serial-no','UI-NEW-001');await page.fill('#model-name','待清空机型');await page.fill('#owner-name','原登记人');await page.setInputFiles('#photo-1',{name:'photo.png',mimeType:'image/png',buffer:png});await page.click('#register-button');await page.locator('#form-message').filter({hasText:'登记成功'}).waitFor();
const card=page.locator('.archive-card').filter({has:page.getByRole('heading',{name:'UI-NEW-001',exact:true})});
await card.getByRole('button',{name:'编辑资料 / 照片'}).click();assert.equal(await page.locator('#edit-model').evaluate(el=>el===document.activeElement),true);await page.click('#edit-cancel');assert.equal(await page.locator('#edit-dialog').isVisible(),false);
await card.getByRole('button',{name:'编辑资料 / 照片'}).click();await page.fill('#edit-model','');await page.fill('#edit-owner','修改后的登记人');await page.check('#edit-delete-1');await page.setInputFiles('#edit-photo-2',{name:'new.png',mimeType:'image/png',buffer:png});
let patches=0;const listener=req=>{if(req.method()==='PATCH')patches++;};page.on('request',listener);await page.click('#edit-save');await page.locator('#edit-dialog').waitFor({state:'hidden'});assert.equal(patches,1);page.off('request',listener);
let records=(await (await fetch(base+'/api/records')).json()).records;let r=records.find(r=>r.serialNo==='UI-NEW-001');assert.equal(r.modelName,'');assert.equal(r.ownerName,'修改后的登记人');assert.equal(r.photo1Url,null);assert.ok(r.photo2Url);
await card.getByRole('button',{name:'编辑资料 / 照片'}).click();await page.fill('#edit-owner','不得保存');await page.setInputFiles('#edit-photo-1',{name:'bad.png',mimeType:'image/png',buffer:Buffer.from('invalid image')});await page.click('#edit-save');await page.locator('#edit-message').filter({hasText:'照片内容与格式不符'}).waitFor();assert.equal((await(await fetch(base+'/api/records')).json()).records.find(item=>item.id===r.id).ownerName,'修改后的登记人');await page.keyboard.press('Escape');
await page.click('#next-page');await page.locator('#page-status').filter({hasText:'第 2 / 2 页'}).waitFor();assert.equal(await page.locator('.archive-card').count(),2);
await page.fill('#history-query','UI-NEW-001');await page.locator('#page-status').filter({hasText:'第 1 / 1 页'}).waitFor();assert.equal(await page.locator('.archive-card').count(),1);
await page.fill('#history-query','');await page.locator('#page-status').filter({hasText:'共 22 条'}).waitFor();await page.check('#select-all');assert.equal(await page.locator('.archive-select input:checked').count(),20);
const downloadPromise=page.waitForEvent('download');const exportRequest=page.waitForRequest(req=>req.url().endsWith('/api/export/excel'));await page.click('#export-excel');assert.equal((await exportRequest).postDataJSON().ids.length,20);const download=await downloadPromise;await download.saveAs(path.join(root,'browser-export.xlsx'));
await page.screenshot({path:path.join(root,'desktop.png'),fullPage:true});await page.setViewportSize({width:390,height:844});await card.getByRole('button',{name:'编辑资料 / 照片'}).click();await page.screenshot({path:path.join(root,'mobile-dialog.png'),fullPage:false});
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=window.innerWidth),true);assert.equal(await page.locator('#edit-dialog').evaluate(el=>el.getBoundingClientRect().right<=innerWidth),true);assert.deepEqual(errors,[]);
console.log(JSON.stringify({status:'PASS',root,scenarios:['real Rust without Node PATH','registration and photo','cancel','focus','atomic edit','invalid photo rollback','pagination','search resets page','current-page selection and XLSX download','desktop and narrow viewport','no browser errors']}));
}finally{if(browser)await browser.close();if(child.exitCode===null&&!spawnError){const exit=new Promise(r=>child.once('exit',r));child.kill();await exit;}await writeFile(path.join(root,'server.log'),output);}
+18
View File
@@ -0,0 +1,18 @@
import fs from 'node:fs';
import vm from 'node:vm';
import assert from 'node:assert/strict';
const source=fs.readFileSync(new URL('../registry/web/app.js',import.meta.url),'utf8');
const elements=new Map();
const $=id=>{if(!elements.has(id))elements.set(id,{textContent:'',value:'',disabled:false,checked:false,classList:{toggle(){},remove(){}},replaceChildren(){},append(){}});return elements.get(id);};
const context={$,currentPage:1,totalPages:3,listRequestId:0,selectedIds:new Set(),listedRecords:[],document:{createElement(){throw Error('unexpected record rendering');}},updateSelectionControls(){},fetch:async()=>{throw Error('network failure');}};
vm.createContext(context);
vm.runInContext(source.slice(source.indexOf('function updatePageButtons'),source.indexOf('function archiveStatus')),context);
vm.runInContext(source.slice(source.indexOf('async function loadRecords'),source.indexOf("$('register-form')")),context);
await assert.rejects(context.loadRecords(2),/network failure/);assert.equal(context.currentPage,1);assert.equal($('next-page').disabled,false);
let calls=[];
context.fetch=async url=>{calls.push(url);return{ok:true,json:async()=>({records:[],page:2,pageSize:20,total:45,totalPages:3})};};
await context.loadRecords(2);assert.equal(context.currentPage,2);assert.match(calls[0],/page=2&/);
let releaseOld;context.fetch=()=>new Promise(resolve=>releaseOld=resolve);const older=context.loadRecords(1);
context.fetch=async()=>({ok:true,json:async()=>({records:[],total:45,totalPages:3})});await context.loadRecords(3);
releaseOld({ok:true,json:async()=>({records:[],total:45,totalPages:3})});await older;assert.equal(context.currentPage,3);
console.log('PASS: failed pagination retains page, successful page commits, stale response ignored');
+50
View File
@@ -0,0 +1,50 @@
$ErrorActionPreference = 'Stop'
$ridRepo = Split-Path $PSScriptRoot -Parent
$ridRoot = Join-Path ([IO.Path]::GetTempPath()) ('RID-package-review-' + [guid]::NewGuid().ToString('N'))
$ridOutput = Join-Path $ridRoot 'output'
$ridDeployment = Join-Path $ridOutput 'FPV-RID-Rust'
$ridData = Join-Path $ridDeployment 'registry/data'
New-Item -ItemType Directory -Force -Path $ridData | Out-Null
$ridSentinel = Join-Path $ridData 'registry.sqlite'
[IO.File]::WriteAllText($ridSentinel, 'sentinel data: must not be touched or packaged')
$ridBefore = (Get-FileHash -LiteralPath $ridSentinel -Algorithm SHA256).Hash
$ridRejected = $false
try { & (Join-Path $PSScriptRoot 'package.ps1') -OutputRoot $ridOutput } catch { $ridRejected = $true }
if (-not $ridRejected) { throw 'Dirty deployment folder was accepted' }
if ((Get-FileHash -LiteralPath $ridSentinel -Algorithm SHA256).Hash -ne $ridBefore) { throw 'Deployment data was modified' }
if (Test-Path -LiteralPath (Join-Path $ridOutput 'FPV-RID-Rust-Windows-x64.zip')) { throw 'Dirty package was published' }
$ridCleanOutput = Join-Path $ridRoot 'clean'
& (Join-Path $PSScriptRoot 'package.ps1') -OutputRoot $ridCleanOutput
if ($LASTEXITCODE -ne 0) { throw 'Clean package failed' }
# Repackage the same clean output, proving repeat builds remain supported.
& (Join-Path $PSScriptRoot 'package.ps1') -OutputRoot $ridCleanOutput
if ($LASTEXITCODE -ne 0) { throw 'Repeat package failed' }
$ridExistingZip = Join-Path $ridCleanOutput 'FPV-RID-Rust-Windows-x64.zip'
$ridOriginalZipHash = (Get-FileHash -LiteralPath $ridExistingZip -Algorithm SHA256).Hash
$ridUsedData = Join-Path $ridCleanOutput 'FPV-RID-Rust/registry/data'
New-Item -ItemType Directory -Force -Path $ridUsedData | Out-Null
[IO.File]::WriteAllText((Join-Path $ridUsedData 'registry.sqlite'), 'used deployment sentinel')
$ridRejected = $false
try { & (Join-Path $PSScriptRoot 'package.ps1') -OutputRoot $ridCleanOutput } catch { $ridRejected = $true }
if (-not $ridRejected) { throw 'Repackaging a used release folder was accepted' }
if ((Get-FileHash -LiteralPath $ridExistingZip -Algorithm SHA256).Hash -ne $ridOriginalZipHash) { throw 'Existing clean ZIP was overwritten on rejection' }
if ([IO.File]::ReadAllText((Join-Path $ridUsedData 'registry.sqlite')) -ne 'used deployment sentinel') { throw 'Existing deployment data was changed' }
Add-Type -AssemblyName System.IO.Compression.FileSystem
$ridZipPath = Join-Path $ridCleanOutput 'FPV-RID-Rust-Windows-x64.zip'
$ridZip = [IO.Compression.ZipFile]::OpenRead($ridZipPath)
try {
$ridExpected = @('fpv-rid-registry.exe','启动Rust版.cmd','使用说明.md','qrcode-LICENSE.txt','dependency-licenses.txt','SHA256SUMS.txt') | ForEach-Object { 'FPV-RID-Rust/' + $_ }
$ridActual = @($ridZip.Entries | ForEach-Object { $_.FullName.Replace('\','/') })
if ($ridActual.Count -ne $ridExpected.Count -or @(Compare-Object $ridActual $ridExpected).Count) { throw 'Archive contains unexpected files' }
} finally { $ridZip.Dispose() }
$ridZipHash = (Get-FileHash -LiteralPath $ridZipPath -Algorithm SHA256).Hash
if (-not (Get-Content -LiteralPath "$ridZipPath.sha256" -Raw).StartsWith($ridZipHash)) { throw 'ZIP checksum mismatch' }
foreach ($ridLine in Get-Content -LiteralPath (Join-Path $ridCleanOutput 'FPV-RID-Rust/SHA256SUMS.txt')) {
if ($ridLine -notmatch '^([A-F0-9]{64}) (.+)$') { throw 'Invalid checksum entry' }
$ridHash = $Matches[1]
$ridFile = Join-Path (Join-Path $ridCleanOutput 'FPV-RID-Rust') $Matches[2]
if ((Get-FileHash -LiteralPath $ridFile -Algorithm SHA256).Hash -ne $ridHash) { throw 'Release file checksum mismatch' }
}
if (@(Get-ChildItem -LiteralPath $ridCleanOutput -Directory -Filter '.package-*').Count) { throw 'Owned staging files were left behind' }
Write-Output "PASS: dirty deployment refused and preserved; repeat package, whitelist, ZIP and file checksums verified. Evidence: $ridRoot"
+17
View File
@@ -0,0 +1,17 @@
import {mkdtemp,cp,access} from 'node:fs/promises';
import {tmpdir} from 'node:os';
import path from 'node:path';
import {spawn} from 'node:child_process';
import assert from 'node:assert/strict';
const repo=path.resolve(import.meta.dirname,'..');const root=await mkdtemp(path.join(tmpdir(),'RID-便携验收-'));const app=path.join(root,'发布程序');
await cp(path.join(repo,'dist/FPV-RID-Rust'),app,{recursive:true});
let occupied=false;try{await fetch('http://127.0.0.1:8787/');occupied=true;}catch{}if(occupied)throw Error('8787 已被占用');
const exe=path.join(app,'fpv-rid-registry.exe');let output='';
const child=spawn(exe,[],{cwd:root,windowsHide:true,env:{...process.env,PATH:'C:\\Windows\\System32'},stdio:['ignore','pipe','pipe']});child.stdout.on('data',b=>output+=b);child.stderr.on('data',b=>output+=b);let spawnError;child.on('error',e=>spawnError=e);
try{
for(let i=0;i<150;i++){if(spawnError||child.exitCode!==null)throw Error(output||String(spawnError));try{if((await fetch('http://127.0.0.1:8787/api/records')).ok)break;}catch{}await new Promise(r=>setTimeout(r,100));}
await access(path.join(app,'registry/data/registry.sqlite'));await assert.rejects(access(path.join(root,'registry/data/registry.sqlite')));
const page=await fetch('http://127.0.0.1:8787/');assert.equal(page.status,200);assert.match(await page.text(),/edit-dialog/);
const second=spawn(exe,['--data-root',path.join(root,'第二实例')],{windowsHide:true,stdio:['ignore','pipe','pipe']});let stderr='';second.stderr.on('data',b=>stderr+=b);const code=await new Promise((resolve,reject)=>{second.on('exit',resolve);second.on('error',reject);});assert.notEqual(code,0);assert.match(stderr,/8787/);await assert.rejects(access(path.join(root,'第二实例/registry/data/registry.sqlite')));
console.log(JSON.stringify({status:'PASS',root,scenarios:['published exe','Chinese install path','different working directory','no Node PATH','embedded webpage','port conflict without new database']}));
}finally{if(child.exitCode===null&&!spawnError){const exit=new Promise(r=>child.once('exit',r));child.kill();await exit;}}
+115
View File
@@ -0,0 +1,115 @@
// Uses built-in Node APIs as test tooling. Runs only Rust against disposable data.
import {mkdtemp,mkdir,writeFile,rm} from 'node:fs/promises';
import {tmpdir} from 'node:os';
import path from 'node:path';
import {spawn,execFileSync} from 'node:child_process';
import assert from 'node:assert/strict';
import {DatabaseSync} from 'node:sqlite';
import {inflateRawSync} from 'node:zlib';
const repo=path.resolve(import.meta.dirname,'..');
const root=await mkdtemp(path.join(tmpdir(),'RID-中文验证-'));
const base='http://127.0.0.1:8787';
const png='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aocsAAAAASUVORK5CYII=';
let child;let output='';
let spawnError;
async function start(command,args){
// Never attach to, or mutate, an unrelated service already listening on this port.
let occupied=false;try{await fetch(base+'/api/records',{signal:AbortSignal.timeout(1000)});occupied=true;}catch{}
if(occupied)throw Error('8787 已被占用,请关闭登记站再执行独立验收');
output='';spawnError=null;child=spawn(command,args,{cwd:root,windowsHide:true,stdio:['ignore','pipe','pipe']});
child.stdout.on('data',b=>output+=b);child.stderr.on('data',b=>output+=b);
child.on('error',e=>{spawnError=e;output+=e.message;});
for(let i=0;i<150;i++){if(spawnError||child.exitCode!==null)throw Error(output);try{const r=await fetch(base+'/api/records');if(r.ok)return;}catch{}await new Promise(r=>setTimeout(r,100));}throw Error('启动超时 '+output);
}
async function stop(){if(child&&!spawnError&&child.exitCode===null){const exited=new Promise(r=>child.once('exit',r));if(child.kill())await exited;}child=null;}
async function api(route,method='GET',body,status=200){const r=await fetch(base+route,{method,headers:body?{'content-type':'application/json'}:{},body:body?JSON.stringify(body):undefined});const v=await r.json();assert.equal(r.status,status,JSON.stringify(v));return v;}
function unzip(bytes){
const end=bytes.lastIndexOf(Buffer.from([0x50,0x4b,0x05,0x06]));assert.ok(end>=0);
const entries=new Map();let offset=bytes.readUInt32LE(end+16);
for(let i=0;i<bytes.readUInt16LE(end+10);i++){
assert.equal(bytes.readUInt32LE(offset),0x02014b50);
const method=bytes.readUInt16LE(offset+10),size=bytes.readUInt32LE(offset+20),rawSize=bytes.readUInt32LE(offset+24);
const nameLength=bytes.readUInt16LE(offset+28),extra=bytes.readUInt16LE(offset+30),comment=bytes.readUInt16LE(offset+32),local=bytes.readUInt32LE(offset+42);
const name=bytes.toString('utf8',offset+46,offset+46+nameLength);
assert.equal(bytes.readUInt32LE(local),0x04034b50);
const start=local+30+bytes.readUInt16LE(local+26)+bytes.readUInt16LE(local+28);
const compressed=bytes.subarray(start,start+size);assert.ok(method===0||method===8);
const data=method===8?inflateRawSync(compressed):compressed;assert.equal(data.length,rawSize);
entries.set(name,data);offset+=46+nameLength+extra+comment;
}return entries;
}
async function exports(id,label){
for(const kind of ['archive','excel']){
const r=await fetch(base+'/api/export/'+kind,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({ids:[id]})});assert.equal(r.status,200);
const bytes=Buffer.from(await r.arrayBuffer());const entries=unzip(bytes);
if(kind==='archive'){
const manifest=JSON.parse(entries.get('档案库/records.json').toString());assert.equal(manifest[0].id,id);assert.equal(manifest[0].fpvCode,'FPV00000001');
assert.deepEqual(entries.get('档案库/照片/TEST-SN-001-1.png'),Buffer.from(png.split(',')[1],'base64'));
assert.match(entries.get('档案库/档案卡/TEST-SN-001.html').toString(),/data:image\/png;base64,/);
}else{
assert.ok(entries.has('[Content_Types].xml'));assert.ok(entries.has('xl/workbook.xml'));assert.ok(entries.has('xl/worksheets/sheet1.xml'));
const xml=[...entries.values()].map(b=>b.toString()).join('');assert.ok(xml.includes(id));assert.ok(xml.includes('TEST-SN-001'));assert.ok(xml.includes('模块 SN'));
}
await writeFile(path.join(root,`${label}-${kind}.zip`),bytes);
}
const r=await fetch(base+`/api/records/${id}/archive`);const html=await r.text();assert.match(html,/data:image\/png;base64,/);assert.ok(!html.includes('${'));assert.ok(html.includes('&lt;测试&gt;'));
}
try{
const cargo=process.env.CARGO_HOME?path.join(process.env.CARGO_HOME,'bin/cargo.exe'):'D:/Rust_Contact/util/cargo/bin/cargo.exe';
const metadata=process.argv[2]?null:JSON.parse(execFileSync(cargo,['metadata','--format-version','1','--no-deps'],{cwd:repo,encoding:'utf8',windowsHide:true}));
const exe=path.resolve(process.argv[2]||path.join(metadata.target_directory,'release/fpv-rid-registry.exe'));
await start(exe,['--data-root',root]);
const a=await api('/api/records','POST',{serialNo:'TEST-SN-001',uasCode:'FPV00000001',modelName:'<测试>',ownerName:'原登记人',photo1:png});
const id=a.record.id;assert.match(id,/^[0-9a-f]{36}$/);assert.equal(a.existing,false);
const b=await api('/api/records','POST',{serialNo:'TEST-SN-001',modelName:'',ownerName:''});assert.equal(b.existing,true);assert.equal(b.record.modelName,'<测试>');
await api('/api/records','POST',{serialNo:'TEST-SN-002',uasCode:'FPV00000001'},400);
await api('/api/records','POST',{serialNo:'x'},400);
assert.equal((await api('/api/records?q='+encodeURIComponent('原登记人'))).records.length,1);
await exports(id,'rust-initial');await stop();
const dbPath=path.join(root,'registry/data/registry.sqlite');
let db=new DatabaseSync(dbPath);const before=db.prepare('SELECT hex(image) AS bytes FROM photos').get().bytes;db.close();
await start(exe,['--data-root',root]);
assert.equal((await api('/api/records')).records[0].id,id);
assert.equal((await api('/api/resolve?url='+encodeURIComponent(base+'/r/'+id))).id,id);
await api('/api/resolve?url='+encodeURIComponent('http://example.com/r/'+id),'GET',undefined,400);
await exports(id,'rust');db=new DatabaseSync(dbPath);assert.equal(db.prepare('SELECT hex(image) AS bytes FROM photos').get().bytes,before);db.close();
const blocked=await fetch(base+'/api/records',{headers:{origin:'https://example.com'}});assert.equal(blocked.status,403);
const p=await api('/api/records?page=1&pageSize=1');assert.equal(p.total,1);assert.equal(p.records.length,1);
await api('/api/records?page=0','GET',undefined,400);
const edited=await api('/api/records/'+id,'PATCH',{modelName:'',ownerName:'新登记人'});assert.equal(edited.record.modelName,'');
await api('/api/records/'+id,'PATCH',{serialNo:'OTHER-SN'},400);
await api('/api/records/'+id,'PATCH',{ownerName:'must rollback',photo1:'invalid'},400);
assert.equal((await api('/api/resolve?url='+encodeURIComponent(base+'/r/'+id))).ownerName,'新登记人');
await api('/api/records/'+id,'PATCH',{photo1:null,photo2:png});
assert.equal((await fetch(base+'/api/records/'+id+'/photos/2')).status,200);
await api('/api/records/'+id+'/photos/1','DELETE');await api('/api/records/'+id+'/photos/1','GET',undefined,404);
await api('/api/records','POST',{serialNo:'TEST-SN-001',photo1:png});
// Simulate an archive directory failure without modifying the active database.
await stop();await rm(path.join(root,'档案库'),{recursive:true});await writeFile(path.join(root,'档案库'),'blocked');
await start(exe,['--data-root',root]);
const pending=await api('/api/records','POST',{serialNo:'TEST-SN-003',ownerName:'已保存'});assert.equal(pending.archiveStatus,'pending');assert.ok(pending.warning);
assert.equal((await api('/api/archive/status')).archiveStatus,'pending');
await api('/api/archive/retry','POST',{},500);
db=new DatabaseSync(dbPath);assert.ok(db.prepare("SELECT value FROM registry_meta WHERE key='archive_pending'").get());db.close();
await rm(path.join(root,'档案库'));await api('/api/archive/retry','POST',{});
assert.equal((await api('/api/records')).records.length,2);
await api('/api/records/'+id,'DELETE');assert.equal((await api('/api/records')).records.length,1);
await api('/api/records/'+id,'PATCH',{ownerName:'resurrect',photo1:png},404);
await stop();await start(exe,['--data-root',root]);assert.equal((await api('/api/records')).records.length,1);await stop();
db=new DatabaseSync(path.join(root,'档案库/登记数据库.sqlite'));assert.equal(db.prepare('SELECT COUNT(*) AS n FROM records').get().n,1);assert.equal(db.prepare('PRAGMA integrity_check').get().integrity_check,'ok');db.close();
const legacyRoot=path.join(root,'legacy-regression');
await mkdir(path.join(legacyRoot,'registry/data'),{recursive:true});
const legacyRows=[{id:'1'.repeat(36),serialNo:'IMPORT-001',uasCode:'FPV00000001',createdAt:'2020-01-01T00:00:00.000Z'},{id:'2'.repeat(36),serialNo:'IMPORT-002',uasCode:'FPV00000002'}];
const legacyFile=path.join(legacyRoot,'registry/data/records.json');
await writeFile(legacyFile,JSON.stringify(legacyRows));
const rejected=spawn(exe,['--data-root',legacyRoot],{windowsHide:true,stdio:['ignore','pipe','pipe']});
let importError='';rejected.stderr.on('data',b=>importError+=b);
const exitCode=await new Promise((resolve,reject)=>{rejected.once('exit',resolve);rejected.once('error',reject);});
assert.notEqual(exitCode,0);assert.match(importError,/第 2 条/);
db=new DatabaseSync(path.join(legacyRoot,'registry/data/registry.sqlite'));
assert.equal(db.prepare('SELECT COUNT(*) AS n FROM records').get().n,0);
assert.equal(db.prepare('SELECT COUNT(*) AS n FROM registry_meta').get().n,0);db.close();
legacyRows[1].createdAt='2020-01-01T00:00:00.000Z';await writeFile(legacyFile,JSON.stringify(legacyRows));
await start(exe,['--data-root',legacyRoot]);assert.equal((await api('/api/records')).records.length,2);await stop();
console.log(JSON.stringify({status:'PASS',root,scenarios:['Rust registration','Rust database restart','photo bytes','QR','ZIP/XLSX contents','HTML escaping','origin','PATCH','photo deletion','pagination','archive fault and retry','restart','backup integrity','invalid legacy import fails visibly and rolls back','corrected legacy file retries successfully']}));
}finally{await stop();}
+266
View File
@@ -0,0 +1,266 @@
use crate::error::{AppError, Result};
use crate::store::{Store, valid_id};
use base64::{Engine, engine::general_purpose::STANDARD};
use serde_json::{Value, json};
use std::{
io::{Cursor, Write},
path::Path,
};
fn escape(s: &str) -> String {
s.replace('&', "&amp;")
.replace('<', "&lt;")
.replace('>', "&gt;")
.replace('"', "&quot;")
.replace('\'', "&#39;")
}
pub fn public(mut r: Value) -> Value {
if let Some(o) = r.as_object_mut() {
o.remove("photo1");
o.remove("photo2");
}
r
}
pub fn card(s: &Store, r: &Value, standalone: bool) -> Result<String> {
let id = r["id"].as_str().ok_or("档案 ID 无效")?;
let mut photos = String::new();
for slot in [1, 2] {
if let Some((mime, data)) = s.photo(id, slot)? {
let src = if standalone {
format!("data:{mime};base64,{}", STANDARD.encode(data))
} else {
format!("/api/records/{id}/photos/{slot}")
};
photos.push_str(&format!("<figure><img src=\"{src}\" alt=\"登记照片 {slot}\"><figcaption>登记照片 {slot}</figcaption></figure>"));
} else {
photos.push_str(&format!("<figure><div class=\"no-photo\">未上传照片 {slot}</div><figcaption>照片 {slot}</figcaption></figure>"));
}
}
// Replace tokens in one pass: user text must never be interpreted as another template token.
let re =
regex::Regex::new(r"\{\{(serialNo|uasCode|modelName|ownerName|createdAt|id|photos)\}\}")
.unwrap();
Ok(re
.replace_all(include_str!("card.html"), |caps: &regex::Captures| {
let key = &caps[1];
if key == "photos" {
return photos.clone();
}
let text = r[key].as_str().unwrap_or("");
escape(
if text.is_empty() && (key == "modelName" || key == "ownerName") {
"—"
} else {
text
},
)
})
.into_owned())
}
pub fn atomic(path: &Path, data: impl AsRef<[u8]>) -> Result<()> {
let tmp = path.with_extension("tmp");
std::fs::write(&tmp, data).map_err(|e| AppError::Internal(e.to_string()))?;
// Windows rename cannot replace an existing destination; use MoveFileExW replacement.
replace(&tmp, path)
}
#[cfg(windows)]
fn replace(from: &Path, to: &Path) -> Result<()> {
use std::os::windows::ffi::OsStrExt;
#[link(name = "kernel32")]
unsafe extern "system" {
fn MoveFileExW(from: *const u16, to: *const u16, flags: u32) -> i32;
}
let from: Vec<u16> = from.as_os_str().encode_wide().chain(Some(0)).collect();
let to: Vec<u16> = to.as_os_str().encode_wide().chain(Some(0)).collect();
if unsafe { MoveFileExW(from.as_ptr(), to.as_ptr(), 1 | 8) } == 0 {
Err(AppError::Internal(
std::io::Error::last_os_error().to_string(),
))
} else {
Ok(())
}
}
#[cfg(not(windows))]
fn replace(from: &Path, to: &Path) -> Result<()> {
std::fs::rename(from, to).map_err(|e| AppError::Internal(e.to_string()))
}
pub fn sync(s: &mut Store) -> Result<()> {
let retain = s.pending()?.unwrap_or(true);
s.mark_pending(retain)?;
let dir = s.root.join("档案库");
let cards = dir.join("档案卡");
std::fs::create_dir_all(&cards).map_err(|e| AppError::Internal(e.to_string()))?;
atomic(
&dir.join("使用说明.txt"),
"FPV-RID 本地档案库\r\n档案卡包含照片,可离线打开。登记数据库.sqlite 为最新备份,previous 为上一次备份。\r\n",
)?;
let records = s.list("")?;
for r in &records {
let id = r["id"].as_str().ok_or("档案 ID 无效")?;
if !valid_id(id) {
return Err("档案 ID 无效".into());
}
atomic(&cards.join(format!("{id}.html")), card(s, r, true)?)?;
}
for file in std::fs::read_dir(&cards).map_err(|e| AppError::Internal(e.to_string()))? {
let file = file.map_err(|e| AppError::Internal(e.to_string()))?;
let name = file.file_name().to_string_lossy().into_owned();
if let Some(id) = name.strip_suffix(".html")
&& valid_id(id)
&& !records.iter().any(|r| r["id"] == id)
{
std::fs::remove_file(file.path()).map_err(|e| AppError::Internal(e.to_string()))?;
}
}
atomic(
&dir.join("记录索引.json"),
serde_json::to_vec_pretty(&records.iter().cloned().map(public).collect::<Vec<_>>())
.map_err(|e| AppError::Internal(e.to_string()))?,
)?;
let current = dir.join("登记数据库.sqlite");
let previous = dir.join("登记数据库.previous.sqlite");
let tmp = dir.join("登记数据库.tmp.sqlite");
if tmp.exists() {
std::fs::remove_file(&tmp).map_err(|e| AppError::Internal(e.to_string()))?;
}
s.db.backup(rusqlite::MAIN_DB, &tmp, None)
.map_err(|e| AppError::Internal(e.to_string()))?;
if retain && current.exists() {
atomic(
&previous,
std::fs::read(&current).map_err(|e| AppError::Internal(e.to_string()))?,
)?;
}
if !retain && previous.exists() {
std::fs::remove_file(&previous).map_err(|e| AppError::Internal(e.to_string()))?;
}
replace(&tmp, &current)?;
s.db.execute("DELETE FROM registry_meta WHERE key='archive_pending'", [])?;
Ok(())
}
pub fn finish(s: &mut Store, mut result: Value) -> Value {
match sync(s) {
Ok(()) => result["archiveStatus"] = json!("synced"),
Err(e) => {
eprintln!("档案同步失败:{e}");
result["archiveStatus"] = json!("pending");
result["warning"] = json!("数据已保存,档案或备份同步失败,请重试 /api/archive/retry");
}
}
result
}
fn zip_entries(entries: Vec<(String, Vec<u8>)>) -> Result<Vec<u8>> {
let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new()));
for (name, data) in entries {
zip.start_file(
name,
zip::write::SimpleFileOptions::default()
.compression_method(zip::CompressionMethod::Deflated),
)
.map_err(|e| AppError::Internal(e.to_string()))?;
zip.write_all(&data)
.map_err(|e| AppError::Internal(e.to_string()))?;
}
Ok(zip
.finish()
.map_err(|e| AppError::Internal(e.to_string()))?
.into_inner())
}
pub fn export(s: &Store, records: Vec<Value>, excel: bool) -> Result<Vec<u8>> {
if excel {
let mut book = rust_xlsxwriter::Workbook::new();
let sheet = book.add_worksheet();
let heading = rust_xlsxwriter::Format::new()
.set_bold()
.set_background_color(0x206D9Fu32)
.set_font_color(0xFFFFFFu32);
let headings = [
"模块 SN",
"FPV 编号",
"机型",
"登记人 / 备注",
"登记时间",
"照片 1",
"照片 2",
"档案 ID",
];
for (col, title) in headings.iter().enumerate() {
sheet
.write_string_with_format(0, col as u16, *title, &heading)
.map_err(|e| AppError::Internal(e.to_string()))?;
sheet
.set_column_width(
col as u16,
[25.0, 19.0, 20.0, 24.0, 25.0, 10.0, 10.0, 40.0][col],
)
.map_err(|e| AppError::Internal(e.to_string()))?;
}
for (i, r) in records.iter().enumerate() {
let cells = [
r["serialNo"].as_str().unwrap_or(""),
r["uasCode"].as_str().unwrap_or(""),
r["modelName"].as_str().unwrap_or(""),
r["ownerName"].as_str().unwrap_or(""),
r["createdAt"].as_str().unwrap_or(""),
if r["photo1"] == true { "有" } else { "无" },
if r["photo2"] == true { "有" } else { "无" },
r["id"].as_str().unwrap_or(""),
];
for (c, v) in cells.iter().enumerate() {
sheet
.write_string((i + 1) as u32, c as u16, *v)
.map_err(|e| AppError::Internal(e.to_string()))?;
}
}
sheet
.set_freeze_panes(1, 0)
.map_err(|e| AppError::Internal(e.to_string()))?;
sheet
.autofilter(0, 0, records.len() as u32, 7)
.map_err(|e| AppError::Internal(e.to_string()))?;
return book
.save_to_buffer()
.map_err(|e| AppError::Internal(e.to_string()));
}
let mut entries = vec![(
"档案库/使用说明.txt".into(),
"每个档案卡 HTML 均包含照片,可离线打开。照片原件见照片目录。"
.as_bytes()
.to_vec(),
)];
let mut manifest = vec![];
for r in records {
let sn = r["serialNo"].as_str().ok_or("SN 无效")?;
if !sn.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') {
return Err("SN 无效".into());
}
let id = r["id"].as_str().ok_or("档案 ID 无效")?;
entries.push((
format!("档案库/档案卡/{sn}.html"),
card(s, &r, true)?.into_bytes(),
));
let mut photos = vec![];
for slot in [1, 2] {
if let Some((mime, data)) = s.photo(id, slot)? {
let ext = match mime.as_str() {
"image/jpeg" => "jpg",
"image/png" => "png",
"image/webp" => "webp",
_ => return Err("照片格式无效".into()),
};
let name = format!("档案库/照片/{sn}-{slot}.{ext}");
photos.push(json!(name));
entries.push((name, data));
} else {
photos.push(Value::Null);
}
}
manifest.push(json!({"id":id,"serialNo":sn,"fpvCode":r["uasCode"],"modelName":r["modelName"],"ownerName":r["ownerName"],"createdAt":r["createdAt"],"photos":photos}));
}
entries.push((
"档案库/records.json".into(),
serde_json::to_vec_pretty(&manifest).map_err(|e| AppError::Internal(e.to_string()))?,
));
zip_entries(entries)
}
+18
View File
@@ -0,0 +1,18 @@
<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{{serialNo}} · 本地档案卡</title><style>
*{box-sizing:border-box}body{font-family:system-ui,"Microsoft YaHei",sans-serif;background:#edf2f7;color:#173047;margin:0;padding:36px 18px}
main{max-width:760px;margin:auto;background:#fff;border:1px solid #dce6f0;border-radius:20px;padding:36px;box-shadow:0 12px 40px #1a385015}
.tag{display:inline-block;background:#e7f4ec;color:#25734a;border-radius:999px;padding:7px 13px;font-size:12px;font-weight:700}
h1{font-size:26px;margin:22px 0 6px}.code{font-size:19px;color:#1c6595;font-weight:800;letter-spacing:.04em}
.note{color:#7a8c9b;font-size:12px;line-height:1.6;margin:12px 0 24px}
dl{display:grid;grid-template-columns:125px 1fr;gap:15px;border-top:1px solid #e5ebf0;padding-top:22px;margin:0}
dt{color:#63768a}dd{margin:0;font-weight:700;overflow-wrap:anywhere}
h2{font-size:16px;margin:30px 0 14px}.photos{display:grid;grid-template-columns:1fr 1fr;gap:14px}
figure{margin:0;border:1px solid #e1e8ee;border-radius:11px;overflow:hidden}figure img,.no-photo{width:100%;height:245px;object-fit:contain;background:#f4f7fa}
.no-photo{display:grid;place-items:center;color:#9aabb8;font-size:13px}figcaption{padding:10px 12px;font-size:12px;color:#63768a}
footer{border-top:1px solid #e5ebf0;margin-top:26px;padding-top:15px;color:#98a7b3;font-size:11px;overflow-wrap:anywhere}
@media(max-width:540px){main{padding:22px}.photos{grid-template-columns:1fr}dl{grid-template-columns:90px 1fr}}
@media print{body{background:#fff;padding:0}main{box-shadow:none;border:0;max-width:none}}
</style></head><body><main><span class="tag">本地备案档案卡</span><h1>{{serialNo}}</h1><div class="code">{{uasCode}}</div>
<p class="note">本档案卡由 FPV-RID 本地登记软件保存,可离线打开。</p>
<dl><dt>模块 SN</dt><dd>{{serialNo}}</dd><dt>FPV 编号</dt><dd>{{uasCode}}</dd><dt>机型</dt><dd>{{modelName}}</dd><dt>登记人 / 备注</dt><dd>{{ownerName}}</dd><dt>登记时间</dt><dd>{{createdAt}}</dd></dl>
<h2>登记照片</h2><div class="photos">{{photos}}</div><footer>档案 ID:{{id}}</footer></main></body></html>
+37
View File
@@ -0,0 +1,37 @@
use std::fmt;
#[derive(Debug)]
pub enum AppError {
Validation(String),
NotFound(&'static str),
Internal(String),
}
pub type Result<T> = std::result::Result<T, AppError>;
impl From<&str> for AppError {
fn from(s: &str) -> Self {
Self::Validation(s.into())
}
}
impl From<String> for AppError {
fn from(s: String) -> Self {
Self::Internal(s)
}
}
impl From<rusqlite::Error> for AppError {
fn from(e: rusqlite::Error) -> Self {
Self::Internal(e.to_string())
}
}
impl From<std::io::Error> for AppError {
fn from(e: std::io::Error) -> Self {
Self::Internal(e.to_string())
}
}
impl fmt::Display for AppError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Validation(s) | Self::Internal(s) => write!(f, "{s}"),
Self::NotFound(s) => write!(f, "{s}"),
}
}
}
impl std::error::Error for AppError {}
+170
View File
@@ -0,0 +1,170 @@
use crate::error::{AppError, Result};
use crate::{
Worker, archive,
store::{Store, valid_id},
};
use axum::{
Router,
body::Body,
extract::{DefaultBodyLimit, Request, State},
http::{HeaderValue, StatusCode},
middleware::{self, Next},
response::{IntoResponse, Response},
};
use serde_json::{Value, json};
pub fn router(worker: Worker) -> Router {
Router::new()
.fallback(handle)
.layer(DefaultBodyLimit::max(16 * 1024 * 1024))
.layer(middleware::from_fn(headers))
.with_state(worker)
}
async fn headers(req: Request, next: Next) -> Response {
let mut r = next.run(req).await;
for (key, value) in [
("cache-control", "no-store"),
("x-content-type-options", "nosniff"),
("access-control-allow-origin", "*"),
(
"access-control-allow-methods",
"GET, POST, PATCH, DELETE, OPTIONS",
),
("access-control-allow-headers", "content-type"),
("access-control-allow-private-network", "true"),
] {
r.headers_mut().insert(key, HeaderValue::from_static(value));
}
if !r.headers().contains_key("content-security-policy") {
r.headers_mut().insert("content-security-policy",HeaderValue::from_static("default-src 'self'; img-src 'self' data: blob:; style-src 'self'; script-src 'self'; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'"));
}
r
}
fn json_response(status: StatusCode, v: Value) -> Response {
(status, axum::Json(v)).into_response()
}
fn error(e: AppError) -> Response {
let (status, message) = match e {
AppError::Validation(s) => (StatusCode::BAD_REQUEST, s),
AppError::NotFound(s) => (StatusCode::NOT_FOUND, s.to_owned()),
AppError::Internal(s) => {
eprintln!("内部错误:{s}");
(
StatusCode::INTERNAL_SERVER_ERROR,
"服务内部错误,请检查日志后重试".to_owned(),
)
}
};
json_response(status, json!({"error":message}))
}
fn binary(data: Vec<u8>, kind: &str, filename: Option<&str>, csp: Option<&str>) -> Response {
let mut r = Response::new(Body::from(data));
r.headers_mut()
.insert("content-type", HeaderValue::from_str(kind).unwrap());
if let Some(name) = filename
&& let Ok(h) = HeaderValue::from_str(&format!("attachment; filename=\"{name}\""))
{
r.headers_mut().insert("content-disposition", h);
}
if let Some(csp) = csp {
r.headers_mut().insert(
"content-security-policy",
HeaderValue::from_str(csp).unwrap(),
);
}
r
}
fn selected(s: &Store, v: &Value) -> Result<Vec<Value>> {
let ids = v["ids"].as_array().ok_or("请先勾选要导出的档案")?;
if ids.is_empty() || ids.len() > 5000 {
return Err("请先勾选要导出的档案".into());
}
let mut wanted = std::collections::HashSet::new();
for id in ids {
let id = id.as_str().filter(|s| valid_id(s)).ok_or("档案 ID 无效")?;
wanted.insert(id);
}
let ids = wanted.into_iter().map(str::to_owned).collect::<Vec<_>>();
match s.selected(&ids) {
Err(AppError::NotFound(_)) => Err("选择的档案已不存在,请刷新记录".into()),
other => other,
}
}
async fn handle(State(worker): State<Worker>, req: Request) -> Response {
let method = req.method().to_string();
let path = req.uri().path().to_owned();
let origin = req.headers().get("origin").and_then(|h| h.to_str().ok());
if origin.is_some_and(|o| o != "http://127.0.0.1:8787" && o != "http://localhost:8787")
&& path != "/api/resolve"
{
return json_response(
StatusCode::FORBIDDEN,
json!({"error":"只允许从本地登记站访问"}),
);
}
if method == "OPTIONS" {
return StatusCode::NO_CONTENT.into_response();
}
let params =
match axum::extract::Query::<std::collections::HashMap<String, String>>::try_from_uri(
req.uri(),
) {
Ok(q) => q.0,
Err(_) => return error("查询参数无效".into()),
};
let body = if method == "POST" || method == "PATCH" {
match axum::body::to_bytes(req.into_body(), 16 * 1024 * 1024).await {
Ok(b) => {
if path == "/api/archive/retry" && b.is_empty() {
json!({})
} else {
match serde_json::from_slice::<Value>(&b) {
Ok(v) => v,
Err(_) => return error("提交内容不是有效 JSON".into()),
}
}
}
Err(_) => return error("提交内容过大,单张照片最多 5 MB".into()),
}
} else {
Value::Null
};
let result=worker.run(move|s|{
if method=="GET"&&path=="/api/archive/status"{return Ok(json_response(StatusCode::OK,if s.pending()?.is_some(){json!({"archiveStatus":"pending","warning":"档案或备份待同步,请重试。"})}else{json!({"archiveStatus":"synced"})}));}
if method=="GET"&&path=="/api/records"{
let q=params.get("q").map(|s|s.trim()).unwrap_or("");
let paged=params.contains_key("page")||params.contains_key("pageSize");
let value=if paged{let parse=|key:&str,default:usize|->Result<usize>{params.get(key).map(|s|s.parse::<usize>().map_err(|_|"分页参数无效".into())).unwrap_or(Ok(default))};s.page(q,parse("page",1)?,parse("pageSize",20)?)?}else{json!({"records":s.list(q)?.into_iter().map(archive::public).collect::<Vec<_>>()})};return Ok(json_response(StatusCode::OK,value));
}
if method=="POST"&&path=="/api/records"{let mut v=s.register(body)?;v["record"]=archive::public(v["record"].take());return Ok(json_response(StatusCode::OK,archive::finish(s,v)))}
if method=="POST"&&path=="/api/archive/retry"{archive::sync(s).map_err(|e|format!("内部错误:档案同步失败:{e}"))?;return Ok(json_response(StatusCode::OK,json!({"archiveStatus":"synced"})))}
if method=="POST"&&(path=="/api/export/archive"||path=="/api/export/excel"){
let excel=path.ends_with("excel");let records=selected(s,&body)?;let bytes=archive::export(s,records,excel).map_err(|e|format!("内部错误:导出失败:{e}"))?;
return Ok(binary(bytes,if excel{"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}else{"application/zip"},Some(if excel{"FPV-RID-records.xlsx"}else{"FPV-RID-archive.zip"}),None));
}
if method=="GET"&&path=="/api/resolve"{
let uri:axum::http::Uri=params.get("url").ok_or("二维码内容不是有效网址")?.parse().map_err(|_|"二维码内容不是有效网址")?;
if uri.scheme_str()!=Some("http")||!matches!(uri.host(),Some("127.0.0.1"|"localhost"))||uri.port_u16()!=Some(8787){return Err("二维码不是本机登记站生成的链接".into())}
let id=uri.path().strip_prefix("/r/").filter(|id|valid_id(id)).ok_or("本地登记链接格式无效")?;
return Ok(json_response(StatusCode::OK,archive::public(s.get(id)?)));
}
let parts=path.trim_start_matches('/').split('/').collect::<Vec<_>>();
if parts.len()>=3&&parts[0]=="api"&&parts[1]=="records"&&valid_id(parts[2]){
let id=parts[2];
if parts.len()==3&&method=="PATCH"{let mut v=s.patch(id,body)?;v["record"]=archive::public(v["record"].take());return Ok(json_response(StatusCode::OK,archive::finish(s,v)))}
if parts.len()==3&&method=="DELETE"{let v=s.delete(id,None)?;return Ok(json_response(StatusCode::OK,archive::finish(s,v)))}
if parts.len()==5&&parts[3]=="photos"&&matches!(parts[4],"1"|"2"){
let slot=parts[4].parse::<u8>().unwrap();if method=="DELETE"{let v=s.delete(id,Some(slot))?;return Ok(json_response(StatusCode::OK,archive::finish(s,v)))}
if method=="GET"{let (mime,data)=s.photo(id,slot)?.ok_or(AppError::NotFound("照片不存在"))?;return Ok(binary(data,&mime,None,None))}
}
if parts.len()==4&&parts[3]=="archive"&&method=="GET"{let r=s.get(id)?;let name=format!("FPV-RID-{}.html",r["serialNo"].as_str().unwrap_or("record"));return Ok(binary(archive::card(s,&r,true)?.into_bytes(),"text/html; charset=utf-8",Some(&name),Some("default-src 'none'; img-src data:; style-src 'unsafe-inline'; base-uri 'none'; frame-ancestors 'none'")))}
}
if method=="GET"&&parts.len()==2&&parts[0]=="r"&&valid_id(parts[1]){return Ok(binary(archive::card(s,&s.get(parts[1])?,false)?.into_bytes(),"text/html; charset=utf-8",None,Some("default-src 'none'; img-src 'self'; style-src 'unsafe-inline'; base-uri 'none'; frame-ancestors 'none'")))}
if method=="GET"{let resource:Option<(&[u8],&str)>=match path.as_str(){"/"=>Some((include_bytes!("../registry/web/index.html"),"text/html; charset=utf-8")),"/app.js"=>Some((include_bytes!("../registry/web/app.js"),"text/javascript; charset=utf-8")),"/app.css"=>Some((include_bytes!("../registry/web/app.css"),"text/css; charset=utf-8")),"/vendor/qrcode.js"=>Some((include_bytes!("../registry/web/vendor/qrcode.js"),"text/javascript; charset=utf-8")),"/fpv-rid-icon.png"=>Some((include_bytes!("../registry/web/fpv-rid-icon.png"),"image/png")),_=>None};if let Some((bytes,mime))=resource{return Ok(binary(bytes.to_vec(),mime,None,None))}}
Ok(json_response(StatusCode::NOT_FOUND,json!({"error":"页面不存在"})))
}).await;
match result {
Ok(response) => response,
Err(e) => error(e),
}
}
+74
View File
@@ -0,0 +1,74 @@
mod archive;
mod error;
mod http;
mod store;
#[cfg(test)]
mod tests;
use std::{path::PathBuf, sync::mpsc};
type Job = Box<dyn FnOnce(&mut store::Store) + Send>;
#[derive(Clone)]
pub struct Worker(mpsc::Sender<Job>);
impl Worker {
async fn run<T: Send + 'static>(
&self,
f: impl FnOnce(&mut store::Store) -> error::Result<T> + Send + 'static,
) -> error::Result<T> {
let (tx, rx) = tokio::sync::oneshot::channel();
self.0
.send(Box::new(move |s| {
let _ = tx.send(f(s));
}))
.map_err(|_| "数据库线程已停止".to_string())?;
rx.await
.map_err(|_| error::AppError::Internal("数据库线程已停止".into()))?
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut args = std::env::args().skip(1);
let root = match args.next().as_deref() {
Some("--data-root") => PathBuf::from(args.next().ok_or("缺少数据目录")?),
None => std::env::current_exe()?
.parent()
.ok_or("无法确定程序目录")?
.to_owned(),
_ => return Err("用法: fpv-rid-registry.exe [--data-root DIRECTORY]".into()),
};
if args.next().is_some() {
return Err("未知启动参数".into());
}
let listener = tokio::net::TcpListener::bind("127.0.0.1:8787")
.await
.map_err(|e| format!("无法监听 8787,请关闭旧版或其他实例:{e}"))?;
std::fs::create_dir_all(root.join("registry/data"))?;
let lock = std::fs::OpenOptions::new()
.create(true)
.truncate(false)
.read(true)
.write(true)
.open(root.join("registry/data/rust.lock"))?;
fs2::FileExt::try_lock_exclusive(&lock).map_err(|_| "该数据目录已被另一个 Rust 实例使用")?;
let store = store::Store::open(root)?;
let (tx, rx) = mpsc::channel::<Job>();
let worker_thread = std::thread::spawn(move || {
let mut store = store;
if let Err(e) = archive::sync(&mut store) {
eprintln!("档案待同步:{e}");
}
for job in rx {
job(&mut store);
}
});
println!("FPV-RID Rust 登记站:http://127.0.0.1:8787");
axum::serve(listener, http::router(Worker(tx)))
.with_graceful_shutdown(async {
let _ = tokio::signal::ctrl_c().await;
})
.await?;
worker_thread.join().map_err(|_| "数据库线程异常退出")?;
drop(lock);
Ok(())
}
+433
View File
@@ -0,0 +1,433 @@
use crate::error::{AppError, Result};
use base64::{Engine, engine::general_purpose::STANDARD};
use rand::Rng;
use rusqlite::{Connection, OptionalExtension, params};
use serde_json::{Value, json};
use std::path::PathBuf;
pub struct Store {
pub db: Connection,
pub root: PathBuf,
}
type Photo = (String, Vec<u8>);
#[derive(serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct LegacyRecord {
id: String,
serial_no: String,
uas_code: String,
#[serde(default)]
model_name: Option<String>,
#[serde(default)]
owner_name: Option<String>,
created_at: String,
}
fn import_legacy(db: &Connection, bytes: &[u8]) -> Result<()> {
let values: Vec<Value> = serde_json::from_slice(bytes)
.map_err(|e| AppError::Internal(format!("旧登记文件无效:{e}")))?;
let mut records = Vec::with_capacity(values.len());
for (index, value) in values.into_iter().enumerate() {
let validate = || -> std::result::Result<LegacyRecord, String> {
let r: LegacyRecord = serde_json::from_value(value).map_err(|e| e.to_string())?;
if !valid_id(&r.id) {
return Err("档案 ID 无效".into());
}
if !(6..=40).contains(&r.serial_no.len())
|| !r
.serial_no
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'-')
{
return Err("serialNo 须为 6–40 位字母、数字或连字符".into());
}
if r.uas_code.len() != 11
|| !r.uas_code.starts_with("FPV")
|| !r.uas_code[3..].bytes().all(|b| b.is_ascii_digit())
{
return Err("uasCode 须为 FPV 加 8 位数字".into());
}
limit(
r.model_name.as_deref().unwrap_or(""),
60,
"机型不能超过 60 字符",
)
.map_err(|e| e.to_string())?;
limit(
r.owner_name.as_deref().unwrap_or(""),
40,
"登记人不能超过 40 字符",
)
.map_err(|e| e.to_string())?;
chrono::DateTime::parse_from_rfc3339(&r.created_at)
.map_err(|_| "createdAt 须为有效的带时区 ISO 时间".to_owned())?;
Ok(r)
};
records.push(validate().map_err(|e| {
AppError::Internal(format!(
"旧登记文件第 {} 条记录无效:{e};本次导入已全部回滚",
index + 1
))
})?);
}
for (index, r) in records.into_iter().enumerate() {
db.execute("INSERT INTO records(id,serial_no,uas_code,model_name,owner_name,created_at) VALUES(?,?,?,?,?,?)", params![r.id,r.serial_no,r.uas_code,r.model_name.unwrap_or_default(),r.owner_name.unwrap_or_default(),r.created_at])
.map_err(|e| AppError::Internal(format!("旧登记文件第 {} 条记录导入失败:{e};本次导入已全部回滚", index + 1)))?;
}
Ok(())
}
const COLUMNS: &str = "SELECT r.id,serial_no,uas_code,model_name,owner_name,created_at,EXISTS(SELECT 1 FROM photos WHERE record_id=r.id AND slot=1),EXISTS(SELECT 1 FROM photos WHERE record_id=r.id AND slot=2) FROM records r";
const SEARCH: &str = "(?1='' OR instr(lower(serial_no),lower(?1))>0 OR instr(lower(uas_code),lower(?1))>0 OR instr(lower(model_name),lower(?1))>0 OR instr(lower(owner_name),lower(?1))>0 OR instr(lower(created_at),lower(?1))>0)";
const ORDER: &str = " ORDER BY created_at DESC,id DESC";
pub fn valid_id(id: &str) -> bool {
id.len() == 36
&& id
.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}
fn text(v: &Value, key: &str) -> String {
match &v[key] {
Value::Null | Value::Bool(false) => String::new(),
Value::String(s) => s.trim().to_owned(),
Value::Number(n) if n.as_f64() == Some(0.0) => String::new(),
x => x.to_string().trim().to_owned(),
}
}
fn limit(s: &str, n: usize, message: &str) -> Result<()> {
if s.encode_utf16().count() > n {
Err(AppError::Validation(message.into()))
} else {
Ok(())
}
}
fn record(r: &rusqlite::Row<'_>) -> rusqlite::Result<Value> {
let id: String = r.get(0)?;
let p1 = r.get::<_, bool>(6)?;
let p2 = r.get::<_, bool>(7)?;
Ok(
json!({"id":id,"serialNo":r.get::<_,String>(1)?,"uasCode":r.get::<_,String>(2)?,"modelName":r.get::<_,String>(3)?,"ownerName":r.get::<_,String>(4)?,"createdAt":r.get::<_,String>(5)?,"photo1":p1,"photo2":p2,"source":"local-fpv-registry","qrUrl":format!("http://127.0.0.1:8787/r/{id}"),"archiveUrl":format!("/r/{id}"),"downloadArchiveUrl":format!("/api/records/{id}/archive"),"photo1Url":p1.then(||format!("/api/records/{id}/photos/1")),"photo2Url":p2.then(||format!("/api/records/{id}/photos/2"))}),
)
}
// This intent is committed together with the record mutation; edits cannot cancel a deletion intent.
pub fn mark_pending(db: &Connection, retain: bool) -> Result<()> {
let old: Option<String> = db
.query_row(
"SELECT value FROM registry_meta WHERE key='archive_pending'",
[],
|r| r.get(0),
)
.optional()?;
let retain = retain && old.as_deref() != Some("delete");
db.execute("INSERT INTO registry_meta(key,value) VALUES('archive_pending',?1) ON CONFLICT(key) DO UPDATE SET value=excluded.value",[if retain{"retain"}else{"delete"}])?;
Ok(())
}
fn apply_photos(db: &Connection, id: &str, photos: [Option<Photo>; 2]) -> Result<()> {
for (i, p) in photos.into_iter().enumerate() {
if let Some((mime, data)) = p {
db.execute("INSERT INTO photos VALUES(?,?,?,?) ON CONFLICT(record_id,slot) DO UPDATE SET mime_type=excluded.mime_type,image=excluded.image",params![id,(i+1) as u8,mime,data])?;
}
}
Ok(())
}
impl Store {
pub fn open(root: PathBuf) -> Result<Self> {
std::fs::create_dir_all(root.join("registry/data"))?;
let mut db = Connection::open(root.join("registry/data/registry.sqlite"))?;
db.busy_timeout(std::time::Duration::from_secs(5))?;
db.execute_batch("PRAGMA foreign_keys=ON; CREATE TABLE IF NOT EXISTS records(id TEXT PRIMARY KEY,serial_no TEXT NOT NULL UNIQUE,uas_code TEXT NOT NULL UNIQUE,model_name TEXT NOT NULL DEFAULT '',owner_name TEXT NOT NULL DEFAULT '',created_at TEXT NOT NULL); CREATE TABLE IF NOT EXISTS photos(record_id TEXT NOT NULL REFERENCES records(id) ON DELETE CASCADE,slot INTEGER NOT NULL CHECK(slot IN (1,2)),mime_type TEXT NOT NULL,image BLOB NOT NULL,PRIMARY KEY(record_id,slot)); CREATE TABLE IF NOT EXISTS registry_meta(key TEXT PRIMARY KEY,value TEXT NOT NULL);")?;
let tx = db.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
let done: bool = tx.query_row(
"SELECT EXISTS(SELECT 1 FROM registry_meta WHERE key='legacy_import_done')",
[],
|r| r.get(0),
)?;
if !done {
let total: i64 = tx.query_row("SELECT COUNT(*) FROM records", [], |r| r.get(0))?;
let old = root.join("registry/data/records.json");
if total == 0 && old.exists() {
import_legacy(&tx, &std::fs::read(old)?)?;
mark_pending(&tx, true)?;
}
tx.execute(
"INSERT INTO registry_meta VALUES('legacy_import_done','1')",
[],
)?;
}
let sidecar = root.join("registry/data/archive-pending.json");
if sidecar.exists() {
let value: Value = serde_json::from_slice(&std::fs::read(&sidecar)?)
.map_err(|e| AppError::Internal(format!("旧同步状态无效:{e}")))?;
mark_pending(
&tx,
value["retainPrevious"]
.as_bool()
.ok_or("旧同步状态格式无效")?,
)?;
}
tx.commit()?;
if sidecar.exists() {
std::fs::remove_file(sidecar)?;
}
Ok(Self { db, root })
}
pub fn list(&self, q: &str) -> Result<Vec<Value>> {
limit(q, 60, "搜索关键词不能超过 60 字")?;
let mut stmt = self
.db
.prepare(&format!("{COLUMNS} WHERE {SEARCH}{ORDER}"))?;
Ok(stmt
.query_map([q], record)?
.collect::<rusqlite::Result<Vec<_>>>()?)
}
pub fn page(&self, q: &str, page: usize, size: usize) -> Result<Value> {
limit(q, 60, "搜索关键词不能超过 60 字")?;
if page == 0 || size == 0 || size > 100 {
return Err("分页参数无效".into());
}
let offset = (page - 1)
.checked_mul(size)
.and_then(|n| i64::try_from(n).ok())
.ok_or("分页参数无效")?;
let total: i64 = self.db.query_row(
&format!("SELECT COUNT(*) FROM records WHERE {SEARCH}"),
[q],
|r| r.get(0),
)?;
let mut stmt = self.db.prepare(&format!(
"{COLUMNS} WHERE {SEARCH}{ORDER} LIMIT ?2 OFFSET ?3"
))?;
let records = stmt
.query_map(params![q, size as i64, offset], record)?
.collect::<rusqlite::Result<Vec<_>>>()?;
Ok(
json!({"records":records.into_iter().map(crate::archive::public).collect::<Vec<_>>(),"page":page,"pageSize":size,"total":total,"totalPages":(total as usize).div_ceil(size)}),
)
}
pub fn get(&self, id: &str) -> Result<Value> {
self.db
.query_row(&format!("{COLUMNS} WHERE r.id=?1"), [id], record)
.optional()?
.ok_or(AppError::NotFound("档案不存在"))
}
pub fn selected(&self, ids: &[String]) -> Result<Vec<Value>> {
let mut rows = Vec::with_capacity(ids.len());
for id in ids {
rows.push(self.get(id)?);
}
rows.sort_by(|a, b| {
b["createdAt"]
.as_str()
.cmp(&a["createdAt"].as_str())
.then_with(|| b["id"].as_str().cmp(&a["id"].as_str()))
});
Ok(rows)
}
pub fn photo(&self, id: &str, slot: u8) -> Result<Option<Photo>> {
Ok(self
.db
.query_row(
"SELECT mime_type,image FROM photos WHERE record_id=? AND slot=?",
params![id, slot],
|r| Ok((r.get(0)?, r.get(1)?)),
)
.optional()?)
}
pub fn pending(&self) -> Result<Option<bool>> {
let v: Option<String> = self
.db
.query_row(
"SELECT value FROM registry_meta WHERE key='archive_pending'",
[],
|r| r.get(0),
)
.optional()?;
match v.as_deref() {
None => Ok(None),
Some("retain") => Ok(Some(true)),
Some("delete") => Ok(Some(false)),
_ => Err(AppError::Internal("同步状态损坏".into())),
}
}
pub fn mark_pending(&self, retain: bool) -> Result<()> {
mark_pending(&self.db, retain)
}
pub fn register(&mut self, input: Value) -> Result<Value> {
if !input.is_object() {
return Err("登记内容格式无效".into());
}
let sn = text(&input, "serialNo");
let model = text(&input, "modelName");
let owner = text(&input, "ownerName");
let requested = text(&input, "uasCode").to_uppercase();
if !(6..=40).contains(&sn.len())
|| !sn.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
{
return Err("SN 须为 6–40 位字母、数字或连字符".into());
}
limit(&model, 60, "机型不能超过 60 字符")?;
limit(&owner, 40, "登记人不能超过 40 字符")?;
if !requested.is_empty()
&& !(requested.len() == 11
&& requested.starts_with("FPV")
&& requested[3..].bytes().all(|b| b.is_ascii_digit()))
{
return Err("FPV 编号须为 FPV 加 8 位数字".into());
}
let photos = [
decode_photo(&input["photo1"])?,
decode_photo(&input["photo2"])?,
];
let tx = self
.db
.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
let existing: Option<(String, String)> = tx
.query_row(
"SELECT id,uas_code FROM records WHERE serial_no=?",
[&sn],
|r| Ok((r.get(0)?, r.get(1)?)),
)
.optional()?;
let was_existing = existing.is_some();
let id = if let Some((id, code)) = existing {
if !requested.is_empty() && requested != code {
return Err("该 SN 已登记其他 FPV 编号".into());
}
tx.execute("UPDATE records SET model_name=CASE WHEN ?1='' THEN model_name ELSE ?1 END,owner_name=CASE WHEN ?2='' THEN owner_name ELSE ?2 END WHERE id=?3",params![model,owner,id])?;
id
} else {
let mut code = requested.clone();
loop {
if code.is_empty() {
code = format!("FPV{:08}", rand::rng().random_range(0..100_000_000u32));
}
let used: bool = tx.query_row(
"SELECT EXISTS(SELECT 1 FROM records WHERE uas_code=?)",
[&code],
|r| r.get(0),
)?;
if !used {
break;
}
if !requested.is_empty() {
return Err("该 FPV 编号已登记其他 SN".into());
}
code.clear();
}
let id = (0..18)
.map(|_| format!("{:02x}", rand::random::<u8>()))
.collect::<String>();
tx.execute("INSERT INTO records(id,serial_no,uas_code,model_name,owner_name,created_at) VALUES(?,?,?,?,?,?)",params![id,sn,code,model,owner,chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis,true)])?;
id
};
apply_photos(&tx, &id, photos)?;
mark_pending(&tx, true)?;
let r = tx.query_row(&format!("{COLUMNS} WHERE r.id=?1"), [&id], record)?;
tx.commit()?;
Ok(json!({"record":r,"existing":was_existing}))
}
pub fn patch(&mut self, id: &str, v: Value) -> Result<Value> {
let obj = v.as_object().ok_or("登记内容格式无效")?;
if obj.is_empty()
|| obj
.keys()
.any(|k| !matches!(k.as_str(), "modelName" | "ownerName" | "photo1" | "photo2"))
{
return Err("登记修改仅支持机型、登记人与照片".into());
}
let mut strings = [None, None];
for (i, (key, max)) in [("modelName", 60), ("ownerName", 40)]
.into_iter()
.enumerate()
{
if let Some(value) = obj.get(key) {
let s = value.as_str().ok_or("登记字段须为字符串")?.trim();
limit(s, max, "登记字段过长")?;
strings[i] = Some(s.to_owned());
}
}
let mut photos = [None, None];
let mut deletes = [false, false];
for (i, key) in ["photo1", "photo2"].into_iter().enumerate() {
if let Some(v) = obj.get(key) {
if v.is_null() {
deletes[i] = true
} else {
photos[i] = Some(decode_photo(v)?.ok_or("照片替换内容不能为空")?);
}
}
}
let tx = self
.db
.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
let found: bool = tx.query_row(
"SELECT EXISTS(SELECT 1 FROM records WHERE id=?)",
[id],
|r| r.get(0),
)?;
if !found {
return Err(AppError::NotFound("档案不存在"));
}
tx.execute("UPDATE records SET model_name=COALESCE(?1,model_name),owner_name=COALESCE(?2,owner_name) WHERE id=?3",params![strings[0],strings[1],id])?;
for (i, delete) in deletes.iter().enumerate() {
if *delete {
tx.execute(
"DELETE FROM photos WHERE record_id=? AND slot=?",
params![id, (i + 1) as u8],
)?;
}
}
apply_photos(&tx, id, photos)?;
mark_pending(&tx, !deletes.iter().any(|d| *d))?;
let r = tx.query_row(&format!("{COLUMNS} WHERE r.id=?1"), [id], record)?;
tx.commit()?;
Ok(json!({"record":r}))
}
pub fn delete(&mut self, id: &str, slot: Option<u8>) -> Result<Value> {
if slot.is_some_and(|n| n != 1 && n != 2) {
return Err("照片槽位无效".into());
}
let tx = self
.db
.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
let found: bool = tx.query_row(
"SELECT EXISTS(SELECT 1 FROM records WHERE id=?)",
[id],
|r| r.get(0),
)?;
if !found {
return Err(AppError::NotFound("档案不存在"));
}
if let Some(slot) = slot {
tx.execute(
"DELETE FROM photos WHERE record_id=? AND slot=?",
params![id, slot],
)?;
} else {
tx.execute("DELETE FROM records WHERE id=?", [id])?;
}
mark_pending(&tx, false)?;
tx.commit()?;
Ok(json!({"deleted":true}))
}
}
fn decode_photo(v: &Value) -> Result<Option<Photo>> {
if v.is_null() || v.as_str() == Some("") {
return Ok(None);
}
let s = v.as_str().ok_or("照片格式无效")?;
let re = regex::Regex::new(r"^data:image/(jpeg|png|webp);base64,([A-Za-z0-9+/]+={0,2})$")
.expect("constant photo regex");
let m = re.captures(s).ok_or("照片仅支持 JPG、PNG 或 WebP")?;
let data = STANDARD.decode(&m[2]).map_err(|_| "照片 Base64 格式无效")?;
if data.is_empty() || data.len() > 5 * 1024 * 1024 {
return Err("照片须小于 5 MB".into());
}
let valid = match &m[1] {
"jpeg" => data.starts_with(&[255, 216, 255]),
"png" => data.starts_with(b"\x89PNG\r\n\x1a\n"),
_ => data.starts_with(b"RIFF") && data.get(8..12) == Some(b"WEBP"),
};
if !valid {
return Err("照片内容与格式不符".into());
}
Ok(Some((format!("image/{}", &m[1]), data)))
}
+385
View File
@@ -0,0 +1,385 @@
use crate::{archive, store::Store};
use serde_json::json;
#[test]
fn legacy_invalid_rows_fail_without_marking_import_done() {
let first = json!({"id":"111111111111111111111111111111111111","serialNo":"IMPORT-001","uasCode":"FPV00000001","createdAt":"2020-01-01T00:00:00.000Z"});
let valid_second = json!({"id":"222222222222222222222222222222222222","serialNo":"IMPORT-002","uasCode":"FPV00000002","createdAt":"2020-01-01T00:00:00.000Z"});
for (key, value) in [
("createdAt", serde_json::Value::Null),
("createdAt", json!("invalid")),
("serialNo", json!(12)),
("uasCode", json!("FPV1")),
("modelName", json!(false)),
] {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join("registry/data")).unwrap();
let file = tmp.path().join("registry/data/records.json");
let mut bad = valid_second.clone();
if value.is_null() {
bad.as_object_mut().unwrap().remove(key);
} else {
bad[key] = value;
}
let bytes = json!([first, bad]).to_string();
std::fs::write(&file, &bytes).unwrap();
let error = Store::open(tmp.path().to_owned())
.err()
.expect("bad import must fail")
.to_string();
assert!(error.contains("第 2 条"), "{error}");
assert_eq!(std::fs::read_to_string(&file).unwrap(), bytes);
let db =
rusqlite::Connection::open(tmp.path().join("registry/data/registry.sqlite")).unwrap();
assert_eq!(
db.query_row("SELECT COUNT(*) FROM records", [], |r| r.get::<_, i64>(0))
.unwrap(),
0
);
assert_eq!(
db.query_row("SELECT COUNT(*) FROM registry_meta", [], |r| r
.get::<_, i64>(0))
.unwrap(),
0
);
drop(db);
std::fs::write(&file, json!([first, valid_second]).to_string()).unwrap();
assert_eq!(
Store::open(tmp.path().to_owned())
.unwrap()
.list("")
.unwrap()
.len(),
2
);
}
}
#[test]
fn legacy_unique_conflicts_roll_back_all_rows() {
let first = json!({"id":"111111111111111111111111111111111111","serialNo":"IMPORT-001","uasCode":"FPV00000001","createdAt":"2020-01-01T00:00:00.000Z"});
for key in ["id", "serialNo", "uasCode"] {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join("registry/data")).unwrap();
let mut second = json!({"id":"222222222222222222222222222222222222","serialNo":"IMPORT-002","uasCode":"FPV00000002","createdAt":"2020-01-01T00:00:00.000Z"});
second[key] = first[key].clone();
std::fs::write(
tmp.path().join("registry/data/records.json"),
json!([first, second]).to_string(),
)
.unwrap();
let error = Store::open(tmp.path().to_owned())
.err()
.expect("conflict must fail")
.to_string();
assert!(
error.contains("第 2 条") && error.contains("UNIQUE"),
"{error}"
);
let db =
rusqlite::Connection::open(tmp.path().join("registry/data/registry.sqlite")).unwrap();
assert_eq!(
db.query_row("SELECT COUNT(*) FROM records", [], |r| r.get::<_, i64>(0))
.unwrap(),
0
);
assert_eq!(
db.query_row("SELECT COUNT(*) FROM registry_meta", [], |r| r
.get::<_, i64>(0))
.unwrap(),
0
);
}
}
#[test]
fn registration_edit_photos_and_exports() {
let tmp = tempfile::tempdir().unwrap();
let mut s = Store::open(tmp.path().to_owned()).unwrap();
let photo = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aocsAAAAASUVORK5CYII=";
let r=s.register(json!({"serialNo":"TEST-001","modelName":"{{ownerName}}<机型>","ownerName":"原登记人","photo1":photo})).unwrap();
let id = r["record"]["id"].as_str().unwrap();
assert_eq!(id.len(), 36);
let original = s.photo(id, 1).unwrap().unwrap().1;
let again = s
.register(json!({"serialNo":"TEST-001","modelName":""}))
.unwrap();
assert_eq!(again["existing"], true);
assert_eq!(again["record"]["id"], id);
assert!(
s.register(json!({"serialNo":"TEST-002","uasCode":r["record"]["uasCode"]}))
.is_err()
);
let html = archive::card(&s, &s.get(id).unwrap(), true).unwrap();
assert!(html.contains("{{ownerName}}&lt;机型&gt;"));
assert!(html.contains("data:image/png;base64,"));
assert!(!html.contains("${"));
let records = s.list("").unwrap();
for excel in [false, true] {
let bytes = archive::export(&s, records.clone(), excel).unwrap();
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
assert!(!zip.is_empty());
if excel {
let mut sheet = String::new();
use std::io::Read;
zip.by_name("xl/worksheets/sheet1.xml")
.unwrap()
.read_to_string(&mut sheet)
.unwrap();
assert!(sheet.contains("worksheet"));
} else {
assert!(zip.by_name("档案库/records.json").is_ok());
}
}
s.patch(id, json!({"modelName":""})).unwrap();
assert_eq!(s.get(id).unwrap()["modelName"], "");
assert_eq!(s.get(id).unwrap()["ownerName"], "原登记人");
assert!(s.patch(id, json!({"serialNo":"OTHER"})).is_err());
assert!(s.patch(id, json!({"ownerName":null})).is_err());
archive::sync(&mut s).unwrap();
assert_eq!(s.photo(id, 1).unwrap().unwrap().1, original);
s.delete(id, Some(1)).unwrap();
archive::sync(&mut s).unwrap();
assert!(s.photo(id, 1).unwrap().is_none());
assert!(
!tmp.path()
.join("档案库/登记数据库.previous.sqlite")
.exists()
);
s.delete(id, None).unwrap();
archive::sync(&mut s).unwrap();
assert!(s.list("").unwrap().is_empty());
}
#[test]
fn archive_failure_recovers_and_deletion_marker_survives() {
let tmp = tempfile::tempdir().unwrap();
let mut s = Store::open(tmp.path().to_owned()).unwrap();
std::fs::write(tmp.path().join("档案库"), "blocked").unwrap();
let r = s.register(json!({"serialNo":"TEST-003"})).unwrap();
let v = archive::finish(&mut s, r);
assert_eq!(v["archiveStatus"], "pending");
assert_eq!(s.list("").unwrap().len(), 1);
s.mark_pending(false).unwrap();
s.mark_pending(true).unwrap();
assert_eq!(s.pending().unwrap(), Some(false));
std::fs::remove_file(tmp.path().join("档案库")).unwrap();
archive::sync(&mut s).unwrap();
assert_eq!(s.pending().unwrap(), None);
let db = rusqlite::Connection::open(tmp.path().join("档案库/登记数据库.sqlite")).unwrap();
assert_eq!(
db.query_row("SELECT COUNT(*) FROM records", [], |r| r.get::<_, i64>(0))
.unwrap(),
1
);
}
#[test]
fn legacy_import_and_validation() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join("registry/data")).unwrap();
let id = "012345678901234567890123456789012345";
std::fs::write(tmp.path().join("registry/data/records.json"),json!([{"id":id,"serialNo":"OLD-001","uasCode":"FPV00000001","createdAt":"2020-01-01T00:00:00.000Z"}]).to_string()).unwrap();
let mut s = Store::open(tmp.path().to_owned()).unwrap();
assert_eq!(s.get(id).unwrap()["serialNo"], "OLD-001");
for v in [
json!({"serialNo":"x"}),
json!({"serialNo":"TEST-004","uasCode":"FPV123"}),
json!({"serialNo":"TEST-004","photo1":"data:image/png;base64,YQ=="}),
json!({"serialNo":"TEST-004","ownerName":"😀".repeat(21)}),
] {
assert!(s.register(v).is_err());
}
s.delete(id, None).unwrap();
drop(s);
assert!(
Store::open(tmp.path().to_owned())
.unwrap()
.list("")
.unwrap()
.is_empty()
);
}
#[test]
fn atomic_edit_rolls_back_and_never_recreates() {
let tmp = tempfile::tempdir().unwrap();
let mut s = Store::open(tmp.path().to_owned()).unwrap();
let r = s
.register(json!({"serialNo":"TEST-ATOMIC","ownerName":"original"}))
.unwrap();
let id = r["record"]["id"].as_str().unwrap();
archive::sync(&mut s).unwrap();
assert_eq!(s.pending().unwrap(), None);
assert!(
s.register(json!({"serialNo":"TEST-ATOMIC","uasCode":"FPV99999999"}))
.is_err()
);
assert_eq!(s.pending().unwrap(), None);
// A database failure after the text UPDATE must roll back text and sync intent too.
s.db.execute_batch("CREATE TRIGGER fail_photo BEFORE INSERT ON photos BEGIN SELECT RAISE(ABORT,'injected photo failure'); END;").unwrap();
let photo = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aocsAAAAASUVORK5CYII=";
assert!(matches!(
s.patch(id, json!({"ownerName":"changed","photo1":photo})),
Err(crate::error::AppError::Internal(_))
));
assert_eq!(s.get(id).unwrap()["ownerName"], "original");
assert_eq!(s.pending().unwrap(), None);
s.db.execute_batch("DROP TRIGGER fail_photo").unwrap();
s.delete(id, None).unwrap();
assert!(matches!(
s.patch(id, json!({"ownerName":"resurrect","photo1":photo})),
Err(crate::error::AppError::NotFound(_))
));
assert!(s.list("").unwrap().is_empty());
}
#[test]
fn sql_pagination_and_sidecar_migration() {
let tmp = tempfile::tempdir().unwrap();
let mut s = Store::open(tmp.path().to_owned()).unwrap();
for i in 0..25 {
s.register(json!({"serialNo":format!("PAGING-{i:03}")}))
.unwrap();
}
s.db.execute(
"UPDATE records SET created_at='2020-01-01T00:00:00.000Z'",
[],
)
.unwrap();
let all = s.list("").unwrap();
let page = s.page("", 2, 20).unwrap();
assert_eq!(page["total"], 25);
assert_eq!(page["records"].as_array().unwrap().len(), 5);
assert_eq!(page["records"][0]["id"], all[20]["id"]);
assert!(s.page("", 0, 20).is_err());
assert!(s.page("", 1, 101).is_err());
assert_eq!(s.page("no-match", 1, 20).unwrap()["total"], 0);
drop(s);
std::fs::write(
tmp.path().join("registry/data/archive-pending.json"),
r#"{"retainPrevious":false}"#,
)
.unwrap();
let s = Store::open(tmp.path().to_owned()).unwrap();
assert_eq!(s.pending().unwrap(), Some(false));
assert!(
!tmp.path()
.join("registry/data/archive-pending.json")
.exists()
);
}
#[tokio::test]
async fn http_status_codes_and_error_redaction() {
use axum::{body::Body, http::Request};
use tower::ServiceExt;
let tmp = tempfile::tempdir().unwrap();
let s = Store::open(tmp.path().to_owned()).unwrap();
s.db.execute_batch("DROP TABLE photos").unwrap();
let (tx, rx) = std::sync::mpsc::channel::<crate::Job>();
std::thread::spawn(move || {
let mut s = s;
for job in rx {
job(&mut s);
}
});
let app = crate::http::router(crate::Worker(tx));
let response = app
.clone()
.oneshot(
Request::builder()
.uri("/api/records")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), 500);
let body = axum::body::to_bytes(response.into_body(), 4096)
.await
.unwrap();
let body = String::from_utf8(body.to_vec()).unwrap();
assert!(!body.contains("photos"));
assert!(!body.contains(&tmp.path().to_string_lossy().into_owned()));
let response = app
.clone()
.oneshot(
Request::builder()
.uri("/api/records?page=0")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), 400);
let response = app
.clone()
.oneshot(
Request::builder()
.uri("/api/records")
.header("origin", "https://example.com")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), 403);
let response = app
.oneshot(
Request::builder()
.uri("/missing")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), 404);
}
#[cfg(windows)]
#[test]
fn locked_backup_retains_delete_intent_until_retry() {
use std::os::windows::fs::OpenOptionsExt;
let tmp = tempfile::tempdir().unwrap();
let mut s = Store::open(tmp.path().to_owned()).unwrap();
let first = s.register(json!({"serialNo":"BACKUP-001"})).unwrap();
archive::sync(&mut s).unwrap();
s.register(json!({"serialNo":"BACKUP-002"})).unwrap();
archive::sync(&mut s).unwrap();
assert!(
tmp.path()
.join("档案库/登记数据库.previous.sqlite")
.exists()
);
let locked = std::fs::OpenOptions::new()
.read(true)
.share_mode(0)
.open(tmp.path().join("档案库/登记数据库.sqlite"))
.unwrap();
s.delete(first["record"]["id"].as_str().unwrap(), None)
.unwrap();
assert!(archive::sync(&mut s).is_err());
assert_eq!(s.pending().unwrap(), Some(false));
drop(locked);
archive::sync(&mut s).unwrap();
assert_eq!(s.pending().unwrap(), None);
assert!(
!tmp.path()
.join("档案库/登记数据库.previous.sqlite")
.exists()
);
let backup = Store::open({
let root = tmp.path().join("restored");
std::fs::create_dir_all(root.join("registry/data")).unwrap();
std::fs::copy(
tmp.path().join("档案库/登记数据库.sqlite"),
root.join("registry/data/registry.sqlite"),
)
.unwrap();
root
})
.unwrap();
assert_eq!(backup.list("").unwrap().len(), 1);
assert_eq!(backup.pending().unwrap(), Some(false));
}
+17
View File
@@ -0,0 +1,17 @@
@echo off
cd /d "%~dp0"
if exist "%~dp0runtime\node.exe" (
"%~dp0runtime\node.exe" "%~dp0registry\server.js"
) else (
where node >nul 2>&1
if errorlevel 1 (
echo Node.js 24 was not found.
echo Install Node.js 24 or copy the original runtime\node.exe into this folder.
pause
exit /b 1
)
node "%~dp0registry\server.js"
)
echo.
echo FPV-RID registration server has stopped.
pause
+10
View File
@@ -0,0 +1,10 @@
@echo off
cd /d "%~dp0"
if exist "%~dp0fpv-rid-registry.exe" (
"%~dp0fpv-rid-registry.exe"
) else if exist "D:\Rust_Contact\util\target\Rid_Drone_Receivev\release\fpv-rid-registry.exe" (
"D:\Rust_Contact\util\target\Rid_Drone_Receivev\release\fpv-rid-registry.exe" --data-root "%~dp0."
) else (
echo Build first: cargo build --release --locked
)
pause
+1 -16
View File
@@ -1,17 +1,2 @@
@echo off @echo off
cd /d "%~dp0" call "%~dp0启动Rust版.cmd"
if exist "%~dp0runtime\node.exe" (
"%~dp0runtime\node.exe" "%~dp0registry\server.js"
) else (
where node >nul 2>&1
if errorlevel 1 (
echo Node.js 24 was not found.
echo Install Node.js 24 or copy the original runtime\node.exe into this folder.
pause
exit /b 1
)
node "%~dp0registry\server.js"
)
echo.
echo FPV-RID registration server has stopped.
pause