diff --git a/.githooks/pre-commit b/.githooks/pre-commit
new file mode 100644
index 0000000..07936db
--- /dev/null
+++ b/.githooks/pre-commit
@@ -0,0 +1,3 @@
+#!/bin/sh
+# 禁止提交服务端私有配置 / 运行期产物 / 版本记录(参考 wms 的 .githooks/pre-commit)
+node backend/scripts/deploy/git-safety-check.cjs
diff --git a/.gitignore b/.gitignore
index 332a55e..8f32af1 100644
--- a/.gitignore
+++ b/.gitignore
@@ -29,6 +29,9 @@ artifacts/
desktop/installer/out/
*.wixpdb
+# Android 设备端安装包产物(backend/android_client/build.ps1 生成)
+backend/android_client/out/
+
# 安装包分发目录(打包脚本复制到后端静态目录;只保留 .gitkeep)
backend/app/public/download/*
!backend/app/public/download/.gitkeep
@@ -41,6 +44,7 @@ logs/
logs-*/
run/
tmp/
+backend/temp/
*.log
*.pid
@@ -48,8 +52,19 @@ tmp/
.env
.env.*
!.env.example
+# 前端生产构建参数不含密钥,允许提交
+!frontend/.env.production
+# 后端生产环境变量(含密码),只保留本机副本,发布时自动上传服务器
+backend/config/env.prod.sh
config.local.js
config.local.*.js
+# 生产配置(数据库/Redis 密码)由运维放在服务器,随发布保留,不进仓库
+config.prod.js
+
+# ---------- 发布脚手架本地状态 ----------
+backend/config/deploy.config.local.cjs
+backend/versioning/*
+!backend/versioning/.gitkeep
# ---------- Egg 自动生成的类型声明(typings/ 由 egg-ts-helper 生成) ----------
typings/
@@ -58,6 +73,9 @@ typings/
.vscode/*
!.vscode/extensions.json
!.vscode/settings.json
+# AndroidStation 的 VS Code 任务(tools/android.ps1 的转发入口)需要入库
+!AndroidStation/.vscode/
+!AndroidStation/.vscode/tasks.json
.idea/
.DS_Store
Thumbs.db
diff --git a/AndroidStation/.github/copilot-instructions.md b/AndroidStation/.github/copilot-instructions.md
new file mode 100644
index 0000000..e3c3a6f
--- /dev/null
+++ b/AndroidStation/.github/copilot-instructions.md
@@ -0,0 +1,102 @@
+# AndroidStation(设备端)
+
+Android TV / 电视盒子上的**扫码设备端**。它扮演网口扫码设备,让 `desktop/` 的扫码服务
+自动发现并读取 USB 扫码枪的结果。
+
+## 角色
+
+```
+桌面端(发现 + 连接) → UDP 48899 发现 / TCP 8087 读取扫码结果 → 本机
+```
+
+- **只做设备端**:不扫描别的设备、不管理通道、不回放、没有手势登录、没有网络设置。
+- **不改 IP**:设备地址由现场网络分配;设置页只配置设备名、服务端口、发现端口和启停开关。
+- **不要搬回中控业务**:`desktop/` 才是中控/桌面端,相关逻辑不在本工程。
+
+## 关键实现
+
+| 文件 | 职责 |
+| --- | --- |
+| `App` | 进程启动时拉起 `StationService` |
+| `core/service/StationService` | 进程级单例:服务启停、扫码历史、UI 回调 |
+| `core/service/DiscoveryResponder` | UDP 发现应答 + JCMD 兼容 |
+| `core/service/ScanServer` | TCP 服务端,向桌面端推送扫码结果 |
+| `core/StationSettings` | 设备名 / TCP 端口 / UDP 端口 / 开关 |
+| `core/StationIdentity` | MAC、IP、型号、版本、Uptime |
+| `core/speech/BarcodeSpeaker` | 离线语音种子拼接 + MediaPlayer 播报 + 启动音量最大 |
+| `MainActivity` | 状态展示 + USB 扫码枪按键采集 |
+| `SettingsActivity` | 服务设置 |
+
+## 协议约定(必须与桌面端保持一致)
+
+桌面端常量在 `desktop/Services/Scan/ScanChannel.cs` 的 `ScanProtocol`:
+
+- UDP 发现端口 **48899**;广播请求 `{"Type":"EP_Tool",...}`。
+- TCP 服务端口 **8087**(桌面端参数名为 `TcpPort`)。
+- SOCK 条目名 **`packcenter`**。
+- 扫码结果按 **UTF-8 + CRLF** 一行一条推送。
+- JCMD 只需支持 `10001 / 10003 / 10005 / 10017`;`20003` 只回 `RC=0`,不要重启本机。
+- 发现回复字段见 `docs/udp-48899-protocol.md` §6;`HostName` 用 UTF-8。
+
+## 构建
+
+```powershell
+powershell -NoProfile -ExecutionPolicy Bypass -File tools\android.ps1 build
+```
+
+或:
+
+```powershell
+$env:JAVA_HOME='C:\Users\lfmingren\AppData\Local\Programs\EclipseAdoptium\jdk-17.0.20.1+1'
+.\gradlew.bat :app:assembleDebug
+```
+
+APK:`app\build\outputs\apk\debug\app-debug.apk`
+
+## 日志
+
+- 统一用 `com.gztbyc.scancenter.util.L`(静态导入 `log/i/w/e`),**不要直接写 `android.util.Log`**。
+- tag 固定 `AndroidStation`;release 包需 `adb shell setprop log.tag.AndroidStation DEBUG` 才输出。
+- 不要删 `buildFeatures { buildConfig true }`,`L` 依赖 `BuildConfig.DEBUG`。
+
+## 扫码热路径(必须保持快)
+
+设备大概率长期不接显示器,扫码链路只允许做最少的事:
+
+```
+dispatchKeyEvent → StringBuilder → commitScan → StationService.pushBarcode
+ → ScanServer 单线程 writer → 桌面端
+```
+
+- **禁止**在 `dispatchKeyEvent` / `commitScan` / `pushBarcode` 里同步刷新 UI 或写日志。
+ 界面刷新由 `MainActivity` 的低频任务兜底(5 秒一次)。
+- **禁止**在主线程写 socket。所有推送都在 `ScanServer` 的 `station-scan-write` 线程完成。
+- **禁止去重**:重复条码也必须上报;连续扫描的重复帧由桌面端判断。
+- 扫码枪没有回车/Tab 后缀时,50ms 无输入自动提交;不要再调大。
+- 条码清理用首尾字符扫描,不要用正则。
+
+## 语音播报
+
+- 设备只有 `PicoTts` 且没有中文数据,**不要用 `TextToSpeech`**;用 `tools/fetch-voice-seeds.ps1`
+ 抓下来的 `res/raw/voice_*.wav` 离线种子。
+- 种子统一为 **44.1kHz / 立体声 / 16-bit PCM**;这台 rk3288 上 `AudioTrack` 初始化会失败,
+ 播放必须走 `MediaPlayer`,且放在 `station-speech` 线程。
+- 播报内容 = 条码末尾 4 个字母/数字 + 「开始打包」;同一码 2.5 秒内不重复播报,
+ 换码立即打断上一句。**语音去重不等于上报去重**,上报仍然逐条发。
+- 启动时把媒体音量设到最大(`MODIFY_AUDIO_SETTINGS`)。不要在扫码热路径里调音量。
+
+## 代码约定
+
+- Java + XML 布局,不用 Kotlin / Compose。
+- 界面文案统一放 `res/values/strings.xml`,不硬编码。
+- 主界面以遥控器为主:可点击控件必须方向键可达,并带 `state_focused` 反馈。
+- 不要再加「跳系统设置页面」的入口(厂商把部分系统页面从 dex 删了,启动会崩)。
+- 权限只需 `INTERNET`、`RECEIVE_BOOT_COMPLETED`、`MODIFY_AUDIO_SETTINGS`;这是普通用户应用,
+ **不要**引入 Device Owner / 设备管理员 / lock task / 系统应用 / 任何需要 ADB 赋权的功能。
+- 开机自启只靠 `BootReceiver` + `RECEIVE_BOOT_COMPLETED`;新装后需手动启动一次。
+
+## 不要做
+
+- 不要恢复 `LoginActivity` / 手势 / 安全设置 / 通道管理 / 扫码回放 / 网络设置 / HTTP 条码上报。
+- 不要在本机提供改 IP、掩码、网关的写入口。
+- 不要把桌面端的 `DeviceScanner` / `ChannelConnection` / `ScanService` 逻辑复制进来。
diff --git a/AndroidStation/.gitignore b/AndroidStation/.gitignore
new file mode 100644
index 0000000..fcb9bb0
--- /dev/null
+++ b/AndroidStation/.gitignore
@@ -0,0 +1,22 @@
+*.iml
+.gradle/
+/local.properties
+
+# 本机真机调试记住的设备序列号(见 tools/android.ps1)
+.dev-adb.local.json
+/.idea/
+.DS_Store
+
+# 所有模块的构建产物。原来写的是 /build(只锚定根目录),
+# 结果 app/build 下上千个中间文件会被 git add 进来。
+build/
+
+/captures
+.externalNativeBuild
+.cxx
+local.properties
+*.log
+
+# 正式签名密钥(不入库;发布机必须自行备份)
+keystore.properties
+keystore/
diff --git a/AndroidStation/.vscode/tasks.json b/AndroidStation/.vscode/tasks.json
new file mode 100644
index 0000000..94b391c
--- /dev/null
+++ b/AndroidStation/.vscode/tasks.json
@@ -0,0 +1,137 @@
+{
+ "version": "2.0.0",
+ "tasks": [
+ {
+ "label": "Android: build",
+ "detail": "构建 debug APK(tools/android.ps1 build)",
+ "type": "shell",
+ "command": "powershell",
+ "args": [
+ "-NoProfile",
+ "-ExecutionPolicy",
+ "Bypass",
+ "-File",
+ "tools\\android.ps1",
+ "build"
+ ],
+ "options": {
+ "cwd": "${workspaceFolder}"
+ },
+ "problemMatcher": [],
+ "group": {
+ "kind": "build",
+ "isDefault": true
+ }
+ },
+ {
+ "label": "Android: install",
+ "detail": "构建 + 安装到设备",
+ "type": "shell",
+ "command": "powershell",
+ "args": [
+ "-NoProfile",
+ "-ExecutionPolicy",
+ "Bypass",
+ "-File",
+ "tools\\android.ps1",
+ "install"
+ ],
+ "options": {
+ "cwd": "${workspaceFolder}"
+ },
+ "problemMatcher": []
+ },
+ {
+ "label": "Android: run",
+ "detail": "构建 + 安装 + 启动",
+ "type": "shell",
+ "command": "powershell",
+ "args": [
+ "-NoProfile",
+ "-ExecutionPolicy",
+ "Bypass",
+ "-File",
+ "tools\\android.ps1",
+ "run"
+ ],
+ "options": {
+ "cwd": "${workspaceFolder}"
+ },
+ "problemMatcher": []
+ },
+ {
+ "label": "Android: dev",
+ "detail": "构建 + 安装 + 启动 + 跟随日志(日常开发用)",
+ "type": "shell",
+ "command": "powershell",
+ "args": [
+ "-NoProfile",
+ "-ExecutionPolicy",
+ "Bypass",
+ "-File",
+ "tools\\android.ps1",
+ "dev"
+ ],
+ "options": {
+ "cwd": "${workspaceFolder}"
+ },
+ "problemMatcher": [],
+ "isBackground": true
+ },
+ {
+ "label": "Android: logcat",
+ "detail": "只跟随日志,不构建",
+ "type": "shell",
+ "command": "powershell",
+ "args": [
+ "-NoProfile",
+ "-ExecutionPolicy",
+ "Bypass",
+ "-File",
+ "tools\\android.ps1",
+ "logs"
+ ],
+ "options": {
+ "cwd": "${workspaceFolder}"
+ },
+ "problemMatcher": [],
+ "isBackground": true
+ },
+ {
+ "label": "Android: devices",
+ "detail": "列出已连接设备",
+ "type": "shell",
+ "command": "powershell",
+ "args": [
+ "-NoProfile",
+ "-ExecutionPolicy",
+ "Bypass",
+ "-File",
+ "tools\\android.ps1",
+ "devices"
+ ],
+ "options": {
+ "cwd": "${workspaceFolder}"
+ },
+ "problemMatcher": []
+ },
+ {
+ "label": "Android: clean",
+ "detail": "清理构建产物",
+ "type": "shell",
+ "command": "powershell",
+ "args": [
+ "-NoProfile",
+ "-ExecutionPolicy",
+ "Bypass",
+ "-File",
+ "tools\\android.ps1",
+ "clean"
+ ],
+ "options": {
+ "cwd": "${workspaceFolder}"
+ },
+ "problemMatcher": []
+ }
+ ]
+}
\ No newline at end of file
diff --git a/AndroidStation/AndroidStation.code-workspace b/AndroidStation/AndroidStation.code-workspace
new file mode 100644
index 0000000..876a149
--- /dev/null
+++ b/AndroidStation/AndroidStation.code-workspace
@@ -0,0 +1,8 @@
+{
+ "folders": [
+ {
+ "path": "."
+ }
+ ],
+ "settings": {}
+}
\ No newline at end of file
diff --git a/AndroidStation/README.md b/AndroidStation/README.md
new file mode 100644
index 0000000..9081aae
--- /dev/null
+++ b/AndroidStation/README.md
@@ -0,0 +1,169 @@
+# AndroidStation(设备端)
+
+面向 Android TV / 电视盒子的**扫码设备端**:把 USB 扫码枪的结果通过局域网推给桌面端
+(`desktop/` 的扫码服务),并且在 UDP 48899 上扮演网口扫码设备,让桌面端自动发现。
+
+原「扫描中心(AndroidScanCenter)」的中控业务已整体删除:不再扫描别的设备、不再管理通道、
+不再有手势登录 / 网络设置 / 条码 HTTP 上报。
+
+## 技术栈
+
+- 语言 / UI:**Java + XML 布局**(不使用 Kotlin、不使用 Compose)
+- 包名:`com.gztbyc.scancenter`(沿用原工程,便于现场覆盖安装)
+- minSdk 21 / targetSdk 28 / compileSdk 35
+- Gradle 8.11.1 + AGP 8.7.3,JDK 17
+- 依赖:仅 `androidx.appcompat`(纯 Java,无 native 库 → 与 CPU 架构无关)
+
+## 工作方式
+
+```
+桌面端(desktop/Services/Scan) AndroidStation
+ │ UDP 48899 广播 {"Type":"EP_Tool",...} → DiscoveryResponder
+ │ ← 自己的 {"MAC","HostName","Type",...} (同一个 socket 回复)
+ │
+ │ TCP 8087 主动连接 → ScanServer(服务端)
+ │ ← 扫码结果(UTF-8 + CRLF) USB 扫码枪(键盘 HID)
+```
+
+- **允许被发现**:`DiscoveryResponder` 绑定 UDP 48899,收到发现广播就按设备固件的字段回复
+ (协议见 [`docs/udp-48899-protocol.md`](docs/udp-48899-protocol.md))。
+- **扫码上报**:`ScanServer` 监听 TCP 8087,桌面端连上后,主界面收到的每一条扫码结果
+ 都会按行推送过去。桌面端下发的扫码枪串口设置指令会被读取并丢弃(本机是 USB HID)。
+- **兼容桌面端添加通道**:响应 JCMD `10001 / 10003 / 10005 / 10017`,报出一条
+ `packcenter / TCP-SERVER / 8087` 的 SOCK 条目;桌面端写 `SYS.HostName` 会更新设备名,
+ 写 `SOCK.LocalPort` 会改本地服务端口。`20003` 只确认,不重启本机。
+- **不改 IP**:网络参数只读上报,设置页没有改 IP / 掩码 / 网关的入口。
+
+## 主界面
+
+- 设备名称 / MAC / IP / 型号版本 / 服务与发现状态 / 累计扫码。
+- 最近 8 条扫码记录(**每 5 秒才刷新一次**,不参与扫码热路径)。
+- USB 扫码枪是键盘设备:在 Activity 层统一收键,连续可打印字符攒成一条条码,
+ 回车/Tab 立即提交;没有后缀时停手 **50ms** 自动提交。
+- 底部「服务设置」「清空记录」两个按钮可用遥控器操作。
+- `FLAG_KEEP_SCREEN_ON` 保证长期不接显示器时 Activity 仍保持前台、服务不被挂起。
+
+### 扫码性能约定(重要)
+
+设备长期不接显示器,扫码路径必须尽量短:
+
+```
+按键 → 追加缓冲 → 提交 → StationService 入队 → 后台写线程 → 桌面端
+```
+
+- **按键/扫码回调里不同步刷新任何 UI、不写日志**;界面由 1 秒的时钟和 5 秒一次的状态刷新兜底。
+- socket 写入只在 `station-scan-write` 单线程里做,避免主线程 `NetworkOnMainThreadException`,
+ 同时保证多条扫码按顺序发出。
+- **不做任何去重**:同一个条码连续扫到多少次就上报多少次,重复帧由桌面端自己判断。
+- 条码校验只做首尾非字母数字清理 + 4~64 位长度检查,不用正则。
+
+## 语音播报(离线)
+
+设备没有显示器,扫码后要能听到「后四位 + 开始打包」。
+
+- 设备上只有 `PicoTts` 且**没有中文语音数据**,所以运行时**不用 TextToSpeech**。
+- 用 `tools/fetch-voice-seeds.ps1` 从现场语音服务(`http://tbdata.gztbyc.com/voice/<文本>`)
+ 一次性抓取 `0-9`、`A-Z`、`开始打包`,统一转成 **44.1kHz / 立体声 / 16-bit PCM**,
+ 放到 `app/src/main/res/raw/voice_*.wav`;运行时只读本地资源,**断网也能播报**。
+- 播放用系统 `MediaPlayer` 读临时拼接的 WAV(这台 rk3288 的 `AudioTrack` 初始化会失败),
+ 在 `station-speech` 独立线程完成,不阻塞扫码上报。
+- 同一串条码 2.5 秒内不重复播报(连续扫描的重复帧);换了条码立即打断上一句播最新的。
+ **上报不受影响**:重复条码仍然逐条发送。
+- 语音内容:条码末尾 4 个字母/数字(标点跳过)+ 「开始打包」。
+- 启动时 `BarcodeSpeaker.maximizeVolume` 把媒体音量设为最大(实测 `11 -> 15`)。
+ 需要 `MODIFY_AUDIO_SETTINGS` 普通权限。
+- 重新生成种子:
+
+ ```powershell
+ powershell -NoProfile -ExecutionPolicy Bypass -File tools\fetch-voice-seeds.ps1 -Force
+ ```
+
+ 脚本依赖 `desktop/native/ffmpeg/ffmpeg.exe`;生成的 WAV 需要一起提交。
+
+## 服务设置
+
+只保留服务参数:
+
+| 项 | 默认值 | 说明 |
+| --- | --- | --- |
+| 设备名称 | `Build.MODEL` / `工位终端` | 广播里的 `HostName`,桌面端用它显示通道名 |
+| 扫码服务端口(TCP) | **8087** | 桌面端连上来读扫码结果 |
+| 设备发现端口(UDP) | **48899** | 桌面端发现广播的目标端口 |
+| 启用扫码服务 | 开 | 关掉后不监听 TCP |
+| 允许被桌面端发现 | 开 | 关掉后不应答 UDP 广播 |
+
+⚠️ 修改端口后要和桌面端约定保持一致(桌面端常量见
+`desktop/Services/Scan/ScanChannel.cs` 的 `ScanProtocol`)。
+
+## 常用命令
+
+所有构建/装机/抓日志统一走 `tools/android.ps1`(`.vscode/tasks.json` 只做转发),
+脚本内会自动探测 JDK 与 adb:
+
+```powershell
+powershell -NoProfile -ExecutionPolicy Bypass -File tools\android.ps1 dev
+```
+
+任务:`build` / `install` / `run` / `dev` / `logs` / `clean` / `devices`;
+选项:`-Variant` / `-Serial` / `-CleanFirst` / `-NoLaunch` / `-NoLogcat`。
+
+直接用 Gradle 也可以(需自行设置 `JAVA_HOME`,本机 `java` 不在 PATH):
+
+```powershell
+$env:JAVA_HOME='C:\Users\lfmingren\AppData\Local\Programs\EclipseAdoptium\jdk-17.0.20.1+1'
+.\gradlew.bat :app:assembleDebug
+```
+
+APK 产物:`app\build\outputs\apk\debug\app-debug.apk`
+
+## 正式包(签名 + 发布)
+
+release 包用仓库根目录 `keystore/packservice-release.jks` 签名,密码放在 `keystore.properties`
+(两者都被 `.gitignore` 忽略,**发布机必须自行备份**;丢了就只能换包名重新发)。
+
+```powershell
+# 只构建正式包(产物 app\build\outputs\apk\release\app-release.apk)
+$env:JAVA_HOME='C:\Users\lfmingren\AppData\Local\Programs\EclipseAdoptium\jdk-17.0.20.1+1'
+.\gradlew.bat :app:assembleRelease -PversionName=1.0.1 -PversionCode=10001
+```
+
+发布(构建 + 上传到服务器 `download/android_client/`)统一走后端脚手架,配置和桌面端同套路:
+
+```powershell
+cd ..\backend
+npm run android:build # 只构建(dry-run),产物在 backend\android_client\out
+npm run android:publish # 构建 + 上传 + 刷新 nginx
+```
+
+下载地址 `https://<域名>/download/android_client/YuncangScan-<版本>.apk`
+(版本信息 `.../android_client/version.json`)。
+
+## 日志
+
+- 统一用 `com.gztbyc.scancenter.util.L`(静态导入后 `log(...)` / `i(...)` / `w(...)` / `e(...)`),
+ **不要直接写 `android.util.Log`**。
+- tag 固定为 `AndroidStation`,类名+方法名+行号自动附在消息里;单条超 3000 字符自动分段。
+- release 包默认不输出,需 `adb shell setprop log.tag.AndroidStation DEBUG` 才打开。
+- **新增代码必须保留日志链路可用**:不要删掉 `buildFeatures { buildConfig true }`,
+ `L` 依赖 `BuildConfig.DEBUG`。
+
+## 安装与开机启动
+
+- 这是**普通用户应用**:只需要 `INTERNET`、`RECEIVE_BOOT_COMPLETED`、
+ `MODIFY_AUDIO_SETTINGS` 三个普通权限,`/data` 直接安装即可。
+- 不依赖 Device Owner / 设备管理员 / lock task / 系统应用 / 任何 ADB 赋权。
+- `BootReceiver` 监听 `BOOT_COMPLETED`,开机后自动拉起 `MainActivity`。
+ ⚠️ Android 的既定行为:**新装后必须手动启动一次**,应用才脱离 stopped 状态,
+ 之后重启才会收到开机广播。
+- 主界面不在后台驻留额外服务;扫码服务随应用进程生命周期运行。
+
+## 约定
+
+- 依赖仓库走阿里云镜像,Gradle 分发走腾讯云镜像,改动仓库配置时保持国内源优先。
+- 主界面以遥控器为主:可点击控件必须方向键可达,并在 `res/drawable/bg_button.xml`
+ 这类 selector 中提供 `state_focused` 视觉反馈。
+- 界面文案统一放 `res/values/strings.xml`,不硬编码在 XML / Java 中。
+- **不要再加「跳系统设置页面」的入口**:这台盒子的 Settings 清单里声明了一些页面,
+ 但厂商把它们从 dex 里删掉了,用组件名启动会让系统设置当场崩。
+- **不要再把中控逻辑搬回来**(设备扫描 / 通道管理 / 回放 / 手势 / 网络设置 / HTTP 上报)。
+ 本工程只负责「当一台扫码设备」。
diff --git a/AndroidStation/app/build.gradle b/AndroidStation/app/build.gradle
new file mode 100644
index 0000000..7a1ccae
--- /dev/null
+++ b/AndroidStation/app/build.gradle
@@ -0,0 +1,87 @@
+plugins {
+ id 'com.android.application'
+}
+
+// 正式签名:keystore.properties 不入库(见 .gitignore);没有它时 debug 构建不受影响,
+// release 构建会退回 debug 签名,正式发布脚本会先检查这个文件。
+def keystorePropertiesFile = rootProject.file('keystore.properties')
+def keystoreProperties = new Properties()
+if (keystorePropertiesFile.exists()) {
+ keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
+}
+
+// 发布脚本可以传 -PversionName=x.y.z -PversionCode=n 覆盖
+def appVersionCode = (project.findProperty('versionCode') ?: '1').toString().toInteger()
+def appVersionName = (project.findProperty('versionName') ?: '1.0.0').toString()
+
+android {
+ namespace 'com.gztbyc.scancenter'
+ compileSdk 35
+
+ defaultConfig {
+ applicationId "com.gztbyc.scancenter"
+ minSdk 21
+ targetSdk 28
+ versionCode appVersionCode
+ versionName appVersionName
+
+ // 本工程是纯 Java,APK 内 lib/ 为空,与 CPU 架构无关(arm32/arm64/x86 通用),
+ // 因此这里不需要限制 ABI。
+ // 一旦引入带 .so 的依赖(如 ML Kit 条码识别或任何 native 库),请取消下面注释,
+ // 否则多套架构的库会被全部打进包内,包体成倍膨胀:
+ // ndk {
+ // abiFilters 'armeabi-v7a', 'arm64-v8a' // 排除 x86,只保留盒子/手机实际用到的架构
+ // }
+ }
+
+ signingConfigs {
+ release {
+ if (keystorePropertiesFile.exists()) {
+ storeFile rootProject.file(keystoreProperties['storeFile'])
+ storePassword keystoreProperties['storePassword']
+ keyAlias keystoreProperties['keyAlias']
+ keyPassword keystoreProperties['keyPassword']
+ }
+ }
+ }
+
+ buildTypes {
+ debug {
+ minifyEnabled false
+ }
+ release {
+ minifyEnabled false
+ // 有正式 keystore 就用正式签名;没有时退回 debug,保证本地仍能 assembleRelease 验证
+ signingConfig keystorePropertiesFile.exists() ? signingConfigs.release : signingConfigs.debug
+ proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
+ }
+ }
+
+ buildFeatures {
+ // util/L.java 依赖 BuildConfig.DEBUG 决定是否输出日志;AGP 8 起 buildConfig 默认关闭
+ buildConfig true
+ }
+
+ compileOptions {
+ sourceCompatibility JavaVersion.VERSION_1_8
+ targetCompatibility JavaVersion.VERSION_1_8
+ encoding = 'UTF-8'
+ }
+
+ packaging {
+ resources {
+ excludes += ['META-INF/*.kotlin_module']
+ }
+ }
+
+ lint {
+ // targetSdk 28 是为在旧 TV 盒子上避开分区存储限制而刻意选择的,不发布 Google Play。
+ // lintVitalRelease 会因 ExpiredTargetSdkVersion 直接中断 release 构建,这里只关掉这一条,
+ // 其余 lint 检查保持开启。
+ disable 'ExpiredTargetSdkVersion'
+ }
+}
+
+dependencies {
+ implementation 'androidx.appcompat:appcompat:1.6.1'
+}
diff --git a/AndroidStation/app/proguard-rules.pro b/AndroidStation/app/proguard-rules.pro
new file mode 100644
index 0000000..fe468dc
--- /dev/null
+++ b/AndroidStation/app/proguard-rules.pro
@@ -0,0 +1,12 @@
+# 当前 release 未开启混淆(minifyEnabled = false),以下规则在启用混淆后才生效。
+-keepattributes SourceFile,LineNumberTable
+
+# 开启混淆时直接移除所有日志调用,避免调试信息进入正式包。
+# 注意:L 类内部已用 BuildConfig.DEBUG 做了运行期开关,这里是编译期的第二道保险。
+-assumenosideeffects class android.util.Log {
+ public static *** d(...);
+ public static *** v(...);
+ public static *** i(...);
+ public static *** w(...);
+ public static *** println(...);
+}
diff --git a/AndroidStation/app/src/main/AndroidManifest.xml b/AndroidStation/app/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..98e1065
--- /dev/null
+++ b/AndroidStation/app/src/main/AndroidManifest.xml
@@ -0,0 +1,74 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/AndroidStation/app/src/main/java/com/gztbyc/scancenter/App.java b/AndroidStation/app/src/main/java/com/gztbyc/scancenter/App.java
new file mode 100644
index 0000000..1dbd436
--- /dev/null
+++ b/AndroidStation/app/src/main/java/com/gztbyc/scancenter/App.java
@@ -0,0 +1,32 @@
+package com.gztbyc.scancenter;
+
+import android.app.Application;
+import android.content.Context;
+
+import com.gztbyc.scancenter.core.service.StationService;
+import com.gztbyc.scancenter.core.speech.BarcodeSpeaker;
+
+/**
+ * 持有进程级单例。
+ *
+ *
发现应答和扫码服务属于整个进程,不挂在页面上:页面重建、切换前后台都不能让
+ * 桌面端的连接断开,也不能让设备从局域网里消失。
+ */
+public class App extends Application {
+
+ private static Context context;
+
+ @Override
+ public void onCreate() {
+ super.onCreate();
+ context = getApplicationContext();
+ // 先把发现/扫码服务拉起来,语音里才能说「初始化已经完成」
+ StationService.instance().start(context);
+ // 设备长期不接显示器:启动就把音量拉满,并准备好离线语音种子/欢迎语
+ BarcodeSpeaker.instance().start(context);
+ }
+
+ public static Context context() {
+ return context;
+ }
+}
diff --git a/AndroidStation/app/src/main/java/com/gztbyc/scancenter/MainActivity.java b/AndroidStation/app/src/main/java/com/gztbyc/scancenter/MainActivity.java
new file mode 100644
index 0000000..09adefb
--- /dev/null
+++ b/AndroidStation/app/src/main/java/com/gztbyc/scancenter/MainActivity.java
@@ -0,0 +1,400 @@
+package com.gztbyc.scancenter;
+
+import android.content.Intent;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Looper;
+import android.os.SystemClock;
+import android.view.KeyEvent;
+import android.view.View;
+import android.view.WindowManager;
+import android.widget.Button;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import androidx.annotation.Nullable;
+import androidx.appcompat.app.AppCompatActivity;
+
+import com.gztbyc.scancenter.core.StationIdentity;
+import com.gztbyc.scancenter.core.StationSettings;
+import com.gztbyc.scancenter.core.service.StationService;
+import com.gztbyc.scancenter.core.speech.BarcodeSpeaker;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.List;
+import java.util.Locale;
+
+import static com.gztbyc.scancenter.util.L.i;
+import static com.gztbyc.scancenter.util.L.w;
+
+/**
+ * 设备端主界面:显示本机身份、服务状态和最近扫码结果。
+ *
+ *
USB 扫码枪是键盘设备,这里在 Activity 层统一收键(不依赖某个输入框有没有焦点):
+ * 连续可打印字符攒成一条条码,回车/Tab 立即提交;没有后缀时停手
+ * {@link #FLUSH_DELAY_MS} 后自动提交,兼容不带后缀的扫码枪。
+ *
+ *
扫码热路径不碰 UI:按键只追加到缓冲并立即提交,不同步刷新任何 TextView;
+ * 界面每 {@link #UI_REFRESH_TICKS} 秒才刷新一次。设备长期不接显示器时,
+ * 这条路径上唯一的耗时就是按键处理 + 把数据丢给后台推送线程。
+ */
+public class MainActivity extends AppCompatActivity {
+
+ /** 扫码枪没有回车后缀时,停手多久算一条扫完(USB HID 每字符通常 <5ms,50ms 足够) */
+ private static final long FLUSH_DELAY_MS = 50L;
+
+ /** 界面信息刷新间隔(秒)。扫码本身不等界面,这里只为偶尔接显示器时能看状态 */
+ private static final int UI_REFRESH_TICKS = 5;
+
+ /** 一条条码最多这么多字符;超过就丢弃重来,避免串口噪声无限累积 */
+ private static final int MAX_INPUT = 128;
+
+ /** 扫码枪尾部回车可能比自动提交晚到,这段时间内要吃掉它,不能让它点到按钮 */
+ private static final long SWALLOW_ENTER_MS = 1200L;
+
+ private final Handler handler = new Handler(Looper.getMainLooper());
+ private final StringBuilder scanBuffer = new StringBuilder();
+ private final SimpleDateFormat clockFormat = new SimpleDateFormat("HH:mm:ss", Locale.US);
+
+ private final StationService service = StationService.instance();
+
+ private TextView deviceNameView;
+ private TextView clockView;
+ private TextView infoNameView;
+ private TextView infoMacView;
+ private TextView infoIpView;
+ private TextView infoVersionView;
+ private TextView infoServiceView;
+ private TextView infoDiscoveryView;
+ private TextView infoTotalView;
+ private TextView lastCodeView;
+ private TextView lastTimeView;
+ private TextView recentView;
+
+ private long lastCommitMs;
+ private boolean listening;
+ private int tick;
+
+ private final Runnable clockTask = new Runnable() {
+ @Override
+ public void run() {
+ renderClock();
+ tick++;
+ // 扫码热路径不刷新界面;这里只是低频兜底,避免每来一条码就重排布局
+ if (tick % UI_REFRESH_TICKS == 0) {
+ renderState();
+ }
+ handler.postDelayed(this, 1000L);
+ }
+ };
+
+ private final Runnable flushTask = new Runnable() {
+ @Override
+ public void run() {
+ if (scanBuffer.length() > 0) {
+ commitScan();
+ }
+ }
+ };
+
+ private final StationService.Listener listener = new StationService.Listener() {
+ @Override
+ public void onStateChanged() {
+ renderState();
+ }
+ };
+
+ @Override
+ protected void onCreate(@Nullable Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_main);
+ applyImmersiveMode();
+ getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
+
+ deviceNameView = findViewById(R.id.tv_device_name);
+ clockView = findViewById(R.id.tv_clock);
+ infoNameView = findViewById(R.id.tv_info_name);
+ infoMacView = findViewById(R.id.tv_info_mac);
+ infoIpView = findViewById(R.id.tv_info_ip);
+ infoVersionView = findViewById(R.id.tv_info_version);
+ infoServiceView = findViewById(R.id.tv_info_service);
+ infoDiscoveryView = findViewById(R.id.tv_info_discovery);
+ infoTotalView = findViewById(R.id.tv_info_total);
+ lastCodeView = findViewById(R.id.tv_last_code);
+ lastTimeView = findViewById(R.id.tv_last_time);
+ recentView = findViewById(R.id.tv_recent);
+
+ Button settings = findViewById(R.id.btn_settings);
+ settings.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ startActivity(new Intent(MainActivity.this, SettingsActivity.class));
+ }
+ });
+
+ Button clear = findViewById(R.id.btn_clear);
+ clear.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ service.clearHistory();
+ Toast.makeText(MainActivity.this, R.string.main_cleared, Toast.LENGTH_SHORT).show();
+ }
+ });
+
+ BarcodeSpeaker.instance().start(this);
+ service.start(this);
+ renderClock();
+ renderState();
+ i("设备端主界面启动", "MAC", StationIdentity.mac(this), "IP", StationIdentity.ip());
+ }
+
+ @Override
+ protected void onStart() {
+ super.onStart();
+ if (!listening) {
+ listening = true;
+ service.addListener(listener);
+ }
+ handler.post(clockTask);
+ }
+
+ @Override
+ protected void onStop() {
+ handler.removeCallbacks(clockTask);
+ handler.removeCallbacks(flushTask);
+ // 中途离开页面(比如进设置)时不要留下半条条码,回来会和新输入粘在一起
+ scanBuffer.setLength(0);
+ if (listening) {
+ listening = false;
+ service.removeListener(listener);
+ }
+ super.onStop();
+ }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+ renderState();
+ }
+
+ @Override
+ protected void onDestroy() {
+ handler.removeCallbacks(clockTask);
+ handler.removeCallbacks(flushTask);
+ super.onDestroy();
+ }
+
+ private void renderClock() {
+ if (clockView != null) {
+ clockView.setText(clockFormat.format(new Date()));
+ }
+ }
+
+ private void renderState() {
+ if (deviceNameView == null) {
+ return;
+ }
+ deviceNameView.setText(StationSettings.deviceName(this));
+ infoNameView.setText(StationSettings.deviceName(this));
+ infoMacView.setText(StationIdentity.displayMac(this));
+
+ String ip = StationIdentity.ip();
+ infoIpView.setText(ip.isEmpty() ? getString(R.string.value_unknown) : ip);
+ infoVersionView.setText(getString(R.string.main_version_value,
+ StationIdentity.MODEL, StationIdentity.version()));
+ infoServiceView.setText(serviceStatusText());
+ infoDiscoveryView.setText(discoveryStatusText());
+ infoTotalView.setText(getString(R.string.main_total_value, service.totalScans()));
+
+ String code = service.lastCode();
+ if (code.isEmpty()) {
+ lastCodeView.setText(R.string.main_waiting);
+ lastTimeView.setText("");
+ }
+ else {
+ lastCodeView.setText(code);
+ long atMs = service.lastScanAt();
+ lastTimeView.setText(getString(R.string.main_last_time,
+ clockFormat.format(new Date(atMs))));
+ }
+
+ List history = service.history();
+ if (history.isEmpty()) {
+ recentView.setText(R.string.main_recent_empty);
+ }
+ else {
+ int limit = Math.min(history.size(), 8);
+ StringBuilder text = new StringBuilder();
+ for (int index = 0; index < limit; index++) {
+ StationService.ScanEntry entry = history.get(index);
+ if (text.length() > 0) {
+ text.append('\n');
+ }
+ text.append(clockFormat.format(new Date(entry.atMs)))
+ .append(" ")
+ .append(entry.code);
+ }
+ recentView.setText(text.toString());
+ }
+ }
+
+ private String serviceStatusText() {
+ if (!StationSettings.serviceEnabled(this)) {
+ return getString(R.string.status_disabled);
+ }
+ if (service.isServiceRunning()) {
+ return getString(R.string.main_service_running, service.servicePort(), service.clientCount());
+ }
+ String error = service.serviceError();
+ if (error != null && !error.isEmpty()) {
+ return getString(R.string.main_service_failed, error);
+ }
+ return getString(R.string.status_starting);
+ }
+
+ private String discoveryStatusText() {
+ if (!StationSettings.discoveryEnabled(this)) {
+ return getString(R.string.status_disabled);
+ }
+ if (service.isDiscoveryRunning()) {
+ return getString(R.string.main_discovery_running, service.discoveryPort());
+ }
+ String error = service.discoveryError();
+ if (error != null && !error.isEmpty()) {
+ return getString(R.string.main_discovery_failed, error);
+ }
+ return getString(R.string.status_starting);
+ }
+
+ /**
+ * 键盘扫码枪的输入在 Activity 层截获:
+ * 方向键/OK 键仍然交给焦点系统,只有可打印字符和回车属于扫码内容。
+ */
+ @Override
+ public boolean dispatchKeyEvent(KeyEvent event) {
+ if (event.getAction() == KeyEvent.ACTION_DOWN) {
+ int keyCode = event.getKeyCode();
+
+ if (keyCode == KeyEvent.KEYCODE_ENTER
+ || keyCode == KeyEvent.KEYCODE_NUMPAD_ENTER
+ || keyCode == KeyEvent.KEYCODE_TAB) {
+ if (scanBuffer.length() > 0) {
+ commitScan();
+ return true;
+ }
+ // 自动提交后扫码枪的尾回车/Tab 才到:吃掉,别让它触发当前焦点按钮
+ if (SystemClock.elapsedRealtime() - lastCommitMs < SWALLOW_ENTER_MS) {
+ return true;
+ }
+ return super.dispatchKeyEvent(event);
+ }
+
+ if (keyCode == KeyEvent.KEYCODE_DEL) {
+ if (scanBuffer.length() > 0) {
+ scanBuffer.setLength(scanBuffer.length() - 1);
+ return true;
+ }
+ return super.dispatchKeyEvent(event);
+ }
+
+ if (isInterruptKey(keyCode) && scanBuffer.length() > 0) {
+ // 方向键/返回等操作说明这次扫码被打断了;修饰键(Shift)不能算
+ scanBuffer.setLength(0);
+ return super.dispatchKeyEvent(event);
+ }
+
+ int unicode = event.getUnicodeChar(event.getMetaState());
+ if (unicode >= 0x20 && unicode != 0x7F
+ && !event.isCtrlPressed() && !event.isAltPressed() && !event.isMetaPressed()) {
+ if (scanBuffer.length() >= MAX_INPUT) {
+ scanBuffer.setLength(0);
+ }
+ scanBuffer.append((char) unicode);
+ handler.removeCallbacks(flushTask);
+ handler.postDelayed(flushTask, FLUSH_DELAY_MS);
+ return true;
+ }
+ }
+ return super.dispatchKeyEvent(event);
+ }
+
+ private void commitScan() {
+ handler.removeCallbacks(flushTask);
+ String raw = scanBuffer.toString();
+ scanBuffer.setLength(0);
+ lastCommitMs = SystemClock.elapsedRealtime();
+
+ String code = cleanBarcode(raw);
+ if (code == null) {
+ if (!raw.isEmpty()) {
+ w("忽略非法扫码内容", raw);
+ }
+ return;
+ }
+ service.pushBarcode(code);
+ }
+
+ private static boolean isInterruptKey(int keyCode) {
+ switch (keyCode) {
+ case KeyEvent.KEYCODE_DPAD_UP:
+ case KeyEvent.KEYCODE_DPAD_DOWN:
+ case KeyEvent.KEYCODE_DPAD_LEFT:
+ case KeyEvent.KEYCODE_DPAD_RIGHT:
+ case KeyEvent.KEYCODE_DPAD_CENTER:
+ case KeyEvent.KEYCODE_ESCAPE:
+ return true;
+ default:
+ return false;
+ }
+ }
+
+ /**
+ * 与桌面端 {@code ScanProtocol.CleanBarcode} 一致:首尾非字母数字削掉,4~64 位。
+ *
+ * 热路径上不用正则:手工扫首尾比 {@code replaceAll} 少两次 Pattern 匹配和字符串分配。
+ * 注意不做任何去重——重复条码也必须原样上报。
+ */
+ private static String cleanBarcode(String raw) {
+ if (raw == null) {
+ return null;
+ }
+ int start = 0;
+ int end = raw.length();
+ while (start < end && !isAsciiAlnum(raw.charAt(start))) {
+ start++;
+ }
+ while (end > start && !isAsciiAlnum(raw.charAt(end - 1))) {
+ end--;
+ }
+ int length = end - start;
+ if (length < 4 || length > 64) {
+ return null;
+ }
+ return raw.substring(start, end);
+ }
+
+ private static boolean isAsciiAlnum(char value) {
+ return (value >= '0' && value <= '9')
+ || (value >= 'A' && value <= 'Z')
+ || (value >= 'a' && value <= 'z');
+ }
+
+ private void applyImmersiveMode() {
+ getWindow().getDecorView().setSystemUiVisibility(
+ View.SYSTEM_UI_FLAG_LAYOUT_STABLE
+ | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
+ | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
+ | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
+ | View.SYSTEM_UI_FLAG_FULLSCREEN
+ | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
+ }
+
+ @Override
+ public void onWindowFocusChanged(boolean hasFocus) {
+ super.onWindowFocusChanged(hasFocus);
+ if (hasFocus) {
+ applyImmersiveMode();
+ }
+ }
+}
diff --git a/AndroidStation/app/src/main/java/com/gztbyc/scancenter/SettingsActivity.java b/AndroidStation/app/src/main/java/com/gztbyc/scancenter/SettingsActivity.java
new file mode 100644
index 0000000..eb9dd28
--- /dev/null
+++ b/AndroidStation/app/src/main/java/com/gztbyc/scancenter/SettingsActivity.java
@@ -0,0 +1,161 @@
+package com.gztbyc.scancenter;
+
+import android.os.Bundle;
+import android.view.View;
+import android.widget.Button;
+import android.widget.EditText;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import androidx.annotation.Nullable;
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.appcompat.widget.SwitchCompat;
+
+import com.gztbyc.scancenter.core.StationIdentity;
+import com.gztbyc.scancenter.core.StationSettings;
+import com.gztbyc.scancenter.core.service.StationService;
+
+/**
+ * 服务设置:只配置设备名、扫码服务端口、发现端口和启停开关。
+ *
+ *
按现场要求不提供改 IP 的入口:设备地址由网络分配,应用只负责应答发现和推扫码数据。
+ */
+public class SettingsActivity extends AppCompatActivity {
+
+ private EditText nameField;
+ private EditText servicePortField;
+ private EditText discoveryPortField;
+ private SwitchCompat serviceSwitch;
+ private SwitchCompat discoverySwitch;
+ private TextView statusView;
+
+ @Override
+ protected void onCreate(@Nullable Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_settings);
+
+ nameField = findViewById(R.id.et_device_name);
+ servicePortField = findViewById(R.id.et_service_port);
+ discoveryPortField = findViewById(R.id.et_discovery_port);
+ serviceSwitch = findViewById(R.id.sw_service_enabled);
+ discoverySwitch = findViewById(R.id.sw_discovery_enabled);
+ statusView = findViewById(R.id.tv_settings_status);
+
+ nameField.setText(StationSettings.deviceName(this));
+ servicePortField.setText(String.valueOf(StationSettings.servicePort(this)));
+ discoveryPortField.setText(String.valueOf(StationSettings.discoveryPort(this)));
+ serviceSwitch.setChecked(StationSettings.serviceEnabled(this));
+ discoverySwitch.setChecked(StationSettings.discoveryEnabled(this));
+
+ Button save = findViewById(R.id.btn_save);
+ save.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ saveSettings();
+ }
+ });
+
+ Button back = findViewById(R.id.btn_back);
+ back.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ finish();
+ }
+ });
+
+ serviceSwitch.setOnCheckedChangeListener((button, checked) -> renderStatus());
+ discoverySwitch.setOnCheckedChangeListener((button, checked) -> renderStatus());
+ renderStatus();
+ }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+ renderStatus();
+ }
+
+ private void saveSettings() {
+ String name = nameField.getText().toString().trim();
+ if (name.isEmpty()) {
+ nameField.setError(getString(R.string.settings_error_name));
+ nameField.requestFocus();
+ return;
+ }
+
+ int servicePort = parsePort(servicePortField);
+ if (servicePort < 0) {
+ servicePortField.setError(getString(R.string.settings_error_service_port));
+ servicePortField.requestFocus();
+ return;
+ }
+ int discoveryPort = parsePort(discoveryPortField);
+ if (discoveryPort < 0) {
+ discoveryPortField.setError(getString(R.string.settings_error_discovery_port));
+ discoveryPortField.requestFocus();
+ return;
+ }
+ if (servicePort == discoveryPort) {
+ discoveryPortField.setError(getString(R.string.settings_error_same_port));
+ discoveryPortField.requestFocus();
+ return;
+ }
+
+ StationSettings.save(this, name, servicePort, discoveryPort,
+ serviceSwitch.isChecked(), discoverySwitch.isChecked());
+ StationService.instance().restart();
+ renderStatus();
+
+ String error = currentError();
+ if (error.isEmpty()) {
+ Toast.makeText(this, R.string.settings_saved, Toast.LENGTH_SHORT).show();
+ }
+ else {
+ Toast.makeText(this, getString(R.string.settings_saved_with_error, error),
+ Toast.LENGTH_LONG).show();
+ }
+ }
+
+ private static int parsePort(EditText field) {
+ try {
+ int port = Integer.parseInt(field.getText().toString().trim());
+ return port >= 1 && port <= 65535 ? port : -1;
+ }
+ catch (Exception ignored) {
+ return -1;
+ }
+ }
+
+ private String currentError() {
+ StationService service = StationService.instance();
+ if (StationSettings.serviceEnabled(this) && !service.isServiceRunning()) {
+ String error = service.serviceError();
+ return error == null || error.isEmpty() ? getString(R.string.status_starting) : error;
+ }
+ if (StationSettings.discoveryEnabled(this) && !service.isDiscoveryRunning()) {
+ String error = service.discoveryError();
+ return error == null || error.isEmpty() ? getString(R.string.status_starting) : error;
+ }
+ return "";
+ }
+
+ private void renderStatus() {
+ StationService service = StationService.instance();
+ String ip = StationIdentity.ip();
+ String serviceState = serviceSwitch.isChecked()
+ ? (service.isServiceRunning()
+ ? getString(R.string.main_service_running, service.servicePort(), service.clientCount())
+ : getString(R.string.status_starting))
+ : getString(R.string.status_disabled);
+ String discoveryState = discoverySwitch.isChecked()
+ ? (service.isDiscoveryRunning()
+ ? getString(R.string.main_discovery_running, service.discoveryPort())
+ : getString(R.string.status_starting))
+ : getString(R.string.status_disabled);
+
+ statusView.setText(getString(R.string.settings_status,
+ StationIdentity.displayMac(this),
+ ip.isEmpty() ? getString(R.string.value_unknown) : ip,
+ serviceState,
+ discoveryState));
+ }
+}
diff --git a/AndroidStation/app/src/main/java/com/gztbyc/scancenter/core/StationIdentity.java b/AndroidStation/app/src/main/java/com/gztbyc/scancenter/core/StationIdentity.java
new file mode 100644
index 0000000..d811b87
--- /dev/null
+++ b/AndroidStation/app/src/main/java/com/gztbyc/scancenter/core/StationIdentity.java
@@ -0,0 +1,214 @@
+package com.gztbyc.scancenter.core;
+
+import android.content.Context;
+import android.os.SystemClock;
+import android.provider.Settings;
+
+import com.gztbyc.scancenter.BuildConfig;
+
+import java.net.Inet4Address;
+import java.net.InetAddress;
+import java.net.NetworkInterface;
+import java.security.MessageDigest;
+import java.util.Collections;
+import java.util.List;
+import java.util.Locale;
+
+/**
+ * 本机在「设备」身份下的固定信息。
+ *
+ *
MAC 是设备发现的唯一标识(桌面端按它去重),取不到网口地址时退化成
+ * 由 ANDROID_ID 派生的 12 位十六进制,保证同一台机器每次报告的值稳定。
+ */
+public final class StationIdentity {
+
+ /** 广播里的型号字段;桌面端只用来展示 */
+ public static final String MODEL = "AndroidStation";
+
+ private static volatile String macCache;
+ private static volatile String ipCache;
+ private static volatile long ipCacheAtMs;
+
+ private StationIdentity() {
+ }
+
+ /** 12 位大写十六进制,无分隔(与设备固件一致) */
+ public static String mac(Context context) {
+ String cached = macCache;
+ if (cached != null) {
+ return cached;
+ }
+ synchronized (StationIdentity.class) {
+ if (macCache == null) {
+ macCache = resolveMac(context);
+ }
+ return macCache;
+ }
+ }
+
+ private static String resolveMac(Context context) {
+ String mac = hardwareAddress("eth0");
+ if (mac.isEmpty()) {
+ mac = hardwareAddress("wlan0");
+ }
+ if (mac.isEmpty()) {
+ mac = anyHardwareAddress();
+ }
+ if (!mac.isEmpty()) {
+ return mac;
+ }
+ return derivedMac(context);
+ }
+
+ private static String hardwareAddress(String name) {
+ try {
+ NetworkInterface network = NetworkInterface.getByName(name);
+ if (network == null) {
+ return "";
+ }
+ return toHex(network.getHardwareAddress());
+ }
+ catch (Exception ignored) {
+ return "";
+ }
+ }
+
+ private static String anyHardwareAddress() {
+ try {
+ for (NetworkInterface network : Collections.list(NetworkInterface.getNetworkInterfaces())) {
+ if (network.isLoopback() || !network.isUp()) {
+ continue;
+ }
+ String mac = toHex(network.getHardwareAddress());
+ if (!mac.isEmpty()) {
+ return mac;
+ }
+ }
+ }
+ catch (Exception ignored) {
+ // 某些 ROM 会直接抛
+ }
+ return "";
+ }
+
+ private static String toHex(byte[] address) {
+ if (address == null || address.length == 0) {
+ return "";
+ }
+ StringBuilder text = new StringBuilder(address.length * 2);
+ for (byte item : address) {
+ text.append(String.format(Locale.US, "%02X", item & 0xFF));
+ }
+ return text.toString();
+ }
+
+ private static String derivedMac(Context context) {
+ String androidId = "";
+ try {
+ androidId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
+ }
+ catch (Exception ignored) {
+ // 忽略
+ }
+ if (androidId == null) {
+ androidId = "";
+ }
+ try {
+ MessageDigest digest = MessageDigest.getInstance("MD5");
+ byte[] hash = digest.digest(androidId.getBytes("UTF-8"));
+ StringBuilder text = new StringBuilder(12);
+ for (int i = 0; i < 6; i++) {
+ text.append(String.format(Locale.US, "%02X", hash[i] & 0xFF));
+ }
+ return text.toString();
+ }
+ catch (Exception ignored) {
+ return "000000000000";
+ }
+ }
+
+ /** 给界面看的冒号分隔形式 */
+ public static String displayMac(Context context) {
+ String mac = mac(context);
+ if (mac.length() != 12) {
+ return mac;
+ }
+ StringBuilder text = new StringBuilder(17);
+ for (int i = 0; i < 12; i += 2) {
+ if (text.length() > 0) {
+ text.append(':');
+ }
+ text.append(mac, i, i + 2);
+ }
+ return text.toString();
+ }
+
+ /** 当前 IPv4 地址;没有可用网口时返回空串 */
+ public static String ip() {
+ String cached = ipCache;
+ long now = SystemClock.elapsedRealtime();
+ if (cached != null && now - ipCacheAtMs < 3000) {
+ return cached;
+ }
+ String value = resolveIp();
+ ipCache = value;
+ ipCacheAtMs = now;
+ return value;
+ }
+
+ private static String resolveIp() {
+ try {
+ NetworkInterface eth0 = NetworkInterface.getByName("eth0");
+ String value = firstIpv4(eth0);
+ if (!value.isEmpty()) {
+ return value;
+ }
+ for (NetworkInterface network : Collections.list(NetworkInterface.getNetworkInterfaces())) {
+ if (network.isLoopback() || !network.isUp()) {
+ continue;
+ }
+ value = firstIpv4(network);
+ if (!value.isEmpty()) {
+ return value;
+ }
+ }
+ }
+ catch (Exception ignored) {
+ // 忽略
+ }
+ return "";
+ }
+
+ private static String firstIpv4(NetworkInterface network) {
+ if (network == null) {
+ return "";
+ }
+ try {
+ List addresses = Collections.list(network.getInetAddresses());
+ for (InetAddress address : addresses) {
+ if (address instanceof Inet4Address && !address.isLoopbackAddress()) {
+ return address.getHostAddress();
+ }
+ }
+ }
+ catch (Exception ignored) {
+ // 忽略
+ }
+ return "";
+ }
+
+ /** 设备固件格式:`0-Day 0:08:44\r\n` */
+ public static String uptime() {
+ long totalSeconds = SystemClock.elapsedRealtime() / 1000L;
+ long days = totalSeconds / 86400L;
+ long hours = (totalSeconds % 86400L) / 3600L;
+ long minutes = (totalSeconds % 3600L) / 60L;
+ long seconds = totalSeconds % 60L;
+ return String.format(Locale.US, "%d-Day %d:%02d:%02d\r\n", days, hours, minutes, seconds);
+ }
+
+ public static String version() {
+ String version = BuildConfig.VERSION_NAME;
+ return version == null || version.isEmpty() ? "1.0" : version;
+ }
+}
diff --git a/AndroidStation/app/src/main/java/com/gztbyc/scancenter/core/StationSettings.java b/AndroidStation/app/src/main/java/com/gztbyc/scancenter/core/StationSettings.java
new file mode 100644
index 0000000..f86425a
--- /dev/null
+++ b/AndroidStation/app/src/main/java/com/gztbyc/scancenter/core/StationSettings.java
@@ -0,0 +1,95 @@
+package com.gztbyc.scancenter.core;
+
+import android.content.Context;
+import android.content.SharedPreferences;
+import android.os.Build;
+
+/**
+ * 设备端服务参数。
+ *
+ * 本机扮演「网口扫码设备」:对局域网广播应答发现报文,并在服务端口上监听,
+ * 把 USB 扫码枪的结果推给连上来的桌面端。这里只存服务参数,不再保存任何 IP/掩码/网关
+ * —— 设备地址由现场网络分配,改地址不属于本应用职责。
+ */
+public final class StationSettings {
+
+ private static final String FILE = "station_settings";
+ private static final String KEY_DEVICE_NAME = "device_name";
+ private static final String KEY_SERVICE_PORT = "service_port";
+ private static final String KEY_DISCOVERY_PORT = "discovery_port";
+ private static final String KEY_SERVICE_ENABLED = "service_enabled";
+ private static final String KEY_DISCOVERY_ENABLED = "discovery_enabled";
+
+ /** 与桌面端 {@code ScanProtocol.TcpPort} 保持一致 */
+ public static final int DEFAULT_SERVICE_PORT = 8087;
+
+ /** 与设备固件 / 桌面端一致 */
+ public static final int DEFAULT_DISCOVERY_PORT = 48899;
+
+ private StationSettings() {
+ }
+
+ private static SharedPreferences prefs(Context context) {
+ return context.getSharedPreferences(FILE, Context.MODE_PRIVATE);
+ }
+
+ public static String deviceName(Context context) {
+ String value = prefs(context).getString(KEY_DEVICE_NAME, "");
+ if (value != null && !value.trim().isEmpty()) {
+ return value.trim();
+ }
+ return defaultDeviceName();
+ }
+
+ /** 桌面端写 HostName 时用,不再走界面 */
+ public static void setDeviceName(Context context, String name) {
+ String value = name == null ? "" : name.trim();
+ if (value.isEmpty()) {
+ return;
+ }
+ // 广播回复要立刻生效,commit 比 apply 更直观
+ prefs(context).edit().putString(KEY_DEVICE_NAME, value).commit();
+ }
+
+ private static String defaultDeviceName() {
+ String model = Build.MODEL == null ? "" : Build.MODEL.trim();
+ if (model.isEmpty() || "Android".equalsIgnoreCase(model)) {
+ return "工位终端";
+ }
+ return model;
+ }
+
+ public static int servicePort(Context context) {
+ return prefs(context).getInt(KEY_SERVICE_PORT, DEFAULT_SERVICE_PORT);
+ }
+
+ public static void setServicePort(Context context, int port) {
+ if (port < 1 || port > 65535) {
+ return;
+ }
+ prefs(context).edit().putInt(KEY_SERVICE_PORT, port).commit();
+ }
+
+ public static int discoveryPort(Context context) {
+ return prefs(context).getInt(KEY_DISCOVERY_PORT, DEFAULT_DISCOVERY_PORT);
+ }
+
+ public static boolean serviceEnabled(Context context) {
+ return prefs(context).getBoolean(KEY_SERVICE_ENABLED, true);
+ }
+
+ public static boolean discoveryEnabled(Context context) {
+ return prefs(context).getBoolean(KEY_DISCOVERY_ENABLED, true);
+ }
+
+ public static void save(Context context, String name, int servicePort, int discoveryPort,
+ boolean serviceEnabled, boolean discoveryEnabled) {
+ prefs(context).edit()
+ .putString(KEY_DEVICE_NAME, name == null ? "" : name.trim())
+ .putInt(KEY_SERVICE_PORT, servicePort)
+ .putInt(KEY_DISCOVERY_PORT, discoveryPort)
+ .putBoolean(KEY_SERVICE_ENABLED, serviceEnabled)
+ .putBoolean(KEY_DISCOVERY_ENABLED, discoveryEnabled)
+ .commit();
+ }
+}
diff --git a/AndroidStation/app/src/main/java/com/gztbyc/scancenter/core/service/DiscoveryResponder.java b/AndroidStation/app/src/main/java/com/gztbyc/scancenter/core/service/DiscoveryResponder.java
new file mode 100644
index 0000000..83a63a4
--- /dev/null
+++ b/AndroidStation/app/src/main/java/com/gztbyc/scancenter/core/service/DiscoveryResponder.java
@@ -0,0 +1,365 @@
+package com.gztbyc.scancenter.core.service;
+
+import android.content.Context;
+
+import com.gztbyc.scancenter.core.StationIdentity;
+import com.gztbyc.scancenter.core.StationSettings;
+
+import org.json.JSONArray;
+import org.json.JSONObject;
+
+import java.net.DatagramPacket;
+import java.net.DatagramSocket;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.SocketTimeoutException;
+import java.nio.charset.StandardCharsets;
+
+import static com.gztbyc.scancenter.util.L.e;
+import static com.gztbyc.scancenter.util.L.i;
+import static com.gztbyc.scancenter.util.L.w;
+
+/**
+ * 设备发现应答器:扮演网口扫码设备,在 UDP 端口上响应桌面端的发现广播。
+ *
+ *
桌面端({@code Services/Scan/DiscoveryMonitor.cs})每 3 秒往
+ * {@code 255.255.255.255:48899} 发一段 {@code {"Type":"EP_Tool",...}},
+ * 设备把**自己的信息**回给发送方的源地址/源端口。这里必须用同一个 socket
+ * 收和回,否则源端口对不上,桌面端收不到。
+ *
+ *
同时兼容桌面端的 JCMD 配置报文({@code CID 10001/10003/10005/10017}):
+ * 桌面端「添加通道」时会读 SOCK 段确认 TCP 服务、把设备名写进 SYS 段。
+ * 网络参数只读不写:本机不改 IP/掩码/网关。
+ */
+public final class DiscoveryResponder {
+
+ public interface Callback {
+ /** 桌面端通过 JCMD 写了设备名 */
+ void onHostNameWritten(String name);
+
+ /** 桌面端要求服务端口(SOCK.LocalPort),需要本地重启扫码服务 */
+ void onServicePortRequested(int port);
+ }
+
+ private static final int CID_GET_STATE = 10001;
+ private static final int CID_GET_CONFIG = 10003;
+ private static final int CID_SET_CONFIG = 10005;
+ private static final int CID_SAVE_FLASH = 10017;
+ private static final int CID_DO_RESTART = 20003;
+
+ private final Context context;
+ private final Callback callback;
+
+ private volatile DatagramSocket socket;
+ private volatile Thread worker;
+ private volatile boolean running;
+ private volatile int port;
+ private volatile String error = "";
+ private volatile long lastReplyLogMs;
+
+ public DiscoveryResponder(Context context, Callback callback) {
+ this.context = context.getApplicationContext();
+ this.callback = callback;
+ }
+
+ public synchronized void start(int port) {
+ stop();
+ this.port = port;
+ this.error = "";
+ DatagramSocket udp = null;
+ try {
+ udp = new DatagramSocket(null);
+ udp.setReuseAddress(true);
+ udp.bind(new InetSocketAddress(port));
+ udp.setSoTimeout(1000);
+ }
+ catch (Exception failure) {
+ error = describe(failure);
+ e(failure, "设备发现端口绑定失败", port);
+ if (udp != null) {
+ udp.close();
+ }
+ return;
+ }
+
+ socket = udp;
+ running = true;
+ worker = new Thread(new Runnable() {
+ @Override
+ public void run() {
+ loop();
+ }
+ }, "station-discovery");
+ worker.start();
+ i("设备发现服务已启动", "UDP", port, "MAC", StationIdentity.mac(context));
+ }
+
+ public synchronized void stop() {
+ running = false;
+ DatagramSocket old = socket;
+ socket = null;
+ if (old != null) {
+ try {
+ old.close();
+ }
+ catch (Exception ignored) {
+ // 忽略
+ }
+ }
+ Thread oldWorker = worker;
+ worker = null;
+ if (oldWorker != null && oldWorker != Thread.currentThread()) {
+ oldWorker.interrupt();
+ }
+ }
+
+ public boolean isRunning() {
+ return running;
+ }
+
+ public int port() {
+ return port;
+ }
+
+ public String error() {
+ return error;
+ }
+
+ private void loop() {
+ byte[] buffer = new byte[4096];
+ while (running) {
+ DatagramSocket udp = socket;
+ if (udp == null || udp.isClosed()) {
+ break;
+ }
+ DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
+ try {
+ udp.receive(packet);
+ }
+ catch (SocketTimeoutException timeout) {
+ continue;
+ }
+ catch (Exception failure) {
+ if (!running || udp.isClosed()) {
+ break;
+ }
+ // 网络抖动不应该让设备从局域网里消失
+ w("接收发现报文失败(继续监听)", describe(failure));
+ try {
+ Thread.sleep(200L);
+ }
+ catch (InterruptedException interrupted) {
+ Thread.currentThread().interrupt();
+ break;
+ }
+ }
+
+ try {
+ handle(udp, packet);
+ }
+ catch (Exception failure) {
+ w("处理发现报文失败", describe(failure));
+ }
+ }
+ }
+
+ private void handle(DatagramSocket udp, DatagramPacket packet) throws Exception {
+ if (!running) {
+ return;
+ }
+ String text = new String(packet.getData(), packet.getOffset(), packet.getLength(),
+ StandardCharsets.UTF_8).trim();
+ if (!text.startsWith("{")) {
+ return;
+ }
+ JSONObject request = new JSONObject(text);
+ if ("EP_Tool".equals(request.optString("Type", ""))) {
+ send(udp, packet, discoveryReply());
+ // 桌面端每 3 秒探测一次,逐条打日志会把 logcat 刷满
+ long now = System.currentTimeMillis();
+ if (now - lastReplyLogMs > 10_000L) {
+ lastReplyLogMs = now;
+ i("已应答设备发现", packet.getAddress().getHostAddress());
+ }
+ return;
+ }
+ if (request.optInt("JCMD", 0) == 1) {
+ handleJcmd(udp, packet, request);
+ }
+ }
+
+ /** 广播回复:字段与设备固件一致(见 docs/udp-48899-protocol.md §6) */
+ private JSONObject discoveryReply() throws Exception {
+ JSONObject reply = new JSONObject();
+ reply.put("Agent", 0);
+ reply.put("Type", StationIdentity.MODEL);
+ reply.put("Version", StationIdentity.version());
+ reply.put("ClientEn", 1);
+ reply.put("HostName", StationSettings.deviceName(context));
+ reply.put("CustomerID", StationIdentity.MODEL);
+ reply.put("Uptime", StationIdentity.uptime());
+ reply.put("Zone", "EPort");
+ reply.put("UdpSupport", 1);
+ reply.put("MAC", StationIdentity.mac(context));
+ reply.put("State", "Idle");
+ return reply;
+ }
+
+ private void handleJcmd(DatagramSocket udp, DatagramPacket packet, JSONObject request)
+ throws Exception {
+ int cid = request.optInt("CID", 0);
+ int replyCid = cid + 1;
+ JSONObject reply = new JSONObject();
+ reply.put("JCMD", 1);
+ reply.put("CID", replyCid);
+ reply.put("RC", 0);
+
+ switch (cid) {
+ case CID_GET_STATE:
+ reply.put("PL", new JSONObject().put("SOCK", sockStates()));
+ break;
+
+ case CID_GET_CONFIG: {
+ String section = requestedSection(request);
+ JSONObject pl = new JSONObject();
+ if ("SOCK".equalsIgnoreCase(section)) {
+ pl.put("SOCK", sockEntries());
+ }
+ else if ("SYS".equalsIgnoreCase(section)) {
+ pl.put("SYS", sysConfig());
+ }
+ reply.put("PL", pl);
+ break;
+ }
+
+ case CID_SET_CONFIG: {
+ JSONObject pl = request.optJSONObject("PL");
+ if (pl != null) {
+ JSONObject sys = pl.optJSONObject("SYS");
+ if (sys != null) {
+ String hostName = sys.optString("HostName", "").trim();
+ if (!hostName.isEmpty()) {
+ StationSettings.setDeviceName(context, hostName);
+ i("桌面端写入设备名", hostName);
+ if (callback != null) {
+ callback.onHostNameWritten(hostName);
+ }
+ }
+ }
+ JSONObject sock = pl.optJSONObject("SOCK");
+ if (sock != null) {
+ int localPort = sock.optInt("LocalPort", 0);
+ if (localPort > 0 && localPort <= 65535
+ && localPort != StationSettings.servicePort(context)) {
+ StationSettings.setServicePort(context, localPort);
+ i("桌面端写入服务端口", localPort);
+ if (callback != null) {
+ callback.onServicePortRequested(localPort);
+ }
+ }
+ }
+ }
+ break;
+ }
+
+ case CID_SAVE_FLASH:
+ // 设置已经 commit 到 SharedPreferences,这里只需确认
+ break;
+
+ case CID_DO_RESTART:
+ // 不主动重启应用:桌面端只是确认设备收到了指令
+ w("收到桌面端重启指令,设备端保持运行");
+ break;
+
+ default:
+ return;
+ }
+
+ send(udp, packet, reply);
+ }
+
+ private static String requestedSection(JSONObject request) {
+ JSONArray sections = request.optJSONArray("PL");
+ if (sections != null && sections.length() > 0) {
+ return sections.optString(0, "");
+ }
+ JSONObject object = request.optJSONObject("PL");
+ if (object != null) {
+ if (object.has("SOCK")) {
+ return "SOCK";
+ }
+ if (object.has("SYS")) {
+ return "SYS";
+ }
+ }
+ return "";
+ }
+
+ /** SYS 段:只读网络参数,DHCP 固定为 1(本机不改地址) */
+ private JSONObject sysConfig() throws Exception {
+ String ip = StationIdentity.ip();
+ JSONObject sys = new JSONObject();
+ sys.put("HostName", StationSettings.deviceName(context));
+ sys.put("IpAddr", ip.isEmpty() ? "0.0.0.0" : ip);
+ sys.put("Mask", "0.0.0.0");
+ sys.put("GateWay", "0.0.0.0");
+ sys.put("Dns", "0.0.0.0");
+ sys.put("DhcpEn", 1);
+ sys.put("User", "");
+ sys.put("Password", "");
+ sys.put("Type", StationIdentity.MODEL);
+ sys.put("Version", StationIdentity.version());
+ sys.put("MAC", StationIdentity.mac(context));
+ return sys;
+ }
+
+ /** SOCK 段:本机只有一条「给桌面端读扫码数据」的 TCP 服务 */
+ private JSONArray sockEntries() throws Exception {
+ JSONObject entry = new JSONObject();
+ entry.put("Name", ScanServer.SOCK_NAME);
+ entry.put("Protocol", "TCP-SERVER");
+ entry.put("LocalPort", StationSettings.servicePort(context));
+ entry.put("maxAccept", 5);
+ entry.put("Rout", "uart");
+ entry.put("BufSize", 512);
+ entry.put("KeepAlive", 60);
+ entry.put("ConnectMode", "Always");
+ entry.put("Timeout", 0);
+ entry.put("Server", "");
+ entry.put("ServerPort", 0);
+ entry.put("HeartBeatEn", 0);
+ entry.put("HeartBeatTime", 0);
+ entry.put("HeartBeatCode", "");
+ entry.put("RegistMode", "Disable");
+ entry.put("RegistCode", "");
+ entry.put("Security", "Disable");
+ entry.put("SecuKey", "");
+ entry.put("VcomEn", 0);
+ entry.put("VpTag", "");
+ return new JSONArray().put(entry);
+ }
+
+ /** SOCK 运行状态:桌面端看门狗用它确认连接是否还活着 */
+ private JSONArray sockStates() throws Exception {
+ JSONObject entry = new JSONObject();
+ entry.put("Name", ScanServer.SOCK_NAME);
+ entry.put("SockName", ScanServer.SOCK_NAME);
+ entry.put("Protocol", "TCP-SERVER");
+ int clients = ScanServer.instance().clientCount();
+ entry.put("State", clients > 0 ? "Connected" : "Listen");
+ entry.put("ClientIP", ScanServer.instance().clientIps());
+ return new JSONArray().put(entry);
+ }
+
+ private void send(DatagramSocket udp, DatagramPacket request, JSONObject reply) throws Exception {
+ byte[] data = reply.toString().getBytes(StandardCharsets.UTF_8);
+ InetAddress address = request.getAddress();
+ int targetPort = request.getPort();
+ udp.send(new DatagramPacket(data, data.length, address, targetPort));
+ }
+
+ private static String describe(Exception failure) {
+ String message = failure.getMessage();
+ return message == null ? failure.getClass().getSimpleName() : message;
+ }
+}
diff --git a/AndroidStation/app/src/main/java/com/gztbyc/scancenter/core/service/ScanServer.java b/AndroidStation/app/src/main/java/com/gztbyc/scancenter/core/service/ScanServer.java
new file mode 100644
index 0000000..2f7b7b9
--- /dev/null
+++ b/AndroidStation/app/src/main/java/com/gztbyc/scancenter/core/service/ScanServer.java
@@ -0,0 +1,363 @@
+package com.gztbyc.scancenter.core.service;
+
+import com.gztbyc.scancenter.BuildConfig;
+
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.InetSocketAddress;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.nio.charset.StandardCharsets;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static com.gztbyc.scancenter.util.L.e;
+import static com.gztbyc.scancenter.util.L.i;
+import static com.gztbyc.scancenter.util.L.w;
+
+/**
+ * 扫码数据服务:本机当服务端,桌面端连上来读取 USB 扫码枪的结果。
+ *
+ *
方向与现场网口设备一致(见桌面端 {@code ChannelConnection.cs}):
+ * 设备监听、桌面端主动连接。每收到一条扫码结果,按行(CRLF 结尾)
+ * 写给所有已连接的客户端;客户端下发的扫码枪设置指令(二进制)只读取并丢弃
+ * —— 本机的扫码枪是 USB HID,不需要这些串口指令。
+ */
+public final class ScanServer {
+
+ /** 与桌面端 {@code ScanProtocol.SockName} 一致,JCMD 里要报这个名字 */
+ public static final String SOCK_NAME = "packcenter";
+
+ public interface Callback {
+ void onClientsChanged(int count);
+ }
+
+ private static final ScanServer INSTANCE = new ScanServer();
+
+ private final CopyOnWriteArrayList clients = new CopyOnWriteArrayList();
+
+ /**
+ * 扫码结果是在主线程(按键回调)产生的,socket 写必须在后台线程做,
+ * 否则 Android 直接抛 {@code NetworkOnMainThreadException}。
+ * 单线程同时保证多条扫码结果按顺序发出。
+ */
+ private final ExecutorService writer = Executors.newSingleThreadExecutor(new ThreadFactory() {
+ @Override
+ public Thread newThread(Runnable runnable) {
+ Thread thread = new Thread(runnable, "station-scan-write");
+ thread.setDaemon(true);
+ return thread;
+ }
+ });
+
+ private volatile ServerSocket server;
+ private volatile Thread acceptThread;
+ private volatile boolean running;
+ private volatile int port;
+ private volatile String error = "";
+ private volatile Callback callback;
+
+ /** 只在写线程里访问:前几条打印排队+写入耗时,之后不再打日志 */
+ private int debugPushes;
+ private int idleScans;
+
+ private ScanServer() {
+ }
+
+ public static ScanServer instance() {
+ return INSTANCE;
+ }
+
+ public void setCallback(Callback callback) {
+ this.callback = callback;
+ }
+
+ public synchronized void start(int port) {
+ stop();
+ this.port = port;
+ this.error = "";
+ ServerSocket socket = null;
+ try {
+ socket = new ServerSocket();
+ socket.setReuseAddress(true);
+ socket.bind(new InetSocketAddress(port), 8);
+ }
+ catch (Exception failure) {
+ error = describe(failure);
+ e(failure, "扫码服务端口绑定失败", port);
+ if (socket != null) {
+ try {
+ socket.close();
+ }
+ catch (Exception ignored) {
+ // 忽略
+ }
+ }
+ return;
+ }
+
+ server = socket;
+ running = true;
+ acceptThread = new Thread(new Runnable() {
+ @Override
+ public void run() {
+ acceptLoop();
+ }
+ }, "station-scan-accept");
+ acceptThread.start();
+ i("扫码服务已启动", "TCP", port);
+ }
+
+ public synchronized void stop() {
+ running = false;
+ ServerSocket old = server;
+ server = null;
+ if (old != null) {
+ try {
+ old.close();
+ }
+ catch (Exception ignored) {
+ // 忽略
+ }
+ }
+ for (Client client : clients) {
+ client.close();
+ }
+ clients.clear();
+ Thread oldAccept = acceptThread;
+ acceptThread = null;
+ if (oldAccept != null && oldAccept != Thread.currentThread()) {
+ oldAccept.interrupt();
+ }
+ notifyClients();
+ }
+
+ public boolean isRunning() {
+ return running;
+ }
+
+ public int port() {
+ return port;
+ }
+
+ public String error() {
+ return error;
+ }
+
+ public int clientCount() {
+ return clients.size();
+ }
+
+ /** 设备侧 SOCK.ClientIP 用;多个客户端时逗号分隔 */
+ public String clientIps() {
+ StringBuilder text = new StringBuilder();
+ for (Client client : clients) {
+ if (client.remoteIp.isEmpty()) {
+ continue;
+ }
+ if (text.length() > 0) {
+ text.append(',');
+ }
+ text.append(client.remoteIp);
+ }
+ return text.toString();
+ }
+
+ /**
+ * 把一条扫码结果推给所有客户端。
+ *
+ * ⚠️ 不去重:重复条码也照发,连续扫描的重复帧由桌面端自己判断。
+ * 这里只做两件事——复制成字节、丢给后台写线程,调用方(按键回调)立即返回。
+ */
+ public void push(String barcode) {
+ if (barcode == null || barcode.isEmpty()) {
+ return;
+ }
+ final String code = barcode;
+ final long queuedAtMs = System.currentTimeMillis();
+ final byte[] data = (code + "\r\n").getBytes(StandardCharsets.UTF_8);
+ writer.execute(new Runnable() {
+ @Override
+ public void run() {
+ int sent = 0;
+ for (Client client : clients) {
+ if (client.write(data)) {
+ sent++;
+ }
+ else {
+ remove(client);
+ }
+ }
+ if (sent == 0) {
+ // 没有桌面端连接:低频提示,避免每条都刷日志
+ if (++idleScans % 20 == 0) {
+ i("扫码结果没有桌面端连接", code);
+ }
+ }
+ else if (BuildConfig.DEBUG && debugPushes < 5) {
+ debugPushes++;
+ i("扫码推送完成", code, "客户端", sent,
+ "排队+写", (System.currentTimeMillis() - queuedAtMs) + "ms");
+ }
+ }
+ });
+ }
+
+ private void acceptLoop() {
+ while (running) {
+ ServerSocket listener = server;
+ if (listener == null || listener.isClosed()) {
+ break;
+ }
+ Socket accepted = null;
+ try {
+ accepted = listener.accept();
+ Client client = new Client(accepted);
+ clients.add(client);
+ i("桌面端已连接扫码服务", client.remoteIp, "当前", clients.size());
+ notifyClients();
+ client.startReader();
+ }
+ catch (Exception failure) {
+ if (accepted != null) {
+ try {
+ accepted.close();
+ }
+ catch (Exception ignored) {
+ // 忽略
+ }
+ }
+ if (!running || listener.isClosed()) {
+ break;
+ }
+ // 单个连接(比如客户端刚连上就断)不应把整个监听线程结束掉
+ w("接受扫码服务连接失败(继续监听)", describe(failure));
+ try {
+ Thread.sleep(200L);
+ }
+ catch (InterruptedException interrupted) {
+ Thread.currentThread().interrupt();
+ break;
+ }
+ }
+ }
+ }
+
+ private void remove(Client client) {
+ if (client.closed.get()) {
+ return;
+ }
+ client.close();
+ if (clients.remove(client)) {
+ i("桌面端已断开扫码服务", client.remoteIp, "当前", clients.size());
+ notifyClients();
+ }
+ }
+
+ private void notifyClients() {
+ Callback current = callback;
+ if (current != null) {
+ current.onClientsChanged(clients.size());
+ }
+ }
+
+ private static String describe(Exception failure) {
+ String message = failure.getMessage();
+ return message == null ? failure.getClass().getSimpleName() : message;
+ }
+
+ /** 双栈 socket 可能把 IPv4 给成 `::ffff:192.168.1.5`,要归一化后才能和桌面端对账 */
+ private static String normalizeIp(java.net.InetAddress address) {
+ if (address == null) {
+ return "";
+ }
+ String text = address.getHostAddress();
+ if (text == null) {
+ return "";
+ }
+ if (text.startsWith("::ffff:")) {
+ text = text.substring(7);
+ }
+ int scope = text.indexOf('%');
+ return scope > 0 ? text.substring(0, scope) : text;
+ }
+
+ private final class Client implements Runnable {
+
+ final Socket socket;
+ final String remoteIp;
+ final AtomicBoolean closed = new AtomicBoolean(false);
+ final InputStream input;
+ final OutputStream output;
+ Thread reader;
+
+ Client(Socket socket) throws Exception {
+ this.socket = socket;
+ this.socket.setTcpNoDelay(true);
+ this.remoteIp = normalizeIp(socket.getInetAddress());
+ this.input = socket.getInputStream();
+ this.output = socket.getOutputStream();
+ }
+
+ void startReader() {
+ reader = new Thread(this, "station-scan-client");
+ reader.start();
+ }
+
+ /** 串行写,避免多条扫码结果在同一个 socket 上交错 */
+ synchronized boolean write(byte[] data) {
+ if (closed.get()) {
+ return false;
+ }
+ try {
+ output.write(data);
+ output.flush();
+ return true;
+ }
+ catch (Exception failure) {
+ w("推送扫码结果失败", remoteIp, describe(failure));
+ return false;
+ }
+ }
+
+ @Override
+ public void run() {
+ byte[] buffer = new byte[512];
+ boolean logged = false;
+ try {
+ while (running && !closed.get()) {
+ int read = input.read(buffer);
+ if (read < 0) {
+ break;
+ }
+ if (!logged) {
+ logged = true;
+ // 桌面端连上后会下发扫码枪设置(串口指令),本机是 USB HID,忽略
+ i("已忽略桌面端下发的扫码枪设置指令", remoteIp, read + " 字节");
+ }
+ }
+ }
+ catch (Exception ignored) {
+ // 断开就是断开,不必刷错误
+ }
+ finally {
+ remove(this);
+ }
+ }
+
+ void close() {
+ if (!closed.compareAndSet(false, true)) {
+ return;
+ }
+ try {
+ socket.close();
+ }
+ catch (Exception ignored) {
+ // 忽略
+ }
+ }
+ }
+}
diff --git a/AndroidStation/app/src/main/java/com/gztbyc/scancenter/core/service/StationService.java b/AndroidStation/app/src/main/java/com/gztbyc/scancenter/core/service/StationService.java
new file mode 100644
index 0000000..342cd35
--- /dev/null
+++ b/AndroidStation/app/src/main/java/com/gztbyc/scancenter/core/service/StationService.java
@@ -0,0 +1,254 @@
+package com.gztbyc.scancenter.core.service;
+
+import android.content.Context;
+import android.os.Handler;
+import android.os.Looper;
+
+import com.gztbyc.scancenter.core.StationSettings;
+import com.gztbyc.scancenter.core.speech.BarcodeSpeaker;
+
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+/**
+ * 设备端服务总入口:发现应答 + 扫码推送。
+ *
+ *
进程级单例,随 {@code App#onCreate} 启动;页面重建不影响服务。
+ */
+public final class StationService {
+
+ public interface Listener {
+ /** 服务状态(启停/客户端数量/设备名)有变化 */
+ void onStateChanged();
+ }
+
+ public static final class ScanEntry {
+ public final String code;
+ public final long atMs;
+
+ ScanEntry(String code, long atMs) {
+ this.code = code;
+ this.atMs = atMs;
+ }
+ }
+
+ private static final int MAX_HISTORY = 30;
+
+ private static final StationService INSTANCE = new StationService();
+
+ private final Handler mainHandler = new Handler(Looper.getMainLooper());
+ private final CopyOnWriteArrayList listeners = new CopyOnWriteArrayList();
+ private final ArrayDeque history = new ArrayDeque();
+
+ private Context context;
+ private DiscoveryResponder discovery;
+ private boolean running;
+
+ private String lastCode = "";
+ private long lastScanAt;
+ private long totalScans;
+
+ private StationService() {
+ }
+
+ public static StationService instance() {
+ return INSTANCE;
+ }
+
+ public synchronized void start(Context context) {
+ if (running) {
+ return;
+ }
+ this.context = context.getApplicationContext();
+ running = true;
+ startInternal();
+ notifyState();
+ }
+
+ public synchronized void stop() {
+ running = false;
+ stopInternal();
+ notifyState();
+ }
+
+ /** 设置变更后整体重启(端口/开关可能都变了) */
+ public synchronized void restart() {
+ stopInternal();
+ if (running) {
+ startInternal();
+ }
+ notifyState();
+ }
+
+ private void startInternal() {
+ if (context == null) {
+ return;
+ }
+
+ ScanServer.instance().setCallback(new ScanServer.Callback() {
+ @Override
+ public void onClientsChanged(int count) {
+ notifyState();
+ }
+ });
+
+ if (StationSettings.discoveryEnabled(context)) {
+ discovery = new DiscoveryResponder(context, new DiscoveryResponder.Callback() {
+ @Override
+ public void onHostNameWritten(String name) {
+ notifyState();
+ }
+
+ @Override
+ public void onServicePortRequested(int port) {
+ mainHandler.post(new Runnable() {
+ @Override
+ public void run() {
+ restartScanServer();
+ }
+ });
+ }
+ });
+ discovery.start(StationSettings.discoveryPort(context));
+ }
+
+ if (StationSettings.serviceEnabled(context)) {
+ ScanServer.instance().start(StationSettings.servicePort(context));
+ }
+ }
+
+ private void stopInternal() {
+ if (discovery != null) {
+ discovery.stop();
+ discovery = null;
+ }
+ ScanServer.instance().stop();
+ }
+
+ private synchronized void restartScanServer() {
+ if (context == null) {
+ return;
+ }
+ ScanServer.instance().stop();
+ if (StationSettings.serviceEnabled(context)) {
+ ScanServer.instance().start(StationSettings.servicePort(context));
+ }
+ notifyState();
+ }
+
+ public void addListener(Listener listener) {
+ if (listener != null && !listeners.contains(listener)) {
+ listeners.add(listener);
+ }
+ }
+
+ public void removeListener(Listener listener) {
+ listeners.remove(listener);
+ }
+
+ /**
+ * 收到一条扫码结果:记入历史并推给所有桌面端连接。
+ *
+ * 无论服务是否启用都记账 —— 现场排查时「扫了但没推出去」比「没扫上」更难分辨。
+ */
+ public void pushBarcode(String code) {
+ if (code == null || code.isEmpty()) {
+ return;
+ }
+ long now = System.currentTimeMillis();
+ synchronized (history) {
+ lastCode = code;
+ lastScanAt = now;
+ totalScans++;
+ history.addFirst(new ScanEntry(code, now));
+ while (history.size() > MAX_HISTORY) {
+ history.removeLast();
+ }
+ }
+ // 热路径只入队,不写日志、不通知 UI:桌面端连接与否都由后台写线程处理
+ ScanServer.instance().push(code);
+ // 语音播报同样在独立线程,主线程只做一次很轻的判重/入队
+ BarcodeSpeaker.instance().announce(code);
+ }
+
+ public void clearHistory() {
+ synchronized (history) {
+ history.clear();
+ lastCode = "";
+ lastScanAt = 0L;
+ totalScans = 0L;
+ }
+ notifyState();
+ }
+
+ public String lastCode() {
+ synchronized (history) {
+ return lastCode;
+ }
+ }
+
+ public long lastScanAt() {
+ synchronized (history) {
+ return lastScanAt;
+ }
+ }
+
+ public long totalScans() {
+ synchronized (history) {
+ return totalScans;
+ }
+ }
+
+ public List history() {
+ synchronized (history) {
+ return new ArrayList(history);
+ }
+ }
+
+ public boolean isDiscoveryRunning() {
+ DiscoveryResponder current = discovery;
+ return current != null && current.isRunning();
+ }
+
+ public String discoveryError() {
+ DiscoveryResponder current = discovery;
+ return current == null ? "" : current.error();
+ }
+
+ public int discoveryPort() {
+ return context == null ? StationSettings.DEFAULT_DISCOVERY_PORT
+ : StationSettings.discoveryPort(context);
+ }
+
+ public boolean isServiceRunning() {
+ return ScanServer.instance().isRunning();
+ }
+
+ public String serviceError() {
+ return ScanServer.instance().error();
+ }
+
+ public int servicePort() {
+ return ScanServer.instance().port() > 0 ? ScanServer.instance().port()
+ : (context == null ? StationSettings.DEFAULT_SERVICE_PORT
+ : StationSettings.servicePort(context));
+ }
+
+ public int clientCount() {
+ return ScanServer.instance().clientCount();
+ }
+
+ private void notifyState() {
+ mainHandler.post(new Runnable() {
+ @Override
+ public void run() {
+ for (Listener listener : listeners) {
+ listener.onStateChanged();
+ }
+ }
+ });
+ }
+
+}
diff --git a/AndroidStation/app/src/main/java/com/gztbyc/scancenter/core/speech/BarcodeSpeaker.java b/AndroidStation/app/src/main/java/com/gztbyc/scancenter/core/speech/BarcodeSpeaker.java
new file mode 100644
index 0000000..486ac64
--- /dev/null
+++ b/AndroidStation/app/src/main/java/com/gztbyc/scancenter/core/speech/BarcodeSpeaker.java
@@ -0,0 +1,555 @@
+package com.gztbyc.scancenter.core.speech;
+
+import android.content.Context;
+import android.media.AudioAttributes;
+import android.media.AudioManager;
+import android.media.MediaPlayer;
+import android.os.Handler;
+import android.os.Looper;
+import android.os.SystemClock;
+
+import com.gztbyc.scancenter.R;
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ThreadFactory;
+
+import static com.gztbyc.scancenter.util.L.e;
+import static com.gztbyc.scancenter.util.L.i;
+import static com.gztbyc.scancenter.util.L.w;
+
+/**
+ * 离线语音播报:播「条码后四位 + 开始打包」。
+ *
+ * 设备上只有 PicoTts 且没有中文语音数据,所以运行时不用 TextToSpeech:
+ * 事先用 `tools/fetch-voice-seeds.ps1` 从现场语音服务把 0-9、A-Z、「开始打包」
+ * 一次性抓成 44.1kHz/立体声/16-bit PCM,放在 {@code res/raw}。运行时只读本地资源,
+ * 断网也能播报。
+ *
+ *
播放用系统 {@link MediaPlayer} 读一个临时拼接的 WAV:这台 rk3288 的
+ * AudioTrack 直接初始化会失败,MediaPlayer 由音频框架负责重采样/路由,兼容性更好。
+ *
+ *
播报与扫码上报互不阻塞:拼 PCM、写临时 WAV、起播都在 {@code station-speech} 线程,
+ * 主线程只做一个「入队」。连续扫同一个码时 {@link #REPEAT_QUIET_MS} 内不重复播报;
+ * 换了条码会立即停掉上一句、播最新的。
+ */
+public final class BarcodeSpeaker {
+
+ /** 与设备 AudioFlinger 的输出线程一致(实测 rk3288:44100Hz / 立体声 / pcm16) */
+ private static final int SAMPLE_RATE = 44100;
+ private static final int CHANNELS = 2;
+ private static final int BITS_PER_SAMPLE = 16;
+ private static final int BYTES_PER_FRAME = CHANNELS * BITS_PER_SAMPLE / 8;
+
+ /** 数字之间的停顿 */
+ private static final int TOKEN_GAP_MS = 20;
+
+ /** 后四位与「开始打包」之间的停顿 */
+ private static final int PHRASE_GAP_MS = 80;
+
+ /** 同一个条码在这个时间内不重复播报(连续扫描的重复帧) */
+ private static final long REPEAT_QUIET_MS = 2500L;
+
+ /** 启动后延迟多久播欢迎语(等 Activity/服务都就绪) */
+ private static final long WELCOME_DELAY_MS = 1200L;
+
+ private static final int[] DIGIT_RES = {
+ R.raw.voice_0, R.raw.voice_1, R.raw.voice_2, R.raw.voice_3, R.raw.voice_4,
+ R.raw.voice_5, R.raw.voice_6, R.raw.voice_7, R.raw.voice_8, R.raw.voice_9,
+ };
+
+ private static final int[] LETTER_RES = {
+ R.raw.voice_a, R.raw.voice_b, R.raw.voice_c, R.raw.voice_d, R.raw.voice_e,
+ R.raw.voice_f, R.raw.voice_g, R.raw.voice_h, R.raw.voice_i, R.raw.voice_j,
+ R.raw.voice_k, R.raw.voice_l, R.raw.voice_m, R.raw.voice_n, R.raw.voice_o,
+ R.raw.voice_p, R.raw.voice_q, R.raw.voice_r, R.raw.voice_s, R.raw.voice_t,
+ R.raw.voice_u, R.raw.voice_v, R.raw.voice_w, R.raw.voice_x, R.raw.voice_y,
+ R.raw.voice_z,
+ };
+
+ private static final BarcodeSpeaker INSTANCE = new BarcodeSpeaker();
+
+ private final Object lock = new Object();
+ private final Handler mainHandler = new Handler(Looper.getMainLooper());
+ private final Map pcmCache = new HashMap();
+
+ private final ExecutorService worker = Executors.newSingleThreadExecutor(new ThreadFactory() {
+ @Override
+ public Thread newThread(Runnable runnable) {
+ Thread thread = new Thread(runnable, "station-speech");
+ thread.setDaemon(true);
+ return thread;
+ }
+ });
+
+ private volatile Context context;
+ private MediaPlayer player;
+ private File playerFile;
+ private int generation;
+ private String lastCode = "";
+ private long lastAnnouncedAt;
+ private boolean cacheCleaned;
+ private boolean welcomeScheduled;
+
+ private BarcodeSpeaker() {
+ }
+
+ public static BarcodeSpeaker instance() {
+ return INSTANCE;
+ }
+
+ /** 进程启动时调用;重复调用安全(会重新确认一次音量) */
+ public void start(Context context) {
+ this.context = context.getApplicationContext();
+ synchronized (lock) {
+ if (!cacheCleaned) {
+ cacheCleaned = true;
+ cleanupCache();
+ }
+ }
+ maximizeVolume(this.context);
+ scheduleWelcome();
+ }
+
+ /** 进程启动后播一次欢迎语;如果操作员已经先扫码,就让位给扫码播报 */
+ private void scheduleWelcome() {
+ if (welcomeScheduled) {
+ return;
+ }
+ welcomeScheduled = true;
+ mainHandler.postDelayed(new Runnable() {
+ @Override
+ public void run() {
+ synchronized (lock) {
+ if (!lastCode.isEmpty()) {
+ return;
+ }
+ }
+ worker.execute(new Runnable() {
+ @Override
+ public void run() {
+ byte[] pcm = loadPcm(R.raw.voice_welcome);
+ if (pcm.length == 0) {
+ w("欢迎语音种子缺失");
+ return;
+ }
+ playPcm(pcm, "welcome");
+ }
+ });
+ }
+ }, WELCOME_DELAY_MS);
+ }
+
+ /** 把媒体/系统音量开到最大(设备启动后默认满音量) */
+ public static void maximizeVolume(Context context) {
+ AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
+ if (audio == null) {
+ w("拿不到 AudioManager,跳过音量设置");
+ return;
+ }
+ try {
+ audio.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_UNMUTE, 0);
+ }
+ catch (Exception ignored) {
+ // 某些 ROM 在固定音量策略下会拒绝,继续尝试直接写音量
+ }
+
+ int max = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
+ int before = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
+ try {
+ audio.setStreamVolume(AudioManager.STREAM_MUSIC, max, 0);
+ }
+ catch (Exception failure) {
+ w("设置媒体音量失败", describe(failure));
+ }
+ try {
+ int systemMax = audio.getStreamMaxVolume(AudioManager.STREAM_SYSTEM);
+ audio.setStreamVolume(AudioManager.STREAM_SYSTEM, systemMax, 0);
+ }
+ catch (Exception ignored) {
+ // 系统音量不是必需的,失败不影响播报
+ }
+ i("音量已设为最大", before, "->", max);
+ }
+
+ /**
+ * 收到一条扫码结果后调用。
+ *
+ * 只做很轻的判重和入队;拼 PCM、写 WAV、起播都在 {@code station-speech} 线程。
+ */
+ public void announce(String code) {
+ Context ctx = context;
+ if (ctx == null || code == null || code.isEmpty()) {
+ return;
+ }
+ final String tail = lastAlnum(code, 4);
+ if (tail.isEmpty()) {
+ return;
+ }
+
+ long now = SystemClock.elapsedRealtime();
+ synchronized (lock) {
+ if (code.equals(lastCode) && now - lastAnnouncedAt < REPEAT_QUIET_MS) {
+ return;
+ }
+ lastCode = code;
+ lastAnnouncedAt = now;
+ }
+
+ worker.execute(new Runnable() {
+ @Override
+ public void run() {
+ byte[] pcm = buildPcm(tail);
+ if (pcm.length == 0) {
+ w("没有可用的语音种子", tail);
+ return;
+ }
+ playPcm(pcm, tail);
+ }
+ });
+ }
+
+ private void playPcm(byte[] pcm, String label) {
+ Context ctx = context;
+ if (ctx == null) {
+ return;
+ }
+
+ File file = null;
+ MediaPlayer created = null;
+ try {
+ // 文件 I/O 和 prepare 都在锁外做:扫码主线程绝不等待语音准备工作
+ file = File.createTempFile("voice-", ".wav", ctx.getCacheDir());
+ writeWav(file, pcm);
+
+ created = new MediaPlayer();
+ created.setAudioAttributes(new AudioAttributes.Builder()
+ .setUsage(AudioAttributes.USAGE_MEDIA)
+ .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
+ .build());
+ created.setDataSource(file.getAbsolutePath());
+ created.prepare();
+
+ final int myGeneration;
+ MediaPlayer oldPlayer;
+ File oldFile;
+ synchronized (lock) {
+ myGeneration = ++generation;
+ oldPlayer = player;
+ oldFile = playerFile;
+ player = created;
+ playerFile = file;
+ created.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
+ @Override
+ public void onCompletion(MediaPlayer mediaPlayer) {
+ releaseIfCurrent(myGeneration);
+ }
+ });
+ created.setOnErrorListener(new MediaPlayer.OnErrorListener() {
+ @Override
+ public boolean onError(MediaPlayer mediaPlayer, int what, int extra) {
+ w("MediaPlayer 播报错误", label, what, extra);
+ releaseIfCurrent(myGeneration);
+ return true;
+ }
+ });
+ }
+
+ releasePlayer(oldPlayer, oldFile);
+ created.start();
+
+ long durationMs = pcm.length * 1000L / (SAMPLE_RATE * BYTES_PER_FRAME);
+ i("语音播报", label, durationMs + "ms");
+ }
+ catch (Exception failure) {
+ e(failure, "语音播报失败", label);
+ synchronized (lock) {
+ if (player == created) {
+ player = null;
+ playerFile = null;
+ }
+ }
+ if (created != null) {
+ try {
+ created.release();
+ }
+ catch (Exception ignored) {
+ // 忽略
+ }
+ }
+ if (file != null) {
+ // 没交给 MediaPlayer 的文件要清掉
+ try {
+ file.delete();
+ }
+ catch (Exception ignored) {
+ // 忽略
+ }
+ }
+ }
+ }
+
+ private void releaseIfCurrent(int expectedGeneration) {
+ MediaPlayer target;
+ File file;
+ synchronized (lock) {
+ if (expectedGeneration != generation) {
+ return;
+ }
+ target = player;
+ file = playerFile;
+ player = null;
+ playerFile = null;
+ }
+ releasePlayer(target, file);
+ }
+
+ private static void releasePlayer(MediaPlayer target, File file) {
+ if (target != null) {
+ try {
+ target.stop();
+ }
+ catch (Exception ignored) {
+ // 已经播完 / 还没起播
+ }
+ try {
+ target.release();
+ }
+ catch (Exception ignored) {
+ // 忽略
+ }
+ }
+ if (file != null) {
+ try {
+ file.delete();
+ }
+ catch (Exception ignored) {
+ // 忽略
+ }
+ }
+ }
+
+ private void cleanupCache() {
+ try {
+ Context ctx = context;
+ if (ctx == null) {
+ return;
+ }
+ File[] files = ctx.getCacheDir().listFiles();
+ if (files == null) {
+ return;
+ }
+ for (File file : files) {
+ String name = file.getName();
+ if (name.startsWith("voice-") && name.endsWith(".wav")) {
+ try {
+ file.delete();
+ }
+ catch (Exception ignored) {
+ // 忽略
+ }
+ }
+ }
+ }
+ catch (Exception ignored) {
+ // 缓存清理失败不影响主流程
+ }
+ }
+
+ private byte[] buildPcm(String tail) {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ int tokens = 0;
+ for (int index = 0; index < tail.length(); index++) {
+ int resource = resourceFor(tail.charAt(index));
+ if (resource == 0) {
+ continue;
+ }
+ byte[] pcm = loadPcm(resource);
+ if (pcm.length == 0) {
+ continue;
+ }
+ if (tokens > 0) {
+ writeSilence(out, TOKEN_GAP_MS);
+ }
+ out.write(pcm, 0, pcm.length);
+ tokens++;
+ }
+ if (tokens == 0) {
+ return new byte[0];
+ }
+ writeSilence(out, PHRASE_GAP_MS);
+ byte[] phrase = loadPcm(R.raw.voice_start_pack);
+ if (phrase.length > 0) {
+ out.write(phrase, 0, phrase.length);
+ }
+ return out.toByteArray();
+ }
+
+ private byte[] loadPcm(int resource) {
+ synchronized (pcmCache) {
+ byte[] cached = pcmCache.get(resource);
+ if (cached != null) {
+ return cached;
+ }
+ byte[] pcm = readWavPcm(resource);
+ pcmCache.put(resource, pcm);
+ return pcm;
+ }
+ }
+
+ /** 从 res/raw 的 16-bit PCM WAV 里取出 data 段(文件已由脚本统一成 44.1k/stereo/16bit) */
+ private byte[] readWavPcm(int resource) {
+ Context ctx = context;
+ if (ctx == null) {
+ return new byte[0];
+ }
+ InputStream input = null;
+ try {
+ input = ctx.getResources().openRawResource(resource);
+ byte[] all = readAll(input);
+ if (all.length < 44) {
+ return new byte[0];
+ }
+ int position = 12; // 跳过 RIFF + size + WAVE
+ while (position + 8 <= all.length) {
+ String id = new String(all, position, 4, StandardCharsets.US_ASCII);
+ int size = littleEndianInt(all, position + 4);
+ int dataStart = position + 8;
+ if (size < 0 || dataStart + size > all.length) {
+ size = all.length - dataStart;
+ }
+ if ("data".equals(id)) {
+ byte[] pcm = new byte[size];
+ System.arraycopy(all, dataStart, pcm, 0, size);
+ return pcm;
+ }
+ position = dataStart + size + (size & 1);
+ }
+ }
+ catch (Exception failure) {
+ w("读语音种子失败", resource, describe(failure));
+ }
+ finally {
+ if (input != null) {
+ try {
+ input.close();
+ }
+ catch (Exception ignored) {
+ // 忽略
+ }
+ }
+ }
+ return new byte[0];
+ }
+
+ private static void writeWav(File file, byte[] pcm) throws Exception {
+ FileOutputStream out = new FileOutputStream(file);
+ try {
+ out.write(wavHeader(pcm.length));
+ out.write(pcm);
+ out.flush();
+ }
+ finally {
+ out.close();
+ }
+ }
+
+ private static byte[] wavHeader(int dataLength) {
+ byte[] header = new byte[44];
+ putAscii(header, 0, "RIFF");
+ putInt(header, 4, 36 + dataLength);
+ putAscii(header, 8, "WAVE");
+ putAscii(header, 12, "fmt ");
+ putInt(header, 16, 16);
+ putShort(header, 20, 1); // PCM
+ putShort(header, 22, CHANNELS);
+ putInt(header, 24, SAMPLE_RATE);
+ putInt(header, 28, SAMPLE_RATE * BYTES_PER_FRAME);
+ putShort(header, 32, BYTES_PER_FRAME);
+ putShort(header, 34, BITS_PER_SAMPLE);
+ putAscii(header, 36, "data");
+ putInt(header, 40, dataLength);
+ return header;
+ }
+
+ private static void putAscii(byte[] target, int offset, String value) {
+ for (int index = 0; index < value.length(); index++) {
+ target[offset + index] = (byte) value.charAt(index);
+ }
+ }
+
+ private static void putInt(byte[] target, int offset, int value) {
+ target[offset] = (byte) value;
+ target[offset + 1] = (byte) (value >>> 8);
+ target[offset + 2] = (byte) (value >>> 16);
+ target[offset + 3] = (byte) (value >>> 24);
+ }
+
+ private static void putShort(byte[] target, int offset, int value) {
+ target[offset] = (byte) value;
+ target[offset + 1] = (byte) (value >>> 8);
+ }
+
+ private static byte[] readAll(InputStream input) throws Exception {
+ ByteArrayOutputStream buffer = new ByteArrayOutputStream();
+ byte[] chunk = new byte[4096];
+ int read;
+ while ((read = input.read(chunk)) > 0) {
+ buffer.write(chunk, 0, read);
+ }
+ return buffer.toByteArray();
+ }
+
+ private static int littleEndianInt(byte[] data, int offset) {
+ return (data[offset] & 0xFF)
+ | ((data[offset + 1] & 0xFF) << 8)
+ | ((data[offset + 2] & 0xFF) << 16)
+ | ((data[offset + 3] & 0xFF) << 24);
+ }
+
+ private static void writeSilence(ByteArrayOutputStream out, int milliseconds) {
+ int bytes = SAMPLE_RATE * milliseconds / 1000 * BYTES_PER_FRAME;
+ if (bytes <= 0) {
+ return;
+ }
+ byte[] silence = new byte[bytes];
+ out.write(silence, 0, bytes);
+ }
+
+ private static int resourceFor(char value) {
+ char upper = Character.toUpperCase(value);
+ if (upper >= '0' && upper <= '9') {
+ return DIGIT_RES[upper - '0'];
+ }
+ if (upper >= 'A' && upper <= 'Z') {
+ return LETTER_RES[upper - 'A'];
+ }
+ return 0;
+ }
+
+ /** 取条码末尾的 count 个字母/数字,保持原顺序 */
+ private static String lastAlnum(String code, int count) {
+ StringBuilder tail = new StringBuilder(count);
+ for (int index = code.length() - 1; index >= 0 && tail.length() < count; index--) {
+ char value = code.charAt(index);
+ if ((value >= '0' && value <= '9')
+ || (value >= 'A' && value <= 'Z')
+ || (value >= 'a' && value <= 'z')) {
+ tail.append(Character.toUpperCase(value));
+ }
+ }
+ return tail.reverse().toString();
+ }
+
+ private static String describe(Exception failure) {
+ String message = failure.getMessage();
+ return message == null ? failure.getClass().getSimpleName() : message;
+ }
+}
diff --git a/AndroidStation/app/src/main/java/com/gztbyc/scancenter/receiver/BootReceiver.java b/AndroidStation/app/src/main/java/com/gztbyc/scancenter/receiver/BootReceiver.java
new file mode 100644
index 0000000..9796bc6
--- /dev/null
+++ b/AndroidStation/app/src/main/java/com/gztbyc/scancenter/receiver/BootReceiver.java
@@ -0,0 +1,59 @@
+package com.gztbyc.scancenter.receiver;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+
+import com.gztbyc.scancenter.MainActivity;
+
+import static com.gztbyc.scancenter.util.L.e;
+import static com.gztbyc.scancenter.util.L.i;
+import static com.gztbyc.scancenter.util.L.w;
+
+/**
+ * 开机自启动:工位设备断电重启后自动进入设备端主界面。
+ *
+ *
应用本体是服务型终端,主界面只是状态展示,所以直接拉起 {@link MainActivity}。
+ *
+ *
为什么可以直接 startActivity:
+ *
+ * - Android 10 起限制「后台启动 Activity」,但只对 targetSdk ≥ 29 生效,
+ * 本工程 targetSdk 28,不在限制范围内;
+ * - {@code BOOT_COMPLETED} 在 Android 8.0+ 的隐式广播限制豁免名单里,
+ * 所以清单里静态注册仍然有效。
+ *
+ *
+ * ⚠️ 应用新装且从未启动过时处于 stopped 状态,系统不会给它发开机广播,
+ * 必须手动启动一次之后才会生效。这是 Android 的既定行为,不是 bug。
+ */
+public class BootReceiver extends BroadcastReceiver {
+
+ /** 部分国产 ROM(HTC / 一些定制系统)用这个代替标准的 BOOT_COMPLETED */
+ private static final String ACTION_QUICKBOOT = "android.intent.action.QUICKBOOT_POWERON";
+ private static final String ACTION_HTC_QUICKBOOT = "com.htc.intent.action.QUICKBOOT_POWERON";
+
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ String action = intent == null ? "" : intent.getAction();
+
+ if (!Intent.ACTION_BOOT_COMPLETED.equals(action)
+ && !ACTION_QUICKBOOT.equals(action)
+ && !ACTION_HTC_QUICKBOOT.equals(action)) {
+ return;
+ }
+
+ i("收到开机广播,准备自启动", action);
+ try {
+ Intent launch = new Intent(context, MainActivity.class);
+ // 从 Receiver 启动 Activity 必须带 NEW_TASK,否则直接抛异常
+ launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+ context.startActivity(launch);
+ i("开机自启动已拉起设备端主界面");
+ }
+ catch (Exception error) {
+ // 自启动失败不该让进程崩掉:用户手动点图标仍然能进
+ w("开机自启动失败,需要手动启动应用");
+ e("开机自启动异常", error);
+ }
+ }
+}
diff --git a/AndroidStation/app/src/main/java/com/gztbyc/scancenter/util/L.java b/AndroidStation/app/src/main/java/com/gztbyc/scancenter/util/L.java
new file mode 100644
index 0000000..9898f20
--- /dev/null
+++ b/AndroidStation/app/src/main/java/com/gztbyc/scancenter/util/L.java
@@ -0,0 +1,168 @@
+package com.gztbyc.scancenter.util;
+
+import android.util.Log;
+
+import com.gztbyc.scancenter.BuildConfig;
+
+import java.util.Arrays;
+
+/**
+ * 轻量日志工具:静态导入之后就能像 console.log 一样一次打印多个参数。
+ *
+ *
+ * import static com.gztbyc.scancenter.util.L.*;
+ *
+ * log("扫码结果", code, "耗时", ms);
+ * e(exception, "请求失败", url);
+ *
+ *
+ * 设计要点:
+ *
+ * - 固定 tag({@link #TAG}),长度不超过 23,避免 API 24 以下被系统截断;
+ * 类名/方法名/行号放在消息里,便于定位的同时仍能用一个 tag 过滤全部日志。
+ * - 单条日志超过 {@link #MAX_CHUNK} 时自动分段,规避 logcat 约 4000 字节的截断。
+ * - release 包默认不输出:仅当 {@code BuildConfig.DEBUG} 为真,
+ * 或运行期用 {@code adb shell setprop log.tag.AndroidStation DEBUG} 显式打开。
+ * 这样排查线上包时无需重新编译。
+ *
+ */
+public final class L {
+
+ /** 所有日志统一使用这一个 tag,方便 adb logcat 过滤 */
+ public static final String TAG = "AndroidStation";
+
+ /** logcat 单条约 4000 字节,留出前缀余量后按 3000 分段 */
+ private static final int MAX_CHUNK = 3000;
+
+ private L() {
+ // 工具类,不允许实例化
+ }
+
+ // ---------------- console.log 风格 ----------------
+
+ /** 等价于 console.log(...) */
+ public static void log(Object... args) {
+ d(args);
+ }
+
+ public static void d(Object... args) {
+ if (!isEnabled(Log.DEBUG)) {
+ return;
+ }
+ write(Log.DEBUG, null, build(args));
+ }
+
+ public static void i(Object... args) {
+ if (!isEnabled(Log.INFO)) {
+ return;
+ }
+ write(Log.INFO, null, build(args));
+ }
+
+ public static void w(Object... args) {
+ if (!isEnabled(Log.WARN)) {
+ return;
+ }
+ write(Log.WARN, null, build(args));
+ }
+
+ public static void e(Object... args) {
+ e((Throwable) null, args);
+ }
+
+ public static void e(Throwable throwable, Object... args) {
+ if (!isEnabled(Log.ERROR)) {
+ return;
+ }
+ write(Log.ERROR, throwable, build(args));
+ }
+
+ // ---------------- 内部实现 ----------------
+
+ private static boolean isEnabled(int priority) {
+ // debug 包全开;release 包需要用 setprop 显式打开,避免把日志带上线
+ return BuildConfig.DEBUG || Log.isLoggable(TAG, priority);
+ }
+
+ private static String build(Object[] args) {
+ StringBuilder builder = new StringBuilder(96);
+ builder.append(caller());
+
+ if (args != null && args.length > 0) {
+ builder.append(" | ");
+ for (int index = 0; index < args.length; index++) {
+ if (index > 0) {
+ builder.append(' ');
+ }
+ builder.append(stringify(args[index]));
+ }
+ }
+ return builder.toString();
+ }
+
+ /**
+ * 取调用方位置(类名.方法名:行号)。
+ *
+ * 做法是「跳过 L 自己的所有连续栈帧,取紧随其后的那一帧」,而不是
+ * 「跳过 class == L 的帧」—— 后者在 Android 上会出错:
+ * {@code Thread.getStackTrace()} 的栈顶是 {@code dalvik.system.VMStack.getThreadStackTrace}
+ * (行号 -2,native 方法),它既不是 L 也不是 Thread,会被当成调用方返回,
+ * 于是每条日志的前缀都变成 {@code VMStack.getThreadStackTrace:-2}。
+ *
+ *
顺带也处理了 L 内部互相调用的情况({@code e(args)} → {@code e(null, args)}),
+ * 因为连续帧会被一起跳过,取到的仍是真正的外部调用方。
+ */
+ private static String caller() {
+ StackTraceElement[] frames = Thread.currentThread().getStackTrace();
+ String self = L.class.getName();
+
+ int index = 0;
+ while (index < frames.length && !self.equals(frames[index].getClassName())) {
+ index++;
+ }
+ while (index < frames.length && self.equals(frames[index].getClassName())) {
+ index++;
+ }
+ if (index >= frames.length) {
+ return "?";
+ }
+
+ StackTraceElement frame = frames[index];
+ String className = frame.getClassName();
+ String simpleName = className.substring(className.lastIndexOf('.') + 1);
+ return simpleName + "." + frame.getMethodName() + ":" + frame.getLineNumber();
+ }
+
+ private static String stringify(Object value) {
+ if (value == null) {
+ return "null";
+ }
+ if (value instanceof Throwable) {
+ return Log.getStackTraceString((Throwable) value);
+ }
+ if (value instanceof Object[]) {
+ return Arrays.deepToString((Object[]) value);
+ }
+ return String.valueOf(value);
+ }
+
+ private static void write(int priority, Throwable throwable, String message) {
+ String body = (message == null || message.isEmpty()) ? "-" : message;
+
+ if (body.length() <= MAX_CHUNK) {
+ Log.println(priority, TAG, body);
+ }
+ else {
+ int total = (body.length() + MAX_CHUNK - 1) / MAX_CHUNK;
+ for (int index = 0; index < total; index++) {
+ int start = index * MAX_CHUNK;
+ int end = Math.min(body.length(), start + MAX_CHUNK);
+ Log.println(priority, TAG, "[" + (index + 1) + "/" + total + "] " + body.substring(start, end));
+ }
+ }
+
+ if (throwable != null) {
+ Log.println(priority, TAG, Log.getStackTraceString(throwable));
+ }
+ }
+}
diff --git a/AndroidStation/app/src/main/res/drawable/app_banner.xml b/AndroidStation/app/src/main/res/drawable/app_banner.xml
new file mode 100644
index 0000000..aea2109
--- /dev/null
+++ b/AndroidStation/app/src/main/res/drawable/app_banner.xml
@@ -0,0 +1,69 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/AndroidStation/app/src/main/res/drawable/bg_button.xml b/AndroidStation/app/src/main/res/drawable/bg_button.xml
new file mode 100644
index 0000000..930c3b9
--- /dev/null
+++ b/AndroidStation/app/src/main/res/drawable/bg_button.xml
@@ -0,0 +1,22 @@
+
+
+
+
+ -
+
+
+
+
+
+
+ -
+
+
+
+
+
+
diff --git a/AndroidStation/app/src/main/res/drawable/bg_button_danger.xml b/AndroidStation/app/src/main/res/drawable/bg_button_danger.xml
new file mode 100644
index 0000000..01e8d3a
--- /dev/null
+++ b/AndroidStation/app/src/main/res/drawable/bg_button_danger.xml
@@ -0,0 +1,23 @@
+
+
+
+
+ -
+
+
+
+
+
+
+ -
+
+
+
+
+
+
diff --git a/AndroidStation/app/src/main/res/drawable/bg_card.xml b/AndroidStation/app/src/main/res/drawable/bg_card.xml
new file mode 100644
index 0000000..174eacb
--- /dev/null
+++ b/AndroidStation/app/src/main/res/drawable/bg_card.xml
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
diff --git a/AndroidStation/app/src/main/res/drawable/bg_header.xml b/AndroidStation/app/src/main/res/drawable/bg_header.xml
new file mode 100644
index 0000000..742f1be
--- /dev/null
+++ b/AndroidStation/app/src/main/res/drawable/bg_header.xml
@@ -0,0 +1,13 @@
+
+
+
+
+
diff --git a/AndroidStation/app/src/main/res/drawable/bg_panel.xml b/AndroidStation/app/src/main/res/drawable/bg_panel.xml
new file mode 100644
index 0000000..326e5ec
--- /dev/null
+++ b/AndroidStation/app/src/main/res/drawable/bg_panel.xml
@@ -0,0 +1,11 @@
+
+
+
+
+
+
diff --git a/AndroidStation/app/src/main/res/drawable/ic_launcher_foreground.xml b/AndroidStation/app/src/main/res/drawable/ic_launcher_foreground.xml
new file mode 100644
index 0000000..45b7e64
--- /dev/null
+++ b/AndroidStation/app/src/main/res/drawable/ic_launcher_foreground.xml
@@ -0,0 +1,34 @@
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/AndroidStation/app/src/main/res/layout/activity_main.xml b/AndroidStation/app/src/main/res/layout/activity_main.xml
new file mode 100644
index 0000000..a6ab6de
--- /dev/null
+++ b/AndroidStation/app/src/main/res/layout/activity_main.xml
@@ -0,0 +1,373 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/AndroidStation/app/src/main/res/layout/activity_settings.xml b/AndroidStation/app/src/main/res/layout/activity_settings.xml
new file mode 100644
index 0000000..aeb560c
--- /dev/null
+++ b/AndroidStation/app/src/main/res/layout/activity_settings.xml
@@ -0,0 +1,216 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/AndroidStation/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/AndroidStation/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
new file mode 100644
index 0000000..9b99325
--- /dev/null
+++ b/AndroidStation/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
diff --git a/AndroidStation/app/src/main/res/mipmap-anydpi/ic_launcher.xml b/AndroidStation/app/src/main/res/mipmap-anydpi/ic_launcher.xml
new file mode 100644
index 0000000..a79a5e8
--- /dev/null
+++ b/AndroidStation/app/src/main/res/mipmap-anydpi/ic_launcher.xml
@@ -0,0 +1,38 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/AndroidStation/app/src/main/res/raw/voice_0.wav b/AndroidStation/app/src/main/res/raw/voice_0.wav
new file mode 100644
index 0000000..af16872
Binary files /dev/null and b/AndroidStation/app/src/main/res/raw/voice_0.wav differ
diff --git a/AndroidStation/app/src/main/res/raw/voice_1.wav b/AndroidStation/app/src/main/res/raw/voice_1.wav
new file mode 100644
index 0000000..059c7ec
Binary files /dev/null and b/AndroidStation/app/src/main/res/raw/voice_1.wav differ
diff --git a/AndroidStation/app/src/main/res/raw/voice_2.wav b/AndroidStation/app/src/main/res/raw/voice_2.wav
new file mode 100644
index 0000000..0b5ab2a
Binary files /dev/null and b/AndroidStation/app/src/main/res/raw/voice_2.wav differ
diff --git a/AndroidStation/app/src/main/res/raw/voice_3.wav b/AndroidStation/app/src/main/res/raw/voice_3.wav
new file mode 100644
index 0000000..a96e115
Binary files /dev/null and b/AndroidStation/app/src/main/res/raw/voice_3.wav differ
diff --git a/AndroidStation/app/src/main/res/raw/voice_4.wav b/AndroidStation/app/src/main/res/raw/voice_4.wav
new file mode 100644
index 0000000..bd9b275
Binary files /dev/null and b/AndroidStation/app/src/main/res/raw/voice_4.wav differ
diff --git a/AndroidStation/app/src/main/res/raw/voice_5.wav b/AndroidStation/app/src/main/res/raw/voice_5.wav
new file mode 100644
index 0000000..baa0fe5
Binary files /dev/null and b/AndroidStation/app/src/main/res/raw/voice_5.wav differ
diff --git a/AndroidStation/app/src/main/res/raw/voice_6.wav b/AndroidStation/app/src/main/res/raw/voice_6.wav
new file mode 100644
index 0000000..3adbe4a
Binary files /dev/null and b/AndroidStation/app/src/main/res/raw/voice_6.wav differ
diff --git a/AndroidStation/app/src/main/res/raw/voice_7.wav b/AndroidStation/app/src/main/res/raw/voice_7.wav
new file mode 100644
index 0000000..51f9e94
Binary files /dev/null and b/AndroidStation/app/src/main/res/raw/voice_7.wav differ
diff --git a/AndroidStation/app/src/main/res/raw/voice_8.wav b/AndroidStation/app/src/main/res/raw/voice_8.wav
new file mode 100644
index 0000000..287299e
Binary files /dev/null and b/AndroidStation/app/src/main/res/raw/voice_8.wav differ
diff --git a/AndroidStation/app/src/main/res/raw/voice_9.wav b/AndroidStation/app/src/main/res/raw/voice_9.wav
new file mode 100644
index 0000000..4acc9ff
Binary files /dev/null and b/AndroidStation/app/src/main/res/raw/voice_9.wav differ
diff --git a/AndroidStation/app/src/main/res/raw/voice_a.wav b/AndroidStation/app/src/main/res/raw/voice_a.wav
new file mode 100644
index 0000000..3c6a7a3
Binary files /dev/null and b/AndroidStation/app/src/main/res/raw/voice_a.wav differ
diff --git a/AndroidStation/app/src/main/res/raw/voice_b.wav b/AndroidStation/app/src/main/res/raw/voice_b.wav
new file mode 100644
index 0000000..b9f834c
Binary files /dev/null and b/AndroidStation/app/src/main/res/raw/voice_b.wav differ
diff --git a/AndroidStation/app/src/main/res/raw/voice_c.wav b/AndroidStation/app/src/main/res/raw/voice_c.wav
new file mode 100644
index 0000000..133e41c
Binary files /dev/null and b/AndroidStation/app/src/main/res/raw/voice_c.wav differ
diff --git a/AndroidStation/app/src/main/res/raw/voice_d.wav b/AndroidStation/app/src/main/res/raw/voice_d.wav
new file mode 100644
index 0000000..7088621
Binary files /dev/null and b/AndroidStation/app/src/main/res/raw/voice_d.wav differ
diff --git a/AndroidStation/app/src/main/res/raw/voice_e.wav b/AndroidStation/app/src/main/res/raw/voice_e.wav
new file mode 100644
index 0000000..cb93613
Binary files /dev/null and b/AndroidStation/app/src/main/res/raw/voice_e.wav differ
diff --git a/AndroidStation/app/src/main/res/raw/voice_f.wav b/AndroidStation/app/src/main/res/raw/voice_f.wav
new file mode 100644
index 0000000..26b7122
Binary files /dev/null and b/AndroidStation/app/src/main/res/raw/voice_f.wav differ
diff --git a/AndroidStation/app/src/main/res/raw/voice_g.wav b/AndroidStation/app/src/main/res/raw/voice_g.wav
new file mode 100644
index 0000000..2611dbc
Binary files /dev/null and b/AndroidStation/app/src/main/res/raw/voice_g.wav differ
diff --git a/AndroidStation/app/src/main/res/raw/voice_h.wav b/AndroidStation/app/src/main/res/raw/voice_h.wav
new file mode 100644
index 0000000..a60e18b
Binary files /dev/null and b/AndroidStation/app/src/main/res/raw/voice_h.wav differ
diff --git a/AndroidStation/app/src/main/res/raw/voice_i.wav b/AndroidStation/app/src/main/res/raw/voice_i.wav
new file mode 100644
index 0000000..f3f811c
Binary files /dev/null and b/AndroidStation/app/src/main/res/raw/voice_i.wav differ
diff --git a/AndroidStation/app/src/main/res/raw/voice_j.wav b/AndroidStation/app/src/main/res/raw/voice_j.wav
new file mode 100644
index 0000000..6aa8357
Binary files /dev/null and b/AndroidStation/app/src/main/res/raw/voice_j.wav differ
diff --git a/AndroidStation/app/src/main/res/raw/voice_k.wav b/AndroidStation/app/src/main/res/raw/voice_k.wav
new file mode 100644
index 0000000..8df6b5c
Binary files /dev/null and b/AndroidStation/app/src/main/res/raw/voice_k.wav differ
diff --git a/AndroidStation/app/src/main/res/raw/voice_l.wav b/AndroidStation/app/src/main/res/raw/voice_l.wav
new file mode 100644
index 0000000..3fd1591
Binary files /dev/null and b/AndroidStation/app/src/main/res/raw/voice_l.wav differ
diff --git a/AndroidStation/app/src/main/res/raw/voice_m.wav b/AndroidStation/app/src/main/res/raw/voice_m.wav
new file mode 100644
index 0000000..cc487b1
Binary files /dev/null and b/AndroidStation/app/src/main/res/raw/voice_m.wav differ
diff --git a/AndroidStation/app/src/main/res/raw/voice_n.wav b/AndroidStation/app/src/main/res/raw/voice_n.wav
new file mode 100644
index 0000000..1c1e232
Binary files /dev/null and b/AndroidStation/app/src/main/res/raw/voice_n.wav differ
diff --git a/AndroidStation/app/src/main/res/raw/voice_o.wav b/AndroidStation/app/src/main/res/raw/voice_o.wav
new file mode 100644
index 0000000..59b2a86
Binary files /dev/null and b/AndroidStation/app/src/main/res/raw/voice_o.wav differ
diff --git a/AndroidStation/app/src/main/res/raw/voice_p.wav b/AndroidStation/app/src/main/res/raw/voice_p.wav
new file mode 100644
index 0000000..311394e
Binary files /dev/null and b/AndroidStation/app/src/main/res/raw/voice_p.wav differ
diff --git a/AndroidStation/app/src/main/res/raw/voice_q.wav b/AndroidStation/app/src/main/res/raw/voice_q.wav
new file mode 100644
index 0000000..205510e
Binary files /dev/null and b/AndroidStation/app/src/main/res/raw/voice_q.wav differ
diff --git a/AndroidStation/app/src/main/res/raw/voice_r.wav b/AndroidStation/app/src/main/res/raw/voice_r.wav
new file mode 100644
index 0000000..482d5ba
Binary files /dev/null and b/AndroidStation/app/src/main/res/raw/voice_r.wav differ
diff --git a/AndroidStation/app/src/main/res/raw/voice_s.wav b/AndroidStation/app/src/main/res/raw/voice_s.wav
new file mode 100644
index 0000000..dbb7e40
Binary files /dev/null and b/AndroidStation/app/src/main/res/raw/voice_s.wav differ
diff --git a/AndroidStation/app/src/main/res/raw/voice_start_pack.wav b/AndroidStation/app/src/main/res/raw/voice_start_pack.wav
new file mode 100644
index 0000000..c26c1fc
Binary files /dev/null and b/AndroidStation/app/src/main/res/raw/voice_start_pack.wav differ
diff --git a/AndroidStation/app/src/main/res/raw/voice_t.wav b/AndroidStation/app/src/main/res/raw/voice_t.wav
new file mode 100644
index 0000000..d60e955
Binary files /dev/null and b/AndroidStation/app/src/main/res/raw/voice_t.wav differ
diff --git a/AndroidStation/app/src/main/res/raw/voice_u.wav b/AndroidStation/app/src/main/res/raw/voice_u.wav
new file mode 100644
index 0000000..ed3b250
Binary files /dev/null and b/AndroidStation/app/src/main/res/raw/voice_u.wav differ
diff --git a/AndroidStation/app/src/main/res/raw/voice_v.wav b/AndroidStation/app/src/main/res/raw/voice_v.wav
new file mode 100644
index 0000000..eb0297c
Binary files /dev/null and b/AndroidStation/app/src/main/res/raw/voice_v.wav differ
diff --git a/AndroidStation/app/src/main/res/raw/voice_w.wav b/AndroidStation/app/src/main/res/raw/voice_w.wav
new file mode 100644
index 0000000..faa6188
Binary files /dev/null and b/AndroidStation/app/src/main/res/raw/voice_w.wav differ
diff --git a/AndroidStation/app/src/main/res/raw/voice_welcome.wav b/AndroidStation/app/src/main/res/raw/voice_welcome.wav
new file mode 100644
index 0000000..40f98e8
Binary files /dev/null and b/AndroidStation/app/src/main/res/raw/voice_welcome.wav differ
diff --git a/AndroidStation/app/src/main/res/raw/voice_x.wav b/AndroidStation/app/src/main/res/raw/voice_x.wav
new file mode 100644
index 0000000..09f249c
Binary files /dev/null and b/AndroidStation/app/src/main/res/raw/voice_x.wav differ
diff --git a/AndroidStation/app/src/main/res/raw/voice_y.wav b/AndroidStation/app/src/main/res/raw/voice_y.wav
new file mode 100644
index 0000000..6d0011f
Binary files /dev/null and b/AndroidStation/app/src/main/res/raw/voice_y.wav differ
diff --git a/AndroidStation/app/src/main/res/raw/voice_z.wav b/AndroidStation/app/src/main/res/raw/voice_z.wav
new file mode 100644
index 0000000..cebb012
Binary files /dev/null and b/AndroidStation/app/src/main/res/raw/voice_z.wav differ
diff --git a/AndroidStation/app/src/main/res/values/colors.xml b/AndroidStation/app/src/main/res/values/colors.xml
new file mode 100644
index 0000000..0e0f977
--- /dev/null
+++ b/AndroidStation/app/src/main/res/values/colors.xml
@@ -0,0 +1,18 @@
+
+
+ #1565C0
+ #FFB300
+ #121212
+ #FFFFFF
+ #B0BEC5
+
+ #1E1E1E
+
+ #EF5350
+ #8C2F2B
+
+ #33FFFFFF
+
+ #1C2733
+ #131A21
+
diff --git a/AndroidStation/app/src/main/res/values/strings.xml b/AndroidStation/app/src/main/res/values/strings.xml
new file mode 100644
index 0000000..07ccd9d
--- /dev/null
+++ b/AndroidStation/app/src/main/res/values/strings.xml
@@ -0,0 +1,58 @@
+
+
+ 扫码终端
+
+
+ 设备信息
+ 扫码结果
+ 设备名称
+ MAC 地址
+ IP 地址
+ 型号 / 版本
+ 扫码服务
+ 设备发现
+ 累计扫码
+ %1$s · %2$s
+ %1$d 条
+ 运行中 · TCP %1$d · 已连接 %2$d
+ 启动失败:%1$s
+ 运行中 · UDP %1$d
+ 启动失败:%1$s
+ 等待扫码…
+ 扫码时间:%1$s
+ 最近扫码
+ 暂无扫码记录
+ 请使用 USB 扫码枪扫描条码
+ 服务设置
+ 清空记录
+ USB 扫码枪 → 扫码服务 → 桌面端
+ 扫码记录已清空
+
+
+ 未启用
+ 启动中
+ 未获取到
+
+
+ 服务设置
+ 不改 IP,只配置服务
+ 设备
+ 设备名称
+ 桌面端发现的设备名
+ 服务
+ 扫码服务端口(TCP)
+ 设备发现端口(UDP)
+ 启用扫码服务
+ 允许被桌面端发现
+ 桌面端会在局域网内自动发现本机,并连接上面的扫码服务端口读取 USB 扫码枪结果。\n默认:TCP 8087 / UDP 48899。修改后请与桌面端约定保持一致。
+ 当前状态
+ MAC %1$s · IP %2$s\n扫码服务:%3$s\n设备发现:%4$s
+ 保存
+ 返回
+ 已保存,服务已重启
+ 已保存,但服务启动异常:%1$s
+ 设备名称不能为空
+ 扫码服务端口要写成 1~65535 的数字
+ 设备发现端口要写成 1~65535 的数字
+ 两个端口不能相同
+
diff --git a/AndroidStation/app/src/main/res/values/styles.xml b/AndroidStation/app/src/main/res/values/styles.xml
new file mode 100644
index 0000000..f3222e5
--- /dev/null
+++ b/AndroidStation/app/src/main/res/values/styles.xml
@@ -0,0 +1,72 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/AndroidStation/build.gradle b/AndroidStation/build.gradle
new file mode 100644
index 0000000..3b88535
--- /dev/null
+++ b/AndroidStation/build.gradle
@@ -0,0 +1,26 @@
+// 顶层构建脚本:沿用「buildscript + allprojects」经典写法,仓库统一走国内镜像。
+buildscript {
+ repositories {
+ maven { url 'https://maven.aliyun.com/repository/google' }
+ maven { url 'https://maven.aliyun.com/repository/gradle-plugin' }
+ maven { url 'https://maven.aliyun.com/repository/public' }
+ google()
+ mavenCentral()
+ }
+ dependencies {
+ classpath 'com.android.tools.build:gradle:8.7.3'
+ }
+}
+
+allprojects {
+ repositories {
+ maven { url 'https://maven.aliyun.com/repository/google' }
+ maven { url 'https://maven.aliyun.com/repository/public' }
+ google()
+ mavenCentral()
+ }
+}
+
+tasks.register('clean', Delete) {
+ delete rootProject.layout.buildDirectory
+}
diff --git a/AndroidStation/docs/udp-48899-protocol.md b/AndroidStation/docs/udp-48899-protocol.md
new file mode 100644
index 0000000..8fad5ba
--- /dev/null
+++ b/AndroidStation/docs/udp-48899-protocol.md
@@ -0,0 +1,380 @@
+# UDP 48899 设备发现协议(ScanHome / 庆科 High-Flying)
+
+> 来源:设备商工具 `E:\BaiduNetdiskDownload\ScanHome网口配置\IOTService`
+> 分析方式:实测抓包 + 反查运行配置 + 提取 jar 内字符串常量。
+> 标注 **[实测]** 的是抓到的原始数据,**[代码]** 来自 jar 常量,**[推断]** 需真机复验。
+
+## 1. 结论摘要
+
+局域网设备发现走 **UDP 广播**:工具向 `255.255.255.255:48899` 发一段 **JSON**,
+设备回包给发送方,工具据此得到设备 MAC / IP / 型号等信息,随后切到设备的管理端口做配置。
+
+- **报文是纯文本 JSON**,`PasswordEn=0` 时**不加密**(见 §5)。
+- 广播**间隔约 3 秒**,设备 **30 秒**无响应判掉线。
+- 广播里的 `ConnectMode` 决定**是否顺带改写设备的服务器地址**——配置端必须用 `Forbidden`。
+
+## 2. 端口分配
+
+来自 `IOTService\IOTService\res\ep_tool.properties` **[代码]**:
+
+| 配置项 | 值 | 含义 |
+| --- | --- | --- |
+| `UDP_BROADCAST_PORT` | **48899** | 广播目标端口(设备在此监听) |
+| `UDP_LOCAL_PORT` | 48897 | 工具本地端口 |
+| `JCMDUDP_PORT` | 48896 | JCMD 协议 UDP 端口 |
+| `JCMDTCP_PORT_START/END` | 48898 / 49898 | JCMD 协议 TCP 端口段 |
+| `VPATH_UDP_PORT` | 28987 | 虚拟串口 UDP |
+| `VPATH_TCP_PORT_START/END` | 28990 / 29990 | 虚拟串口 TCP 端口段 |
+| `VTH_SERVER_PORT` | 28986 | — |
+| `SCAN_INTERVAL` | 2999 ms | 广播间隔 [代码] |
+| `DEVICE_TIMEOUT` | 30000 ms | 掉线判定 |
+| `IOT_HEARTBEAT_INTERVAL` | 30 | 心跳 |
+| `ZONE` | `EPort` | 区域标识,出现在报文里 |
+
+另实测到设备的管理端口是 **UDP 5555**(见 §4)。
+
+## 3. 广播请求报文 **[实测]**
+
+抓到的原始包(161 字节,UTF-8,无换行):
+
+```json
+{"Agent":0,"Type":"EP_Tool","PasswordEn":0,"ServPort":0,"Version":"3.1.3f",
+ "ConnectMode":"Forbidden","Zone":"EPort","ServEn":1,"ServAddr":"0.0.0.0","ClientEn":0}
+```
+
+字段含义(对照 `iotservice/device/jcmd/JcmdBroadcast.pack()` **[代码]**):
+
+| 字段 | 类型 | 说明 |
+| --- | --- | --- |
+| `Agent` | int | 代理号,0 = 本机直连 |
+| `Type` | String | 报文类型,固定 `EP_Tool` |
+| `Version` | String | 工具版本,实测 `3.1.3f`(取 `iotservice/IOTService.version`) |
+| `PasswordEn` | int | **是否启用密码/加密**,0 = 明文 |
+| `Zone` | String | 区域,`EPort` |
+| `ConnectMode` | String | **是否改写设备服务器配置**,`Forbidden` = 只发现不修改 |
+| `ServEn` | int | 是否让设备启用「主动连接服务器」 |
+| `ServAddr` | String | 让设备连接的服务器地址,`0.0.0.0` 表示不改 |
+| `ServPort` | int | 同上,端口 0 表示不改 |
+| `ClientEn` | int | 是否启用客户端模式 |
+| `DevMac` | String | **定向查询**时才有:指定 MAC 只查该设备(广播时省略) |
+
+注意抓包里**没有 `DevMac`**,因为它只在定向查询时出现——`JcmdBroadcast` 里该字段是按需 `put` 的。
+
+## 4. 交互时序
+
+日志 `IOTService\IOTService\log.txt` 第 15–31 行 **[实测]**:
+
+```
+15: VcomManager started...
+16: Start to Scan...
+17: ***VcomDriver recv len:55 ← 设备心跳
+19: VCOM recv heartBeat!
+20: ***VcomDriver recv len:62 ← 设备发现回复(62 字节)
+22: ..VCOM recv add! ← 识别为新设备
+23-28: (另外两台设备,同样 62 字节)
+29: Device ACCF23EA6D8C is on!192.168.10.83:48899
+30: vcomudp channel connected!
+31: Send:10-Bytes,To:192.168.10.83/5555 ← 切到设备管理端口
+```
+
+所以完整流程是:
+
+1. PC 广播 JSON → `255.255.255.255:48899`(多网卡时每个广播地址各发一次)
+2. **设备回一段明文 JSON 给发送方**(实测 **188~189 字节**,见 §6)
+3. PC 与设备建立 `vcomudp` 通道做后续配置
+
+> 日志里的 `***VcomDriver recv len:62` / `len:55` 是**另一条链路**(vcom 心跳)的长度,
+> 不是广播回复;广播回复实测是 188~189 字节,不要混。
+
+### 两个关键行为 [实测]
+
+- **回复发往「广播的源地址 + 源端口」**。工具发送用的是临时端口(实测 53278),
+ 不是 `UDP_LOCAL_PORT=48897`。
+ → **在 48899 上 bind 收不到回复**,必须自己发广播并在**同一个 socket** 上收。
+- **一次广播可能收到多个回复**:实测发 10 次探测收到 20 个包。
+ 因为同时发往 `255.255.255.255` 与子网广播 `192.168.11.255`,
+ 同一块网卡上的设备**两个包都收得到,于是各回一次**。
+ → 实现时必须**按 MAC 去重**,不能按“收到几个包”算设备数。
+- 设备回复的**源端口是 48899**(即设备从自己的 48899 发出)。
+
+## 5. 加密
+
+`util/AESCrypt.class` **[代码]**:
+
+- 硬编码密钥(16 字符 = AES-128):`` `&hFiotseRViCe$' ``
+- 算法:`AES/CBC/NoPadding`,IV 取密钥自身
+- `HFEncrypt(byte[])` = `padding()` + `EncryptCBC()`;`HFDecrypt(byte[])` = `DecryptCBC()` + `unPadding()`
+- 提供 `byteToHexString` / `hexStringToByte` 一组十六进制辅助方法
+
+**但实测广播报文是明文。** 结合 `PasswordEn=0` 与配置里没有任何密码项,可以判断:
+**未设密码时收发都不加密**,AES 只在设了密码的场景启用(`HFEncrypt` 内部对空密钥做了短路)。
+
+> 这意味着接入时**不需要实现 AES**——先按明文做,等遇到设了密码的设备再补。
+> 若将来要支持加密,注意 `NoPadding` + 自定义 padding 需要逐字节对齐还原。
+
+## 6. 设备回复报文 **[实测]**
+
+实测抓到一台真实设备(`192.168.9.208`,与探测机同在 `192.168.11.56/22` 网段),
+**188~189 字节,明文 JSON**:
+
+```json
+{"Agent":0,"Type":"E10C","Version":"1.41.1","ClientEn":1,"HostName":"8号",
+ "CustomerID":"E10C","Uptime":"0-Day 0:8:44\r\n","Zone":"EPort",
+ "UdpSupport":1,"MAC":"402A8FBB15D8","State":"Idle"}
+```
+
+| 字段 | 示例值 | 说明 |
+| --- | --- | --- |
+| `Agent` | `0` | 代理号 |
+| `Type` | `E10C` | **设备型号**(非固定值,这里是 E10C) |
+| `Version` | `1.41.1` | **设备固件版本** |
+| `ClientEn` | `1` | 客户端模式开关 |
+| `HostName` | `8号` | 设备名,**UTF-8 编码**(用 GBK 解会乱码) |
+| `CustomerID` | `E10C` | 客户/型号标识 |
+| `Uptime` | `0-Day 0:8:44\r\n` | 运行时长,**字符串尾部带转义的 `\r\n`**,解析时要 trim |
+| `Zone` | `EPort` | 区域,与请求一致 |
+| `UdpSupport` | `1` | 是否支持 UDP 配置 |
+| `MAC` | `402A8FBB15D8` | **设备唯一标识**,12 位十六进制无分隔 |
+| `State` | `Idle` | 设备状态 |
+
+### 字段名对照
+
+`JcmdBroadcast.parse(JSONObject, Device)` 还会读
+`Status / productID / uartStatus / uartSetup / swVer / Local / position`——
+但这些**不在广播回复里**,应该是**定向查询**(带 `DevMac`)或连上之后才返回。
+
+与**云端 bridge** 协议的字段名不同,两套不要混:
+
+| 含义 | 局域网广播回复 | 云端 bridge |
+| --- | --- | --- |
+| MAC | `MAC` | `DevMac` |
+| 型号 | `Type` / `CustomerID` | `ModuleType` |
+| 版本 | `Version` | `Version` |
+| 在线 | `State` | `Online` |
+| 设备名 | `HostName` | `HostName` |
+
+> 设备型号实测到 `E10C`;云端日志里出现过的型号:
+> `E10` / `E20` / `E30` / `EP10` / `EP20` / `HF2211` / `HF5111A` / `HF5111B` / `HF2221` /
+> `HF5142A` / `HF5142B` / `HF5182` / `HF5111` / `HF2111` / `HF2411` / `HF2421` / `HF2321` / `HF9111` / `HF5122`。
+
+## 7. 接入建议
+
+### 7.1 发现方(桌面端)
+
+1. 广播地址用 `255.255.255.255`,端口 48899;本机有**多块网卡时每块各广播一次**(实测抓到 2 个包,间隔 64ms)。
+2. 发送消息体直接照抄上面那段 JSON,**务必保留 `ConnectMode":"Forbidden"`**,
+ 否则可能被误当成「配置指令」改写设备的服务器地址。
+3. 用**同一个 socket** 发广播并收回复(绑临时端口);发完等 ~1 秒再收,
+ **不要**用 48899 去 bind 收回复。
+4. **按 `MAC` 去重**:同一台设备会因为收到多个广播地址而回多个包(实测 2 个/次)。
+5. 设备名按 **UTF-8** 解码(`HostName` 实测含中文「8号」)。
+6. 扫描周期参考 3 秒,设备 30 秒无回复即标记离线。
+7. 若收不到回复,优先排查 AP/交换机是否开了**客户端隔离**(AP isolation)。
+
+### 7.2 设备端(本工程 AndroidStation)
+
+AndroidStation 扮演的是「网口扫码设备」这一侧:
+
+- **UDP 48899**:`DiscoveryResponder` 绑定 48899,收到 `{"Type":"EP_Tool",...}` 就按 §6 的字段
+ 回复自己的 `MAC / HostName / Type / Version / Uptime / State`。回复走同一个 socket,
+ 源端口就是 48899。
+- **TCP 8087**:`ScanServer` 监听服务端口(默认 8087,与桌面端 `ScanProtocol.TcpPort` 一致),
+ 桌面端主动连上来;USB 扫码结果按 **CRLF 结尾的 UTF-8 行**推送。桌面端连上后下发的
+ 扫码枪串口设置指令会被读取并丢弃(本机是 USB HID,不做串口透传)。
+- **JCMD**:兼容桌面端「添加通道」用到的 `10001 / 10003 / 10005 / 10017`:
+ - `10003 + PL:["SOCK"]` → 返回一条 `packcenter / TCP-SERVER / 8087`;
+ - `10003 + PL:["SYS"]` → 返回 `HostName / IpAddr / DhcpEn=1` 等只读信息;
+ - `10005` 写 `SYS.HostName` 会更新设备名;写 `SOCK.LocalPort` 会改本地服务端口并重启监听;
+ - `10017` 直接确认(设置已经落到 SharedPreferences);
+ - `20003` 只确认,不重启本机。
+- **不改 IP**:本机不提供网络参数写入,`SYS` 里的地址只读上报。
+- 只需 `INTERNET` 权限(UDP/TCP 都是普通 socket,不需要系统应用权限)。
+
+## 8. 待复验
+
+- [x] ~~设备回复的确切内容~~ → 已实测:明文 JSON,188~189 字节,见 §6
+- [ ] **定向查询(带 `DevMac`)的回复**是否包含 `productID` / `swVer` / `Local` / `position` 等字段
+- [ ] 设备管理端口 5555 的 10 字节命令格式
+- [ ] 设了密码的设备是否真的走 AES,密钥是否就是那个硬编码值
+- [ ] 是否存在**只回包不响应广播**的设备(即必须先定向查询)
+
+## 9. 控制命令(JCMD)**[实测]**
+
+发现之后的配置/控制走同一套机制。证据来自官方工具 V2 的运行日志
+(`IOTService\IOTService_V2\logs\log.log`):
+
+```
+SendJcmd(289C6E833560):{"JCMD":1,"PL":["SYS","UART","SOCK"],"CID":10001},to:169.254.1.1/48899
+Recv:{"CID":10002,"RC":0,"Remain":1,"PL":{"SOCK":[...]}}
+SendJcmd(289C6E833560):{"JCMD":1,"Remain":1,"CID":10002},to:169.254.1.1/48899 ← 没取完就继续要
+Recv:{"CID":10002,"RC":0,"Remain":0,"PL":{"SYS":{...}}}
+```
+
+### 传输
+
+- **UDP 单播**到设备自己的 IP,端口 **48899**(与发现同一个端口)。
+ 实测 604 次 `SendJcmd` **全部**发往 48899。
+- **不需要握手**,发现完直接发。
+- 靠**目标 IP** 区分设备,请求里**不带** `MAC`。
+
+### 报文结构
+
+请求:
+
+```json
+{"JCMD": 1, "CID": <命令号>, "PL": <可选载荷>, "Remain": <可选,取后续分片时带>}
+```
+
+响应:
+
+```json
+{"CID": <响应号>, "RC": <错误码>, "Remain": <0|1>, "PL": <可选载荷>}
+```
+
+- `RC = 0` 表示成功(`JCMD_ERR_SUCCUSS`)。
+- `Remain = 1` 表示设备还有后续分片,客户端要用 **响应 CID** 再发一次带 `Remain:1` 的请求,
+ 直到 `Remain = 0`。这就是状态查询要来回多次的原因。
+
+### CID 命令表(`iotservice.device.jcmd.Jcmd`,javap 读出)
+
+| CID | 名称 | 说明 |
+| --- | --- | --- |
+| 10001 / 10002 | `JCMD_GET_STATE` | 取状态(`PL:["SYS","UART","SOCK"]`) |
+| 10003 / 10004 | `JCMD_GET_CONFIG` | 取配置 |
+| 10005 / 10006 | `JCMD_SET_CONFIG` | 写配置 |
+| 10007–10010 | `*_CONFIG_XML` | 读/写 XML 配置 |
+| 10011 / 10012 | `JCMD_WIFISCAN` | WiFi 扫描 |
+| 10013–10018 | `*_SCRIPT` / `*_FSETTING` | 脚本与出厂设置 |
+| 10019–10022 | `*_FLASH_PARA` | Flash 参数 |
+| 10023 / 10024 | `JCMD_GET_NLOG` | 取运行日志 |
+| 20001 / 20002 | `JCMD_DO_RELOAD` | 重载配置 |
+| **20003 / 20004** | **`JCMD_DO_RESTART`** | **重启设备** |
+| 20005 / 20006 | `JCMD_DO_UPGRADE` | 固件升级 |
+| 20009–20012 | `JCMD_MODBUS_*` | Modbus 读写 |
+| 30001 / 30002 | `JCMD_DO_DATASEND` | 透传发数据 |
+| 40001 / 40002 | `JCMD_LOG` | 日志 |
+| 90000 | `JCMD_CONNECTED` | 连接标记 |
+
+错误码:`RC = 0` 成功;`1` 失败;`2` 需要 PL;`3` 需要 SockName;`4` 还有更多;
+`5` JCMD 被占用;`6` 已断开;`7` 超时;`8` 无需操作。
+
+### 系统配置读写(已实现,实机验证通过)
+
+**读配置:CID 10003 → 10004**
+
+```
+-> {"JCMD":1,"PL":["SYS"],"CID":10003}
+<- {"CID":10004,"RC":0,"Remain":0,"PL":{"SYS":{...}}}
+```
+
+- `PL` 是**段名数组**。只要 SYS 就传 `["SYS"]`(实测可用,返回也更小);
+ 官方工具传的是 `["SYS","UART","SOCK"]`。
+- `Remain=1` 时用**响应 CID** 续取:`{"JCMD":1,"Remain":1,"CID":10004}`。
+ 实测 E10C 读 SYS 一次返回,不分片。
+
+**SYS 字段**(实测 E10C 全字段):
+
+| 字段 | 示例 | 说明 |
+| --- | --- | --- |
+| `User` / `Password` | `admin` / `admin` | Web/Telnet 登录账号,**明文返回** |
+| `HostName` | `8号` | 设备名(UTF-8) |
+| `DhcpEn` | `0` | 0 = 静态,1 = DHCP |
+| `IpAddr` | `192.168.9.208` | IP 地址 |
+| `Mask` | `255.255.252.0` | 掩码——**字段名是 `Mask`,不是 `NetMask`** |
+| `GateWay` | `192.168.8.1` | 网关(注意 G/W 大写) |
+| `Dns` | `192.168.8.1` | DNS |
+| 其余 | | `Telnet*` / `Web*` / `Ipv6*` / `ntp*` / `ModbusTime` / `Longitude` / `Latitude` / `Lang` |
+
+> ⚠️ **字段集因型号而异**:官方日志里另一台设备还有 `NetworkMode` / `WiFi*` /
+> `LanIpAddress` / `LanMarsk` / `EthernetMode` / `SmartConfig`,而这台 E10C 没有。
+
+**切到 DHCP 的实测行为(2026-10-15)**
+
+`{"JCMD":1,"PL":{"SYS":{"DhcpEn":1}},"CID":10005}` + 保存:
+
+- **不需要重启**就生效(实测 `Uptime` 未归零)。
+- 设备**保持原 IP 可达**(本例仍是 `192.168.9.208`;不排除是 DHCP 恰好分配了同一地址)。
+- ⚠️ **`IpAddr` / `Mask` / `GateWay` 会被清零成 `0.0.0.0`**,`Dns` 保留。
+ 所以**改回静态时这三个字段必须一起写**,只写 `DhcpEn=0` 会让设备拿 `0.0.0.0` 跑:
+
+ ```
+ -> {"JCMD":1,"PL":{"SYS":{"DhcpEn":0,"IpAddr":"192.168.9.208",
+ "Mask":"255.255.252.0","GateWay":"192.168.8.1","Dns":"192.168.8.1"}},"CID":10005}
+ ```
+
+- **兜底手段**:换 IP 后设备仍在 48899 上广播,所以「广播发现」是把设备找回来的可靠方式。
+ 实测 `tools/device-restart.ps1`(不带参数)就能找回并列出当前 IP。
+
+**写配置:CID 10005 → 10006,增量**
+
+```
+-> {"JCMD":1,"PL":{"SYS":{"Dns":"192.168.8.1"}},"CID":10005}
+<- {"CID":10006,"RC":0}
+```
+
+只传要改的字段。**不要回传整份配置**:字段集因型号而异,整份回写会把设备上
+本应用不认识的字段一并覆盖掉。
+
+**DO_RELOAD:CID 20001 → 20002 —— ⚠️ 不是「应用配置」,不要用**
+
+```
+-> {"JCMD":1,"PL":["SYS","UART","SOCK"],"CID":20001}
+<- {"CID":20002,"RC":0}
+```
+
+官方工具里 `Reload` 是设备状态窗口上一个**独立按钮**(`ui/DlgStatus.btnReload`,
+确认文案 "Do you want to do Reload?"),与 `Restart`、`F-Set Clear` / `Default Setting`
+(对应 `JCMD_SET_FSETTING` 10017)是三个不同动作,所以它**不是**恢复出厂。
+
+但它也**不是「让配置生效」**——实测它会把改动抹掉。同一台设备上写 `HostName` 的对照实验:
+
+| 操作 | 读回结果 |
+| --- | --- |
+| 写入 + `DO_RELOAD` | `Eport-E10C`(出厂默认)❌ 改动丢了 |
+| 只写入、**不 reload** | `8号工作台` ✅ |
+| 只写入 + **重启设备** | `8号工作台` ✅(重启后 `Uptime` 归零,确认真的重启过) |
+
+- 佐证:官方工具里有一条文案 `Config OK! And Restart Device.`
+ ——改完配置,官方期望的是**重启**,不是 reload。
+- 所以本项目的做法是:**`SET_CONFIG` 写完就结束,什么都不补。**
+ `SET_CONFIG` 会落盘并对重启免疫,不需要额外动作。
+
+> 两个附带观察(机制均未确认):
+> `DO_RELOAD` 之后 `ModbusTime` 从 `0` 变成 `-1`;
+> 本项目发的 `Restart`(CID 20003)在设备上**延后几分钟**才真正复位
+> (探测期间 `Uptime` 从 `3:12` 掉到 `0:40`)。
+
+AndroidStation 侧:只处理 `SYS.HostName` 与 `SOCK.LocalPort`,其余网络字段只读上报。
+PC 侧:`tools/device-config.ps1`(读直接执行;写要 `-Yes`;**不要加 `-Reload`**)。
+
+### 重启设备(已实现,实机验证通过)
+
+```
+发 {"JCMD":1,"CID":20003} ← 无 PL
+收 {"CID":20004,"RC":0}
+```
+
+实测日志片段:
+
+```
+13:17:25 SendJcmd(289C6E833560):{"JCMD":1,"CID":20003},to:169.254.1.1/48899
+13:17:25 Restart Device 289C6E833560
+13:17:25 Recv:{"CID":20004,"RC":0}
+13:17:25 BroadCast:1 ← 重启后工具暂停广播
+13:17:30 BroadCast:0 ← 5 秒后恢复
+```
+
+> 设备应答后才会真正重启,重启期间会失联一段时间,发现列表里会自然变为离线。
+
+AndroidStation 侧:收到 `20003` 只回 `RC=0`,不会重启本机(设备端要保持服务在线)。
+PC 侧:`tools/device-restart.ps1`(默认演练,加 `-Yes` 才真发)。
+
+## 附:复现命令
+
+```powershell
+# 被动监听:只能看到工具/自己发出的广播请求
+powershell -NoProfile -ExecutionPolicy Bypass -File tools\udp-listen.ps1 -Minutes 3
+
+# 主动探测:自己发广播并在同一 socket 收回复(发现设备用这个)
+powershell -NoProfile -ExecutionPolicy Bypass -File tools\udp-listen.ps1 -Probe -Minutes 2
+```
diff --git a/AndroidStation/gradle.properties b/AndroidStation/gradle.properties
new file mode 100644
index 0000000..a14c561
--- /dev/null
+++ b/AndroidStation/gradle.properties
@@ -0,0 +1,9 @@
+# JVM 参数:UTF-8 必须显式指定,否则中文资源可能乱码
+org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
+
+# 使用 AndroidX(appcompat)
+android.useAndroidX=true
+
+# 并行与构建缓存
+org.gradle.parallel=true
+org.gradle.caching=true
diff --git a/AndroidStation/gradle/wrapper/gradle-wrapper.jar b/AndroidStation/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 0000000..13372ae
Binary files /dev/null and b/AndroidStation/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/AndroidStation/gradle/wrapper/gradle-wrapper.properties b/AndroidStation/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 0000000..7f1fdea
--- /dev/null
+++ b/AndroidStation/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,6 @@
+#Mon Dec 28 18:07:31 CST 2020
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
+distributionUrl=https\://mirrors.cloud.tencent.com/gradle/gradle-8.11.1-bin.zip
diff --git a/AndroidStation/gradlew b/AndroidStation/gradlew
new file mode 100644
index 0000000..cccdd3d
--- /dev/null
+++ b/AndroidStation/gradlew
@@ -0,0 +1,172 @@
+#!/usr/bin/env sh
+
+##############################################################################
+##
+## Gradle start up script for UN*X
+##
+##############################################################################
+
+# Attempt to set APP_HOME
+# Resolve links: $0 may be a link
+PRG="$0"
+# Need this for relative symlinks.
+while [ -h "$PRG" ] ; do
+ ls=`ls -ld "$PRG"`
+ link=`expr "$ls" : '.*-> \(.*\)$'`
+ if expr "$link" : '/.*' > /dev/null; then
+ PRG="$link"
+ else
+ PRG=`dirname "$PRG"`"/$link"
+ fi
+done
+SAVED="`pwd`"
+cd "`dirname \"$PRG\"`/" >/dev/null
+APP_HOME="`pwd -P`"
+cd "$SAVED" >/dev/null
+
+APP_NAME="Gradle"
+APP_BASE_NAME=`basename "$0"`
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS=""
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD="maximum"
+
+warn () {
+ echo "$*"
+}
+
+die () {
+ echo
+ echo "$*"
+ echo
+ exit 1
+}
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+nonstop=false
+case "`uname`" in
+ CYGWIN* )
+ cygwin=true
+ ;;
+ Darwin* )
+ darwin=true
+ ;;
+ MINGW* )
+ msys=true
+ ;;
+ NONSTOP* )
+ nonstop=true
+ ;;
+esac
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD="$JAVA_HOME/jre/sh/java"
+ else
+ JAVACMD="$JAVA_HOME/bin/java"
+ fi
+ if [ ! -x "$JAVACMD" ] ; then
+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+else
+ JAVACMD="java"
+ which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+fi
+
+# Increase the maximum file descriptors if we can.
+if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
+ MAX_FD_LIMIT=`ulimit -H -n`
+ if [ $? -eq 0 ] ; then
+ if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
+ MAX_FD="$MAX_FD_LIMIT"
+ fi
+ ulimit -n $MAX_FD
+ if [ $? -ne 0 ] ; then
+ warn "Could not set maximum file descriptor limit: $MAX_FD"
+ fi
+ else
+ warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
+ fi
+fi
+
+# For Darwin, add options to specify how the application appears in the dock
+if $darwin; then
+ GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
+fi
+
+# For Cygwin, switch paths to Windows format before running java
+if $cygwin ; then
+ APP_HOME=`cygpath --path --mixed "$APP_HOME"`
+ CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
+ JAVACMD=`cygpath --unix "$JAVACMD"`
+
+ # We build the pattern for arguments to be converted via cygpath
+ ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
+ SEP=""
+ for dir in $ROOTDIRSRAW ; do
+ ROOTDIRS="$ROOTDIRS$SEP$dir"
+ SEP="|"
+ done
+ OURCYGPATTERN="(^($ROOTDIRS))"
+ # Add a user-defined pattern to the cygpath arguments
+ if [ "$GRADLE_CYGPATTERN" != "" ] ; then
+ OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
+ fi
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
+ i=0
+ for arg in "$@" ; do
+ CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
+ CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
+
+ if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
+ eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
+ else
+ eval `echo args$i`="\"$arg\""
+ fi
+ i=$((i+1))
+ done
+ case $i in
+ (0) set -- ;;
+ (1) set -- "$args0" ;;
+ (2) set -- "$args0" "$args1" ;;
+ (3) set -- "$args0" "$args1" "$args2" ;;
+ (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
+ (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
+ (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
+ (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
+ (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
+ (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
+ esac
+fi
+
+# Escape application args
+save () {
+ for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
+ echo " "
+}
+APP_ARGS=$(save "$@")
+
+# Collect all arguments for the java command, following the shell quoting and substitution rules
+eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
+
+# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
+if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
+ cd "$(dirname "$0")"
+fi
+
+exec "$JAVACMD" "$@"
diff --git a/AndroidStation/gradlew.bat b/AndroidStation/gradlew.bat
new file mode 100644
index 0000000..f955316
--- /dev/null
+++ b/AndroidStation/gradlew.bat
@@ -0,0 +1,84 @@
+@if "%DEBUG%" == "" @echo off
+@rem ##########################################################################
+@rem
+@rem Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+set DIRNAME=%~dp0
+if "%DIRNAME%" == "" set DIRNAME=.
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS=
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if "%ERRORLEVEL%" == "0" goto init
+
+echo.
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto init
+
+echo.
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:init
+@rem Get command-line arguments, handling Windows variants
+
+if not "%OS%" == "Windows_NT" goto win9xME_args
+
+:win9xME_args
+@rem Slurp the command line arguments.
+set CMD_LINE_ARGS=
+set _SKIP=2
+
+:win9xME_args_slurp
+if "x%~1" == "x" goto execute
+
+set CMD_LINE_ARGS=%*
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
+
+:end
+@rem End local scope for the variables with windows NT shell
+if "%ERRORLEVEL%"=="0" goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
+exit /b 1
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
diff --git a/AndroidStation/settings.gradle b/AndroidStation/settings.gradle
new file mode 100644
index 0000000..f7d08b9
--- /dev/null
+++ b/AndroidStation/settings.gradle
@@ -0,0 +1,3 @@
+rootProject.name = "AndroidStation"
+
+include ':app'
diff --git a/AndroidStation/tools/android.ps1 b/AndroidStation/tools/android.ps1
new file mode 100644
index 0000000..f427eb4
--- /dev/null
+++ b/AndroidStation/tools/android.ps1
@@ -0,0 +1,475 @@
+<#
+.SYNOPSIS
+ AndroidStation 设备端真机调试脚手架:构建 / 装机 / 启动 / 抓日志。
+
+.DESCRIPTION
+ 约定:薄入口 + 厚实现。所有逻辑都在本脚本里,.vscode/tasks.json 与命令行只做转发。
+
+ 已内置处理(都是本机 / 本设备实际踩过的坑):
+ - JAVA_HOME 自动探测(本机 java 不在 PATH)
+ - adb 自动探测(不在 PATH)
+ - 多设备自动记住上次选择(.dev-adb.local.json,不入库)
+ - adb install 失败自动降级为 push + pm install(老盒子报 fork failed)
+ - 启动依次尝试 am start / am start(LEANBACK) / monkey,全失败时明确提示手动启动
+ - logcat 只跟随本应用 tag,并附带 AndroidRuntime:E 以便看到崩溃
+ - 设备端只建 UDP/TCP socket,普通装 /data 即可,不需要系统应用权限
+
+.EXAMPLE
+ powershell -NoProfile -ExecutionPolicy Bypass -File tools\android.ps1 dev
+
+.EXAMPLE
+ powershell -NoProfile -ExecutionPolicy Bypass -File tools\android.ps1 install -Serial 4235737
+#>
+[CmdletBinding()]
+param(
+ [Parameter(Position = 0)]
+ [ValidateSet('build', 'install', 'run', 'dev', 'logs', 'clean', 'devices', 'help')]
+ [string]$Task = 'help',
+
+ [ValidateSet('debug', 'release')]
+ [string]$Variant = 'debug',
+
+ [string]$Serial = '',
+
+ [switch]$CleanFirst,
+ [switch]$NoLaunch,
+ [switch]$NoLogcat
+)
+
+$ErrorActionPreference = 'Stop'
+
+# ============================ 常量 ============================
+
+$ProjectRoot = Split-Path -Parent $PSScriptRoot
+$PackageName = 'com.gztbyc.scancenter'
+$ActivityName = "$PackageName/.MainActivity"
+$LogTag = 'AndroidStation'
+$StateFile = Join-Path $ProjectRoot '.dev-adb.local.json'
+$LocalProps = Join-Path $ProjectRoot 'local.properties'
+
+# ============================ 输出 ============================
+
+function Write-Step([string]$Message) { Write-Host "[android] $Message" -ForegroundColor Cyan }
+function Write-Ok([string]$Message) { Write-Host "[android] OK $Message" -ForegroundColor Green }
+function Write-Warn([string]$Message) { Write-Host "[android] !! $Message" -ForegroundColor Yellow }
+
+# ============================ 外部命令封装 ============================
+
+# 统一调用外部程序:不因 stderr 输出而抛异常,并返回退出码与合并后的文本
+function Invoke-Native {
+ param(
+ [Parameter(Mandatory = $true)][string]$FilePath,
+ [string[]]$Arguments = @(),
+ [switch]$Quiet
+ )
+
+ $previous = $ErrorActionPreference
+ $ErrorActionPreference = 'Continue'
+ try {
+ if ($Quiet) {
+ $output = & $FilePath @Arguments 2>&1
+ $text = ($output | Out-String)
+ return [pscustomobject]@{ ExitCode = $LASTEXITCODE; Output = $text }
+ }
+
+ & $FilePath @Arguments
+ return [pscustomobject]@{ ExitCode = $LASTEXITCODE; Output = '' }
+ }
+ finally {
+ $ErrorActionPreference = $previous
+ }
+}
+
+# ============================ 环境探测 ============================
+
+function Resolve-JavaHome {
+ if ($env:JAVA_HOME) {
+ if (Test-Path (Join-Path $env:JAVA_HOME 'bin\java.exe')) { return $env:JAVA_HOME }
+ }
+
+ $roots = @()
+ if ($env:LOCALAPPDATA) { $roots += (Join-Path $env:LOCALAPPDATA 'Programs\EclipseAdoptium') }
+ $roots += 'C:\Program Files\Eclipse Adoptium'
+ $roots += 'C:\Program Files\Java'
+
+ foreach ($root in $roots) {
+ if (-not (Test-Path $root)) { continue }
+ $jdk = Get-ChildItem -Path $root -Directory -ErrorAction SilentlyContinue |
+ Where-Object { Test-Path (Join-Path $_.FullName 'bin\java.exe') } |
+ Sort-Object Name -Descending |
+ Select-Object -First 1
+ if ($jdk) { return $jdk.FullName }
+ }
+ return ''
+}
+
+function Resolve-SdkDir {
+ if (Test-Path $LocalProps) {
+ $match = Select-String -Path $LocalProps -Pattern '^\s*sdk\.dir\s*=' -ErrorAction SilentlyContinue | Select-Object -First 1
+ if ($match) {
+ # local.properties 里的 Windows 路径是转义写法(C\:\\Users\\...),需要还原
+ return ($match.Line -split '=', 2)[1].Trim().Replace('\:', ':').Replace('\\', '\')
+ }
+ }
+ if ($env:ANDROID_HOME) { return $env:ANDROID_HOME }
+ if ($env:ANDROID_SDK_ROOT) { return $env:ANDROID_SDK_ROOT }
+ if ($env:LOCALAPPDATA) { return (Join-Path $env:LOCALAPPDATA 'Android\Sdk') }
+ return ''
+}
+
+function Resolve-Adb {
+ $candidates = @()
+ $sdk = Resolve-SdkDir
+ if ($sdk) { $candidates += (Join-Path $sdk 'platform-tools\adb.exe') }
+ if ($env:LOCALAPPDATA) { $candidates += (Join-Path $env:LOCALAPPDATA 'Android\Sdk\platform-tools\adb.exe') }
+
+ foreach ($candidate in $candidates) {
+ if (Test-Path $candidate) { return $candidate }
+ }
+ # 退回 PATH
+ $onPath = Get-Command adb.exe -ErrorAction SilentlyContinue
+ if ($onPath) { return $onPath.Source }
+ throw '未找到 adb.exe,请确认 Android SDK platform-tools 已安装'
+}
+
+$Adb = $null
+function Get-Adb {
+ if (-not $script:Adb) { $script:Adb = Resolve-Adb }
+ return $script:Adb
+}
+
+# ============================ 设备选择(含记忆) ============================
+
+function Get-ConnectedDevices {
+ $adb = Get-Adb
+ $result = Invoke-Native $adb @('devices', '-l') -Quiet
+ $devices = @()
+ $abnormal = @()
+
+ foreach ($line in ($result.Output -split "`r?`n")) {
+ if ($line -match '^(\S+)\s+(device|unauthorized|offline|no permissions)\b\s*(.*)$') {
+ if ($Matches[2] -eq 'device') {
+ $devices += [pscustomobject]@{ Serial = $Matches[1]; Desc = $Matches[3].Trim() }
+ }
+ else {
+ $abnormal += "$($Matches[1]) [$($Matches[2])]"
+ }
+ }
+ }
+
+ if ($abnormal.Count -gt 0) {
+ Write-Warn ("下列设备状态异常:" + ($abnormal -join ','))
+ }
+ return $devices
+}
+
+function Read-SavedSerial {
+ if (-not (Test-Path $StateFile)) { return '' }
+ try { return (Get-Content $StateFile -Raw | ConvertFrom-Json).serial } catch { return '' }
+}
+
+function Save-Serial([string]$Value) {
+ $json = "{`r`n `"serial`": `"$Value`"`r`n}`r`n"
+ try {
+ # 不写 BOM,避免其它工具解析 JSON 出错
+ [System.IO.File]::WriteAllText($StateFile, $json, (New-Object System.Text.UTF8Encoding($false)))
+ }
+ catch {
+ # 写入失败不影响主流程
+ }
+}
+
+function Select-Device {
+ if ($Serial) {
+ Save-Serial $Serial
+ return $Serial
+ }
+
+ $devices = @(Get-ConnectedDevices)
+ if ($devices.Count -eq 0) {
+ throw '未检测到已连接设备。请检查 USB / 无线调试,或执行 adb devices 确认。'
+ }
+
+ $saved = Read-SavedSerial
+ if ($saved) {
+ foreach ($device in $devices) {
+ if ($device.Serial -eq $saved) {
+ Write-Step "使用上次选择的设备:$($device.Serial) $($device.Desc)(可用 -Serial 更换)"
+ return $device.Serial
+ }
+ }
+ }
+
+ if ($devices.Count -eq 1) {
+ Save-Serial $devices[0].Serial
+ Write-Step "使用设备:$($devices[0].Serial) $($devices[0].Desc)"
+ return $devices[0].Serial
+ }
+
+ Write-Host '[android] 检测到多台设备:' -ForegroundColor Cyan
+ for ($i = 0; $i -lt $devices.Count; $i++) {
+ Write-Host (" [{0}] {1} {2}" -f ($i + 1), $devices[$i].Serial, $devices[$i].Desc)
+ }
+
+ if (-not $Host.Name -or [Console]::IsInputRedirected) {
+ throw "多台设备时请用 -Serial 指定,例如:-Serial $($devices[0].Serial)"
+ }
+
+ $answer = Read-Host "请选择设备序号 [1-$($devices.Count)],直接回车取 1"
+ $index = 0
+ if ($answer) { $index = [int]$answer - 1 }
+ if ($index -lt 0 -or $index -ge $devices.Count) { throw "无效序号:$answer" }
+
+ Save-Serial $devices[$index].Serial
+ return $devices[$index].Serial
+}
+
+# ============================ 构建 ============================
+
+function Invoke-Gradle {
+ param([string[]]$Arguments)
+
+ $javaHome = Resolve-JavaHome
+ if ($javaHome) {
+ $env:JAVA_HOME = $javaHome
+ Write-Step "JAVA_HOME = $javaHome"
+ }
+ else {
+ Write-Warn '未探测到 JDK,若构建失败请手动设置 JAVA_HOME'
+ }
+
+ $gradlew = Join-Path $ProjectRoot 'gradlew.bat'
+ if (-not (Test-Path $gradlew)) { throw "未找到 gradlew.bat:$gradlew" }
+
+ Write-Step ("gradlew " + ($Arguments -join ' '))
+ $result = Invoke-Native $gradlew $Arguments
+ if ($result.ExitCode -ne 0) { throw "构建失败(gradlew 退出码 $($result.ExitCode))" }
+}
+
+function Get-ApkPath {
+ $dir = Join-Path $ProjectRoot "app\build\outputs\apk\$Variant"
+ $expected = Join-Path $dir "app-$Variant.apk"
+ if (Test-Path $expected) { return $expected }
+
+ if (Test-Path $dir) {
+ $latest = Get-ChildItem -Path $dir -Filter '*.apk' -ErrorAction SilentlyContinue |
+ Sort-Object LastWriteTime -Descending | Select-Object -First 1
+ if ($latest) { return $latest.FullName }
+ }
+ throw "未找到 APK:$expected"
+}
+
+function Invoke-Build {
+ if ($CleanFirst) { Invoke-Gradle @('clean', '--console=plain') }
+
+ $variantCap = $Variant.Substring(0, 1).ToUpper() + $Variant.Substring(1)
+ Invoke-Gradle @(":app:assemble$variantCap", '--console=plain')
+
+ $apk = Get-ApkPath
+ $size = [math]::Round((Get-Item $apk).Length / 1MB, 2)
+ Write-Ok "APK = $apk ($size MB)"
+ return $apk
+}
+
+# ============================ 装机 ============================
+
+function Install-Apk {
+ param([string]$TargetSerial, [string]$Apk)
+
+ $adb = Get-Adb
+ for ($attempt = 1; $attempt -le 3; $attempt++) {
+ Write-Step "adb install -r(第 $attempt/3 次)"
+ $result = Invoke-Native $adb @('-s', $TargetSerial, 'install', '-r', $Apk) -Quiet
+ Write-Host $result.Output.TrimEnd()
+ if ($result.ExitCode -eq 0) {
+ Write-Ok '安装成功'
+ return
+ }
+ if ($attempt -lt 3) { Start-Sleep -Seconds 2 }
+ }
+
+ # 老盒子(Android 7.1.2 等)的流式安装常报 fork failed,改用两段式
+ Write-Warn 'adb install 连续失败,降级为 push + pm install'
+ $remote = '/data/local/tmp/' + [System.IO.Path]::GetFileName($Apk)
+ $push = Invoke-Native $adb @('-s', $TargetSerial, 'push', $Apk, $remote) -Quiet
+ Write-Host $push.Output.TrimEnd()
+ if ($push.ExitCode -ne 0) { throw '推送到设备失败' }
+
+ $install = Invoke-Native $adb @('-s', $TargetSerial, 'shell', 'pm', 'install', '-r', $remote) -Quiet
+ Write-Host $install.Output.TrimEnd()
+ Invoke-Native $adb @('-s', $TargetSerial, 'shell', 'rm', '-f', $remote) -Quiet | Out-Null
+
+ if ($install.Output -notmatch 'Success') { throw 'pm install 失败,请查看上方设备输出' }
+ Write-Ok '安装成功(push + pm install)'
+}
+
+# ============================ 预置成系统应用 ============================
+
+# ============================ 启动 ============================
+
+function Start-App {
+ param([string]$TargetSerial)
+
+ $adb = Get-Adb
+ Invoke-Native $adb @('-s', $TargetSerial, 'shell', 'am', 'force-stop', $PackageName) -Quiet | Out-Null
+
+ $attempts = @(
+ [pscustomobject]@{
+ Name = 'am start -n'
+ Args = @('-s', $TargetSerial, 'shell', 'am', 'start', '-n', $ActivityName)
+ Expect = 'Starting:'
+ },
+ [pscustomobject]@{
+ Name = 'am start (LEANBACK)'
+ Args = @('-s', $TargetSerial, 'shell', 'am', 'start', '-a', 'android.intent.action.MAIN',
+ '-c', 'android.intent.category.LEANBACK_LAUNCHER', '-n', $ActivityName)
+ Expect = 'Starting:'
+ },
+ [pscustomobject]@{
+ Name = 'monkey'
+ Args = @('-s', $TargetSerial, 'shell', 'monkey', '-p', $PackageName,
+ '-c', 'android.intent.category.LAUNCHER', '1')
+ Expect = 'Events injected'
+ }
+ )
+
+ foreach ($attempt in $attempts) {
+ $result = Invoke-Native $adb $attempt.Args -Quiet
+ if ($result.ExitCode -eq 0 -and $result.Output -match [regex]::Escape($attempt.Expect)) {
+ Write-Ok "已启动应用($($attempt.Name))"
+ return $true
+ }
+
+ $firstLine = ($result.Output -split "`r?`n" | Where-Object { $_.Trim() } | Select-Object -First 1)
+ Write-Warn "$($attempt.Name) 未成功:$firstLine"
+ }
+
+ Write-Warn '自动启动失败。部分海思/定制固件的 am 与 monkey 都会报 AMS 空指针,'
+ Write-Warn '本机无法绕过,请用遥控器手动打开「扫描中心」。'
+ return $false
+}
+
+# ============================ 日志 ============================
+
+function Start-Logcat {
+ param([string]$TargetSerial)
+
+ $adb = Get-Adb
+ Invoke-Native $adb @('-s', $TargetSerial, 'logcat', '-c') -Quiet | Out-Null
+
+ Write-Step "跟随日志中(tag=$LogTag,含崩溃栈),Ctrl+C 退出"
+ Write-Host ("[android] 单独抓取:`"$adb`" -s $TargetSerial logcat -v time $LogTag`:V AndroidRuntime:E `*:S") -ForegroundColor DarkGray
+
+ $previous = $ErrorActionPreference
+ $ErrorActionPreference = 'Continue'
+ try {
+ & $adb -s $TargetSerial logcat -v time "$($LogTag):V" 'AndroidRuntime:E' '*:S'
+ }
+ finally {
+ $ErrorActionPreference = $previous
+ }
+}
+
+# ============================ 帮助 ============================
+
+function Show-Help {
+ Write-Host @'
+AndroidStation 设备端真机调试脚手架
+
+用法:
+ powershell -NoProfile -ExecutionPolicy Bypass -File tools\android.ps1 <任务> [选项]
+
+任务:
+ build 仅构建 APK
+ install 构建 + 安装
+ run 构建 + 安装 + 启动
+ dev 构建 + 安装 + 启动 + 跟随日志(日常开发用这个)
+ logs 只跟随日志(不构建)
+ clean 清理构建产物
+ devices 列出已连接设备与当前记住的设备
+ help 显示本帮助
+
+选项:
+ -Variant debug|release 构建类型,默认 debug
+ -Serial <序列号> 指定设备(默认自动选择,多设备时记住上次选择)
+ -CleanFirst 构建前先执行 gradle clean(全量重编)
+ -NoLaunch 不自动启动应用
+ -NoLogcat 不跟随日志
+
+示例:
+ ... -File tools\android.ps1 dev
+ ... -File tools\android.ps1 install -Serial 4235737
+ ... -File tools\android.ps1 dev -CleanFirst
+ ... -File tools\android.ps1 run -Variant release
+'@
+}
+
+function Show-Devices {
+ $devices = @(Get-ConnectedDevices)
+ $saved = Read-SavedSerial
+
+ if ($devices.Count -eq 0) {
+ Write-Warn '未检测到已连接设备'
+ return
+ }
+
+ Write-Host '[android] 已连接设备:' -ForegroundColor Cyan
+ foreach ($device in $devices) {
+ $mark = ''
+ if ($saved -and $device.Serial -eq $saved) { $mark = ' <- 当前记住' }
+ Write-Host (" {0} {1}{2}" -f $device.Serial, $device.Desc, $mark)
+ }
+}
+
+# ============================ 主流程 ============================
+
+Set-Location $ProjectRoot
+
+try {
+ switch ($Task) {
+ 'help' { Show-Help }
+
+ 'devices' { Show-Devices }
+
+ 'clean' {
+ Invoke-Gradle @('clean', '--console=plain')
+ Write-Ok '已清理'
+ }
+
+ 'build' {
+ $apk = Invoke-Build
+ # 单独输出一遍路径到管道,便于其它脚本捕获
+ Write-Output $apk
+ }
+
+ 'install' {
+ $apk = Invoke-Build
+ Install-Apk -TargetSerial (Select-Device) -Apk $apk
+ }
+
+ 'run' {
+ $apk = Invoke-Build
+ $target = Select-Device
+ Install-Apk -TargetSerial $target -Apk $apk
+ if (-not $NoLaunch) { Start-App -TargetSerial $target | Out-Null }
+ if (-not $NoLogcat) { Start-Logcat -TargetSerial $target }
+ }
+
+ 'dev' {
+ $apk = Invoke-Build
+ $target = Select-Device
+ Install-Apk -TargetSerial $target -Apk $apk
+ if (-not $NoLaunch) { Start-App -TargetSerial $target | Out-Null }
+ if (-not $NoLogcat) { Start-Logcat -TargetSerial $target }
+ else { Write-Ok '完成(-NoLogcat 未跟随日志)' }
+ }
+
+ 'logs' {
+ Start-Logcat -TargetSerial (Select-Device)
+ }
+ }
+}
+catch {
+ Write-Host "[android] 失败:$($_.Exception.Message)" -ForegroundColor Red
+ exit 1
+}
diff --git a/AndroidStation/tools/fetch-voice-seeds.ps1 b/AndroidStation/tools/fetch-voice-seeds.ps1
new file mode 100644
index 0000000..33f8088
--- /dev/null
+++ b/AndroidStation/tools/fetch-voice-seeds.ps1
@@ -0,0 +1,150 @@
+<#
+.SYNOPSIS
+ 从语音服务一次性抓取播报种子,转换成 Android res/raw 可直接使用的 WAV。
+
+.DESCRIPTION
+ 设备上没有中文 TTS 引擎(只有 PicoTts,无中文数据),所以播报必须在本地做。
+ 这个脚本把「0-9、A-Z、开始打包」逐条请求语音服务,下载 WAV 并统一转成
+ 44.1kHz / 立体声 / 16-bit PCM(与设备 AudioFlinger 输出一致),
+ 去掉首尾静音并提到 1.25x 语速,放到 app/src/main/res/raw/voice_*.wav。
+ 运行时只读本地资源,断网也能播报。
+
+.EXAMPLE
+ powershell -NoProfile -ExecutionPolicy Bypass -File tools\fetch-voice-seeds.ps1
+
+.EXAMPLE
+ powershell -NoProfile -ExecutionPolicy Bypass -File tools\fetch-voice-seeds.ps1 -Force
+#>
+[CmdletBinding()]
+param(
+ [string]$BaseUrl = 'http://tbdata.gztbyc.com',
+
+ [string]$OutDir = '',
+
+ [string]$Ffmpeg = 'D:\packService\desktop\native\ffmpeg\ffmpeg.exe',
+
+ # 只重新抓某几个 key(例如 -Only welcome);不传则抓全部
+ [string[]]$Only = @(),
+
+ [switch]$Force
+)
+
+$ErrorActionPreference = 'Stop'
+
+if (-not $OutDir) {
+ $scriptDir = if ($PSScriptRoot) { $PSScriptRoot } else { Split-Path -Parent $MyInvocation.MyCommand.Path }
+ $OutDir = Join-Path $scriptDir '..\app\src\main\res\raw'
+}
+
+if (-not (Test-Path $Ffmpeg)) {
+ throw "找不到 ffmpeg:$Ffmpeg(可用 -Ffmpeg 指定)"
+}
+New-Item -ItemType Directory -Force -Path $OutDir | Out-Null
+
+# key = 资源文件名后缀(必须是小写字母/数字/下划线),value = 送给语音服务的文本
+$tokens = [ordered]@{
+ '0' = '零'
+ '1' = '一'
+ '2' = '二'
+ '3' = '三'
+ '4' = '四'
+ '5' = '五'
+ '6' = '六'
+ '7' = '七'
+ '8' = '八'
+ '9' = '九'
+ 'a' = 'A'
+ 'b' = 'B'
+ 'c' = 'C'
+ 'd' = 'D'
+ 'e' = 'E'
+ 'f' = 'F'
+ 'g' = 'G'
+ 'h' = 'H'
+ 'i' = 'I'
+ 'j' = 'J'
+ 'k' = 'K'
+ 'l' = 'L'
+ 'm' = 'M'
+ 'n' = 'N'
+ 'o' = 'O'
+ 'p' = 'P'
+ 'q' = 'Q'
+ 'r' = 'R'
+ 's' = 'S'
+ 't' = 'T'
+ 'u' = 'U'
+ 'v' = 'V'
+ 'w' = 'W'
+ 'x' = 'X'
+ 'y' = 'Y'
+ 'z' = 'Z'
+ 'start_pack' = '开始打包'
+ 'welcome' = '欢迎使用溯源系统,初始化已经完成,扫码即可开始打包'
+}
+
+function Get-VoiceSeed {
+ param([string]$Text)
+
+ $encoded = [Uri]::EscapeDataString($Text)
+ $uri = "$BaseUrl/voice/$encoded"
+ $lastError = $null
+
+ for ($attempt = 1; $attempt -le 3; $attempt++) {
+ try {
+ $json = Invoke-RestMethod -Uri $uri -TimeoutSec 30
+ if (-not $json.audio) {
+ throw '接口没有返回 audio 路径'
+ }
+ $audioUri = $BaseUrl + $json.audio
+ $bytes = (Invoke-WebRequest -UseBasicParsing -Uri $audioUri -TimeoutSec 60).Content
+ if (-not $bytes -or $bytes.Length -lt 1024) {
+ throw "音频太小($($bytes.Length) 字节)"
+ }
+ return $bytes
+ }
+ catch {
+ $lastError = $_.Exception.Message
+ Start-Sleep -Seconds (1 * $attempt)
+ }
+ }
+ throw "抓取「$Text」失败:$lastError"
+}
+
+$total = $tokens.Count
+$index = 0
+foreach ($key in $tokens.Keys) {
+ $index++
+ if ($Only.Count -gt 0 -and $Only -notcontains $key) {
+ continue
+ }
+ $text = $tokens[$key]
+ $target = Join-Path $OutDir "voice_$key.wav"
+ if ((Test-Path $target) -and -not $Force) {
+ Write-Host ("[{0}/{1}] 跳过 {2}(已存在)" -f $index, $total, $target) -ForegroundColor DarkGray
+ continue
+ }
+
+ Write-Host ("[{0}/{1}] {2} -> voice_{3}.wav" -f $index, $total, $text, $key) -ForegroundColor Cyan
+ $bytes = Get-VoiceSeed -Text $text
+
+ $temp = Join-Path $env:TEMP "voice-seed-$key-raw.wav"
+ [IO.File]::WriteAllBytes($temp, $bytes)
+
+ # 去掉首尾静音并把语速提到 1.25x(保持音调),播报更跟手
+ $filter = 'silenceremove=start_periods=1:start_duration=0.02:start_threshold=-45dB:stop_periods=-1:stop_duration=0.02:stop_threshold=-45dB,atempo=1.25'
+ # 设备音频输出固定 44100Hz 立体声;种子也统一成这个格式,老 rk3288 的 AudioTrack 才认
+ & $Ffmpeg -y -loglevel error -i $temp -af $filter -ac 2 -ar 44100 -acodec pcm_s16le $target
+ if ($LASTEXITCODE -ne 0 -or -not (Test-Path $target)) {
+ throw "ffmpeg 转换失败:$text"
+ }
+
+ $size = (Get-Item $target).Length
+ Write-Host (" {0} 字节" -f $size) -ForegroundColor DarkGray
+ Remove-Item -Force $temp -ErrorAction SilentlyContinue
+}
+
+Write-Host ''
+Write-Host '语音种子已就绪:' -ForegroundColor Green
+Get-ChildItem $OutDir -Filter 'voice_*.wav' | Sort-Object Name |
+ Select-Object Name, Length | Format-Table -AutoSize
diff --git a/AndroidStation/tools/udp-listen.ps1 b/AndroidStation/tools/udp-listen.ps1
new file mode 100644
index 0000000..2071000
--- /dev/null
+++ b/AndroidStation/tools/udp-listen.ps1
@@ -0,0 +1,301 @@
+<#
+.SYNOPSIS
+ 监听指定 UDP 端口,打印收到的每一个报文,用于分析局域网设备的广播协议。
+
+.DESCRIPTION
+ 用在「设备发现」的前期调研:把设备发出的广播原样抓下来,看它的
+ 载荷格式、广播地址与频率,再去写解析代码。
+
+ 每个报文会输出:
+ - 时间、来源 IP:端口、字节数
+ - 十六进制(前 256 字节)
+ - ASCII 可打印视图(不可打印字符显示为 .)
+ - UTF-8 与 GB18030 两种解码结果(中文设备常见两种编码)
+
+.EXAMPLE
+ powershell -NoProfile -ExecutionPolicy Bypass -File tools\udp-listen.ps1 -Minutes 5
+
+.EXAMPLE
+ powershell -NoProfile -ExecutionPolicy Bypass -File tools\udp-listen.ps1 -Probe -Minutes 2
+
+.EXAMPLE
+ powershell -NoProfile -ExecutionPolicy Bypass -File tools\udp-listen.ps1 -Port 48899 -Minutes 3 -OutFile D:\packets.log
+#>
+[CmdletBinding()]
+param(
+ [int]$Port = 48899,
+
+ [double]$Minutes = 5,
+
+ [string]$OutFile = '',
+
+ # 主动探测:自己发广播,并在同一个 socket 上收回复。
+ # 被动监听收不到设备回复——回包发往「广播的源端口」,不是 48899。
+ [switch]$Probe,
+
+ # 主动探测的重复间隔(毫秒),默认与官方工具 SCAN_INTERVAL=2999 一致
+ [int]$Interval = 3000,
+
+ # 探测载荷,默认用抓包得到的官方报文
+ [string]$Payload = ''
+)
+
+$ErrorActionPreference = 'Stop'
+
+if (-not $OutFile) {
+ $stamp = Get-Date -Format 'yyyyMMdd-HHmmss'
+ $OutFile = Join-Path $env:TEMP "udp-$Port-$stamp.log"
+}
+
+$lines = New-Object System.Collections.Generic.List[string]
+
+function Emit([string]$Text) {
+ Write-Host $Text
+ [void]$lines.Add($Text)
+}
+
+function Hex-Dump([byte[]]$Bytes, [int]$MaxBytes) {
+ $take = [Math]::Min($Bytes.Length, $MaxBytes)
+ $parts = @()
+ for ($i = 0; $i -lt $take; $i++) {
+ $parts += $Bytes[$i].ToString('X2')
+ }
+ $text = ($parts -join ' ')
+ if ($Bytes.Length -gt $MaxBytes) {
+ $text += " ... (后续 " + ($Bytes.Length - $MaxBytes) + " 字节省略)"
+ }
+ return $text
+}
+
+function Ascii-View([byte[]]$Bytes, [int]$MaxBytes) {
+ $take = [Math]::Min($Bytes.Length, $MaxBytes)
+ $chars = @()
+ for ($i = 0; $i -lt $take; $i++) {
+ $b = $Bytes[$i]
+ if ($b -ge 32 -and $b -lt 127) { $chars += [char]$b } else { $chars += '.' }
+ }
+ return (-join $chars)
+}
+
+# ---------------- 本机网络情况 ----------------
+
+Emit ("=" * 72)
+Emit "UDP 监听端口 : $Port"
+Emit "监听时长 : $Minutes 分钟"
+Emit "输出文件 : $OutFile"
+Emit ("=" * 72)
+Emit "本机 IPv4 地址(确认与目标设备在同一网段):"
+$localIps = @()
+$broadcastAddrs = @()
+try {
+ $netAddrs = @(Get-NetIPAddress -AddressFamily IPv4 -ErrorAction SilentlyContinue |
+ Where-Object { $_.IPAddress -ne '127.0.0.1' })
+ $localIps = @($netAddrs | ForEach-Object { $_.IPAddress })
+
+ $broadcastAddrs = @($netAddrs | ForEach-Object {
+ $prefix = $_.PrefixLength
+ $bytes = [System.Net.IPAddress]::Parse($_.IPAddress).GetAddressBytes()
+ $mask = 0
+ for ($i = 0; $i -lt $prefix; $i++) { $mask = $mask -bor (1 -shl (31 - $i)) }
+ $maskBytes = [System.BitConverter]::GetBytes([int]$mask)
+ [array]::Reverse($maskBytes)
+ $bcast = @()
+ for ($i = 0; $i -lt 4; $i++) { $bcast += ($bytes[$i] -bor ($maskBytes[$i] -bxor 255)) }
+ ($bcast -join '.')
+ })
+
+ for ($i = 0; $i -lt $netAddrs.Count; $i++) {
+ Emit (" {0}/{1} 广播地址 {2}" -f $netAddrs[$i].IPAddress, $netAddrs[$i].PrefixLength, $broadcastAddrs[$i])
+ }
+}
+catch {
+ Emit " (无法枚举网卡:$($_.Exception.Message))"
+}
+Emit ""
+
+# ---------------- 探测载荷 ----------------
+
+# 抓包得到的官方 IOTService 广播报文(明文 JSON)。
+# ⚠️ ConnectMode 必须保持 Forbidden:它决定设备是否顺带改写自己的服务器地址,
+# 改成别的值可能把现场设备的配置改掉。
+$DEFAULT_PAYLOAD = '{"Agent":0,"Type":"EP_Tool","PasswordEn":0,"ServPort":0,"Version":"3.1.3f","ConnectMode":"Forbidden","Zone":"EPort","ServEn":1,"ServAddr":"0.0.0.0","ClientEn":0}'
+
+if (-not $Payload) { $Payload = $DEFAULT_PAYLOAD }
+$payloadBytes = [System.Text.Encoding]::UTF8.GetBytes($Payload)
+
+# ---------------- 建立 socket ----------------
+
+$client = $null
+$targets = @()
+
+try {
+ $client = New-Object System.Net.Sockets.UdpClient
+ $client.ExclusiveAddressUse = $false
+ $client.Client.SetSocketOption(
+ [System.Net.Sockets.SocketOptionLevel]::Socket,
+ [System.Net.Sockets.SocketOptionName]::ReuseAddress,
+ $true)
+
+ if ($Probe) {
+ # 绑到临时端口(0 = 由系统分配)。
+ # 设备把回复发回「广播的源端口」,所以必须用同一个 socket 发送与接收——
+ # 绑到 48899 是收不到回复的。
+ $client.Client.Bind((New-Object System.Net.IPEndPoint([System.Net.IPAddress]::Any, 0)))
+ $client.EnableBroadcast = $true
+
+ # 255.255.255.255 与各网卡的子网广播都发一遍(官方工具也是每块网卡各发一次)
+ $targets = @($targets + '255.255.255.255' + $broadcastAddrs | Select-Object -Unique)
+ Emit "主动探测模式:发往 $($targets -join '、'),端口 $Port,间隔 $Interval ms"
+ }
+ else {
+ $client.Client.Bind((New-Object System.Net.IPEndPoint([System.Net.IPAddress]::Any, $Port)))
+ Emit "被动监听模式:只收不发(注意:此模式收不到设备回复,只会看到别的工具发出的广播)"
+ }
+}
+catch {
+ Write-Host "绑定失败:$($_.Exception.Message)" -ForegroundColor Red
+ Write-Host "可能原因:端口被占用(先关掉占用程序),或需要管理员权限。" -ForegroundColor Yellow
+ if ($client) { $client.Close() }
+ exit 1
+}
+
+Emit "已开始(Ctrl+C 可提前结束)"
+Emit ""
+
+# 主动探测时用较短的接收超时,保证探测节奏准确
+if ($Probe) {
+ $client.Client.ReceiveTimeout = [Math]::Max(100, [Math]::Min(500, $Interval))
+}
+else {
+ $client.Client.ReceiveTimeout = 1000
+}
+
+$deadline = (Get-Date).AddMinutes($Minutes)
+$nextProbe = (Get-Date)
+$probeCount = 0
+$total = 0
+$sources = @{}
+$payloads = @{}
+$utf8 = New-Object System.Text.UTF8Encoding($false)
+try {
+ $gbk = [System.Text.Encoding]::GetEncoding('GB18030')
+}
+catch {
+ $gbk = $null
+}
+
+try {
+ while ((Get-Date) -lt $deadline) {
+
+ # 主动探测:到点就再广播一次(设备可能后上电,或上一个包丢了)
+ if ($Probe -and (Get-Date) -ge $nextProbe) {
+ foreach ($target in $targets) {
+ try {
+ [void]$client.Send($payloadBytes, $payloadBytes.Length,
+ (New-Object System.Net.IPEndPoint([System.Net.IPAddress]::Parse($target), $Port)))
+ }
+ catch {
+ Emit (" 广播到 {0} 失败:{1}" -f $target, $_.Exception.Message)
+ }
+ }
+ $probeCount++
+ Emit ("[{0}] 第 {1} 次探测已发出({2} 字节)" -f (Get-Date -Format 'HH:mm:ss.fff'), $probeCount, $payloadBytes.Length)
+ $nextProbe = (Get-Date).AddMilliseconds($Interval)
+ }
+
+ $remote = New-Object System.Net.IPEndPoint([System.Net.IPAddress]::Any, 0)
+ $data = $null
+
+ try {
+ $data = $client.Receive([ref]$remote)
+ }
+ catch [System.Net.Sockets.SocketException] {
+ if ($_.Exception.SocketErrorCode -eq [System.Net.Sockets.SocketError]::TimedOut) {
+ continue
+ }
+ throw
+ }
+
+ $total++
+ $key = "$($remote.Address):$($remote.Port)"
+ if (-not $sources.ContainsKey($key)) { $sources[$key] = 0 }
+ $sources[$key]++
+
+ $ascii = Ascii-View $data 256
+ if (-not $payloads.ContainsKey($ascii)) { $payloads[$ascii] = 0 }
+ $payloads[$ascii]++
+
+ Emit ("[{0}] #{1} 来自 {2} 共 {3} 字节" -f (Get-Date -Format 'HH:mm:ss.fff'), $total, $key, $data.Length)
+
+ # 来源是本机地址时,说明是本机某个进程在广播 —— 顺手把进程揪出来
+ if ($localIps -contains $remote.Address.ToString()) {
+ $owner = $null
+ try {
+ $owner = Get-NetUDPEndpoint -LocalPort $remote.Port -ErrorAction SilentlyContinue
+ }
+ catch {
+ $owner = $null
+ }
+ if ($owner) {
+ $proc = Get-Process -Id $owner.OwningProcess -ErrorAction SilentlyContinue
+ Emit (" ↑ 本机进程:PID {0} {1} {2}" -f $owner.OwningProcess, $proc.ProcessName, $proc.Path)
+ }
+ else {
+ Emit " ↑ 来自本机,但发送方端口已关闭(瞬时 socket,发完即关)"
+ }
+ }
+
+ Emit (" HEX : " + (Hex-Dump $data 256))
+ Emit (" ASCII : " + $ascii)
+ Emit (" UTF-8 : " + $utf8.GetString($data))
+ if ($gbk) {
+ Emit (" GBK : " + $gbk.GetString($data))
+ }
+ Emit ""
+ }
+}
+finally {
+ $client.Close()
+
+ Emit ("=" * 72)
+ Emit "监听结束,共发出 $probeCount 次探测,收到 $total 个报文"
+ if ($total -gt 0) {
+ Emit ""
+ Emit "来源统计:"
+ foreach ($k in ($sources.Keys | Sort-Object)) {
+ Emit (" {0} {1} 个" -f $k, $sources[$k])
+ }
+ Emit ""
+ Emit "载荷去重(相同内容只列一次,附出现次数):"
+ foreach ($k in ($payloads.Keys | Sort-Object)) {
+ Emit (" x{0} {1}" -f $payloads[$k], $k)
+ }
+ }
+ else {
+ Emit "没收到任何报文。排查方向:"
+ if ($Probe) {
+ Emit " 1. 设备是否真的在线且在同一网段(跨网段/VLAN 收不到广播)"
+ Emit " 2. Windows 防火墙是否拦了入站 UDP —— 探测包的回复是发回本机临时端口的,"
+ Emit " 没有放行的话会静默丢弃(这是最常见的原因)"
+ Emit " 3. AP/交换机是否开了客户端隔离(AP isolation)"
+ Emit " 4. 设备是否设了密码(PasswordEn=1)—— 那时收发都是 AES 密文,不会回明文"
+ Emit " 5. 端口号是否正确"
+ }
+ else {
+ Emit " 1. 被动模式只能看到别人发出的广播;设备回复是发往广播源端口的,本模式收不到"
+ Emit " → 想抓回复请加 -Probe"
+ Emit " 2. 设备是否真的会主动广播(有些设备只在被询问后才回应)"
+ Emit " 3. Windows 防火墙 / 网段 / VLAN 问题"
+ }
+ }
+ Emit ("=" * 72)
+
+ try {
+ [System.IO.File]::WriteAllLines($OutFile, $lines, (New-Object System.Text.UTF8Encoding($false)))
+ Write-Host ""
+ Write-Host "完整日志已写入:$OutFile"
+ }
+ catch {
+ Write-Host "写日志失败:$($_.Exception.Message)" -ForegroundColor Yellow
+ }
+}
diff --git a/README.md b/README.md
index 97beace..a87bfd2 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,6 @@
# 云仓视频溯源系统
-前后端分离 + 一个浏览器扩展 + 一个 Windows 本机软件(WPF)+ 一个微信小程序,五个目录:
+前后端分离 + 一个浏览器扩展 + 一个 Windows 本机软件(WPF)+ 一个微信小程序 + 一个 Android 设备端,六个目录:
```
packService/
@@ -8,7 +8,8 @@ packService/
├── frontend/ # Vite + Vue3 + TypeScript(用户端 SPA)
├── miniprogram/ # uni-app + Vue3 + TypeScript(微信小程序:抽屉登录(个人中心为整页登录)/ 协议弹窗 / 首页统计 / 扫码记录 / 我的)
├── extension/ # Chrome MV3 扩展:注入第三方 WMS 页面,把运单号加工成溯源入口
-└── desktop/ # WPF 本机软件:HTTP 17300(查询/唤起/下载)+ WS 17301(拉通道/预览/云台)+ yuncang:// 启动协议
+├── desktop/ # WPF 本机软件:HTTP 17300(查询/唤起/下载)+ WS 17301(拉通道/预览/云台)+ yuncang:// 启动协议
+└── AndroidStation/ # Android 设备端:UDP 48899 被桌面端发现 + TCP 8087 推送 USB 扫码结果
```
## 端口约定(⚠️ 本机项目多,不要用 Vite 默认的 5173)
@@ -26,7 +27,12 @@ packService/
- 后端端口可用 `PORT=7400 npm run dev` 覆盖(默认 **7300**,配置在 `backend/config/config.default.js` 的 `config.cluster.listen.port`)。
- 前端调接口走**同源代理**:Vite 把 `/api`、`/health` 反代到后端(默认 `127.0.0.1:7300`,用 `VITE_BACKEND` 覆盖)。
- 联调更方便的做法:直接开后端 `:7300`,由后端(dev)把 `/` 反代到前端 dev server(`FRONTEND_DEV_SERVER`,默认 `http://127.0.0.1:7301`)。
-- **上线**:后端托管 `frontend/dist`(静态资源 + SPA fallback),`/` 出前端、`/api/*` 出 JSON。
+- **上线**:前端构建产物发布到 `deployRoot/frontend`,由 **nginx 直接托管**(静态资源 + SPA fallback);`/api/*`、`/health` 由 nginx 反代到 Egg,`/download/*` 由 nginx 直接托管安装包目录。发布走 `cd backend && npm run deploy`(双实例蓝绿发布,详见 [`backend/README.md`](backend/README.md)「发布到服务器」)。
+- **安装包分发**(`/download/` 由 nginx 直接托管):桌面端 MSI 在 `/download/desktop/`、Android APK 在 `/download/android_client/`,
+ 版本信息分别是 `/download/version.json`(桌面端自动更新读这个地址,不能改)和 `/download/android_client/version.json`。
+ 单独发版:`cd backend && npm run desktop:publish` / `npm run android:publish`(都只构建+上传,不动后端)。
+- **生产强制 HTTPS**:站点 vhost 对 HTTP 一律 `301` 到 HTTPS,HSTS 由 `front.conf` 各 location 声明;后端 `config.proxy = true`,`SITE_URL` / `desktopBaseUrl` 均为 `https://`,桌面端安装包内嵌地址也是 HTTPS。
+- **AndroidStation 设备端**不用这些开发端口:它在局域网上监听 **TCP 8087**(桌面端读扫码结果)和 **UDP 48899**(被桌面端发现),详见 [`AndroidStation/README.md`](AndroidStation/README.md)。
## 身份与通讯约定
@@ -46,8 +52,8 @@ packService/
- [x] 小程序脚手架 `miniprogram/`(uni-app + Vue3 + TS):微信一键登录(code2Session)+ 账号登录双 tab / 首页统计 / 扫码记录 / 个人中心;登录前需阅读并同意协议(版本落库);不强制登录(启动不弹窗,点功能或 401 才提示,符合小程序审核)
- [x] 浏览器扩展 `extension/`(MV3,零构建):注入第三方 WMS 页面,在运单号**旁边**渲染「查看打包视频」按钮 → 点按钮打开溯源页
- [x] **后端去掉服务端渲染**:删除 `app/controller/page/`、`app/view/`、`app/lib/page.js`、nunjucks / session / CSRF 配置与依赖,后端只剩 JSON 接口
-- [x] 页面全部迁移到前端:登录 / 注册 / 找回密码 / 扫码 / 扫码确认 / 首页统计 / 设备管理 / 扫码记录 / 个人中心 / 测试页
-- [x] 后端 dev 反代前端(`app/middleware/frontend.js`)+ 生产托管 `frontend/dist`(SPA 深链回退)
+- [x] 页面全部迁移到前端:登录 / 注册 / 找回密码 / 扫码 / 扫码确认 / 首页统计 / 设备管理 / 扫码记录 / 个人中心 / 测试页(仅开发构建,生产不打包)
+- [x] 后端 dev 反代前端(`app/middleware/frontend.js`);生产由 nginx 直接托管前端构建产物(Egg 只提供 API)
- [x] 运维接口加鉴权:`app/controller/admin/` → `internal/`,统一挂 `middleware.internalAuth()`
- [x] 新增用户端接口:`/api/web/{stats,devices*,records,test/*}`(范围一律限定在令牌对应的那个用户)
- [ ] 扩展:目标地址换成真实打包视频页(现在指向百度占位)—— 在扩展「设置」里改「目标地址模板」即可,需要真实地址
@@ -76,7 +82,7 @@ packService/
cd frontend
npm run dev # 7301(VITE_PORT 可覆盖)
npm run typecheck # vue-tsc --noEmit
-npm run build # typecheck + vite build(产物 dist/,后端生产模式托管)
+npm run build # typecheck + vite build(产物 dist/,发布时由 nginx 直接托管)
```
@@ -86,7 +92,7 @@ npm run build # typecheck + vite build(产物 dist/,后端生产模式
| --- | --- | --- |
| `PORT` | `7300` | 后端监听端口 |
| `FRONTEND_DEV_SERVER` | `http://127.0.0.1:7301` | 开发时把页面请求反代到哪里 |
-| `FRONTEND_DIST` | `frontend/dist` | 生产托管的前端构建产物目录 |
+| `FRONTEND_DIST` | `frontend/dist` | 仅当让 Egg 托管前端时使用(默认由 nginx 托管,`FRONTEND_ENABLE=false`) |
| `FRONTEND_ENABLE` | `true` | 关掉后后端不管页面(纯接口模式) |
| `INTERNAL_TOKEN` | 空 | 运维接口的静态令牌(header `X-Internal-Token`);不配就只能靠白名单账号的 user JWT |
| `INTERNAL_ADMIN_IDS` | `1` | 哪些用户 id 能调运维接口(逗号分隔) |
diff --git a/backend/README.md b/backend/README.md
index 0e0b26f..41f0ff2 100644
--- a/backend/README.md
+++ b/backend/README.md
@@ -34,7 +34,7 @@ packService/backend
│ │ │ ├── stats.js # /api/web/stats 首页统计(按当前用户)
│ │ │ ├── device.js # /api/web/devices* 我的设备(列表/详情/通道/解绑/删除)
│ │ │ ├── record.js # /api/web/records 我的扫码记录(按自己设备过滤)
-│ │ │ └── test.js # /api/web/test/{device-login,scan} 前端测试页的模拟接口
+│ │ │ └── test.js # /api/web/test/{device-login,scan} 前端测试页的模拟接口(仅非生产环境注册)
│ │ ├── internal/ # 运维/内部(❗需内部令牌,挂在 middleware.internalAuth() 后面)
│ │ │ ├── user.js # /api/users* 用户 CRUD(含缓存)
│ │ │ ├── wechat.js # /api/wechat/:appid/:openid、bind、tokens、解绑、用户的授权列表
@@ -159,6 +159,19 @@ npm run db:deploy # ① 建库(有权限时) ② 基线表 sql/schema
npm run db:deploy -- --check # 只检查(列出未执行的迁移;有 pending 时退出码 1),适合上线前/CI 卡一道
```
+### 生产库迁移(本地执行,目标 = 生产库)
+
+生产 MySQL 账号是 `packservice@localhost`,只能从服务器本机登录,所以脚本会先建 **SSH 隧道**再跑同一套迁移:
+
+```bash
+npm run db:check:prod # 只检查生产库还有哪些迁移没执行(不改库)
+npm run db:deploy:prod # 基线表 + 全部未执行迁移(幂等,可反复跑)
+```
+
+- 连接信息来自本机 `config/env.prod.sh`(`MYSQL_*`),SSH 信息来自 `config/deploy.config.local.cjs`;
+- 隧道:`127.0.0.1:<随机端口> → <服务器>:127.0.0.1:3306`,执行完自动关闭;
+- 显式设置的 `MYSQL_*` 环境变量优先于 `config.local.js`(不会被本机开发库密码覆盖)。
+
规则(**所有迁移脚本都保留在仓库里,不删不改**):
| 位置 | 作用 | 什么时候跑 |
@@ -169,11 +182,166 @@ npm run db:deploy -- --check # 只检查(列出未执行的迁移;有 pendin
| `scripts/backfill-snapshot.js`、`scripts/dedupe-scan-records.js` | 一次性数据修复(需带参数,可 `--dry-run`) | 按需手动,不是部署必跑 |
执行顺序固定为「基线表 → 迁移(按文件名升序)」,所以新库和老库走同一条命令,结果一致;
-连接信息与运行时同源(环境变量 > `config/config.local.js` > 默认值)。
+连接信息与运行时同源(环境变量 > `config/config.prod.js`(`EGG_SERVER_ENV=prod`)> `config/config.local.js` > 默认值)。
> 生产库如果由 DBA 预建、且应用账号没有建库权限,`db:deploy` 会打印一行「跳过建库」后继续,不影响后续迁移。
+## 发布到服务器(npm run deploy)
+
+参考 `D:\wms` 的双实例蓝绿发布:`v1` / `v2` 两个目录轮流发布,新实例健康检查(`/health`)通过后才切 Nginx upstream,再停旧实例;失败会回滚 `current.md` 并保留旧实例继续服务。
+
+### 一次性准备
+
+1. 本机:Node 18+、git、tar(Win10/11 自带 bsdtar)、OpenSSH Client(`ssh` / `scp`)。
+2. 填写发布配置 `config/deploy.config.local.cjs`(该文件已被 `.gitignore` 忽略;若缺失可从模板复制):
+
+ ```powershell
+ cd backend
+ # 已存在则直接编辑;缺失时:
+ Copy-Item config/deploy.config.example.cjs config/deploy.config.local.cjs
+ ```
+
+3. 服务器目录结构(首次发布时脚本会自动建 `v1` / `v2` / `.deploy` / `shared-config`):
+
+ ```
+ /www/wwwroot/packService/
+ ├── current.md # 内容只能是 v1 或 v2
+ ├── nginx-upstream.conf # 只有一行:proxy_pass http://127.0.0.1:7301;(API 端口)
+ ├── front.conf # nginx 前端静态 + /api、/health 反代 + /download 静态(自动维护)
+ ├── frontend/ # 前端构建产物(nginx 直接托管)
+ ├── frontend.prev/ # 上一版前端(回退用)
+ ├── download/ # 安装包分发(nginx 直接托管)
+ │ ├── version.json # 桌面端版本信息(不缓存,客户端写死这个地址)
+ │ ├── desktop/ # 桌面端 MSI(长缓存)
+ │ └── android_client/ # Android APK + version.json
+ ├── shared-config/ # 服务端私有配置(不随发布包走)
+ │ └── env.prod.sh # 启动前 source 的环境变量
+ ├── v1/ v2/ # 两个后端发布目录
+ └── .deploy/ # incoming / backups / state
+ ```
+
+ 站点 vhost 里只需要 include 一次前端/反代配置:
+
+ ```nginx
+ server {
+ server_name pack.example.com;
+
+ # 前端静态 + /api、/health 反代 + /download 静态,全部由 front.conf 维护
+ include /www/wwwroot/packService/front.conf;
+ }
+ ```
+
+ > `front.conf` 由 `npm run deploy` 自动生成;`nginx-upstream.conf` 里的端口在发布健康检查通过后切换。
+ > 首次发布前先创建 `current.md`(内容 `v1` 或 `v2`);发布总是部署到**另一个**目录。
+
+ > 生产站点强制 HTTPS:vhost 里对 `$scheme != https` 直接 `return 301 https://$host$request_uri`,
+ > 且 `front.conf` 的每个带 `add_header` 的 location 都会重复声明 `Strict-Transport-Security`
+ > (nginx 的 `add_header` 一旦在 location 内出现,就不再继承 server 级配置)。
+
+4. **服务端私有配置放在 `shared-config/`,不要改版本目录里的 `config.default.js`**
+ (后者是仓库代码,每次发布都会被覆盖)。`shared-config/env.prod.sh` 会在启动前被 `source`,
+ 每次发布也会把 `shared-config/config.prod.js`、`config.local.js`(若存在)复制进目标版本目录。
+
+ ```bash
+ # /www/wwwroot/packService/shared-config/env.prod.sh(chmod 600)
+ export JWT_SECRET='由 openssl rand -hex 32 生成的随机串'
+ export MYSQL_HOST='127.0.0.1'
+ export MYSQL_PORT='3306'
+ export MYSQL_PASSWORD='...'
+ export REDIS_HOST='127.0.0.1'
+ export REDIS_PASSWORD='...'
+ ```
+
+ 本项目已经准备好两份生产 env:
+
+ | 文件 | 用途 | 是否提交 |
+ |---|---|---|
+ | `backend/config/env.prod.sh` | 后端运行时变量(`JWT_SECRET`、`MYSQL_*`、`REDIS_*`、`SITE_URL`) | **否**(gitignore,本机权威副本,发布前自动上传到 `shared-config/`) |
+ | `frontend/.env.production` | 前端构建变量(`VITE_*`,不含密钥) | 是 |
+
+ > 改后端 env 后执行 `npm run deploy` 会自动上传并生效;改前端 env 后同样重新发布即可(`deploy` 会重新构建前端)。
+
+ > 生产环境 `config.default.js` 会强制要求 `JWT_SECRET` 环境变量,缺少会启动失败(健康检查不通过,自动保留旧实例)。
+
+5. 可选:安装提交前检查钩子(禁止提交私有配置 / 运行期产物 / 版本记录):
+
+ ```bash
+ npm run setup:hooks
+ ```
+
+### 常用命令
+
+| 命令 | 说明 |
+|---|---|
+| `npm run deploy:precheck` | 检查本地工具、SSH、远端目录 / Node / Nginx / 当前实例健康状态 |
+| `npm run deploy` | 构建前端 → 打包 → 上传 → 解压安装 → 启动新实例 → 健康检查 → 切 Nginx → 停旧实例 |
+| `npm run deploy:verify` | 查看当前版本 / 备份并冒烟探测 `/`、`/health`、`/download/version.json` |
+| `npm run deploy:version` | 查看远端活跃版本与最近一次发布记录(`--history=20` 看历史) |
+| `npm run deploy:smoke` | 只做冒烟探测 |
+| `npm run deploy:inspect` | 只看 `.deploy` 状态与备份清单 |
+| `npm run rollback` | 蓝绿回退到上一个版本目录(不重新解压,秒级切换) |
+| `npm run rollback -- --backup=backup-<时间戳>.tar.gz` | 用指定备份包恢复当前活跃目录 |
+| `npm run deploy:cleanup-backups -- backup-xxx.tar.gz` | 删除指定备份包 |
+
+发布说明:
+
+- 前端构建产物单独上传到 `deployRoot/frontend`,由 **nginx 直接托管**(SPA 回退到 `index.html`);上一版保留在 `frontend.prev`,`npm run rollback` 会连前端一起切回。
+ nginx 前端/反代配置由发布脚本写入 `deployRoot/front.conf`;Egg 只提供 `/api`、`/health`(`FRONTEND_ENABLE=false`)。
+ `buildFrontend: false` 时跳过前端构建与发布(适合前端完全独立部署)。
+- 生产发布**不含「测试页」**:前端 `TestView` 只在 dev 构建里注册路由与菜单(生产包不会产出该 chunk),
+ 后端 `/api/web/test/*` 只在 `env != prod` 时注册,生产请求直接 404。
+- 发布包只包含 git 跟踪的源码;版本目录里的 `config/config.prod.js`、`config/config.local.js`、`app/public/download`、`app/public/version` 在清理前暂存、解压后放回,随后再用 `shared-config/` 里的同名配置覆盖,保证所有版本配置一致。
+- 启动前会 `source shared-config/env.prod.sh`(`JWT_SECRET`、`MYSQL_*`、`REDIS_*` 等);**不要编辑版本目录里的 `config.default.js`**,它属于仓库代码,会被每次发布覆盖。
+- 每次发布会在 `.deploy/backups/` 留一份旧代码备份(默认保留最近 5 个;`node_modules` / `logs` / `run` / `temp`、安装包目录和服务端私有配置不进备份,它们本身会被保留)。
+- 需要发布时顺带升级库结构,把 `config/deploy.config.local.cjs` 里的 `remoteDbDeploy` 改成 `true`(远端会先 source `shared-config/env.prod.sh`,再以 `EGG_SERVER_ENV=prod` 执行 `npm run db:deploy`;连接信息来自 `MYSQL_*` 环境变量或 `config.prod.js`)。
+
+### 桌面端正式包(单独发布,不动后端)
+
+改桌面端时只需要发安装包,**不用重新发布后端**:
+
+```bash
+cd backend
+npm run desktop:build # 只构建(dry-run),产物在 desktop/installer/out
+npm run desktop:publish # 构建 + 上传 + 刷新 nginx
+npm run desktop:publish -- --version=1.0.90 --notes="修复 xxx"
+npm run desktop:publish -- --skip-nginx
+```
+
+- 版本默认取本地已有最高版本 + 1(补丁号),也可用 `--version=` 指定;
+- 构建复用 `desktop/installer/build.ps1 -Environment Production`;
+- 上传到 `deployRoot/download/desktop/`(MSI),`version.json` 传到 `deployRoot/download/`
+ (路径不能改:老客户端写死 `/download/version.json`;先传 MSI,再原子替换 `version.json`);
+- nginx 的 `/download/` 静态托管该目录:`version.json` 不缓存,MSI 长缓存;
+- `desktop/installer/package.config.json` 的 Production `serverBaseUrl` 必须是 `https://`,安装包内嵌的接口 / 下载地址会跟着变;
+- **谷歌插件一起打进包**:`extension/` 发布到 `<安装目录>\extension`,菜单「工具 → 复制谷歌插件地址」给出该 Windows 路径;
+- 不会重启 Egg、不会重新发布后端、不会跑数据库迁移;
+- 前置:.NET 8 SDK、WiX 5.0.2(`dotnet tool install --global wix --version 5.0.2`)、`desktop/native/ffmpeg/ffmpeg.exe`。
+
+下载地址:`/download/desktop/YuncangTraceSetup-<版本>.msi`
+更新信息:`/download/version.json`
+
+### Android 设备端正式包(单独发布,不动后端)
+
+```bash
+cd backend
+npm run android:build # 只构建(dry-run),产物在 backend/android_client/out
+npm run android:publish # 构建 + 上传 + 刷新 nginx
+npm run android:publish -- --version=1.0.2 --notes="扫码上报更稳"
+npm run android:publish -- --skip-nginx
+```
+
+- 构建复用 `backend/android_client/build.ps1 -Environment Production`(配置在 `backend/android_client/package.config.json`,和桌面端同一套路);
+- 版本默认取已有 APK / version.json 的最高版本 +1 补丁号;`versionCode` 由 `x.y.z` 换算(`major*10000+minor*100+patch`);
+- 上传到 `deployRoot/download/android_client/`:APK + `version.json`(nginx 对 `version.json` 单独关缓存);
+- 签名读 `AndroidStation/keystore.properties` + `keystore/*.jks`(**不入库**,发布机必须自行备份);
+- 前置:JDK 17(`JAVA_HOME`,或自动找 `%LOCALAPPDATA%\Programs\EclipseAdoptium\jdk-*` / Android Studio 的 `jbr`)、
+ Android SDK(`AndroidStation/local.properties` 的 `sdk.dir` 或 `ANDROID_HOME`)。
+
+下载地址:`/download/android_client/YuncangScan-<版本>.apk`
+更新信息:`/download/android_client/version.json`
+
+
## 单元测试
```bash
@@ -219,7 +387,7 @@ npm run cov
| `SMTP_HOST` | 空 | SMTP 主机;**不配就走开发模式**(验证码只写日志 + 注册页回显,不发真邮件) |
| `SMTP_PORT` | `465` | SMTP 端口 |
| `SMTP_SECURE` | `true` | 是否用 TLS(465 用 true,587 用 false) |
-| `SMTP_USER` / `SMTP_PASSWORD` | 空 | SMTP 账号密码(放 `config/config.local.js` 或环境变量) |
+| `SMTP_USER` / `SMTP_PASSWORD` | 空 | SMTP 账号 / 密码(QQ 邮箱填「授权码」,不是登录密码;放 `shared-config/env.prod.sh` 或环境变量) |
| `SMTP_FROM` | `云仓视频溯源系统 ` | 发件人(默认取 `SITE_NAME` 作显示名) |
| `EMAIL_CODE_TTL` | `600` | 邮箱验证码有效期(秒) |
| `EMAIL_CODE_RESEND` | `60` | 同一邮箱重发验证码的间隔(秒) |
@@ -432,15 +600,18 @@ node scripts/backfill-snapshot.js --dry-run
| 设备管理 | `/devices` | `/api/web/devices*` |
| 扫码记录 | `/records` | `/api/web/records` |
| 个人中心 | `/profile` | `/api/web/me*` |
-| 测试页 | `/test` | `/api/web/test/*`、`/api/wechat/{status,confirm}` |
+| 测试页(**仅开发构建**,生产不打包) | `/test` | `/api/web/test/*`、`/api/wechat/{status,confirm}` |
+
+> 「测试页」只在 `vite dev` / 本地开发构建里存在:生产构建不产出 `TestView` 的 chunk,
+> 路由与左侧菜单也一并去掉;后端 `/api/web/test/*` 只在 `env != prod` 时注册(生产请求返回 404)。
**后端怎么把页面交出去**(`app/middleware/frontend.js`,只接管「非 `/api`、`/health`」的 GET/HEAD 请求):
- **开发**(`env=local`):**反代**到 `FRONTEND_DEV_SERVER`(默认 `http://127.0.0.1:7301`,即 `frontend/ && npm run dev`),
包含 HMR 的 WebSocket 升级 —— 所以联调只开 `http://127.0.0.1:7300` 一个地址就够(前端热更新照常生效);
前端没起来时会回一个 502 提示页,而不是白屏;
-- **生产**:托管 `FRONTEND_DIST`(默认 `../frontend/dist`);找不到文件且请求要 HTML 时回退 `index.html`
- (SPA 深链 `/devices` 刷新不会 404);dist 不存在时回 503 并提示先 `npm run build`;
+- **生产**:本仓库的发布脚手架默认由 **nginx 直接托管** `deployRoot/frontend`,Egg 侧用 `FRONTEND_ENABLE=false` 关闭页面托管(只出 `/api`、`/health`);安装包由 nginx 静态托管 `deployRoot/download`。
+ 如果仍想让 Egg 托管(例如没有 nginx),设置 `FRONTEND_ENABLE=true` 并在启动时用 `FRONTEND_DIST` 指向构建产物;找不到文件且请求要 HTML 时回退 `index.html`(SPA 深链不会 404)。
- **单测**(`env=unittest`):整个中间件跳过(不连前端、也不要求 dist 存在)。
## 接口
diff --git a/backend/android_client/build.ps1 b/backend/android_client/build.ps1
new file mode 100644
index 0000000..f30b1e0
--- /dev/null
+++ b/backend/android_client/build.ps1
@@ -0,0 +1,250 @@
+#requires -Version 5.1
+<#
+.SYNOPSIS
+ 打「AndroidStation 设备端」的正式签名 APK,并生成下载用的 version.json。
+
+.DESCRIPTION
+ 1. 按 -Environment 从 package.config.json 取该环境的下载域名 / 目标目录;
+ 2. gradlew assembleRelease:版本号用 -PversionName/-PversionCode 覆盖,
+ 签名读 AndroidStation\keystore.properties(正式 keystore,不入库);
+ 3. 算 MD5 → 写 version.json(version / versionCode / downloadUrl / md5 / size / publishedAt / buildId);
+ 4. APK 复制到 out\;copyToServer=true 时再复制到后端:
+ APK → app\public\download\android_client\(nginx 长缓存)
+ version.json → app\public\version\android_client\(由 controller/download.js 关缓存后提供)
+ 5. out\ 与后端目录各只保留最近 keepVersions(默认 5)个安装包。
+
+.PARAMETER Environment
+ Development(连本机 7300)/ Production(正式域名)。
+
+.PARAMETER Version
+ 版本号 x.y.z(必填;发布脚本会按已有包自动 +1 补丁号)。
+
+.PARAMETER VersionCode
+ Android versionCode(默认由 x.y.z 换算:major*10000 + minor*100 + patch)。
+
+.PARAMETER ServerBaseUrl
+ 覆盖该环境配置里的域名(生成下载地址用,APK 本体不写死域名)。
+
+.PARAMETER Keep
+ 保留多少个历史安装包(默认读 package.config.json 的 keepVersions = 5)。
+
+.PARAMETER ReleaseNotes
+ 写进 version.json 的更新说明。
+
+.EXAMPLE
+ .\build.ps1 -Environment Production -Version 1.0.1 -ReleaseNotes "扫码上报更稳"
+
+.NOTES
+ 前置:JDK 17、Android SDK(AndroidStation\local.properties 的 sdk.dir 或 ANDROID_HOME)、
+ AndroidStation\keystore.properties + keystore\*.jks(正式签名)。
+ 本文件必须保存为 UTF-8 with BOM —— PowerShell 5.1 读无 BOM 脚本会按 GBK 解析,中文注释直接语法报错。
+#>
+param(
+ [ValidateSet('Development', 'Production')]
+ [string]$Environment = 'Development',
+
+ [string]$Version,
+ [int]$VersionCode = 0,
+ [string]$ServerBaseUrl,
+ [int]$Keep = 0,
+ [string]$ReleaseNotes = ''
+)
+
+$ErrorActionPreference = 'Stop'
+
+function Read-Utf8([string]$p) {
+ return [System.IO.File]::ReadAllText($p, (New-Object System.Text.UTF8Encoding($false)))
+}
+
+function Write-Utf8NoBom([string]$p, [string]$text) {
+ [System.IO.File]::WriteAllText($p, $text, (New-Object System.Text.UTF8Encoding($false)))
+}
+
+# ---------------- 1. 配置 ----------------
+$configPath = Join-Path $PSScriptRoot 'package.config.json'
+$cfg = Read-Utf8 $configPath | ConvertFrom-Json
+
+$envProp = $cfg.environments.PSObject.Properties[$Environment]
+if (-not $envProp) { throw "package.config.json 里没有环境:$Environment" }
+$envCfg = $envProp.Value
+
+if (-not $ServerBaseUrl) { $ServerBaseUrl = $envCfg.serverBaseUrl }
+if (-not $ServerBaseUrl) { throw "环境 $Environment 没配 serverBaseUrl" }
+$ServerBaseUrl = $ServerBaseUrl.TrimEnd('/')
+
+if ($Keep -le 0) { $Keep = [int]$cfg.keepVersions }
+if ($Keep -le 0) { $Keep = 5 }
+
+$projectDir = [System.IO.Path]::GetFullPath((Join-Path $PSScriptRoot $envCfg.projectDir))
+$outDir = Join-Path $PSScriptRoot 'out'
+$gradlew = Join-Path $projectDir 'gradlew.bat'
+if (-not (Test-Path $gradlew)) { throw "找不到 gradlew.bat:$gradlew(检查 package.config.json 的 projectDir)" }
+
+# ---------------- 2. 版本 ----------------
+if (-not $Version) { throw "请用 -Version x.y.z 指定版本号(npm run android:publish 会自动带上)" }
+$Version = $Version.Trim().TrimStart('v', 'V')
+$null = [version]$Version # 提前校验格式(不合法直接报错)
+
+$parts = $Version.Split('.')
+$major = [int]$parts[0]
+$minor = 0
+if ($parts.Length -gt 1) { $minor = [int]$parts[1] }
+$patch = 0
+if ($parts.Length -gt 2) { $patch = [int]$parts[2] }
+if ($VersionCode -le 0) { $VersionCode = $major * 10000 + $minor * 100 + $patch }
+
+Write-Host "环境:$Environment"
+Write-Host "版本:$Version(versionCode $VersionCode)"
+Write-Host "工程:$projectDir"
+
+# ---------------- 3. 环境检查 ----------------
+$keystoreProps = Join-Path $projectDir 'keystore.properties'
+if (-not (Test-Path $keystoreProps)) {
+ throw "缺少正式签名配置:$keystoreProps`n(keystore.properties 与 keystore/*.jks 不入库,发布机需自行备份)"
+}
+
+$localProps = Join-Path $projectDir 'local.properties'
+if (-not (Test-Path $localProps) -and -not $env:ANDROID_HOME -and -not $env:ANDROID_SDK_ROOT) {
+ throw "找不到 Android SDK:请写 $localProps 的 sdk.dir 或设置 ANDROID_HOME"
+}
+
+$javaHome = $env:JAVA_HOME
+if (-not $javaHome -or -not (Test-Path (Join-Path $javaHome 'bin\java.exe'))) {
+ $roots = @(
+ 'C:\Program Files\Android\Android Studio\jbr',
+ (Join-Path $env:LOCALAPPDATA 'Programs\EclipseAdoptium'),
+ 'C:\Program Files\Eclipse Adoptium',
+ 'C:\Program Files\Java'
+ )
+ $javaHome = $null
+ foreach ($root in $roots) {
+ if (-not (Test-Path $root)) { continue }
+ if (Test-Path (Join-Path $root 'bin\java.exe')) { $javaHome = $root; break }
+ $child = Get-ChildItem -Path $root -Directory -ErrorAction SilentlyContinue |
+ Where-Object { Test-Path (Join-Path $_.FullName 'bin\java.exe') } |
+ Sort-Object Name -Descending | Select-Object -First 1
+ if ($child) { $javaHome = $child.FullName; break }
+ }
+}
+if (-not $javaHome) { throw '找不到 JDK:请安装 JDK 17 并设置 JAVA_HOME。' }
+$env:JAVA_HOME = $javaHome
+Write-Host "JAVA_HOME=$javaHome"
+
+# ---------------- 4. 构建 APK ----------------
+Push-Location $projectDir
+try {
+ & $gradlew --no-daemon assembleRelease "-PversionName=$Version" "-PversionCode=$VersionCode"
+ if ($LASTEXITCODE -ne 0) { throw "gradlew assembleRelease 失败($LASTEXITCODE)" }
+}
+finally {
+ Pop-Location
+}
+
+$builtApk = Join-Path $projectDir 'app\build\outputs\apk\release\app-release.apk'
+if (-not (Test-Path $builtApk)) { throw "构建产物不存在:$builtApk" }
+
+New-Item -ItemType Directory -Force -Path $outDir | Out-Null
+$apkName = [string]$envCfg.apkName
+if (-not $apkName) { $apkName = 'YuncangScan-{version}.apk' }
+$apkName = $apkName.Replace('{version}', $Version)
+$apk = Join-Path $outDir $apkName
+Copy-Item -Path $builtApk -Destination $apk -Force
+
+# ---------------- 5. version.json ----------------
+$hash = (Get-FileHash -Algorithm MD5 -Path $apk).Hash.ToLowerInvariant()
+$size = (Get-Item $apk).Length
+$downloadUrl = "$ServerBaseUrl/download/android_client/$apkName"
+$now = Get-Date
+
+$versionJson = [ordered]@{
+ version = $Version
+ versionCode = $VersionCode
+ package = 'com.gztbyc.scancenter'
+ downloadUrl = $downloadUrl
+ md5 = $hash
+ size = $size
+ publishedAt = $now.ToString('yyyy-MM-ddTHH:mm:sszzz')
+ buildId = $now.ToString('yyyyMMddHHmmss')
+ environment = $Environment
+ releaseNotes = $ReleaseNotes
+} | ConvertTo-Json
+
+$versionFile = Join-Path $outDir 'version.json'
+Write-Utf8NoBom $versionFile $versionJson
+
+Write-Host "APK:$apk($([math]::Round($size / 1MB, 1)) MB)"
+Write-Host "MD5:$hash"
+Write-Host "下载地址:$downloadUrl"
+
+# ---------------- 6. 复制到后端 ----------------
+$skipVersionJson = $false
+$downloadDir = $null
+$versionDir = $null
+
+if ($envCfg.copyToServer -ne $false) {
+ $downloadDir = [System.IO.Path]::GetFullPath((Join-Path $PSScriptRoot $envCfg.downloadFolder))
+ $versionDir = [System.IO.Path]::GetFullPath((Join-Path $PSScriptRoot $envCfg.versionFolder))
+ New-Item -ItemType Directory -Force -Path $downloadDir | Out-Null
+ New-Item -ItemType Directory -Force -Path $versionDir | Out-Null
+
+ # 后端已经是更新版本:说明这次在补打旧版本,不能把 version.json 降回去
+ $existingVj = Join-Path $versionDir 'version.json'
+ if (Test-Path $existingVj) {
+ try {
+ $old = (Read-Utf8 $existingVj) | ConvertFrom-Json
+ if ($old.version -and ([version]$old.version -gt [version]$Version)) {
+ $skipVersionJson = $true
+ Write-Warning "后端 version.json 已是更新版本($($old.version)),本次不覆盖它"
+ }
+ }
+ catch { /* 旧文件坏了就当没有 */ }
+ }
+
+ $dstApk = Join-Path $downloadDir $apkName
+ Copy-Item -Path $apk -Destination $dstApk -Force
+ # 刷新 mtime:即使上游还有一层协商缓存,也能认出文件变了
+ (Get-Item $dstApk).LastWriteTime = $now
+
+ if (-not $skipVersionJson) {
+ Write-Utf8NoBom $existingVj $versionJson
+ (Get-Item $existingVj).LastWriteTime = $now
+ }
+
+ Write-Host "已复制到:$downloadDir(APK)、$versionDir(version.json)"
+}
+else {
+ Write-Host "(该环境 copyToServer=false,跳过复制到后端)"
+}
+
+# ---------------- 7. 只保留最近 N 个安装包 ----------------
+function Remove-OldPackages([string]$dir, [int]$keep) {
+ if (-not (Test-Path $dir)) { return }
+
+ $items = @(
+ Get-ChildItem -Path $dir -Filter 'YuncangScan-*.apk' -File | ForEach-Object {
+ if ($_.BaseName -match 'YuncangScan-(\d+(\.\d+){1,3})$') {
+ [pscustomobject]@{ File = $_; Ver = [version]$Matches[1] }
+ }
+ } | Sort-Object Ver -Descending
+ )
+
+ $removed = 0
+ $items | Select-Object -Skip $keep | ForEach-Object {
+ Remove-Item $_.File.FullName -Force
+ $removed++
+ Write-Host " 清理旧包:$($_.File.Name)"
+ }
+
+ if ($removed -eq 0) { Write-Host " $dir:共 $($items.Count) 个,未超过 $keep 个" }
+}
+
+Write-Host "保留最近 $Keep 个安装包:"
+Remove-OldPackages $outDir $Keep
+if ($downloadDir) { Remove-OldPackages $downloadDir $Keep }
+
+# ---------------- 8. 摘要 ----------------
+Write-Host ""
+Write-Host "完成:$apk" -ForegroundColor Green
+Write-Host "版本文件:$versionFile"
+Write-Host "下载地址:$downloadUrl"
+Write-Host "安装:adb install -r `"$apk`"(设备上无需任何特殊权限)"
diff --git a/backend/android_client/package.config.json b/backend/android_client/package.config.json
new file mode 100644
index 0000000..b411cfb
--- /dev/null
+++ b/backend/android_client/package.config.json
@@ -0,0 +1,26 @@
+{
+ "$comment": "Android 设备端打包配置(android_client/build.ps1 -Environment Development|Production 读取对应环境,和桌面端 desktop/installer/package.config.json 一个套路)。版本号必须由发布脚本传 -Version 覆盖,versionCode 默认由 x.y.z 换算(major*10000+minor*100+patch)。",
+ "keepVersions": 5,
+
+ "environments": {
+ "Development": {
+ "$comment": "开发环境:后端本机 7300。打包后会把 APK + version.json 复制到后端,本机即可验证下载地址。",
+ "serverBaseUrl": "http://127.0.0.1:7300",
+ "projectDir": "../../AndroidStation",
+ "apkName": "YuncangScan-{version}.apk",
+ "downloadFolder": "../app/public/download/android_client",
+ "versionFolder": "../app/public/version/android_client",
+ "copyToServer": true
+ },
+
+ "Production": {
+ "$comment": "生产环境:正式域名(APK 本身不写域名,只用于生成下载地址)。",
+ "serverBaseUrl": "https://pack.wms.gztbyc.com",
+ "projectDir": "../../AndroidStation",
+ "apkName": "YuncangScan-{version}.apk",
+ "downloadFolder": "../app/public/download/android_client",
+ "versionFolder": "../app/public/version/android_client",
+ "copyToServer": true
+ }
+ }
+}
diff --git a/backend/app/controller/download.js b/backend/app/controller/download.js
index 1ebb97b..a0fefe9 100644
--- a/backend/app/controller/download.js
+++ b/backend/app/controller/download.js
@@ -12,21 +12,42 @@ const { Controller } = require('egg');
* 而 egg-static 生产默认强缓存一年 → 软件永远拿旧的 version.json,永远检测不到更新。
*
* 所以:
- * - `version.json` 放在 `app/public/version/`(不在静态 prefix 下),由本控制器读文件;
- * - 安装包 `*.msi` 仍走 egg-static(`/download/xxx.msi`),文件名带版本号,可以长缓存。
+ * - 版本信息放在 `app/public/version/<平台>/version.json`(不在静态 prefix 下),由本控制器读文件:
+ * desktop → app/public/version/desktop/version.json
+ * (更早的版本放在 app/public/version/version.json,仍作为兜底读一次)
+ * android_client → app/public/version/android_client/version.json
+ * - 安装包本体仍走 egg-static(`/download/desktop/*.msi`、`/download/android_client/*.apk`),
+ * 文件名带版本号,可以长缓存。
*
* 缓存策略:no-store + no-cache + Expires 0,且不产生 ETag/Last-Modified(不走 304)。
- * 生产前面若还有 nginx/CDN,也要对 `/download/version.json` 关缓存。
+ * 生产前面若还有 nginx/CDN,也要对这些 version.json 关缓存(见 deploy-lib.cjs 的 buildFrontConf)。
*/
class DownloadController extends Controller {
- /** GET /download/version.json */
+ /** GET /download/version.json(桌面端;路径不能改:老客户端写死了这个地址) */
async version() {
- const { ctx, app } = this;
- const file = path.join(app.baseDir, 'app/public/version/version.json');
+ return this.sendVersion('desktop', [
+ 'app/public/version/desktop/version.json',
+ 'app/public/version/version.json',
+ ]);
+ }
- if (!fs.existsSync(file)) {
+ /** GET /download/android_client/version.json */
+ async androidVersion() {
+ return this.sendVersion('android_client', [
+ 'app/public/version/android_client/version.json',
+ ]);
+ }
+
+ /** 按候选路径顺序取第一个存在的 version.json,null 缓存直出 */
+ sendVersion(label, candidates) {
+ const { ctx, app } = this;
+ const file = candidates
+ .map(item => path.join(app.baseDir, item))
+ .find(item => fs.existsSync(item));
+
+ if (!file) {
ctx.status = 404;
- ctx.body = { ok: false, message: 'version.json 不存在(还没打包过?)' };
+ ctx.body = { ok: false, message: `${label} version.json 不存在(还没打包过?)` };
return;
}
diff --git a/backend/app/controller/web/auth.js b/backend/app/controller/web/auth.js
index b9ff5a2..a0e87f0 100644
--- a/backend/app/controller/web/auth.js
+++ b/backend/app/controller/web/auth.js
@@ -82,13 +82,14 @@ class WebAuthController extends Controller {
if (!result.ok) ctx.throw(429, result.message);
ctx.logger.info('[web] 注册验证码已发送到 %s', email);
+ const exposeDevCode = ctx.app.config.env !== 'prod' && Boolean(result.devMode);
ctx.body = {
ok: true,
data: {
email,
// 开发模式(未配 SMTP)把验证码带回来,前端可直接提示;生产不返回
- devMode: Boolean(result.devMode),
- code: result.devMode ? result.code : undefined,
+ devMode: exposeDevCode,
+ code: exposeDevCode ? result.code : undefined,
},
};
}
@@ -163,13 +164,14 @@ class WebAuthController extends Controller {
}
ctx.logger.info('[web] 已向 %s 发送重置密码链接', email);
+ const exposeDevUrl = ctx.app.config.env !== 'prod' && Boolean(result.devMode);
ctx.body = {
ok: true,
data: {
sent: true,
// 开发模式(未配 SMTP)把链接返回,前端可直接点开
- devMode: Boolean(result.devMode),
- url: result.devMode ? result.url : undefined,
+ devMode: exposeDevUrl,
+ url: exposeDevUrl ? result.url : undefined,
},
};
return;
diff --git a/backend/app/router.js b/backend/app/router.js
index e66729f..2dc97a2 100644
--- a/backend/app/router.js
+++ b/backend/app/router.js
@@ -26,9 +26,12 @@ module.exports = (app) => {
router.get('/health', controller.health.index);
// ---------- 安装包分发(软件自动更新) ----------
- // 安装包本体 `GET /download/YuncangTraceSetup-x.y.z.msi` 由 egg-static 提供(config.static);
+ // 安装包本体由 egg-static 提供(config.static):
+ // 桌面端 `GET /download/desktop/YuncangTraceSetup-x.y.z.msi`
+ // Android `GET /download/android_client/YuncangScan-x.y.z.apk`
// version.json **必须走路由**:static 命中后不会 next(),改不了缓存头(会被缓存一年)。
router.get('/download/version.json', controller.download.version);
+ router.get('/download/android_client/version.json', controller.download.androidVersion);
// ---------- 协议(公开读取;同意记录在登录时落库) ----------
router.get('/api/agreements/current', controller.agreement.current);
@@ -126,8 +129,11 @@ module.exports = (app) => {
router.delete('/api/web/workstations/:id/scan-channels/:linkId', apiAuth, subjectAuth, controller.web.workstation.unbindScanChannel);
// 前端「测试页」的模拟接口(模拟设备扫码登录 / 模拟中控上报),与真机走同一套 service
- router.post('/api/web/test/device-login', apiAuth, subjectAuth, controller.web.test.deviceLogin);
- router.post('/api/web/test/scan', apiAuth, subjectAuth, controller.web.test.scan);
+ // 只在非生产环境注册:生产不暴露模拟链路
+ if (app.config.env !== 'prod') {
+ router.post('/api/web/test/device-login', apiAuth, subjectAuth, controller.web.test.deviceLogin);
+ router.post('/api/web/test/scan', apiAuth, subjectAuth, controller.web.test.scan);
+ }
// ---------- 运维/内部(脚本、后台系统;**需内部令牌**,见 middleware/internal_auth.js)----------
router.get('/api/users', internalAuth, controller.internal.user.index);
diff --git a/backend/app/service/mail.js b/backend/app/service/mail.js
index 1977c89..fc38bd2 100644
--- a/backend/app/service/mail.js
+++ b/backend/app/service/mail.js
@@ -26,7 +26,8 @@ class MailService extends Service {
const text = `你的 ${site} 注册验证码是 ${code},${minutes} 分钟内有效。\n`
+ '如果不是你本人操作,忽略本邮件即可。';
- if (cfg.devMode) {
+ const devMode = this.app.config.env !== 'prod' && cfg.devMode;
+ if (devMode) {
this.ctx.logger.info('[mail][dev] 未配置 SMTP,验证码不发真邮件 → %s : %s', email, code);
return { devMode: true, code };
}
@@ -50,7 +51,8 @@ class MailService extends Service {
+ `${url}\n`
+ '如果不是你本人操作,忽略本邮件即可,你的密码不会被修改。';
- if (cfg.devMode) {
+ const devMode = this.app.config.env !== 'prod' && cfg.devMode;
+ if (devMode) {
this.ctx.logger.info('[mail][dev] 未配置 SMTP,重置链接不发真邮件 → %s : %s', email, url);
return { devMode: true, url };
}
diff --git a/backend/app/service/password_reset.js b/backend/app/service/password_reset.js
index 4d48541..c38592f 100644
--- a/backend/app/service/password_reset.js
+++ b/backend/app/service/password_reset.js
@@ -95,7 +95,9 @@ class PasswordResetService extends Service {
}
this.ctx.logger.info('[reset] 重置链接已生成 user=%s email=%s', user.id, user.email);
- return { ok: true, devMode: mail.devMode, url: mail.devMode ? url : undefined };
+ // 生产环境绝不回传重置链接(即使配置误开 devMode 也兜底)
+ const exposeDevUrl = this.app.config.env !== 'prod' && !!mail.devMode;
+ return { ok: true, devMode: exposeDevUrl, url: exposeDevUrl ? url : undefined };
}
/**
diff --git a/backend/app/service/verify_code.js b/backend/app/service/verify_code.js
index 2850780..1eeb08e 100644
--- a/backend/app/service/verify_code.js
+++ b/backend/app/service/verify_code.js
@@ -62,13 +62,15 @@ class VerifyCodeService extends Service {
}
this.ctx.logger.info('[verify] %s 验证码已生成: %s (devMode=%s)', scene, email, !!mail.devMode);
+ // 生产环境绝不回传验证码(即使配置误开 devMode 也兜底)
+ const exposeDevCode = this.app.config.env !== 'prod' && !!mail.devMode;
return {
ok: true,
ttl: this.cfg.codeTtl,
resendInterval: this.cfg.resendInterval,
- devMode: !!mail.devMode,
+ devMode: exposeDevCode,
// 开发模式才把验证码回传给页面(生产走邮件)
- code: mail.devMode ? code : undefined,
+ code: exposeDevCode ? code : undefined,
};
} catch (err) {
this.ctx.logger.error('[verify] 验证码发送失败 %s : %s', email, err.message);
diff --git a/backend/config/config.default.js b/backend/config/config.default.js
index 4076484..91bdbed 100644
--- a/backend/config/config.default.js
+++ b/backend/config/config.default.js
@@ -14,6 +14,10 @@ module.exports = (appInfo) => {
// cookie/session 签名用的 key,生产环境请改成随机字符串
config.keys = `${appInfo.name}_1729000000000_1971`;
+ // 部署在 nginx 后面:信任 X-Forwarded-Proto / X-Forwarded-For,
+ // 否则 ctx.origin / ctx.protocol 会一直认为是 http,二维码、邮件链接会拼成 http://
+ config.proxy = true;
+
// ==================== 站点/产品名 ====================
// 页标题、品牌位、邮件正文都用它 —— **改名字只改这里**(或设环境变量 SITE_NAME)
config.siteName = env.SITE_NAME || '云仓视频溯源系统';
@@ -35,17 +39,21 @@ module.exports = (appInfo) => {
};
// ==================== 安装包分发(软件自动更新) ====================
- // 打包脚本(desktop/installer/build.ps1)会把:
- // - MSI → app/public/download/ (egg-static 提供 /download/xxx.msi,文件名带版本号→可长缓存)
- // - version.json → app/public/version/ (**不在静态目录里**,由 controller/download.js 提供,
- // 因为 koa-static 命中后不 next(),改不了它的缓存头)
- // 软件启动时请求 GET /download/version.json 判断是否有新版本。
+ // 打包脚本会把产物放进按平台划分的子目录:
+ // - 桌面端 desktop/installer/build.ps1
+ // MSI → app/public/download/desktop/ (egg-static 提供 /download/desktop/*.msi,长缓存)
+ // version.json → app/public/version/desktop/ (**不在静态目录里**,由 controller/download.js 提供,
+ // 因为 koa-static 命中后不 next(),改不了缓存头)
+ // - Android backend/android_client/build.ps1
+ // APK → app/public/download/android_client/ (/download/android_client/*.apk)
+ // version.json → app/public/version/android_client/
+ // 桌面端软件启动时请求 GET /download/version.json 判断是否有新版本(路径不能改,老客户端写死了)。
config.static = {
prefix: '/download/',
dir: path.join(appInfo.baseDir, 'app/public/download'),
- // 这里只会放“文件名带版本号”的 MSI,内容永不变 → 可以放心长缓存
+ // 这里只会放“文件名带版本号”的 MSI / APK,内容永不变 → 可以放心长缓存
maxAge: 31536000,
- buffer: false, // MSI 几十 MB,流式发送
+ buffer: false, // MSI / APK 几十 MB,流式发送
};
// ==================== 前端入口(页面不在后端渲染) ====================
@@ -208,7 +216,8 @@ module.exports = (appInfo) => {
// ==================== 邮件 / 邮箱验证码(注册时需要验证邮箱) ====================
config.email = {
// 未配置 SMTP_HOST 时走开发模式:验证码写日志并在注册页回显(仅本地/测试用)
- devMode: !env.SMTP_HOST,
+ // ⚠️ 生产环境(env=prod)永远不启用 devMode,避免把验证码 / 重置链接回传给前端
+ devMode: appInfo.env !== 'prod' && !env.SMTP_HOST,
// 发件人显示名用站点名(邮箱域名保持 pack-service.local,技术标识不动)
from: env.SMTP_FROM || `${config.siteName} `,
smtp: {
diff --git a/backend/config/deploy.config.example.cjs b/backend/config/deploy.config.example.cjs
new file mode 100644
index 0000000..86af47d
--- /dev/null
+++ b/backend/config/deploy.config.example.cjs
@@ -0,0 +1,99 @@
+'use strict';
+
+/**
+ * 发布配置模板(提交到仓库)
+ *
+ * 复制为 config/deploy.config.local.cjs 后填入真实 SSH 信息:
+ * Copy-Item config/deploy.config.example.cjs config/deploy.config.local.cjs
+ *
+ * config/deploy.config.local.cjs 已被 .gitignore 忽略,禁止提交。
+ */
+module.exports = {
+ production: {
+ // ==================== SSH ====================
+ host: '__FILL_SSH_HOST__',
+ port: 22,
+ username: '__FILL_SSH_USERNAME__',
+ // 绝对路径;Windows 写法示例:C:/Users/you/.ssh/id_rsa
+ privateKeyPath: 'C:/Users/your-user/.ssh/id_rsa',
+
+ // ==================== 远端目录 ====================
+ // 双实例目录:${deployRoot}/v1、${deployRoot}/v2;
+ // ${deployRoot}/current.md 记录当前活跃版本,${deployRoot}/.deploy 存放发布包/备份/状态。
+ deployRoot: '/www/wwwroot/packService',
+
+ // v1 / v2 两个实例的监听端口(egg config.cluster.listen.port 由启动脚本的 PORT 覆盖)
+ ports: { v1: 7301, v2: 7302 },
+
+ // ==================== 健康检查 ====================
+ // /health 会同时检查 MySQL / Redis,任一不可用即 503
+ healthCheckPath: '/health',
+ healthCheckAttempts: 30,
+ healthCheckInterval: 2,
+
+ // Nginx upstream 文件(内容只有一行 proxy_pass)。置空字符串则不自动切换。
+ // 需要在 Nginx 配置里 include 这个文件,例如:
+ // upstream pack_service { include /www/wwwroot/packService/nginx-upstream.conf; }
+ nginxUpstreamFile: '/www/wwwroot/packService/nginx-upstream.conf',
+
+ // 服务端私有配置目录(不随发布包走):可放 config.prod.js / config.local.js;
+ // envFile 会在启动前被 source,用于 JWT_SECRET、数据库密码等环境变量。
+ sharedConfigDir: '/www/wwwroot/packService/shared-config',
+ envFile: 'env.prod.sh',
+ // 本机权威 env 副本(已 gitignore);存在时发布前自动上传到 shared-config/
+ envFileLocalPath: 'config/env.prod.sh',
+ uploadEnvFile: true,
+
+ // ==================== 发布内容 ====================
+ // 远端保留目录(清理旧代码时跳过)
+ sharedDirs: [ 'node_modules', 'logs', 'run', 'temp' ],
+
+ // 服务端私有文件/目录:发布前暂存、解压后放回,不会被发布包覆盖或删除。
+ // config/config.prod.js 需要运维在服务器上首次放置(数据库/Redis 密码等)。
+ preservePaths: [
+ 'config/config.prod.js',
+ 'config/config.local.js',
+ 'app/public/download',
+ 'app/public/version',
+ ],
+
+ // 发布前本地构建 ../frontend,产物单独上传到 frontendDeployDir(由 nginx 托管)
+ buildFrontend: true,
+ frontendDir: '../frontend',
+ // 前端构建产物由 nginx 直接托管(上一版保留在 frontend.prev,供回退)
+ frontendDeployDir: '/www/wwwroot/packService/frontend',
+ // 由发布脚本维护的 nginx 前端/反代配置(站点配置里 include)
+ nginxFrontConf: '/www/wwwroot/packService/front.conf',
+ manageNginxFrontConf: true,
+ serverName: 'pack.example.com',
+ // 桌面端发布(npm run desktop:publish):只构建/上传安装包,不动后端
+ desktopBuildScript: '../desktop/installer/build.ps1',
+ desktopOutDir: '../desktop/installer/out',
+ // 安装包目录(nginx 长缓存):deployRoot/download/desktop/YuncangTraceSetup-x.y.z.msi
+ desktopDownloadDir: '/www/wwwroot/packService/download/desktop',
+ // version.json 目录(nginx 对 /download/version.json 关缓存,客户端路径不变)
+ desktopVersionDir: '/www/wwwroot/packService/download',
+ desktopBaseUrl: 'https://pack.example.com',
+ desktopKeepVersions: 5,
+ desktopOwner: 'www:www',
+
+ // Android 设备端发布(npm run android:publish):同样只构建/上传 APK
+ androidBuildScript: 'android_client/build.ps1',
+ androidOutDir: 'android_client/out',
+ androidDownloadDir: '/www/wwwroot/packService/download/android_client',
+ androidVersionDir: '/www/wwwroot/packService/download/android_client',
+ androidBaseUrl: 'https://pack.example.com',
+ androidKeepVersions: 5,
+ androidOwner: 'www:www',
+
+ // 目标目录 npm install --production 后是否执行 npm run db:deploy
+ remoteDbDeploy: false,
+
+ // 保留最近多少个备份包(backup-*.tar.gz)
+ keepBackups: 5,
+
+ sshOptions: [
+ 'StrictHostKeyChecking=accept-new',
+ ],
+ },
+};
diff --git a/backend/database/config.cjs b/backend/database/config.cjs
index 3bbba1e..4b8ae79 100644
--- a/backend/database/config.cjs
+++ b/backend/database/config.cjs
@@ -3,7 +3,7 @@
/**
* sequelize-cli 配置入口(`.sequelizerc` 指到这里)
*
- * 连接信息与后端运行时**完全同源**:环境变量 > config/config.local.js > 默认值,
+ * 连接信息与后端运行时**完全同源**:环境变量 > config/config.prod.js(EGG_SERVER_ENV=prod)> config/config.local.js > 默认值,
* 统一由 scripts/db-config.js 解析,避免迁移改到一个库、服务连另一个库。
*
* 用法:
diff --git a/backend/database/migrations/20261018230000-create-subject-tables.js b/backend/database/migrations/20261018230000-create-subject-tables.js
index 917ea5c..f28d7aa 100644
--- a/backend/database/migrations/20261018230000-create-subject-tables.js
+++ b/backend/database/migrations/20261018230000-create-subject-tables.js
@@ -9,10 +9,37 @@
*
* 数据迁移:给**已有数据**的用户各建一个主体(管理员=本人,期限 +365 天),
* 并把其名下数据回填到该主体,保证升级后旧数据仍然可见。
+ *
+ * 注意:`sql/schema.sql` 基线可能已经包含 `scan_records.subject_id` 等列,
+ * 所以这里所有建表 / 加列 / 加索引都做成幂等,空库和旧库都能反复执行。
*/
+
+async function hasTable(queryInterface, table) {
+ const tables = await queryInterface.showAllTables();
+ return tables.some(item => (typeof item === 'string' ? item : Object.values(item)[0]) === table);
+}
+
+async function hasColumn(queryInterface, table, column) {
+ try {
+ const description = await queryInterface.describeTable(table);
+ return Boolean(description[column]);
+ } catch (error) {
+ return false;
+ }
+}
+
+async function hasIndex(queryInterface, table, name) {
+ try {
+ const indexes = await queryInterface.showIndex(table);
+ return indexes.some(item => item.name === name);
+ } catch (error) {
+ return false;
+ }
+}
+
module.exports = {
async up(queryInterface, Sequelize) {
- const { BIGINT, STRING, TINYINT, DATE, INTEGER } = Sequelize;
+ const { BIGINT, STRING, TINYINT, DATE } = Sequelize;
const audit = {
created_at: { type: DATE, allowNull: false, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP') },
@@ -20,37 +47,49 @@ module.exports = {
deleted_at: { type: DATE, allowNull: true },
};
- await queryInterface.createTable('subjects', {
- id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, allowNull: false },
- name: { type: STRING(64), allowNull: false, comment: '主体名称' },
- admin_user_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '管理员用户 users.id(默认创建人)' },
- expire_at: { type: DATE, allowNull: false, comment: '使用期限(到期后不可进入)' },
- status: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 1, comment: '状态:1启用 0停用' },
- remark: { type: STRING(255), allowNull: true, comment: '备注' },
- ...audit,
- }, { comment: '主体表' });
+ if (!await hasTable(queryInterface, 'subjects')) {
+ await queryInterface.createTable('subjects', {
+ id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, allowNull: false },
+ name: { type: STRING(64), allowNull: false, comment: '主体名称' },
+ admin_user_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '管理员用户 users.id(默认创建人)' },
+ expire_at: { type: DATE, allowNull: false, comment: '使用期限(到期后不可进入)' },
+ status: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 1, comment: '状态:1启用 0停用' },
+ remark: { type: STRING(255), allowNull: true, comment: '备注' },
+ ...audit,
+ }, { comment: '主体表' });
+ }
- await queryInterface.addIndex('subjects', [ 'admin_user_id' ], { name: 'idx_subjects_admin' });
- await queryInterface.addIndex('subjects', [ 'expire_at' ], { name: 'idx_subjects_expire' });
+ if (!await hasIndex(queryInterface, 'subjects', 'idx_subjects_admin')) {
+ await queryInterface.addIndex('subjects', [ 'admin_user_id' ], { name: 'idx_subjects_admin' });
+ }
+ if (!await hasIndex(queryInterface, 'subjects', 'idx_subjects_expire')) {
+ await queryInterface.addIndex('subjects', [ 'expire_at' ], { name: 'idx_subjects_expire' });
+ }
- await queryInterface.createTable('subject_members', {
- id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, allowNull: false },
- subject_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '主体 subjects.id' },
- user_id: { type: BIGINT.UNSIGNED, allowNull: true, comment: '绑定账号 users.id(未绑定为空)' },
- name: { type: STRING(32), allowNull: false, comment: '成员姓名' },
- role: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 2, comment: '角色:1管理员 2成员' },
- wechat_openid: { type: STRING(64), allowNull: true, comment: '绑定的微信 openid' },
- bound_at: { type: DATE, allowNull: true, comment: '成员绑定账号/微信的时间' },
- status: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 1, comment: '状态:1正常 0禁用' },
- ...audit,
- }, { comment: '主体成员表' });
+ if (!await hasTable(queryInterface, 'subject_members')) {
+ await queryInterface.createTable('subject_members', {
+ id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, allowNull: false },
+ subject_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '主体 subjects.id' },
+ user_id: { type: BIGINT.UNSIGNED, allowNull: true, comment: '绑定账号 users.id(未绑定为空)' },
+ name: { type: STRING(32), allowNull: false, comment: '成员姓名' },
+ role: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 2, comment: '角色:1管理员 2成员' },
+ wechat_openid: { type: STRING(64), allowNull: true, comment: '绑定的微信 openid' },
+ bound_at: { type: DATE, allowNull: true, comment: '成员绑定账号/微信的时间' },
+ status: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 1, comment: '状态:1正常 0禁用' },
+ ...audit,
+ }, { comment: '主体成员表' });
+ }
// 同一主体下同一账号只能有一条(NULL 不参与唯一性,所以「未绑定的成员」可以有多条)
- await queryInterface.addIndex('subject_members', [ 'subject_id', 'user_id' ], {
- name: 'uk_subject_members_subject_user',
- unique: true,
- });
- await queryInterface.addIndex('subject_members', [ 'user_id' ], { name: 'idx_subject_members_user' });
+ if (!await hasIndex(queryInterface, 'subject_members', 'uk_subject_members_subject_user')) {
+ await queryInterface.addIndex('subject_members', [ 'subject_id', 'user_id' ], {
+ name: 'uk_subject_members_subject_user',
+ unique: true,
+ });
+ }
+ if (!await hasIndex(queryInterface, 'subject_members', 'idx_subject_members_user')) {
+ await queryInterface.addIndex('subject_members', [ 'user_id' ], { name: 'idx_subject_members_user' });
+ }
// 业务表挂到主体
const targets = [
@@ -62,25 +101,34 @@ module.exports = {
[ 'scan_records', '扫码记录表' ],
];
for (const [ table ] of targets) {
- await queryInterface.addColumn(table, 'subject_id', {
- type: BIGINT.UNSIGNED,
- allowNull: true,
- comment: '所属主体 subjects.id',
- after: 'id',
- });
- await queryInterface.addIndex(table, [ 'subject_id' ], { name: `idx_${table}_subject` });
+ if (!await hasColumn(queryInterface, table, 'subject_id')) {
+ await queryInterface.addColumn(table, 'subject_id', {
+ type: BIGINT.UNSIGNED,
+ allowNull: true,
+ comment: '所属主体 subjects.id',
+ after: 'id',
+ });
+ }
+ if (!await hasIndex(queryInterface, table, `idx_${table}_subject`)) {
+ await queryInterface.addIndex(table, [ 'subject_id' ], { name: `idx_${table}_subject` });
+ }
}
// ---------------- 回填:给已有数据的用户建主体 ----------------
- const expireExpr = "DATE_ADD(NOW(), INTERVAL 365 DAY)";
+ const expireExpr = 'DATE_ADD(NOW(), INTERVAL 365 DAY)';
await queryInterface.sequelize.query(`
INSERT INTO subjects (name, admin_user_id, expire_at, status, remark, created_at, updated_at)
SELECT LEFT(CONCAT(COALESCE(NULLIF(u.nickname, ''), NULLIF(u.username, ''), CONCAT('用户', u.id)), ' 的主体'), 64),
u.id, ${expireExpr}, 1, '升级时自动创建的历史主体', NOW(), NOW()
FROM users u
- WHERE EXISTS (SELECT 1 FROM nvrs n WHERE n.user_id = u.id AND n.deleted_at IS NULL)
- OR EXISTS (SELECT 1 FROM workstations w WHERE w.user_id = u.id AND w.deleted_at IS NULL)
- OR EXISTS (SELECT 1 FROM scanners s WHERE s.user_id = u.id AND s.deleted_at IS NULL)
+ WHERE (
+ EXISTS (SELECT 1 FROM nvrs n WHERE n.user_id = u.id AND n.deleted_at IS NULL)
+ OR EXISTS (SELECT 1 FROM workstations w WHERE w.user_id = u.id AND w.deleted_at IS NULL)
+ OR EXISTS (SELECT 1 FROM scanners s WHERE s.user_id = u.id AND s.deleted_at IS NULL)
+ )
+ AND NOT EXISTS (
+ SELECT 1 FROM subjects s2 WHERE s2.admin_user_id = u.id AND s2.deleted_at IS NULL
+ )
`);
await queryInterface.sequelize.query(`
diff --git a/backend/database/migrations/20261018240000-add-scan-record-workstation-snapshot.js b/backend/database/migrations/20261018240000-add-scan-record-workstation-snapshot.js
index 6cec529..8e979d6 100644
--- a/backend/database/migrations/20261018240000-add-scan-record-workstation-snapshot.js
+++ b/backend/database/migrations/20261018240000-add-scan-record-workstation-snapshot.js
@@ -13,36 +13,66 @@
* 索引:
* - `(subject_id, barcode)`:按运单号查(主体内精确匹配)
* - `(scanner_id, channel_id, scan_time)`:散单要取同通道的「上一条/下一条」扫码时间
+ *
+ * 注意:`sql/schema.sql` 基线已经包含这些列和索引,空库执行时必须幂等。
*/
+async function hasColumn(queryInterface, table, column) {
+ try {
+ const description = await queryInterface.describeTable(table);
+ return Boolean(description[column]);
+ } catch (error) {
+ return false;
+ }
+}
+
+async function hasIndex(queryInterface, table, name) {
+ try {
+ const indexes = await queryInterface.showIndex(table);
+ return indexes.some(item => item.name === name);
+ } catch (error) {
+ return false;
+ }
+}
+
module.exports = {
async up(queryInterface, Sequelize) {
const { BIGINT, JSON: JSONType } = Sequelize;
- await queryInterface.addColumn('scan_records', 'workstation_id', {
- type: BIGINT.UNSIGNED,
- allowNull: true,
- comment: '当时绑定的工作台 workstations.id(快照里有完整信息)',
- });
+ if (!await hasColumn(queryInterface, 'scan_records', 'workstation_id')) {
+ await queryInterface.addColumn('scan_records', 'workstation_id', {
+ type: BIGINT.UNSIGNED,
+ allowNull: true,
+ comment: '当时绑定的工作台 workstations.id(快照里有完整信息)',
+ });
+ }
- await queryInterface.addColumn('scan_records', 'workstation_snapshot', {
- type: JSONType,
- allowNull: true,
- comment: '工作台快照(录像机/摄像头/布局/录制范围),回放按它拉流',
- });
+ if (!await hasColumn(queryInterface, 'scan_records', 'workstation_snapshot')) {
+ await queryInterface.addColumn('scan_records', 'workstation_snapshot', {
+ type: JSONType,
+ allowNull: true,
+ comment: '工作台快照(录像机/摄像头/布局/录制范围),回放按它拉流',
+ });
+ }
- await queryInterface.addIndex('scan_records', [ 'subject_id', 'barcode' ], {
- name: 'idx_scan_subject_barcode',
- });
+ if (!await hasIndex(queryInterface, 'scan_records', 'idx_scan_subject_barcode')) {
+ await queryInterface.addIndex('scan_records', [ 'subject_id', 'barcode' ], {
+ name: 'idx_scan_subject_barcode',
+ });
+ }
- await queryInterface.addIndex('scan_records', [ 'scanner_id', 'channel_id', 'scan_time' ], {
- name: 'idx_scan_channel_seq',
- });
+ if (!await hasIndex(queryInterface, 'scan_records', 'idx_scan_channel_seq')) {
+ await queryInterface.addIndex('scan_records', [ 'scanner_id', 'channel_id', 'scan_time' ], {
+ name: 'idx_scan_channel_seq',
+ });
+ }
// 中控上报时按 (scanner_id, channel_id) 找工作台,没索引会全表扫
- await queryInterface.addIndex('workstation_scan_channels', [ 'scanner_id', 'channel_id' ], {
- name: 'idx_wsc_scanner_channel',
- });
+ if (!await hasIndex(queryInterface, 'workstation_scan_channels', 'idx_wsc_scanner_channel')) {
+ await queryInterface.addIndex('workstation_scan_channels', [ 'scanner_id', 'channel_id' ], {
+ name: 'idx_wsc_scanner_channel',
+ });
+ }
},
async down(queryInterface) {
diff --git a/backend/database/migrations/20261019120000-dedupe-scan-records.js b/backend/database/migrations/20261019120000-dedupe-scan-records.js
index ff3f0c8..8da2000 100644
--- a/backend/database/migrations/20261019120000-dedupe-scan-records.js
+++ b/backend/database/migrations/20261019120000-dedupe-scan-records.js
@@ -14,29 +14,48 @@
* - 每组保留:`scan_time` 最新的那一条,时间相同时保留 `id` 最大的(最后写入);
* - 其余行**物理删除**(scan_records 是流水表,没有软删除)。
*
+ * 兼容性:生产 MySQL 5.7 不支持窗口函数(ROW_NUMBER),这里用
+ * 「先按组查重、再逐组取最新一条」的方式实现,空表直接跳过。
+ *
* 不可逆:down() 不做恢复(被删的都是同一运单的旧记录,没有保留价值)。
*/
module.exports = {
async up(queryInterface) {
- const [ rows ] = await queryInterface.sequelize.query(`
- SELECT id FROM (
- SELECT id,
- ROW_NUMBER() OVER (
- PARTITION BY COALESCE(subject_id, 0), barcode
- ORDER BY scan_time DESC, id DESC
- ) AS rn
- FROM scan_records
- ) ranked
- WHERE rn > 1
+ const [ groups ] = await queryInterface.sequelize.query(`
+ SELECT COALESCE(subject_id, 0) AS sid, barcode, COUNT(*) AS total
+ FROM scan_records
+ GROUP BY COALESCE(subject_id, 0), barcode
+ HAVING COUNT(*) > 1
`);
- const ids = rows.map(row => Number(row.id));
- if (!ids.length) {
+ if (!groups.length) {
console.log('[dedupe] scan_records 没有重复运单号,跳过');
return;
}
+ const ids = [];
+ for (const group of groups) {
+ const [ rows ] = await queryInterface.sequelize.query(
+ `SELECT id
+ FROM scan_records
+ WHERE COALESCE(subject_id, 0) = ?
+ AND barcode = ?
+ ORDER BY scan_time DESC, id DESC`,
+ { replacements: [ group.sid, group.barcode ] }
+ );
+
+ // 第一条是「最新一条」,其余都是重复记录
+ for (const row of rows.slice(1)) {
+ ids.push(Number(row.id));
+ }
+ }
+
+ if (!ids.length) {
+ console.log('[dedupe] scan_records 没有需要删除的重复记录');
+ return;
+ }
+
await queryInterface.bulkDelete('scan_records', { id: ids });
console.log(`[dedupe] 已删除 ${ids.length} 条重复扫码记录(同一运单号只保留最后一条)`);
},
diff --git a/backend/package-lock.json b/backend/package-lock.json
index 0444951..c8b8ebe 100644
--- a/backend/package-lock.json
+++ b/backend/package-lock.json
@@ -19,12 +19,12 @@
"mysql2": "^3.24.6",
"nodemailer": "^10.1.2",
"qrcode-generator": "^2.0.4",
- "sequelize": "^6.37.8"
+ "sequelize": "^6.37.8",
+ "sequelize-cli": "^6.6.5"
},
"devDependencies": {
"egg-bin": "^6.13.0",
- "egg-mock": "^5.15.2",
- "sequelize-cli": "^6.6.5"
+ "egg-mock": "^5.15.2"
},
"engines": {
"node": ">=18.0.0"
@@ -269,7 +269,6 @@
"version": "8.0.2",
"resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz",
"integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==",
- "dev": true,
"license": "ISC",
"dependencies": {
"string-width": "^5.1.2",
@@ -287,7 +286,6 @@
"version": "6.4.0",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.4.0.tgz",
"integrity": "sha512-KzTVk2tCWAHtYrvvvaP8bJKJq2pVinhLcGEQdtLIYPbmNGNyYe8QwNaTUYQp2J7/vIsUKt5QCqAfUkYyG9DkOw==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">=12"
@@ -300,7 +298,6 @@
"version": "6.2.3",
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz",
"integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">=12"
@@ -313,14 +310,12 @@
"version": "9.2.2",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz",
"integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==",
- "dev": true,
"license": "MIT"
},
"node_modules/@isaacs/cliui/node_modules/string-width": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz",
"integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==",
- "dev": true,
"license": "MIT",
"dependencies": {
"eastasianwidth": "^0.2.0",
@@ -338,7 +333,6 @@
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz",
"integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==",
- "dev": true,
"license": "MIT",
"dependencies": {
"ansi-regex": "^6.2.2"
@@ -354,7 +348,6 @@
"version": "8.1.0",
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz",
"integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==",
- "dev": true,
"license": "MIT",
"dependencies": {
"ansi-styles": "^6.1.0",
@@ -565,7 +558,6 @@
"version": "0.1.1",
"resolved": "https://registry.npmjs.org/@one-ini/wasm/-/wasm-0.1.1.tgz",
"integrity": "sha512-XuySG1E38YScSJoMlqovLru4KTUNSjgVTIjyh7qMX6aNN5HY5Ct5LhRJdxO79JtTzKfzV/bnWpz+zquYrISsvw==",
- "dev": true,
"license": "MIT"
},
"node_modules/@paralleldrive/cuid2": {
@@ -582,7 +574,6 @@
"version": "0.11.0",
"resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz",
"integrity": "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==",
- "dev": true,
"license": "MIT",
"optional": true,
"engines": {
@@ -1308,7 +1299,6 @@
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/abbrev/-/abbrev-2.0.0.tgz",
"integrity": "sha512-6/mh1E2u2YgEsCHdY0Yx5oW+61gZU+1vXaoiHHrpKeuRNNgFvS+/jrwHiQhB5apAf5oB7UB7E19ol2R2LKH8hQ==",
- "dev": true,
"license": "ISC",
"engines": {
"node": "^14.17.0 || ^16.13.0 || >=18.0.0"
@@ -1415,7 +1405,6 @@
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
@@ -1522,7 +1511,6 @@
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/at-least-node/-/at-least-node-1.0.0.tgz",
"integrity": "sha512-+q/t7Ekv1EDY2l6Gda6LLiX14rU9TV20Wa3ofeQmwPFZbOMo9DXrLbOjFaaclkXKWidIaopwAObQDqwWtGUjqg==",
- "dev": true,
"license": "ISC",
"engines": {
"node": ">= 4.0.0"
@@ -1625,14 +1613,12 @@
"version": "3.7.2",
"resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.2.tgz",
"integrity": "sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==",
- "dev": true,
"license": "MIT"
},
"node_modules/brace-expansion": {
"version": "2.1.7",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz",
"integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==",
- "dev": true,
"license": "MIT",
"dependencies": {
"balanced-match": "^1.0.0"
@@ -2656,7 +2642,6 @@
"version": "1.1.13",
"resolved": "https://registry.npmjs.org/config-chain/-/config-chain-1.1.13.tgz",
"integrity": "sha512-qj+f8APARXHrM0hraqXYb2/bOVSV4PvJQlNZ/DVj0QrmNM2q2euizkeuVckQ57J+W0mRH6Hvi+k50M4Jul2VRQ==",
- "dev": true,
"license": "MIT",
"dependencies": {
"ini": "^1.3.4",
@@ -3150,7 +3135,6 @@
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz",
"integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==",
- "dev": true,
"license": "MIT"
},
"node_modules/ecdsa-sig-formatter": {
@@ -3166,7 +3150,6 @@
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/editorconfig/-/editorconfig-1.0.7.tgz",
"integrity": "sha512-e0GOtq/aTQhVdNyDU9e02+wz9oDDM+SIOQxWME2QRjzRX5yyLAuHDE+0aE8vHb9XRC8XD37eO2u57+F09JqFhw==",
- "dev": true,
"license": "MIT",
"dependencies": {
"@one-ini/wasm": "0.1.1",
@@ -3185,7 +3168,6 @@
"version": "10.0.1",
"resolved": "https://registry.npmjs.org/commander/-/commander-10.0.1.tgz",
"integrity": "sha512-y4Mg2tXshplEbSGzx7amzPwKKOCGuoSRP/CjEdwwk0FOGlUbq6lKuoyDZTNZkmxHdJtp54hdfY/JUrdL7Xfdug==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">=14"
@@ -3195,7 +3177,6 @@
"version": "9.0.9",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.9.tgz",
"integrity": "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==",
- "dev": true,
"license": "ISC",
"dependencies": {
"brace-expansion": "^2.0.2"
@@ -3211,7 +3192,6 @@
"version": "7.8.5",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
"integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
- "dev": true,
"license": "ISC",
"bin": {
"semver": "bin/semver.js"
@@ -4110,7 +4090,6 @@
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
"integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
- "dev": true,
"license": "MIT"
},
"node_modules/encodeurl": {
@@ -4194,7 +4173,6 @@
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",
"integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">=6"
@@ -4467,7 +4445,6 @@
"version": "3.3.1",
"resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz",
"integrity": "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==",
- "dev": true,
"license": "ISC",
"dependencies": {
"cross-spawn": "^7.0.6",
@@ -4484,7 +4461,6 @@
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
"integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
- "dev": true,
"license": "MIT",
"dependencies": {
"path-key": "^3.1.0",
@@ -4499,7 +4475,6 @@
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
"integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
@@ -4509,7 +4484,6 @@
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
"integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
- "dev": true,
"license": "MIT",
"dependencies": {
"shebang-regex": "^3.0.0"
@@ -4522,7 +4496,6 @@
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
"integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
@@ -4532,7 +4505,6 @@
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
"integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
- "dev": true,
"license": "ISC",
"dependencies": {
"isexe": "^2.0.0"
@@ -4871,7 +4843,6 @@
"version": "4.2.11",
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
"integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
- "dev": true,
"license": "ISC"
},
"node_modules/graceful-process": {
@@ -5323,7 +5294,6 @@
"version": "2.17.0",
"resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.17.0.tgz",
"integrity": "sha512-J/vG0zBCbIKOQFfufSwyXdMrsohyJIUNkrnmo6WZGzoM7tr/lsbfW5b2BvisL6zsyMzK9UxV9L6c7AoFbyXHOA==",
- "dev": true,
"license": "MIT",
"dependencies": {
"hasown": "^2.0.4"
@@ -5357,7 +5327,6 @@
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
"integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
@@ -5515,7 +5484,6 @@
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
"integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
- "dev": true,
"license": "ISC"
},
"node_modules/isstream": {
@@ -5590,7 +5558,6 @@
"version": "3.4.3",
"resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-3.4.3.tgz",
"integrity": "sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==",
- "dev": true,
"license": "BlueOak-1.0.0",
"dependencies": {
"@isaacs/cliui": "^8.0.2"
@@ -5715,7 +5682,6 @@
"version": "1.15.4",
"resolved": "https://registry.npmjs.org/js-beautify/-/js-beautify-1.15.4.tgz",
"integrity": "sha512-9/KXeZUKKJwqCXUdBxFJ3vPh467OCckSBmYDwSK/EtV090K+iMJ7zx2S3HLVDIWFQdqMIsZWbnaGiba18aWhaA==",
- "dev": true,
"license": "MIT",
"dependencies": {
"config-chain": "^1.1.13",
@@ -5738,7 +5704,6 @@
"resolved": "https://registry.npmjs.org/glob/-/glob-10.5.0.tgz",
"integrity": "sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==",
"deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me",
- "dev": true,
"license": "ISC",
"dependencies": {
"foreground-child": "^3.1.0",
@@ -5759,7 +5724,6 @@
"version": "9.0.9",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.9.tgz",
"integrity": "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==",
- "dev": true,
"license": "ISC",
"dependencies": {
"brace-expansion": "^2.0.2"
@@ -5775,7 +5739,6 @@
"version": "3.0.8",
"resolved": "https://registry.npmjs.org/js-cookie/-/js-cookie-3.0.8.tgz",
"integrity": "sha512-yeJd4aNAdYZQjaon2bpD/Gb0B/omw7HQOsynXXcOiWVCacbBcPlgn8S/d1X6blFSaHao7ozqtW7NZW19xpCtIw==",
- "dev": true,
"license": "MIT"
},
"node_modules/js-tokens": {
@@ -5830,7 +5793,6 @@
"version": "6.2.1",
"resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz",
"integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==",
- "dev": true,
"license": "MIT",
"dependencies": {
"universalify": "^2.0.0"
@@ -6443,7 +6405,6 @@
"version": "10.4.3",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz",
"integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==",
- "dev": true,
"license": "ISC"
},
"node_modules/lru.min": {
@@ -6673,7 +6634,6 @@
"version": "7.1.3",
"resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz",
"integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==",
- "dev": true,
"license": "BlueOak-1.0.0",
"engines": {
"node": ">=16 || 14 >=14.17"
@@ -7427,7 +7387,6 @@
"version": "7.2.1",
"resolved": "https://registry.npmjs.org/nopt/-/nopt-7.2.1.tgz",
"integrity": "sha512-taM24ViiimT/XntxbPyJQzCG+p4EKOpgD3mxFwW38mGjVUrfERQOeY4EDHjdnptttfHuHQXFx+lTP08Q+mLa/w==",
- "dev": true,
"license": "ISC",
"dependencies": {
"abbrev": "^2.0.0"
@@ -7757,7 +7716,6 @@
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz",
"integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==",
- "dev": true,
"license": "BlueOak-1.0.0"
},
"node_modules/param-case": {
@@ -7832,14 +7790,12 @@
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz",
"integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==",
- "dev": true,
"license": "MIT"
},
"node_modules/path-scurry": {
"version": "1.11.1",
"resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz",
"integrity": "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==",
- "dev": true,
"license": "BlueOak-1.0.0",
"dependencies": {
"lru-cache": "^10.2.0",
@@ -7892,7 +7848,6 @@
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
"integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
- "dev": true,
"license": "ISC"
},
"node_modules/picomatch": {
@@ -8014,7 +7969,6 @@
"version": "1.2.4",
"resolved": "https://registry.npmjs.org/proto-list/-/proto-list-1.2.4.tgz",
"integrity": "sha512-vtK/94akxsTMhe0/cbfpR+syPuszcuwhqVjJq26CuNDgFGj682oRBXOP5MJpv2r7JtE8MsiepGIqvvOTBwn2vA==",
- "dev": true,
"license": "ISC"
},
"node_modules/ps-tree": {
@@ -8309,7 +8263,6 @@
"version": "1.22.13",
"resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.13.tgz",
"integrity": "sha512-Dj/cW9zBV2aRj6XzCxuGIs3ESZKv02jixne3q6jFZYZ3/Tg09gHHviSMDL4kObh9pqSahdRHEnDoaP2gn8YLhA==",
- "dev": true,
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
@@ -8702,7 +8655,6 @@
"version": "6.6.5",
"resolved": "https://registry.npmjs.org/sequelize-cli/-/sequelize-cli-6.6.5.tgz",
"integrity": "sha512-DqyISCULOaEbTM+rRQH4YvcUWeOC1XDiSKcjsC6TfAnT7W837mNkChJhtB/Z4FdCFHRCojmiP7zsrA4pARmacA==",
- "dev": true,
"license": "MIT",
"dependencies": {
"fs-extra": "^9.1.0",
@@ -8725,7 +8677,6 @@
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
"integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
- "dev": true,
"license": "MIT",
"dependencies": {
"color-convert": "^2.0.1"
@@ -8741,7 +8692,6 @@
"version": "7.0.4",
"resolved": "https://registry.npmjs.org/cliui/-/cliui-7.0.4.tgz",
"integrity": "sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==",
- "dev": true,
"license": "ISC",
"dependencies": {
"string-width": "^4.2.0",
@@ -8753,7 +8703,6 @@
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
"integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
- "dev": true,
"license": "MIT",
"dependencies": {
"color-name": "~1.1.4"
@@ -8766,14 +8715,12 @@
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
- "dev": true,
"license": "MIT"
},
"node_modules/sequelize-cli/node_modules/fs-extra": {
"version": "9.1.0",
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-9.1.0.tgz",
"integrity": "sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ==",
- "dev": true,
"license": "MIT",
"dependencies": {
"at-least-node": "^1.0.0",
@@ -8789,7 +8736,6 @@
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz",
"integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==",
- "dev": true,
"license": "MIT",
"dependencies": {
"ansi-styles": "^4.0.0",
@@ -8807,7 +8753,6 @@
"version": "16.2.2",
"resolved": "https://registry.npmjs.org/yargs/-/yargs-16.2.2.tgz",
"integrity": "sha512-Nt9ZJjXTv5R8MHbqby/wXQ6Gi0Bb3TcYZkR1bzuL4yB2OxWPkXknz513gEF0GoA6tn00UpbPvERW8rzCuWCA6w==",
- "dev": true,
"license": "MIT",
"dependencies": {
"cliui": "^7.0.2",
@@ -8826,7 +8771,6 @@
"version": "20.2.9",
"resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.9.tgz",
"integrity": "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==",
- "dev": true,
"license": "ISC",
"engines": {
"node": ">=10"
@@ -9055,7 +8999,6 @@
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz",
"integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==",
- "dev": true,
"license": "ISC",
"engines": {
"node": ">=14"
@@ -9214,7 +9157,6 @@
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
"integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
- "dev": true,
"license": "MIT",
"dependencies": {
"emoji-regex": "^8.0.0",
@@ -9230,7 +9172,6 @@
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
"integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
- "dev": true,
"license": "MIT",
"dependencies": {
"emoji-regex": "^8.0.0",
@@ -9245,7 +9186,6 @@
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
- "dev": true,
"license": "MIT",
"dependencies": {
"ansi-regex": "^5.0.1"
@@ -9259,7 +9199,6 @@
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
- "dev": true,
"license": "MIT",
"dependencies": {
"ansi-regex": "^5.0.1"
@@ -9420,7 +9359,6 @@
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz",
"integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.4"
@@ -9877,7 +9815,6 @@
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/umzug/-/umzug-2.3.0.tgz",
"integrity": "sha512-Z274K+e8goZK8QJxmbRPhl89HPO1K+ORFtm6rySPhFKfKc5GHhqdzD0SGhSWHkzoXasqJuItdhorSvY7/Cgflw==",
- "dev": true,
"license": "MIT",
"dependencies": {
"bluebird": "^3.7.2"
@@ -9920,7 +9857,6 @@
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
"integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">= 10.0.0"
@@ -10289,7 +10225,6 @@
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz",
"integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==",
- "dev": true,
"license": "MIT",
"dependencies": {
"ansi-styles": "^4.0.0",
@@ -10307,7 +10242,6 @@
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
"integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
- "dev": true,
"license": "MIT",
"dependencies": {
"color-convert": "^2.0.1"
@@ -10323,7 +10257,6 @@
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
"integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
- "dev": true,
"license": "MIT",
"dependencies": {
"color-name": "~1.1.4"
@@ -10336,7 +10269,6 @@
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
- "dev": true,
"license": "MIT"
},
"node_modules/wrap-ansi/node_modules/ansi-styles": {
@@ -10454,7 +10386,6 @@
"version": "5.0.8",
"resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",
"integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==",
- "dev": true,
"license": "ISC",
"engines": {
"node": ">=10"
diff --git a/backend/package.json b/backend/package.json
index 5d9ffda..0100ee1 100644
--- a/backend/package.json
+++ b/backend/package.json
@@ -18,12 +18,12 @@
"mysql2": "^3.24.6",
"nodemailer": "^10.1.2",
"qrcode-generator": "^2.0.4",
- "sequelize": "^6.37.8"
+ "sequelize": "^6.37.8",
+ "sequelize-cli": "^6.6.5"
},
"devDependencies": {
"egg-bin": "^6.13.0",
- "egg-mock": "^5.15.2",
- "sequelize-cli": "^6.6.5"
+ "egg-mock": "^5.15.2"
},
"engines": {
"node": ">=18.0.0"
@@ -37,12 +37,34 @@
"cov": "egg-bin cov",
"db:init": "node scripts/init-db.js",
"db:deploy": "node scripts/db-deploy.js",
+ "db:deploy:prod": "node ./scripts/deploy/db-migrate-prod.cjs production",
+ "db:check:prod": "node ./scripts/deploy/db-migrate-prod.cjs production --check",
"db:migrate": "sequelize-cli db:migrate",
"db:migrate:undo": "sequelize-cli db:migrate:undo",
"db:migrate:status": "sequelize-cli db:migrate:status",
"db:migration:generate": "sequelize-cli migration:generate --name",
"user:pass": "node scripts/set-password.js",
"backfill:snapshot": "node scripts/backfill-snapshot.js",
- "records:dedupe": "node scripts/dedupe-scan-records.js"
+ "records:dedupe": "node scripts/dedupe-scan-records.js",
+ "deploy": "npm run deploy:prod",
+ "deploy:prod": "node ./scripts/deploy/deploy-remote.cjs production",
+ "deploy:precheck": "node ./scripts/deploy/deploy-precheck.cjs",
+ "deploy:authcheck": "node ./scripts/deploy/deploy-auth-check.cjs",
+ "deploy:version": "node ./scripts/deploy/deploy-version.cjs production",
+ "deploy:version:history": "node ./scripts/deploy/deploy-version.cjs production --history=20",
+ "deploy:inspect": "node ./scripts/deploy/deploy-ops.cjs production inspect",
+ "deploy:smoke": "node ./scripts/deploy/deploy-ops.cjs production smoke",
+ "deploy:verify": "node ./scripts/deploy/deploy-ops.cjs production verify",
+ "deploy:cleanup-backups": "node ./scripts/deploy/deploy-ops.cjs production cleanup-backups",
+ "rollback": "node ./scripts/deploy/rollback-remote.cjs production",
+ "rollback:prod": "node ./scripts/deploy/rollback-remote.cjs production",
+ "version:record": "node ./scripts/deploy/version-record.cjs",
+ "version:history": "node ./scripts/deploy/version-history.cjs --limit=50",
+ "desktop:build": "node ./scripts/deploy/publish-desktop.cjs production --dry-run",
+ "desktop:publish": "node ./scripts/deploy/publish-desktop.cjs production",
+ "android:build": "node ./scripts/deploy/publish-android.cjs production --dry-run",
+ "android:publish": "node ./scripts/deploy/publish-android.cjs production",
+ "guard:git": "node ./scripts/deploy/git-safety-check.cjs",
+ "setup:hooks": "node ./scripts/deploy/setup-git-hooks.cjs"
}
}
diff --git a/backend/scripts/db-config.js b/backend/scripts/db-config.js
index 0cde474..65f707b 100644
--- a/backend/scripts/db-config.js
+++ b/backend/scripts/db-config.js
@@ -2,13 +2,28 @@
/**
* 脚本共用的数据库连接信息解析:
- * 环境变量 > config/config.local.js(已 gitignore)> 内置默认值
+ * 环境变量 > 服务端配置 config.prod.js(EGG_SERVER_ENV=prod 时)> config/config.local.js(已 gitignore)> 内置默认值
*/
const fs = require('fs');
const path = require('path');
const { env } = process;
+const CONFIG_DIR = path.join(__dirname, '..', 'config');
+const APP_ROOT = path.join(__dirname, '..');
+const SERVER_ENV = String(env.EGG_SERVER_ENV || env.NODE_ENV || '').toLowerCase();
+
+/** 按 Egg 的加载规则读取配置(支持 config.prod.js 导出对象或函数) */
+function loadConfigFile(filePath, envName) {
+ if (!fs.existsSync(filePath)) {
+ return null;
+ }
+ const loaded = require(filePath);
+ if (typeof loaded === 'function') {
+ return loaded({ baseDir: APP_ROOT, env: envName, name: 'pack-service' });
+ }
+ return loaded;
+}
module.exports = function resolveDbConfig() {
const config = {
@@ -20,14 +35,33 @@ module.exports = function resolveDbConfig() {
multipleStatements: true,
};
- const localPath = path.join(__dirname, '..', 'config', 'config.local.js');
- if (fs.existsSync(localPath)) {
- const { sequelize = {} } = require(localPath);
- if (sequelize.host) config.host = sequelize.host;
- if (sequelize.port) config.port = sequelize.port;
- if (sequelize.username) config.user = sequelize.username;
- if (sequelize.password !== undefined) config.password = sequelize.password;
- if (sequelize.database) config.database = sequelize.database;
+ // 文档约定「环境变量 > 配置文件」:显式给了环境变量的字段,不允许被 local/prod 配置覆盖
+ const fromEnv = {
+ host: env.MYSQL_HOST !== undefined,
+ port: env.MYSQL_PORT !== undefined,
+ user: env.MYSQL_USER !== undefined,
+ password: env.MYSQL_PASSWORD !== undefined,
+ database: env.MYSQL_DATABASE !== undefined,
+ };
+
+ const isProd = SERVER_ENV === 'prod' || SERVER_ENV === 'production';
+ const candidates = isProd
+ ? [ path.join(CONFIG_DIR, 'config.prod.js'), path.join(CONFIG_DIR, 'config.local.js') ]
+ : [ path.join(CONFIG_DIR, 'config.local.js') ];
+
+ for (const filePath of candidates) {
+ const loaded = loadConfigFile(filePath, isProd ? 'prod' : 'local');
+ if (!loaded) continue;
+
+ const { sequelize = {} } = loaded;
+ if (sequelize.host && !fromEnv.host) config.host = sequelize.host;
+ if (sequelize.port && !fromEnv.port) config.port = sequelize.port;
+ if (sequelize.username && !fromEnv.user) config.user = sequelize.username;
+ if (sequelize.password !== undefined && !fromEnv.password) config.password = sequelize.password;
+ if (sequelize.database && !fromEnv.database) config.database = sequelize.database;
+ break;
}
+
return config;
};
+
diff --git a/backend/scripts/db-deploy.js b/backend/scripts/db-deploy.js
index 1c56d9e..dbd9612 100644
--- a/backend/scripts/db-deploy.js
+++ b/backend/scripts/db-deploy.js
@@ -15,7 +15,7 @@
* 只为老库保留:新库的 schema.sql 已经包含最终结构,重复执行会报 Duplicate column。
* 需要给很老的库补跑时手动执行,见 README「快速开始」。
*
- * 连接信息与运行时同源:环境变量 > config/config.local.js > 默认值(scripts/db-config.js)。
+ * 连接信息与运行时同源:环境变量 > config/config.prod.js(EGG_SERVER_ENV=prod)> config/config.local.js > 默认值(scripts/db-config.js)。
*/
const fs = require('fs');
diff --git a/backend/scripts/deploy/db-migrate-prod.cjs b/backend/scripts/deploy/db-migrate-prod.cjs
new file mode 100644
index 0000000..c820bfa
--- /dev/null
+++ b/backend/scripts/deploy/db-migrate-prod.cjs
@@ -0,0 +1,186 @@
+'use strict';
+
+/**
+ * 生产数据库迁移(本地执行,目标是生产库)
+ *
+ * 背景:生产 MySQL 账号是 `packservice@localhost`,只能从服务器本机登录,
+ * 所以这里用 SSH 隧道把「服务器 127.0.0.1:3306」映射到本地随机端口,
+ * 再复用 scripts/db-deploy.js(基线表 + 全部 Sequelize 迁移)。
+ *
+ * 用法:
+ * npm run db:deploy:prod # 执行基线 + 所有未执行迁移
+ * npm run db:check:prod # 只检查还有哪些迁移没执行(不改库)
+ *
+ * 连接信息来自本机权威副本 backend/config/env.prod.sh(含 MYSQL_*),
+ * SSH 信息来自 config/deploy.config.local.cjs(与 npm run deploy 相同)。
+ */
+
+const fs = require('node:fs');
+const net = require('node:net');
+const path = require('node:path');
+const { spawn, spawnSync } = require('node:child_process');
+const {
+ ROOT,
+ ensureCommandAvailable,
+ loadDeployConfig,
+} = require('./deploy-lib.cjs');
+
+const ENV_FILE = path.join(ROOT, 'config', 'env.prod.sh');
+const LOCAL_DB_HOSTS = new Set([ '127.0.0.1', 'localhost', '::1', '' ]);
+
+/** 解析 env.prod.sh 里的 `export KEY='value'`(不执行 shell) */
+function parseShellEnv(content) {
+ const result = {};
+ for (const line of content.split(/\r?\n/)) {
+ const match = line.match(/^\s*export\s+([A-Za-z_][A-Za-z0-9_]*)=(.*)$/);
+ if (!match) continue;
+
+ let value = match[2].trim();
+ if ((value.startsWith("'") && value.endsWith("'")) || (value.startsWith('"') && value.endsWith('"'))) {
+ value = value.slice(1, -1);
+ }
+ result[match[1]] = value;
+ }
+ return result;
+}
+
+function getFreePort() {
+ return new Promise((resolve, reject) => {
+ const server = net.createServer();
+ server.unref();
+ server.on('error', reject);
+ server.listen(0, '127.0.0.1', () => {
+ const { port } = server.address();
+ server.close(() => resolve(port));
+ });
+ });
+}
+
+function waitForPort(port, timeoutMs = 15000) {
+ const deadline = Date.now() + timeoutMs;
+ return new Promise((resolve, reject) => {
+ const attempt = () => {
+ const socket = net.connect({ host: '127.0.0.1', port });
+ socket.once('connect', () => {
+ socket.destroy();
+ resolve();
+ });
+ socket.once('error', () => {
+ socket.destroy();
+ if (Date.now() > deadline) {
+ reject(new Error(`等待 SSH 隧道端口 ${port} 超时`));
+ return;
+ }
+ setTimeout(attempt, 200);
+ });
+ };
+ attempt();
+ });
+}
+
+async function openTunnel(config, remotePort) {
+ const localPort = await getFreePort();
+ const args = [ '-N', '-p', String(config.port), '-i', config.privateKeyPath ];
+ for (const option of config.sshOptions) {
+ args.push('-o', option);
+ }
+ args.push('-L', `127.0.0.1:${localPort}:127.0.0.1:${remotePort}`, `${config.username}@${config.host}`);
+
+ const child = spawn('ssh', args, { stdio: [ 'ignore', 'ignore', 'pipe' ] });
+ let stderr = '';
+ child.stderr.on('data', chunk => { stderr += chunk.toString('utf8'); });
+
+ try {
+ await waitForPort(localPort);
+ } catch (err) {
+ child.kill();
+ throw new Error(`${err.message}${stderr ? `\n${stderr.trim()}` : ''}`);
+ }
+
+ return { child, localPort, getStderr: () => stderr };
+}
+
+async function main() {
+ const args = process.argv.slice(2);
+ const envName = args.find(item => !item.startsWith('--')) || 'production';
+ const checkOnly = args.includes('--check') || args.includes('--dry-run');
+
+ if (!fs.existsSync(ENV_FILE)) {
+ throw new Error(`缺少生产环境变量文件: ${ENV_FILE}(npm run deploy 会自动上传,但本地迁移需要本机副本)`);
+ }
+
+ const envValues = parseShellEnv(fs.readFileSync(ENV_FILE, 'utf8'));
+ const database = envValues.MYSQL_DATABASE || 'packservice';
+ const dbUser = envValues.MYSQL_USER || 'packservice';
+ const dbPassword = envValues.MYSQL_PASSWORD || '';
+ const dbHost = envValues.MYSQL_HOST || '127.0.0.1';
+ const dbPort = Number(envValues.MYSQL_PORT || 3306);
+
+ if (!dbPassword) {
+ throw new Error(`env.prod.sh 未提供 MYSQL_PASSWORD,拒绝连接生产库`);
+ }
+
+ const config = loadDeployConfig(envName);
+ ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。');
+
+ console.log(`[DB-PROD] 目标库: ${dbHost}:${dbPort}/${database} as ${dbUser}`);
+ console.log(`[DB-PROD] 模式: ${checkOnly ? '只检查(--check)' : '执行迁移'}`);
+
+ let tunnel = null;
+ const cleanup = () => {
+ if (tunnel && !tunnel.child.killed) {
+ tunnel.child.kill();
+ }
+ };
+ process.on('exit', cleanup);
+ process.on('SIGINT', () => {
+ cleanup();
+ process.exit(130);
+ });
+
+ let mysqlHost = dbHost;
+ let mysqlPort = dbPort;
+
+ if (LOCAL_DB_HOSTS.has(dbHost)) {
+ console.log(`[DB-PROD] MySQL 仅服务器本机可连,建立 SSH 隧道: ${config.username}@${config.host}`);
+ tunnel = await openTunnel(config, dbPort);
+ mysqlHost = '127.0.0.1';
+ mysqlPort = tunnel.localPort;
+ console.log(`[DB-PROD] 隧道就绪: 127.0.0.1:${mysqlPort} -> ${config.host}:127.0.0.1:${dbPort}`);
+ }
+
+ const childEnv = {
+ ...process.env,
+ NODE_ENV: 'production',
+ EGG_SERVER_ENV: 'prod',
+ MYSQL_HOST: mysqlHost,
+ MYSQL_PORT: String(mysqlPort),
+ MYSQL_USER: dbUser,
+ MYSQL_PASSWORD: dbPassword,
+ MYSQL_DATABASE: database,
+ };
+
+ const dbArgs = [ path.join('scripts', 'db-deploy.js') ];
+ if (checkOnly) {
+ dbArgs.push('--check');
+ }
+
+ try {
+ const result = spawnSync(process.execPath, dbArgs, {
+ cwd: ROOT,
+ env: childEnv,
+ stdio: 'inherit',
+ });
+ process.exitCode = result.status === null ? 1 : result.status;
+ } finally {
+ cleanup();
+ if (tunnel && tunnel.getStderr().trim()) {
+ console.warn(`[DB-PROD] SSH 隧道日志: ${tunnel.getStderr().trim().split('\n').slice(-3).join(' | ')}`);
+ }
+ }
+}
+
+main().catch(err => {
+ console.error(`[DB-PROD] 失败: ${err && err.message ? err.message : err}`);
+ process.exit(1);
+});
diff --git a/backend/scripts/deploy/deploy-auth-check.cjs b/backend/scripts/deploy/deploy-auth-check.cjs
new file mode 100644
index 0000000..b1c2431
--- /dev/null
+++ b/backend/scripts/deploy/deploy-auth-check.cjs
@@ -0,0 +1,38 @@
+'use strict';
+
+const { spawnSync } = require('node:child_process');
+const { loadDeployConfig } = require('./deploy-lib.cjs');
+
+function main() {
+ const config = loadDeployConfig('production');
+
+ const args = [ '-vv' ];
+ args.push('-p', String(config.port));
+ args.push('-i', config.privateKeyPath);
+ for (const option of config.sshOptions) {
+ args.push('-o', option);
+ }
+ args.push(`${config.username}@${config.host}`);
+ args.push('echo AUTH_CHECK_OK');
+
+ const result = spawnSync('ssh', args, {
+ encoding: 'utf8',
+ stdio: 'pipe',
+ shell: false,
+ });
+
+ const text = `${result.stdout || ''}\n${result.stderr || ''}`;
+ const summary = {
+ keyOffered: /Offering public key:/i.test(text) || /Will attempt key:/i.test(text),
+ keyAccepted: /Authenticated to .* using "publickey"/i.test(text) || /AUTH_CHECK_OK/i.test(text),
+ authFailed: /Permission denied|Authentication failed/i.test(text),
+ hostKeyFailed: /Host key verification failed|REMOTE HOST IDENTIFICATION HAS CHANGED/i.test(text),
+ networkFailed: /Connection timed out|No route to host|Connection refused|Could not resolve hostname|Operation timed out/i.test(text),
+ };
+
+ console.log(JSON.stringify(summary, null, 2));
+
+ process.exit(summary.keyAccepted ? 0 : 1);
+}
+
+main();
diff --git a/backend/scripts/deploy/deploy-lib.cjs b/backend/scripts/deploy/deploy-lib.cjs
new file mode 100644
index 0000000..0ff3cd8
--- /dev/null
+++ b/backend/scripts/deploy/deploy-lib.cjs
@@ -0,0 +1,707 @@
+'use strict';
+
+/**
+ * 发布脚手架公共库(参考 D:\wms\script\deploy-lib.cjs)
+ *
+ * 约定:
+ * - 远端采用 v1 / v2 双实例目录 + current.md 记录当前活跃版本,健康检查通过后才切 Nginx upstream;
+ * - 发布包只包含 git 跟踪的后端源码;前端构建产物单独发布到 deployRoot/frontend,由 nginx 直接托管;
+ * - 服务端私有配置(config/config.prod.js 等)与运行期目录(logs/run/temp、安装包)在发布前暂存、发布后放回。
+ */
+
+const fs = require('node:fs');
+const path = require('node:path');
+const { spawnSync } = require('node:child_process');
+
+/** backend 根目录 */
+const ROOT = path.resolve(__dirname, '..', '..');
+/** git 仓库根目录(monorepo 根) */
+const REPO_ROOT = path.resolve(ROOT, '..');
+const LOCAL_CONFIG_PATH = path.join(ROOT, 'config', 'deploy.config.local.cjs');
+const EXAMPLE_CONFIG_PATH = path.join(ROOT, 'config', 'deploy.config.example.cjs');
+const DEFAULT_ENV = 'production';
+const DEFAULT_PORTS = { v1: 7301, v2: 7302 };
+
+/** 发布包包含的后端源码路径(相对 backend/) */
+const DEFAULT_INCLUDE_PATHS = [
+ '.sequelizerc',
+ 'jsconfig.json',
+ 'package.json',
+ 'package-lock.json',
+ 'app/**',
+ 'config/**',
+ 'database/**',
+ 'scripts/**',
+ 'sql/**',
+];
+
+/** 默认保留的服务端私有文件/目录(清理前暂存,解压后放回) */
+const DEFAULT_PRESERVE_PATHS = [
+ 'config/config.prod.js',
+ 'config/config.local.js',
+ 'app/public/download',
+ 'app/public/version',
+];
+
+/** 服务端托管的运行期目录:清理代码时保留 */
+const DEFAULT_SHARED_DIRS = [ 'node_modules', 'logs', 'run', 'temp' ];
+
+/** 无论配置怎么写都不允许进入发布包的私有配置 */
+function isServerManagedConfig(relativePath) {
+ const normalized = String(relativePath || '').replace(/\\/g, '/');
+ const baseName = normalized.split('/').pop();
+ if (!normalized.startsWith('config/')) {
+ return false;
+ }
+ return baseName === 'config.prod.js'
+ || baseName === 'config.local.js'
+ || /^deploy\.config\..*\.cjs$/.test(baseName)
+ || /^env\..*\.sh$/.test(baseName)
+ || /\.local\.js$/.test(baseName);
+}
+
+function quoteForBash(value) {
+ return `'${String(value).replace(/'/g, "'\"'\"'")}'`;
+}
+
+function runCommand(command, args, options = {}) {
+ const result = spawnSync(command, args, {
+ cwd: options.cwd || ROOT,
+ encoding: 'utf8',
+ stdio: options.stdio || 'pipe',
+ shell: Boolean(options.shell),
+ });
+
+ if (result.error) {
+ throw result.error;
+ }
+
+ if (result.status !== 0) {
+ const stderr = (result.stderr || '').trim();
+ const stdout = (result.stdout || '').trim();
+ throw new Error(stderr || stdout || `${command} exited with code ${result.status}`);
+ }
+
+ return (result.stdout || '').trim();
+}
+
+function runNpm(args, cwd) {
+ if (process.platform === 'win32') {
+ const comspec = process.env.ComSpec || 'cmd.exe';
+ return runCommand(comspec, [ '/d', '/s', '/c', `npm ${args.join(' ')}` ], {
+ cwd: cwd || ROOT,
+ stdio: 'inherit',
+ });
+ }
+ return runCommand('npm', args, {
+ cwd: cwd || ROOT,
+ stdio: 'inherit',
+ });
+}
+
+function ensureCommandAvailable(command, installHint) {
+ const result = spawnSync(command, [], {
+ cwd: ROOT,
+ encoding: 'utf8',
+ stdio: 'pipe',
+ shell: false,
+ });
+
+ if (result.error && result.error.code === 'ENOENT') {
+ throw new Error(`${command} 不可用。${installHint}`);
+ }
+}
+
+function getNowStamp() {
+ const now = new Date();
+ const pad = value => String(value).padStart(2, '0');
+ return `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
+}
+
+function ensureTempDeployDir() {
+ const tempDir = path.join(ROOT, 'temp', 'deploy');
+ fs.mkdirSync(tempDir, { recursive: true });
+ return tempDir;
+}
+
+function isPlaceholder(value) {
+ if (!value) {
+ return true;
+ }
+ return String(value).includes('__FILL_');
+}
+
+function normalizeDeployConfig(config, envName) {
+ const deployRoot = String(config.deployRoot || '/www/wwwroot/packService').replace(/\/+$/, '');
+ const privateKeyPath = config.privateKeyPath ? path.resolve(ROOT, config.privateKeyPath) : '';
+ const ports = {
+ v1: Number((config.ports && config.ports.v1) || DEFAULT_PORTS.v1),
+ v2: Number((config.ports && config.ports.v2) || DEFAULT_PORTS.v2),
+ };
+
+ if (!Number.isInteger(ports.v1) || !Number.isInteger(ports.v2) || ports.v1 === ports.v2) {
+ throw new Error(`部署端口配置无效: ${JSON.stringify(ports)},v1 / v2 必须是两个不同的整数端口。`);
+ }
+
+ const preservePaths = Array.isArray(config.preservePaths) && config.preservePaths.length > 0
+ ? [ ...config.preservePaths ]
+ : [ ...DEFAULT_PRESERVE_PATHS ];
+
+ for (const item of preservePaths) {
+ if (path.posix.isAbsolute(String(item)) || String(item).split('/').includes('..')) {
+ throw new Error(`preservePaths 只允许 backend/ 下的相对路径: ${item}`);
+ }
+ }
+
+ const sshOptions = Array.isArray(config.sshOptions) ? [ ...config.sshOptions ] : [];
+ const requiredSshOptions = [
+ [ /^IdentitiesOnly=/i, 'IdentitiesOnly=yes' ],
+ [ /^PreferredAuthentications=/i, 'PreferredAuthentications=publickey' ],
+ [ /^PubkeyAuthentication=/i, 'PubkeyAuthentication=yes' ],
+ [ /^PasswordAuthentication=/i, 'PasswordAuthentication=no' ],
+ [ /^KbdInteractiveAuthentication=/i, 'KbdInteractiveAuthentication=no' ],
+ [ /^BatchMode=/i, 'BatchMode=yes' ],
+ [ /^ConnectTimeout=/i, 'ConnectTimeout=10' ],
+ ];
+ for (const [ matcher, option ] of requiredSshOptions) {
+ if (!sshOptions.some(item => matcher.test(item))) {
+ sshOptions.push(option);
+ }
+ }
+
+ return {
+ envName,
+ host: config.host,
+ port: Number(config.port || 22),
+ username: config.username,
+ privateKeyPath,
+ deployRoot,
+ controlDir: `${deployRoot}/.deploy`,
+ incomingDir: `${deployRoot}/.deploy/incoming`,
+ backupDir: `${deployRoot}/.deploy/backups`,
+ stateDir: `${deployRoot}/.deploy/state`,
+ ports,
+ healthCheckPath: config.healthCheckPath || '/health',
+ healthCheckAttempts: Number(config.healthCheckAttempts || 30),
+ healthCheckInterval: Number(config.healthCheckInterval || 2),
+ nginxUpstreamFile: config.nginxUpstreamFile === undefined
+ ? `${deployRoot}/nginx-upstream.conf`
+ : String(config.nginxUpstreamFile || ''),
+ // 服务端私有配置目录(不随发布包走):放 config.prod.js / config.local.js / env.prod.sh
+ sharedConfigDir: config.sharedConfigDir === undefined
+ ? `${deployRoot}/shared-config`
+ : String(config.sharedConfigDir || ''),
+ envFile: config.envFile || 'env.prod.sh',
+ envFileLocalPath: path.resolve(ROOT, config.envFileLocalPath || path.join('config', config.envFile || 'env.prod.sh')),
+ uploadEnvFile: config.uploadEnvFile !== false,
+ sharedDirs: Array.isArray(config.sharedDirs) ? config.sharedDirs : [ ...DEFAULT_SHARED_DIRS ],
+ preservePaths,
+ keepBackups: Number(config.keepBackups || 5),
+ buildFrontend: config.buildFrontend !== false,
+ frontendDir: config.frontendDir || '../frontend',
+ frontendDeployDir: config.frontendDeployDir || `${deployRoot}/frontend`,
+ frontendPrevDir: `${config.frontendDeployDir || `${deployRoot}/frontend`}.prev`,
+ nginxFrontConf: config.nginxFrontConf === undefined ? `${deployRoot}/front.conf` : String(config.nginxFrontConf || ''),
+ manageNginxFrontConf: config.manageNginxFrontConf !== false,
+ serverName: config.serverName || '',
+ // 桌面端发布(npm run desktop:publish)
+ desktopBuildScript: config.desktopBuildScript || '../desktop/installer/build.ps1',
+ desktopOutDir: config.desktopOutDir || '../desktop/installer/out',
+ desktopDownloadDir: config.desktopDownloadDir || `${deployRoot}/download/desktop`,
+ // version.json 不放安装包目录里:nginx 对 /download/version.json 单独关缓存,安装包目录走长缓存
+ desktopVersionDir: config.desktopVersionDir || `${deployRoot}/download`,
+ desktopBaseUrl: config.desktopBaseUrl || (config.serverName ? `http://${config.serverName}` : ''),
+ desktopKeepVersions: Number(config.desktopKeepVersions || 5),
+ desktopOwner: config.desktopOwner || 'www:www',
+ // Android 设备端发布(npm run android:publish)
+ androidBuildScript: config.androidBuildScript || 'android_client/build.ps1',
+ androidOutDir: config.androidOutDir || 'android_client/out',
+ androidDownloadDir: config.androidDownloadDir || `${deployRoot}/download/android_client`,
+ androidVersionDir: config.androidVersionDir || config.androidDownloadDir || `${deployRoot}/download/android_client`,
+ androidBaseUrl: config.androidBaseUrl || config.desktopBaseUrl || (config.serverName ? `http://${config.serverName}` : ''),
+ androidKeepVersions: Number(config.androidKeepVersions || 5),
+ androidOwner: config.androidOwner || 'www:www',
+ remoteDbDeploy: Boolean(config.remoteDbDeploy),
+ deployIncludePaths: Array.isArray(config.deployIncludePaths) && config.deployIncludePaths.length > 0
+ ? [ ...config.deployIncludePaths ]
+ : [ ...DEFAULT_INCLUDE_PATHS ],
+ deployExcludePaths: Array.isArray(config.deployExcludePaths) ? [ ...config.deployExcludePaths ] : [],
+ sshOptions,
+ };
+}
+
+function validateDeployConfig(config, configPath, envName) {
+ if (!config) {
+ throw new Error(`${configPath} 中未找到 ${envName} 配置。`);
+ }
+
+ const missing = [];
+ if (isPlaceholder(config.host)) missing.push('host');
+ if (isPlaceholder(config.username)) missing.push('username');
+ if (isPlaceholder(config.privateKeyPath)) missing.push('privateKeyPath');
+
+ if (missing.length > 0) {
+ throw new Error(`请先完善 SSH 配置字段: ${missing.join(', ')}。配置文件: ${configPath}`);
+ }
+
+ const resolvedPrivateKeyPath = path.resolve(ROOT, config.privateKeyPath);
+ if (!fs.existsSync(resolvedPrivateKeyPath)) {
+ throw new Error(`SSH 私钥不存在: ${resolvedPrivateKeyPath}。请先修正 config/deploy.config.local.cjs 中的 privateKeyPath。`);
+ }
+}
+
+function loadDeployConfig(envName = DEFAULT_ENV) {
+ if (!fs.existsSync(LOCAL_CONFIG_PATH)) {
+ throw new Error(`缺少本地部署配置 ${LOCAL_CONFIG_PATH}。请复制 ${EXAMPLE_CONFIG_PATH} 并填入 SSH 信息。`);
+ }
+
+ delete require.cache[LOCAL_CONFIG_PATH];
+ const loaded = require(LOCAL_CONFIG_PATH);
+ const config = loaded[envName];
+ validateDeployConfig(config, LOCAL_CONFIG_PATH, envName);
+ return normalizeDeployConfig(config, envName);
+}
+
+function buildSshBaseArgs(config) {
+ const args = [ '-p', String(config.port), '-i', config.privateKeyPath ];
+ for (const option of config.sshOptions) {
+ args.push('-o', option);
+ }
+ return args;
+}
+
+function runSsh(config, remoteScript, options = {}) {
+ const args = [
+ ...buildSshBaseArgs(config),
+ `${config.username}@${config.host}`,
+ `bash -lc ${quoteForBash(remoteScript)}`,
+ ];
+
+ return runCommand('ssh', args, {
+ stdio: options.stdio || 'inherit',
+ });
+}
+
+function runScp(config, localPath, remotePath) {
+ const args = [ '-P', String(config.port), '-i', config.privateKeyPath ];
+ for (const option of config.sshOptions) {
+ args.push('-o', option);
+ }
+
+ args.push(localPath, `${config.username}@${config.host}:${remotePath}`);
+
+ return runCommand('scp', args, { stdio: 'inherit' });
+}
+
+function normalizeRule(rule) {
+ return String(rule || '').replace(/\\/g, '/').trim();
+}
+
+function pathMatchesRule(filePath, rule) {
+ const normalizedPath = String(filePath || '').replace(/\\/g, '/');
+ const normalizedRule = normalizeRule(rule);
+
+ if (!normalizedRule) {
+ return false;
+ }
+ if (normalizedRule.endsWith('/**')) {
+ const prefix = normalizedRule.slice(0, -3);
+ return normalizedPath === prefix || normalizedPath.startsWith(`${prefix}/`);
+ }
+ if (normalizedRule.endsWith('/')) {
+ return normalizedPath.startsWith(normalizedRule);
+ }
+ return normalizedPath === normalizedRule;
+}
+
+function listDeployableFiles(config) {
+ const output = runCommand('git', [ 'ls-files', '--cached', '--others', '--exclude-standard' ]);
+ const includeRules = config.deployIncludePaths || DEFAULT_INCLUDE_PATHS;
+ const excludeRules = config.deployExcludePaths || [];
+
+ return Array.from(new Set(
+ output
+ .split(/\r?\n/)
+ .map(item => item.trim())
+ .filter(Boolean)
+ .filter(item => !item.startsWith('.git/'))
+ .filter(item => fs.existsSync(path.join(ROOT, item)))
+ .filter(item => includeRules.some(rule => pathMatchesRule(item, rule)))
+ .filter(item => !excludeRules.some(rule => pathMatchesRule(item, rule)))
+ .filter(item => !isServerManagedConfig(item)),
+ ));
+}
+
+function resolveFrontendDistDir(config) {
+ return path.resolve(ROOT, config.frontendDir, 'dist');
+}
+
+/**
+ * 生成发布包:只包含后端源码(前端由 buildFrontendArchive 单独发布)
+ *
+ * @param {string} stamp - 时间戳
+ * @param {object} config - 规范化后的部署配置
+ * @return {{ archivePath: string, fileCount: number }} 发布包路径与后端文件数量
+ */
+function buildArchive(stamp, config) {
+ const tempDir = ensureTempDeployDir();
+ const stageDir = path.join(tempDir, `stage-${stamp}`);
+ const archivePath = path.join(tempDir, `release-${stamp}.tar.gz`);
+ const files = listDeployableFiles(config);
+
+ if (files.length === 0) {
+ throw new Error('git ls-files 未返回可发布文件,无法生成发布包。');
+ }
+
+ fs.rmSync(stageDir, { recursive: true, force: true });
+ fs.mkdirSync(stageDir, { recursive: true });
+
+ for (const relativePath of files) {
+ const source = path.join(ROOT, relativePath);
+ const destination = path.join(stageDir, relativePath);
+ fs.mkdirSync(path.dirname(destination), { recursive: true });
+ fs.copyFileSync(source, destination);
+ }
+
+ try {
+ runCommand('tar', [ '-czf', archivePath, '-C', stageDir, '.' ], { stdio: 'inherit' });
+ } finally {
+ fs.rmSync(stageDir, { recursive: true, force: true });
+ }
+
+ return { archivePath, fileCount: files.length };
+}
+
+/**
+ * 生成前端发布包(frontend/dist → nginx 静态目录)
+ *
+ * @param {string} stamp - 时间戳
+ * @param {object} config - 部署配置
+ * @return {{ archivePath: string }} 前端发布包路径
+ */
+function buildFrontendArchive(stamp, config) {
+ const distDir = resolveFrontendDistDir(config);
+ if (!fs.existsSync(path.join(distDir, 'index.html'))) {
+ throw new Error(`前端构建产物不存在: ${path.join(distDir, 'index.html')}。请先执行 frontend 的 npm run build。`);
+ }
+
+ const archivePath = path.join(ensureTempDeployDir(), `frontend-${stamp}.tar.gz`);
+ runCommand('tar', [ '-czf', archivePath, '-C', distDir, '.' ], { stdio: 'inherit' });
+ return { archivePath };
+}
+
+/** 生成由 nginx 直接托管的前端 / 反代配置(front.conf) */
+function buildFrontConf(config) {
+ const upstreamInclude = config.nginxUpstreamFile
+ ? ` include ${config.nginxUpstreamFile};\n`
+ : '';
+ const proxyCommon = [
+ ' proxy_set_header Host $http_host;',
+ ' proxy_set_header X-Real-IP $remote_addr;',
+ ' proxy_set_header X-Real-Port $remote_port;',
+ ' proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;',
+ ' proxy_set_header X-Forwarded-Proto $scheme;',
+ ' proxy_set_header X-Forwarded-Host $host;',
+ ' proxy_set_header X-Forwarded-Port $server_port;',
+ ' proxy_connect_timeout 60s;',
+ ' proxy_send_timeout 600s;',
+ ' proxy_read_timeout 600s;',
+ ' proxy_http_version 1.1;',
+ ' proxy_set_header Upgrade $http_upgrade;',
+ ' proxy_set_header Connection $connection_upgrade;',
+ ].join('\n');
+
+ const proxyLocation = name => [
+ `${name} {`,
+ upstreamInclude + proxyCommon,
+ '}',
+ ].join('\n');
+
+ // nginx 的 add_header 一旦在 location 里出现就不会继承 server 级配置,
+ // 因此每个自带 add_header 的 location 都要重复声明 HSTS。
+ const hsts = ' add_header Strict-Transport-Security "max-age=31536000" always;';
+
+ return [
+ '# 由 packService 发布脚本自动维护,请勿手工修改(改模板见 backend/scripts/deploy/deploy-lib.cjs)',
+ '',
+ 'location / {',
+ ` root ${config.frontendDeployDir};`,
+ ' index index.html;',
+ hsts,
+ ' try_files $uri $uri/ /index.html;',
+ '}',
+ '',
+ 'location = /index.html {',
+ ` root ${config.frontendDeployDir};`,
+ ' add_header Cache-Control "no-cache, no-store, must-revalidate";',
+ hsts,
+ '}',
+ '',
+ 'location ^~ /assets/ {',
+ ` root ${config.frontendDeployDir};`,
+ ' expires 30d;',
+ ' add_header Cache-Control "public, immutable";',
+ hsts,
+ ' try_files $uri =404;',
+ '}',
+ '',
+ ...(config.nginxUpstreamFile
+ ? [
+ proxyLocation('location ^~ /api/'),
+ '',
+ proxyLocation('location = /health'),
+ ]
+ : [ '# nginxUpstreamFile 未配置,跳过 /api、/health 反代' ]),
+ '',
+ '# 桌面端 / Android 安装包:由 nginx 直接托管 deployRoot/download',
+ '# download/desktop/*.msi、download/android_client/*.apk 长缓存;',
+ '# version.json 一律不缓存(客户端靠它判断有没有新版本)。',
+ 'location = /download/version.json {',
+ ` root ${config.deployRoot};`,
+ ' default_type application/json;',
+ ' add_header Cache-Control "no-store, no-cache, must-revalidate, max-age=0";',
+ ' add_header Pragma "no-cache";',
+ hsts,
+ ' expires 0;',
+ '}',
+ '',
+ 'location = /download/android_client/version.json {',
+ ` root ${config.deployRoot};`,
+ ' default_type application/json;',
+ ' add_header Cache-Control "no-store, no-cache, must-revalidate, max-age=0";',
+ ' add_header Pragma "no-cache";',
+ hsts,
+ ' expires 0;',
+ '}',
+ '',
+ 'location ^~ /download/ {',
+ ` root ${config.deployRoot};`,
+ ' expires 30d;',
+ ' add_header Cache-Control "public";',
+ hsts,
+ ' try_files $uri =404;',
+ '}',
+ '',
+ ].join('\n');
+}
+
+function buildRemoteCleanupGuard(sharedDirs) {
+ const preserved = Array.from(new Set([ ...sharedDirs ]));
+ return preserved.map(item => `! -name ${quoteForBash(item)}`).join(' ');
+}
+
+/**
+ * 写 front.conf(静态 /download + /api 反代)并 reload nginx
+ *
+ * 桌面端 / Android 发布脚本共用:只动静态托管配置,不碰 Egg 进程。
+ */
+function refreshNginx(config) {
+ if (!config.manageNginxFrontConf || !config.nginxFrontConf) {
+ console.log('未启用 nginxFrontConf 维护,跳过 nginx 配置更新。');
+ return;
+ }
+
+ const base64 = Buffer.from(buildFrontConf(config), 'utf8').toString('base64');
+ runSsh(config, [
+ 'set -euo pipefail',
+ `TARGET=${quoteForBash(config.nginxFrontConf)}`,
+ 'mkdir -p "$(dirname "$TARGET")"',
+ `printf '%s' ${quoteForBash(base64)} | base64 -d > "$TARGET"`,
+ 'echo "FRONT_CONF_WRITTEN"',
+ ].join('\n'), { stdio: 'pipe' });
+
+ try {
+ runSsh(config, 'set -euo pipefail; nginx -t && nginx -s reload', { stdio: 'pipe' });
+ console.log(`nginx 已刷新: ${config.nginxFrontConf}`);
+ } catch (err) {
+ console.warn(`[WARN] nginx reload 失败: ${err.message}`);
+ console.warn('[WARN] 请人工执行 nginx -t && nginx -s reload');
+ }
+}
+
+/**
+ * 生成「服务端私有文件保护」远端脚本行(发布 / 回退共用)
+ *
+ * @param {string} dirVar - 目标目录变量名,如 TARGET_DIR
+ * @param {string} stashDirVar - 暂存目录变量名,如 PINNED_DIR
+ * @param {string[]} preservePaths - backend/ 下的相对路径(文件或目录)
+ * @return {{ stash: string[], restore: string[] }} 远端脚本行
+ */
+function buildPinnedPathGuardLines(dirVar, stashDirVar, preservePaths) {
+ const quoted = preservePaths.map(quoteForBash);
+ const stash = [
+ `mkdir -p "$${stashDirVar}"`,
+ `for REL in ${quoted.join(' ')}; do`,
+ ` if [ -e "$${dirVar}/$REL" ]; then`,
+ ` mkdir -p "$${stashDirVar}/$(dirname "$REL")"`,
+ ` rm -rf "$${stashDirVar}/$REL"`,
+ ` cp -a "$${dirVar}/$REL" "$${stashDirVar}/$REL" && echo "PINNED_SAVED $REL"`,
+ ' fi',
+ 'done',
+ ];
+ const restore = [
+ `for REL in ${quoted.join(' ')}; do`,
+ ` if [ -e "$${stashDirVar}/$REL" ]; then`,
+ ` rm -rf "$${dirVar}/$REL"`,
+ ` mkdir -p "$${dirVar}/$(dirname "$REL")"`,
+ ` cp -a "$${stashDirVar}/$REL" "$${dirVar}/$REL" && echo "PINNED_RESTORED $REL"`,
+ ' fi',
+ 'done',
+ `rm -rf "$${stashDirVar}"`,
+ ];
+ return { stash, restore };
+}
+
+/** 生成释放指定端口的远端脚本 */
+function buildKillPortScript(port) {
+ return [
+ 'set -euo pipefail',
+ `TARGET_PORT=${Number(port)}`,
+ "PORT_PID=$(ss -tlnp 2>/dev/null | awk -v p=\":$TARGET_PORT \" 'index($0, p)' | grep -oP 'pid=\\K[0-9]+' | head -1 || true)",
+ 'if [ -n "$PORT_PID" ]; then',
+ ' echo "检测到端口 $TARGET_PORT 被进程 $PORT_PID 占用,发送停止信号..."',
+ ' kill "$PORT_PID" 2>/dev/null || true',
+ ' sleep 5',
+ " PORT_PID_CHECK=$(ss -tlnp 2>/dev/null | awk -v p=\":$TARGET_PORT \" 'index($0, p)' | grep -oP 'pid=\\K[0-9]+' | head -1 || true)",
+ ' if [ -n "$PORT_PID_CHECK" ]; then',
+ ' echo "[WARN] 端口 $TARGET_PORT 仍有进程 $PORT_PID_CHECK,强制停止..."',
+ ' kill -9 "$PORT_PID_CHECK" 2>/dev/null || true',
+ ' fuser -k "$TARGET_PORT/tcp" 2>/dev/null || true',
+ ' fi',
+ ' echo "端口 $TARGET_PORT 已释放"',
+ 'else',
+ ' echo "端口 $TARGET_PORT 空闲,无需清理"',
+ 'fi',
+ ].join('\n');
+}
+
+/** 远端环境变量文件(由 start 脚本 source,里面的变量会导出给 npm start) */
+function getRemoteEnvFile(config) {
+ if (!config.sharedConfigDir) {
+ return '';
+ }
+ return `${config.sharedConfigDir}/${config.envFile}`;
+}
+
+/** 生成在指定目录启动实例的远端脚本(前端已由 nginx 托管,不再注入 FRONTEND_DIST) */
+function buildStartScript({ dir, port, envFile, logPath }) {
+ const envLines = envFile
+ ? [
+ `if [ -f ${quoteForBash(envFile)} ]; then`,
+ ` set -a; . ${quoteForBash(envFile)}; set +a`,
+ ` echo "已加载服务端环境变量: ${envFile}"`,
+ 'fi',
+ ]
+ : [];
+ return [
+ 'set -euo pipefail',
+ `TARGET_DIR=${quoteForBash(dir)}`,
+ 'cd "$TARGET_DIR"',
+ ...envLines,
+ `PORT=${Number(port)} nohup bash -lc 'npm start' > ${quoteForBash(logPath)} 2>&1 &`,
+ `echo "已在 $TARGET_DIR 启动实例(PORT=${port}),启动日志: ${logPath}"`,
+ ].join('\n');
+}
+
+/** 生成健康检查远端脚本(失败退出码 1) */
+function buildHealthCheckScript({ port, healthPath, attempts, interval }) {
+ return [
+ 'set -euo pipefail',
+ `TARGET_PORT=${Number(port)}`,
+ `HEALTH_PATH=${quoteForBash(healthPath || '/health')}`,
+ `for attempt in $(seq 1 ${Number(attempts || 30)}); do`,
+ ' if curl -fsS --connect-timeout 2 --max-time 5 "http://127.0.0.1:$TARGET_PORT$HEALTH_PATH" >/dev/null 2>&1; then',
+ ' echo "健康检查通过: http://127.0.0.1:$TARGET_PORT$HEALTH_PATH"',
+ ' exit 0',
+ ' fi',
+ ` sleep ${Number(interval || 2)}`,
+ 'done',
+ 'echo "健康检查超时: http://127.0.0.1:$TARGET_PORT$HEALTH_PATH" >&2',
+ 'exit 1',
+ ].join('\n');
+}
+
+/** 生成停止指定目录实例的远端脚本(kill + kill -9 兜底) */
+function buildStopDirScript(dir, label) {
+ const safeLabel = String(label || 'instance');
+ return [
+ 'set -euo pipefail',
+ `OLD_DIR=${quoteForBash(dir)}`,
+ `OLD_LABEL=${quoteForBash(safeLabel)}`,
+ "OLD_PIDS=$(ps -eo pid=,args= | awk -v root=\"$OLD_DIR\" 'index($0, root) && $2 ~ /node$/ { print $1 }')",
+ 'if [ -z "$OLD_PIDS" ]; then',
+ ' echo "未找到 $OLD_LABEL 进程,跳过停止步骤"',
+ 'else',
+ ' echo "正在停止 $OLD_LABEL: $OLD_PIDS"',
+ ' kill $OLD_PIDS || true',
+ ' sleep 30',
+ " OLD_PIDS_REMAIN=$(ps -eo pid=,args= | awk -v root=\"$OLD_DIR\" 'index($0, root) && $2 ~ /node$/ { print $1 }')",
+ ' if [ -n "$OLD_PIDS_REMAIN" ]; then',
+ ' echo "$OLD_LABEL 仍有残留进程,强制停止: $OLD_PIDS_REMAIN"',
+ ' kill -9 $OLD_PIDS_REMAIN || true',
+ ' fi',
+ ' echo "$OLD_LABEL 已停止"',
+ 'fi',
+ ].join('\n');
+}
+
+/** 生成切换 Nginx upstream 并 reload 的远端脚本 */
+function buildNginxSwitchScript(upstreamFile, port) {
+ return [
+ 'set -euo pipefail',
+ `printf 'proxy_pass http://127.0.0.1:%s;\\n' ${Number(port)} > ${quoteForBash(upstreamFile)}`,
+ 'nginx -t && nginx -s reload',
+ `echo "Nginx upstream 已切换至 127.0.0.1:${Number(port)}"`,
+ ].join('\n');
+}
+
+/**
+ * 生成把 JSON 写入远端文件的脚本行
+ *
+ * @param {string} stateDir - 远端目录
+ * @param {string} fileName - 文件名
+ * @param {object} payload - JSON 对象
+ * @param {boolean} append - true 追加(jsonl),false 覆盖
+ * @return {string[]} 远端脚本行
+ */
+function buildRemoteJsonWriteLines(stateDir, fileName, payload, append) {
+ const content = append
+ ? `${JSON.stringify(payload)}\n`
+ : `${JSON.stringify(payload, null, 2)}\n`;
+ const base64 = Buffer.from(content, 'utf8').toString('base64');
+ return [
+ `printf '%s' ${quoteForBash(base64)} | base64 -d ${append ? '>>' : '>'} ${quoteForBash(`${stateDir}/${fileName}`)}`,
+ ];
+}
+
+module.exports = {
+ EXAMPLE_CONFIG_PATH,
+ LOCAL_CONFIG_PATH,
+ REPO_ROOT,
+ ROOT,
+ buildArchive,
+ buildFrontConf,
+ buildFrontendArchive,
+ buildHealthCheckScript,
+ buildKillPortScript,
+ buildNginxSwitchScript,
+ buildPinnedPathGuardLines,
+ buildRemoteCleanupGuard,
+ buildRemoteJsonWriteLines,
+ buildStartScript,
+ buildStopDirScript,
+ ensureCommandAvailable,
+ ensureTempDeployDir,
+ getNowStamp,
+ getRemoteEnvFile,
+ isServerManagedConfig,
+ listDeployableFiles,
+ loadDeployConfig,
+ quoteForBash,
+ refreshNginx,
+ resolveFrontendDistDir,
+ runCommand,
+ runNpm,
+ runScp,
+ runSsh,
+};
diff --git a/backend/scripts/deploy/deploy-ops.cjs b/backend/scripts/deploy/deploy-ops.cjs
new file mode 100644
index 0000000..3af3036
--- /dev/null
+++ b/backend/scripts/deploy/deploy-ops.cjs
@@ -0,0 +1,160 @@
+'use strict';
+
+const { loadDeployConfig, quoteForBash, runSsh } = require('./deploy-lib.cjs');
+
+const COMMANDS = new Set([ 'inspect', 'smoke', 'verify', 'cleanup-backups' ]);
+const DEFAULT_SMOKE_PATHS = [ '/', '/health', '/download/version.json' ];
+
+function parseArgs(argv) {
+ const options = { envName: 'production', command: '', args: [] };
+ const tokens = [ ...argv ];
+ if (tokens.length === 0) {
+ throw new Error('缺少命令: inspect | smoke | verify | cleanup-backups');
+ }
+
+ if (!COMMANDS.has(tokens[0])) {
+ options.envName = tokens[0];
+ tokens.shift();
+ }
+
+ if (tokens.length === 0) {
+ throw new Error('缺少命令: inspect | smoke | verify | cleanup-backups');
+ }
+
+ options.command = tokens[0];
+ options.args = tokens.slice(1);
+
+ if (!COMMANDS.has(options.command)) {
+ throw new Error(`不支持的命令: ${options.command}`);
+ }
+
+ return options;
+}
+
+function getActivePortInfo(config) {
+ const currentMdPath = `${config.deployRoot}/current.md`;
+ const output = runSsh(config, `cat ${quoteForBash(currentMdPath)} 2>/dev/null || true`, { stdio: 'pipe' });
+ const rawContent = String(output || '').trim();
+
+ if (!rawContent) {
+ throw new Error(`无法读取远端 ${currentMdPath},内容为空或文件不存在。`);
+ }
+
+ const version = rawContent.replace(/\r/g, '').trim();
+ if (version !== 'v1' && version !== 'v2') {
+ throw new Error(`远端 current.md 内容无效: "${rawContent}",期望值为 v1 或 v2。`);
+ }
+
+ return { port: config.ports[version], version, rawContent };
+}
+
+function inspectState(config) {
+ const latestBackupFile = `${config.stateDir}/latest-backup.txt`;
+ const remoteScript = [
+ 'set -euo pipefail',
+ `STATE_DIR=${quoteForBash(config.stateDir)}`,
+ `BACKUP_DIR=${quoteForBash(config.backupDir)}`,
+ `LATEST_FILE=${quoteForBash(latestBackupFile)}`,
+ 'printf "[STATE]\\n"',
+ 'if [ -d "$STATE_DIR" ]; then ls -la "$STATE_DIR"; else echo MISSING; fi',
+ 'printf "\\n[LATEST_BACKUP]\\n"',
+ 'if [ -f "$LATEST_FILE" ]; then cat "$LATEST_FILE"; else echo MISSING; fi',
+ 'printf "\\n[BACKUPS]\\n"',
+ 'if [ -d "$BACKUP_DIR" ]; then ls -1t "$BACKUP_DIR"; else echo MISSING; fi',
+ ].join('\n');
+
+ return runSsh(config, remoteScript, { stdio: 'pipe' }).trim();
+}
+
+function smokeRoutes(config) {
+ const { port } = getActivePortInfo(config);
+ const paths = DEFAULT_SMOKE_PATHS.map(quoteForBash).join(' ');
+ const useNginx = Boolean(config.serverName);
+ const baseUrl = useNginx ? 'http://127.0.0.1' : `http://127.0.0.1:${port}`;
+ const remoteScript = [
+ 'set -euo pipefail',
+ `BASE_URL=${quoteForBash(baseUrl)}`,
+ `SERVER_NAME=${quoteForBash(config.serverName || '')}`,
+ `for path in ${paths}; do`,
+ ' if [ -n "$SERVER_NAME" ]; then',
+ ' code=$(curl -sS -o /dev/null -w "%{http_code}" -H "Host: $SERVER_NAME" "$BASE_URL$path" || true)',
+ ' else',
+ ' code=$(curl -sS -o /dev/null -w "%{http_code}" "$BASE_URL$path" || true)',
+ ' fi',
+ ' printf "%s %s\\n" "$path" "$code"',
+ 'done',
+ ].join('\n');
+
+ return runSsh(config, remoteScript, { stdio: 'pipe' }).trim();
+}
+
+function cleanupBackups(config, names) {
+ if (!names.length) {
+ throw new Error('cleanup-backups 需要至少一个备份文件名');
+ }
+
+ const remoteScript = [
+ 'set -euo pipefail',
+ `BACKUP_DIR=${quoteForBash(config.backupDir)}`,
+ ...names.map((name, index) => `FILE_${index}=${quoteForBash(name)}`),
+ ...names.map((_, index) => `if [ -f "$BACKUP_DIR/$FILE_${index}" ]; then rm -f "$BACKUP_DIR/$FILE_${index}"; echo "REMOVED $FILE_${index}"; else echo "MISS $FILE_${index}"; fi`),
+ ].join('\n');
+
+ return runSsh(config, remoteScript, { stdio: 'pipe' }).trim();
+}
+
+function showActiveInfo(config) {
+ let activeInfo;
+ try {
+ activeInfo = getActivePortInfo(config);
+ } catch (err) {
+ console.log(`[CURRENT_MD] 读取失败: ${err.message}`);
+ console.log('');
+ return;
+ }
+
+ console.log(`[CURRENT_MD] 内容: ${activeInfo.rawContent}`);
+ console.log(`[ACTIVE] 端口: ${activeInfo.port} (${activeInfo.version})`);
+ console.log('');
+}
+
+function main() {
+ const options = parseArgs(process.argv.slice(2));
+ const config = loadDeployConfig(options.envName);
+
+ if (options.command === 'inspect') {
+ showActiveInfo(config);
+ console.log(inspectState(config));
+ return;
+ }
+
+ if (options.command === 'smoke') {
+ showActiveInfo(config);
+ console.log('[SMOKE]');
+ console.log(smokeRoutes(config));
+ return;
+ }
+
+ if (options.command === 'verify') {
+ showActiveInfo(config);
+ console.log(inspectState(config));
+ console.log('');
+ console.log('[SMOKE]');
+ console.log(smokeRoutes(config));
+ return;
+ }
+
+ if (options.command === 'cleanup-backups') {
+ console.log(cleanupBackups(config, options.args));
+ return;
+ }
+
+ throw new Error(`不支持的命令: ${options.command}`);
+}
+
+try {
+ main();
+} catch (err) {
+ console.error(`[ERROR] ${err && err.message ? err.message : err}`);
+ process.exit(1);
+}
diff --git a/backend/scripts/deploy/deploy-precheck.cjs b/backend/scripts/deploy/deploy-precheck.cjs
new file mode 100644
index 0000000..e9edea0
--- /dev/null
+++ b/backend/scripts/deploy/deploy-precheck.cjs
@@ -0,0 +1,85 @@
+'use strict';
+
+const fs = require('node:fs');
+const {
+ ensureCommandAvailable,
+ loadDeployConfig,
+ quoteForBash,
+ runSsh,
+} = require('./deploy-lib.cjs');
+
+function main() {
+ try {
+ [ 'ssh', 'scp', 'tar', 'git' ].forEach(cmd => ensureCommandAvailable(cmd, ''));
+ console.log('LOCAL_TOOLS_OK');
+
+ const config = loadDeployConfig('production');
+ if (fs.existsSync(config.envFileLocalPath)) {
+ console.log(`LOCAL_ENV_FILE_OK ${config.envFileLocalPath}`);
+ } else {
+ console.log(`LOCAL_ENV_FILE_MISSING ${config.envFileLocalPath}(将沿用服务器副本)`);
+ }
+ const currentMdPath = `${config.deployRoot}/current.md`;
+ const remoteScript = [
+ 'set -euo pipefail',
+ `DEPLOY_ROOT=${quoteForBash(config.deployRoot)}`,
+ `CURRENT_MD=${quoteForBash(currentMdPath)}`,
+ 'PARENT_DIR=$(dirname "$DEPLOY_ROOT")',
+ 'if [ -d "$DEPLOY_ROOT" ]; then echo DEPLOY_ROOT_EXISTS; else echo DEPLOY_ROOT_MISSING; fi',
+ 'if [ -d "$DEPLOY_ROOT" ] && [ -w "$DEPLOY_ROOT" ]; then echo DEPLOY_ROOT_WRITABLE; else echo DEPLOY_ROOT_NOT_WRITABLE; fi',
+ 'if [ -d "$PARENT_DIR" ] && [ -w "$PARENT_DIR" ]; then echo PARENT_WRITABLE; else echo PARENT_NOT_WRITABLE; fi',
+ 'if [ -d "$DEPLOY_ROOT/v1" ]; then echo V1_DIR_EXISTS; else echo V1_DIR_MISSING; fi',
+ 'if [ -d "$DEPLOY_ROOT/v2" ]; then echo V2_DIR_EXISTS; else echo V2_DIR_MISSING; fi',
+ 'if [ -f "$CURRENT_MD" ]; then echo "CURRENT_MD_CONTENT=$(tr -d \'[:space:]\' < "$CURRENT_MD")"; else echo CURRENT_MD_MISSING; fi',
+ 'for V in v1 v2; do',
+ ' if [ -f "$DEPLOY_ROOT/$V/config/config.prod.js" ]; then echo "PROD_CONFIG_OK $V"; else echo "PROD_CONFIG_MISSING $V"; fi',
+ 'done',
+ `if [ -f ${quoteForBash(`${config.sharedConfigDir}/${config.envFile}`)} ]; then echo SHARED_ENV_OK; else echo SHARED_ENV_MISSING; fi`,
+ `if [ -d ${quoteForBash(config.sharedConfigDir)} ]; then echo SHARED_CONFIG_DIR_EXISTS; else echo SHARED_CONFIG_DIR_MISSING; fi`,
+ `if [ -f ${quoteForBash(config.nginxUpstreamFile || `${config.deployRoot}/nginx-upstream.conf`)} ]; then echo NGINX_UPSTREAM_EXISTS; else echo NGINX_UPSTREAM_MISSING; fi`,
+ 'if command -v nginx >/dev/null 2>&1; then echo REMOTE_NGINX_OK; nginx -v 2>&1; else echo REMOTE_NGINX_MISSING; fi',
+ 'if command -v node >/dev/null 2>&1; then echo REMOTE_NODE_OK; node -v; else echo REMOTE_NODE_MISSING; fi',
+ 'if command -v npm >/dev/null 2>&1; then echo REMOTE_NPM_OK; npm -v; else echo REMOTE_NPM_MISSING; fi',
+ 'if command -v tar >/dev/null 2>&1; then echo REMOTE_TAR_OK; tar --version | head -n 1; else echo REMOTE_TAR_MISSING; fi',
+ 'if command -v curl >/dev/null 2>&1; then',
+ ' echo REMOTE_CURL_OK',
+ ' if [ -f "$CURRENT_MD" ]; then',
+ ' ACTIVE_VERSION=$(tr -d \'[:space:]\' < "$CURRENT_MD")',
+ ` if [ "$ACTIVE_VERSION" = "v1" ]; then ACTIVE_PORT=${config.ports.v1}; elif [ "$ACTIVE_VERSION" = "v2" ]; then ACTIVE_PORT=${config.ports.v2}; else ACTIVE_PORT=""; fi`,
+ ` if [ -n "$ACTIVE_PORT" ] && curl -fsS "http://127.0.0.1:$ACTIVE_PORT${config.healthCheckPath}" >/dev/null; then echo HEALTHCHECK_LOCAL_OK; else echo HEALTHCHECK_LOCAL_FAIL; fi`,
+ ' else',
+ ' echo HEALTHCHECK_LOCAL_SKIP_NO_CURRENT_MD',
+ ' fi',
+ 'else echo REMOTE_CURL_MISSING; fi',
+ ].join('\n');
+
+ const output = runSsh(config, remoteScript, { stdio: 'pipe' });
+ for (const line of output.split(/\r?\n/)) {
+ if (line.trim()) {
+ console.log(line.trim());
+ }
+ }
+
+ console.log('PRECHECK_OK');
+ } catch (error) {
+ const message = String(error && error.message ? error.message : '');
+ let reason = 'UNKNOWN';
+
+ if (/Permission denied|Authentication failed/i.test(message)) {
+ reason = 'AUTH';
+ } else if (/Connection timed out|No route to host|Connection refused|Could not resolve hostname/i.test(message)) {
+ reason = 'NETWORK';
+ } else if (/Host key verification failed|REMOTE HOST IDENTIFICATION HAS CHANGED/i.test(message)) {
+ reason = 'HOST_KEY';
+ } else if (/Operation timed out/i.test(message)) {
+ reason = 'TIMEOUT';
+ }
+
+ console.log('PRECHECK_FAIL');
+ console.log(`PRECHECK_REASON_${reason}`);
+ console.log(message);
+ process.exit(1);
+ }
+}
+
+main();
diff --git a/backend/scripts/deploy/deploy-remote.cjs b/backend/scripts/deploy/deploy-remote.cjs
new file mode 100644
index 0000000..069b153
--- /dev/null
+++ b/backend/scripts/deploy/deploy-remote.cjs
@@ -0,0 +1,480 @@
+'use strict';
+
+const fs = require('node:fs');
+const path = require('node:path');
+const {
+ ROOT,
+ buildArchive,
+ buildFrontConf,
+ buildFrontendArchive,
+ buildHealthCheckScript,
+ buildKillPortScript,
+ buildNginxSwitchScript,
+ buildPinnedPathGuardLines,
+ buildRemoteCleanupGuard,
+ buildRemoteJsonWriteLines,
+ buildStartScript,
+ buildStopDirScript,
+ ensureCommandAvailable,
+ ensureTempDeployDir,
+ getNowStamp,
+ getRemoteEnvFile,
+ loadDeployConfig,
+ quoteForBash,
+ runCommand,
+ runNpm,
+ runScp,
+ runSsh,
+} = require('./deploy-lib.cjs');
+const { recordVersionUpdate } = require('./version-registry.cjs');
+
+/**
+ * 通过 SSH 读取远端 current.md,获取当前活跃版本(v1 / v2)
+ *
+ * @param {object} config - 部署配置
+ * @return {string} 'v1' 或 'v2'
+ */
+function readRemoteCurrentVersion(config) {
+ const currentMdPath = `${config.deployRoot}/current.md`;
+ const output = runSsh(config, `cat ${quoteForBash(currentMdPath)} 2>/dev/null || true`, { stdio: 'pipe' });
+ const rawVersion = String(output || '').trim();
+
+ if (!rawVersion) {
+ throw new Error(
+ `无法读取远端当前版本文件: ${currentMdPath}。请确保远端已存在该文件且内容为 v1 或 v2。`
+ );
+ }
+
+ const normalized = rawVersion.replace(/\r/g, '').trim();
+ if (normalized !== 'v1' && normalized !== 'v2') {
+ throw new Error(`远端 current.md 内容无效: "${rawVersion}",期望值为 v1 或 v2。文件路径: ${currentMdPath}`);
+ }
+
+ return normalized;
+}
+
+function otherVersion(version) {
+ return version === 'v1' ? 'v2' : 'v1';
+}
+
+/** 本地构建前端(产物由 nginx 托管,单独发布到 deployRoot/frontend) */
+function buildFrontend(config) {
+ if (!config.buildFrontend) {
+ console.log('已配置 buildFrontend=false,跳过前端构建。');
+ return;
+ }
+
+ const frontendRoot = path.resolve(ROOT, config.frontendDir);
+ if (!fs.existsSync(path.join(frontendRoot, 'package.json'))) {
+ throw new Error(`前端目录无效: ${frontendRoot}`);
+ }
+
+ console.log(`构建前端: ${frontendRoot}`);
+ runNpm([ 'run', 'build' ], frontendRoot);
+}
+
+/** 远端目标目录:清理、解压、恢复私有文件、安装依赖 */
+function deployToTargetDir(config, { targetDir, targetVersion, remoteArchive, stamp }) {
+ const pinnedStashDir = `/tmp/pack-service-pinned-${targetVersion}`;
+ const pinnedGuard = buildPinnedPathGuardLines('TARGET_DIR', 'PINNED_DIR', config.preservePaths);
+ const cleanupGuard = buildRemoteCleanupGuard(config.sharedDirs);
+ const backupName = `backup-${stamp}.tar.gz`;
+
+ const backupLines = [
+ 'if [ -f "$TARGET_DIR/package.json" ]; then',
+ ' mkdir -p "$BACKUP_DIR"',
+ " tar -czf \"$BACKUP_DIR/$BACKUP_NAME\" -C \"$TARGET_DIR\" --exclude='./node_modules' --exclude='./logs' --exclude='./run' --exclude='./temp' --exclude='./app/public/download' --exclude='./app/public/version' --exclude='./config/config.prod.js' --exclude='./config/config.local.js' .",
+ ' printf \'%s\\n\' "$BACKUP_NAME" > "$STATE_DIR/latest-backup.txt"',
+ ' echo "已备份目标目录旧代码: $BACKUP_DIR/$BACKUP_NAME"',
+ ' COUNT=0',
+ ' for FILE in $(ls -1t "$BACKUP_DIR"/backup-*.tar.gz 2>/dev/null || true); do',
+ ' COUNT=$((COUNT + 1))',
+ ' if [ "$COUNT" -gt "$KEEP_BACKUPS" ]; then rm -f "$FILE"; fi',
+ ' done',
+ 'else',
+ ' echo "目标目录首次发布,跳过备份"',
+ 'fi',
+ ];
+
+ const script = [
+ 'set -euo pipefail',
+ `TARGET_DIR=${quoteForBash(targetDir)}`,
+ `REMOTE_ARCHIVE=${quoteForBash(remoteArchive)}`,
+ `PINNED_DIR=${quoteForBash(pinnedStashDir)}`,
+ `BACKUP_DIR=${quoteForBash(config.backupDir)}`,
+ `STATE_DIR=${quoteForBash(config.stateDir)}`,
+ `SHARED_CONFIG_DIR=${quoteForBash(config.sharedConfigDir)}`,
+ `ENV_FILE=${quoteForBash(getRemoteEnvFile(config))}`,
+ `BACKUP_NAME=${quoteForBash(backupName)}`,
+ `KEEP_BACKUPS=${Number(config.keepBackups || 5)}`,
+ 'mkdir -p "$TARGET_DIR" "$BACKUP_DIR" "$STATE_DIR"',
+ ...backupLines,
+ ...pinnedGuard.stash,
+ 'cd "$TARGET_DIR"',
+ `find . -mindepth 1 -maxdepth 1 ${cleanupGuard} -exec rm -rf {} +`,
+ 'tar -xzf "$REMOTE_ARCHIVE" -C "$TARGET_DIR"',
+ 'rm -f "$REMOTE_ARCHIVE"',
+ ...pinnedGuard.restore,
+ // 服务端共享配置优先:每次发布都从 shared-config 复制,避免各版本配置漂移
+ 'if [ -n "$SHARED_CONFIG_DIR" ] && [ -d "$SHARED_CONFIG_DIR" ]; then',
+ ' for FILE_NAME in config.prod.js config.local.js; do',
+ ' if [ -f "$SHARED_CONFIG_DIR/$FILE_NAME" ]; then',
+ ' mkdir -p "$TARGET_DIR/config"',
+ ' cp -a "$SHARED_CONFIG_DIR/$FILE_NAME" "$TARGET_DIR/config/$FILE_NAME"',
+ ' echo "SHARED_CONFIG_APPLIED $FILE_NAME"',
+ ' fi',
+ ' done',
+ 'else',
+ ' echo "[WARN] 未找到共享配置目录: $SHARED_CONFIG_DIR"',
+ 'fi',
+ 'mkdir -p "$TARGET_DIR/app/public/download" "$TARGET_DIR/app/public/version"',
+ 'mkdir -p "$TARGET_DIR/logs" "$TARGET_DIR/run" "$TARGET_DIR/temp"',
+ 'if [ -n "$ENV_FILE" ] && [ -f "$ENV_FILE" ]; then',
+ ' set -a; . "$ENV_FILE"; set +a',
+ ' echo "已加载服务端环境变量: $ENV_FILE"',
+ 'fi',
+ 'npm install --production',
+ ];
+
+ if (config.remoteDbDeploy) {
+ script.push('EGG_SERVER_ENV=prod npm run db:deploy');
+ }
+
+ runSsh(config, script.join('\n'));
+}
+
+/** 发布失败收尾:回滚 current.md、清理新实例,旧实例继续服务 */
+function abortDeploy(config, { envName, currentVersion, currentMdPath, targetDir, targetVersion, startLogPath, reason }) {
+ console.error(`[ERROR] ${reason}`);
+ console.error(`[ERROR] 发布中止:不切换 Nginx,不停旧实例。启动日志: ${startLogPath}`);
+
+ try {
+ const revertOutput = runSsh(config, [
+ 'set -euo pipefail',
+ `printf '%s\\n' ${quoteForBash(currentVersion)} > ${quoteForBash(currentMdPath)}`,
+ `echo "已回滚 current.md -> ${currentVersion}"`,
+ ].join('\n'), { stdio: 'pipe' });
+ console.log(String(revertOutput || '').trim());
+ } catch (revertErr) {
+ console.error(`[ERROR] 回滚 current.md 失败: ${revertErr.message}`);
+ }
+
+ try {
+ const killOutput = runSsh(config, buildStopDirScript(targetDir, `新实例 (${targetVersion})`), { stdio: 'pipe' });
+ console.log(String(killOutput || '').trim());
+ } catch (killErr) {
+ console.error(`[ERROR] 清理失败的新实例出错: ${killErr.message}`);
+ }
+
+ let oldAlive = false;
+ try {
+ runSsh(config, [
+ 'set -euo pipefail',
+ `curl -fsS --connect-timeout 2 --max-time 5 ${quoteForBash(`http://127.0.0.1:${config.ports[currentVersion]}${config.healthCheckPath}`)} >/dev/null`,
+ ].join('\n'), { stdio: 'pipe' });
+ oldAlive = true;
+ } catch (checkErr) {
+ oldAlive = false;
+ }
+
+ console.error(`[ERROR] 发布失败: ${envName} -> ${config.username}@${config.host}:${targetDir}`);
+ if (oldAlive) {
+ console.error(`[ERROR] 旧实例 (${currentVersion}) 仍在运行,线上服务不受影响`);
+ } else {
+ console.error(`[ERROR] 未检测到旧实例 (${currentVersion}) 在 ${config.ports[currentVersion]} 提供服务,请人工介入`);
+ }
+ process.exit(1);
+}
+
+/** 把本机权威 env 同步到服务器 shared-config(存在才上传;统一转成 LF) */
+function uploadEnvFile(config, stamp) {
+ if (!config.uploadEnvFile || !config.sharedConfigDir) {
+ return;
+ }
+
+ if (!fs.existsSync(config.envFileLocalPath)) {
+ console.log(`未找到本机 env 文件 ${config.envFileLocalPath},沿用服务器 shared-config/${config.envFile}`);
+ return;
+ }
+
+ const content = fs.readFileSync(config.envFileLocalPath, 'utf8').replace(/\r\n?/g, '\n');
+ const uploadDir = ensureTempDeployDir();
+ const localUpload = path.join(uploadDir, `env-${stamp}.sh`);
+ fs.writeFileSync(localUpload, content, 'utf8');
+
+ const remoteTemp = `${config.sharedConfigDir}/${config.envFile}.upload-${stamp}`;
+ try {
+ runScp(config, localUpload, remoteTemp);
+ } finally {
+ fs.rmSync(localUpload, { force: true });
+ }
+
+ runSsh(config, [
+ 'set -euo pipefail',
+ `TARGET=${quoteForBash(`${config.sharedConfigDir}/${config.envFile}`)}`,
+ `TEMP=${quoteForBash(remoteTemp)}`,
+ 'mkdir -p "$(dirname "$TARGET")"',
+ 'mv "$TEMP" "$TARGET"',
+ 'chmod 600 "$TARGET"',
+ // 防御:即使上传来源混入 CRLF,也在服务器上再转一次
+ "sed -i 's/\\r$//' \"$TARGET\"",
+ 'echo "ENV_UPLOADED"',
+ ].join('\n'), { stdio: 'pipe' });
+ console.log(`本机 env 已同步到服务器: ${config.sharedConfigDir}/${config.envFile}`);
+}
+
+/** 写入 nginx 前端静态托管 + 后端反代配置(front.conf,由发布脚本维护) */
+function writeFrontConf(config) {
+ if (!config.manageNginxFrontConf || !config.nginxFrontConf) {
+ return;
+ }
+
+ const base64 = Buffer.from(buildFrontConf(config), 'utf8').toString('base64');
+ runSsh(config, [
+ 'set -euo pipefail',
+ `TARGET=${quoteForBash(config.nginxFrontConf)}`,
+ 'mkdir -p "$(dirname "$TARGET")"',
+ `printf '%s' ${quoteForBash(base64)} | base64 -d > "$TARGET"`,
+ 'echo "FRONT_CONF_WRITTEN"',
+ ].join('\n'), { stdio: 'pipe' });
+ console.log(`nginx 前端配置已更新: ${config.nginxFrontConf}`);
+}
+
+/** 发布前端静态文件:解压到临时目录后整目录切换,上一版保留为 frontend.prev */
+function deployFrontend(config, { stamp, remoteFrontendArchive }) {
+ if (!config.buildFrontend) {
+ console.log('已配置 buildFrontend=false,跳过前端发布。');
+ return;
+ }
+
+ const newDir = `${config.frontendDeployDir}.new-${stamp}`;
+ const script = [
+ 'set -euo pipefail',
+ `FRONTEND_DIR=${quoteForBash(config.frontendDeployDir)}`,
+ `PREV_DIR=${quoteForBash(config.frontendPrevDir)}`,
+ `NEW_DIR=${quoteForBash(newDir)}`,
+ `REMOTE_ARCHIVE=${quoteForBash(remoteFrontendArchive)}`,
+ 'rm -rf "$NEW_DIR"',
+ 'mkdir -p "$NEW_DIR"',
+ 'tar -xzf "$REMOTE_ARCHIVE" -C "$NEW_DIR"',
+ 'rm -f "$REMOTE_ARCHIVE"',
+ 'find "$NEW_DIR" -type d -exec chmod 755 {} +',
+ 'find "$NEW_DIR" -type f -exec chmod 644 {} +',
+ 'if [ -d "$FRONTEND_DIR" ]; then',
+ ' rm -rf "$PREV_DIR"',
+ ' mv "$FRONTEND_DIR" "$PREV_DIR"',
+ 'fi',
+ 'mv "$NEW_DIR" "$FRONTEND_DIR"',
+ 'echo "FRONTEND_DEPLOYED $FRONTEND_DIR"',
+ ].join('\n');
+
+ runSsh(config, script);
+ console.log(`前端已发布到 nginx 静态目录: ${config.frontendDeployDir}`);
+}
+
+function main() {
+ const envName = process.argv[2] || 'production';
+ const config = loadDeployConfig(envName);
+
+ ensureCommandAvailable('git', '请先安装 Git 并确保 git 在 PATH 中。');
+ ensureCommandAvailable('tar', '请先安装 tar,Windows 10/11 通常已内置 bsdtar。');
+ ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。');
+ ensureCommandAvailable('scp', '请先安装 OpenSSH Client 并确保 scp 在 PATH 中。');
+
+ const currentVersion = readRemoteCurrentVersion(config);
+ const targetVersion = otherVersion(currentVersion);
+ const targetDir = `${config.deployRoot}/${targetVersion}`;
+ const oldDir = `${config.deployRoot}/${currentVersion}`;
+ const targetPort = config.ports[targetVersion];
+ console.log(`远端当前活跃版本: ${currentVersion},目标部署目录: ${targetDir}(端口 ${targetPort})`);
+
+ buildFrontend(config);
+
+ const stamp = getNowStamp();
+ const packageJson = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8'));
+ const packageVersion = String(packageJson.version || '0.0.0');
+ const gitCommit = runCommand('git', [ 'rev-parse', 'HEAD' ]);
+ const gitCommitShort = runCommand('git', [ 'rev-parse', '--short', 'HEAD' ]);
+ const gitBranch = runCommand('git', [ 'rev-parse', '--abbrev-ref', 'HEAD' ]);
+ const releaseVersion = `v${packageVersion}-${stamp}-${gitCommitShort}`;
+
+ const { archivePath, fileCount } = buildArchive(stamp, config);
+ console.log(`后端发布包已生成: ${archivePath}(文件 ${fileCount} 个)`);
+
+ let frontendArchivePath = '';
+ if (config.buildFrontend) {
+ frontendArchivePath = buildFrontendArchive(stamp, config).archivePath;
+ console.log(`前端发布包已生成: ${frontendArchivePath}`);
+ }
+
+ const remoteArchive = `${config.incomingDir}/release-${stamp}.tar.gz`;
+ const remoteFrontendArchive = `${config.incomingDir}/frontend-${stamp}.tar.gz`;
+ runSsh(config, [
+ 'set -euo pipefail',
+ `mkdir -p ${quoteForBash(targetDir)} ${quoteForBash(config.incomingDir)} ${quoteForBash(config.backupDir)} ${quoteForBash(config.stateDir)} ${quoteForBash(config.sharedConfigDir)}`,
+ ].join('\n'));
+ console.log(`远端目录已就绪: ${targetDir}`);
+
+ uploadEnvFile(config, stamp);
+
+ runScp(config, archivePath, remoteArchive);
+ console.log(`后端发布包已上传: ${remoteArchive}`);
+
+ if (frontendArchivePath) {
+ runScp(config, frontendArchivePath, remoteFrontendArchive);
+ console.log(`前端发布包已上传: ${remoteFrontendArchive}`);
+ }
+
+ deployToTargetDir(config, { targetDir, targetVersion, remoteArchive, stamp });
+ console.log(`远端目标目录已清理、解压并安装生产依赖: ${targetDir}`);
+
+ const startLogPath = `/tmp/pack-service-${targetVersion}-start.log`;
+ const currentMdPath = `${config.deployRoot}/current.md`;
+
+ try {
+ const killPortOutput = runSsh(config, buildKillPortScript(targetPort), { stdio: 'pipe' });
+ console.log(String(killPortOutput || '').trim());
+ } catch (err) {
+ console.warn(`[WARN] 端口 ${targetPort} 清理失败: ${err.message}`);
+ }
+
+ const switchAndStartScript = [
+ 'set -euo pipefail',
+ `printf '%s\\n' ${quoteForBash(targetVersion)} > ${quoteForBash(currentMdPath)}`,
+ buildStartScript({
+ dir: targetDir,
+ port: targetPort,
+ envFile: getRemoteEnvFile(config),
+ logPath: startLogPath,
+ }),
+ `echo "已更新 current.md -> ${targetVersion}"`,
+ ].join('\n');
+
+ try {
+ const switchOutput = runSsh(config, switchAndStartScript, { stdio: 'pipe' });
+ console.log(String(switchOutput || '').trim());
+ } catch (err) {
+ abortDeploy(config, {
+ envName,
+ currentVersion,
+ currentMdPath,
+ targetDir,
+ targetVersion,
+ startLogPath,
+ reason: `新实例启动命令执行失败: ${err.message}`,
+ });
+ }
+
+ try {
+ const healthOutput = runSsh(config, buildHealthCheckScript({
+ port: targetPort,
+ healthPath: config.healthCheckPath,
+ attempts: config.healthCheckAttempts,
+ interval: config.healthCheckInterval,
+ }), { stdio: 'pipe' });
+ console.log(String(healthOutput || '').trim());
+ } catch (err) {
+ abortDeploy(config, {
+ envName,
+ currentVersion,
+ currentMdPath,
+ targetDir,
+ targetVersion,
+ startLogPath,
+ reason: `新实例健康检查失败: ${err.message}`,
+ });
+ }
+
+ try {
+ writeFrontConf(config);
+ deployFrontend(config, { stamp, remoteFrontendArchive });
+ } catch (err) {
+ abortDeploy(config, {
+ envName,
+ currentVersion,
+ currentMdPath,
+ targetDir,
+ targetVersion,
+ startLogPath,
+ reason: `前端发布失败: ${err.message}`,
+ });
+ }
+
+ if (config.nginxUpstreamFile) {
+ try {
+ const nginxOutput = runSsh(config, buildNginxSwitchScript(config.nginxUpstreamFile, targetPort), { stdio: 'pipe' });
+ console.log(String(nginxOutput || '').trim());
+ } catch (err) {
+ abortDeploy(config, {
+ envName,
+ currentVersion,
+ currentMdPath,
+ targetDir,
+ targetVersion,
+ startLogPath,
+ reason: `Nginx upstream 切换失败: ${err.message}。请确认 ${config.nginxUpstreamFile} 被站点配置 include,且当前账号可执行 nginx -t / nginx -s reload`,
+ });
+ }
+ } else {
+ console.log('已配置 nginxUpstreamFile 为空,跳过 Nginx upstream 切换。');
+ }
+
+ try {
+ const stopOutput = runSsh(config, buildStopDirScript(oldDir, `旧实例 (${currentVersion})`), { stdio: 'pipe' });
+ console.log(String(stopOutput || '').trim());
+ } catch (err) {
+ console.warn(`[WARN] 停止旧实例失败: ${err.message}`);
+ console.warn(`[WARN] 旧实例 (${currentVersion}) 可能仍在运行,请人工确认并停止`);
+ }
+
+ const releaseRecord = {
+ deployedAt: new Date().toISOString(),
+ releaseVersion,
+ packageVersion,
+ gitCommit,
+ gitCommitShort,
+ gitBranch,
+ envName,
+ activeVersion: targetVersion,
+ port: targetPort,
+ dir: targetDir,
+ previousVersion: currentVersion,
+ frontendDir: config.buildFrontend ? config.frontendDeployDir : '',
+ deployedBy: process.env.USERNAME || process.env.USER || '',
+ };
+
+ try {
+ runSsh(config, [
+ 'set -euo pipefail',
+ `STATE_DIR=${quoteForBash(config.stateDir)}`,
+ 'mkdir -p "$STATE_DIR"',
+ ...buildRemoteJsonWriteLines(config.stateDir, 'current-release.json', releaseRecord, false),
+ ...buildRemoteJsonWriteLines(config.stateDir, 'release-history.jsonl', releaseRecord, true),
+ 'echo "远端发布状态已记录"',
+ ].join('\n'), { stdio: 'pipe' });
+ } catch (err) {
+ console.warn(`[WARN] 远端发布状态记录失败: ${err.message}`);
+ }
+
+ try {
+ recordVersionUpdate({
+ source: 'deploy',
+ note: `deploy ${targetVersion}`,
+ releaseVersion,
+ deployRoot: config.deployRoot,
+ });
+ } catch (err) {
+ console.warn(`[WARN] 本地版本记录失败: ${err.message}`);
+ }
+
+ console.log(`发布完成: ${envName} -> ${config.username}@${config.host}:${targetDir}`);
+ console.log(`线上版本号: ${releaseVersion}`);
+ console.log(`当前活跃版本已切换为: ${targetVersion}(端口 ${targetPort})`);
+}
+
+try {
+ main();
+} catch (err) {
+ console.error(`[ERROR] ${err && err.message ? err.message : err}`);
+ process.exit(1);
+}
diff --git a/backend/scripts/deploy/deploy-version.cjs b/backend/scripts/deploy/deploy-version.cjs
new file mode 100644
index 0000000..4d768f5
--- /dev/null
+++ b/backend/scripts/deploy/deploy-version.cjs
@@ -0,0 +1,122 @@
+'use strict';
+
+const path = require('node:path');
+const {
+ ensureCommandAvailable,
+ loadDeployConfig,
+ quoteForBash,
+ runSsh,
+} = require('./deploy-lib.cjs');
+
+function parseArgs(argv) {
+ const options = { history: 0 };
+ for (const item of argv) {
+ if (!item) continue;
+ if (item.startsWith('--history=')) {
+ const value = Number(item.slice('--history='.length));
+ if (Number.isFinite(value) && value > 0) {
+ options.history = Math.floor(value);
+ }
+ }
+ }
+ return options;
+}
+
+function queryActiveInstance(config) {
+ const currentMdFile = path.posix.join(config.deployRoot, 'current.md');
+ const remoteScript = [
+ 'set -euo pipefail',
+ `FILE=${quoteForBash(currentMdFile)}`,
+ 'if [ -f "$FILE" ]; then',
+ ' cat "$FILE"',
+ 'else',
+ ' echo CURRENT_MD_NOT_FOUND',
+ 'fi',
+ ].join('\n');
+
+ const raw = runSsh(config, remoteScript, { stdio: 'pipe' }).trim();
+ if (!raw || raw === 'CURRENT_MD_NOT_FOUND') {
+ return null;
+ }
+
+ const version = raw.replace(/[\r\n\s]/g, '');
+ if (version !== 'v1' && version !== 'v2') {
+ return null;
+ }
+
+ return { version, port: config.ports[version], currentMd: raw.split('\n')[0].trim() };
+}
+
+function queryCurrentRelease(config) {
+ const releaseFile = path.posix.join(config.stateDir, 'current-release.json');
+ const remoteScript = [
+ 'set -euo pipefail',
+ `FILE=${quoteForBash(releaseFile)}`,
+ 'if [ -f "$FILE" ]; then',
+ ' cat "$FILE"',
+ 'else',
+ ' echo ONLINE_VERSION_NOT_FOUND',
+ 'fi',
+ ].join('\n');
+
+ const output = runSsh(config, remoteScript, { stdio: 'pipe' }).trim();
+ if (!output || output === 'ONLINE_VERSION_NOT_FOUND') {
+ return null;
+ }
+
+ try {
+ return JSON.parse(output);
+ } catch (error) {
+ return output;
+ }
+}
+
+function queryReleaseHistory(config, limit) {
+ const historyFile = path.posix.join(config.stateDir, 'release-history.jsonl');
+ const remoteScript = [
+ 'set -euo pipefail',
+ `FILE=${quoteForBash(historyFile)}`,
+ `LIMIT=${Number(limit)}`,
+ 'if [ -f "$FILE" ]; then',
+ ' tail -n "$LIMIT" "$FILE"',
+ 'else',
+ ' echo ONLINE_VERSION_HISTORY_EMPTY',
+ 'fi',
+ ].join('\n');
+
+ const output = runSsh(config, remoteScript, { stdio: 'pipe' }).trim();
+ if (!output || output === 'ONLINE_VERSION_HISTORY_EMPTY') {
+ return null;
+ }
+
+ return output.split(/\r?\n/).map(item => item.trim()).filter(Boolean).map(line => {
+ try {
+ return JSON.parse(line);
+ } catch (error) {
+ return { raw: line };
+ }
+ });
+}
+
+function main() {
+ const envName = process.argv[2] || 'production';
+ const options = parseArgs(process.argv.slice(3));
+
+ ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。');
+ const config = loadDeployConfig(envName);
+ const active = queryActiveInstance(config);
+
+ if (options.history > 0) {
+ console.log(JSON.stringify({ active, history: queryReleaseHistory(config, options.history) }, null, 2));
+ return;
+ }
+
+ console.log(JSON.stringify({ active, release: queryCurrentRelease(config) }, null, 2));
+}
+
+try {
+ main();
+} catch (err) {
+ console.error(`[ERROR] ${err && err.message ? err.message : err}`);
+ process.exit(1);
+}
diff --git a/backend/scripts/deploy/git-safety-check.cjs b/backend/scripts/deploy/git-safety-check.cjs
new file mode 100644
index 0000000..8053f31
--- /dev/null
+++ b/backend/scripts/deploy/git-safety-check.cjs
@@ -0,0 +1,62 @@
+'use strict';
+
+const path = require('node:path');
+const { REPO_ROOT, ROOT, runCommand } = require('./deploy-lib.cjs');
+
+const BLOCKED_PATH_PATTERNS = [
+ /^config\/config\.local\.js$/,
+ /^config\/config\.prod\.js$/,
+ /^config\/deploy\.config\.local\.cjs$/,
+ /^temp\/(?!docs\/).+/,
+ /^logs\//,
+ /^run\//,
+ /^versioning\/(?!\.gitkeep$).+/,
+ /^app\/public\/download\/(?!\.gitkeep$).+/,
+ /^app\/public\/version\/(?!\.gitkeep$).+/,
+ /\.pem$/i,
+ /\.key$/i,
+ /^\.env(?:\..+)?$/,
+];
+
+/** 仓库根视角的禁区:Android 正式签名与本地机器配置,绝不入库 */
+const BLOCKED_REPO_PATH_PATTERNS = [
+ /(^|\/)keystore\.properties$/,
+ /\.jks$/i,
+ /(^|\/)local\.properties$/,
+ /(^|\/)\.dev-adb\.local\.json$/,
+];
+
+function normalizePath(filePath) {
+ return filePath.replace(/\\/g, '/');
+}
+
+function listStagedFiles(cwd, relative) {
+ const args = [ 'diff', '--cached', '--name-only', '--diff-filter=ACMR' ];
+ if (relative) args.push('--relative');
+ const output = runCommand('git', args, { cwd });
+ if (!output) {
+ return [];
+ }
+ return output.split(/\r?\n/).map(item => normalizePath(item.trim())).filter(Boolean);
+}
+
+function main() {
+ const blocked = [
+ ...listStagedFiles(ROOT, true).filter(filePath => BLOCKED_PATH_PATTERNS.some(pattern => pattern.test(filePath))),
+ ...listStagedFiles(REPO_ROOT, false).filter(filePath => BLOCKED_REPO_PATH_PATTERNS.some(pattern => pattern.test(filePath))),
+ ];
+
+ if (blocked.length === 0) {
+ console.log('git safety check passed');
+ return;
+ }
+
+ console.error('以下文件禁止提交到 git,请先取消暂存:');
+ for (const filePath of new Set(blocked)) {
+ console.error(`- ${filePath}`);
+ }
+ console.error('建议使用 git restore --staged 取消暂存,再继续提交。');
+ process.exit(1);
+}
+
+main();
diff --git a/backend/scripts/deploy/publish-android.cjs b/backend/scripts/deploy/publish-android.cjs
new file mode 100644
index 0000000..190a0ae
--- /dev/null
+++ b/backend/scripts/deploy/publish-android.cjs
@@ -0,0 +1,243 @@
+'use strict';
+
+/**
+ * Android 设备端正式包:构建签名 APK + version.json,并单独发布到 nginx 静态目录
+ *
+ * 特点和桌面端一致(见 publish-desktop.cjs):
+ * - 只动 Android 产物,不重新发布后端、不重启 Egg、不跑数据库迁移;
+ * - 构建复用 backend/android_client/build.ps1(Production 环境);
+ * - APK 上传到 androidDownloadDir(默认 deployRoot/download/android_client);
+ * - version.json 上传到 androidVersionDir(默认同一个目录,nginx 对该文件单独关缓存);
+ * - 同时刷新 front.conf 里的 /download/ 静态托管配置并 reload nginx。
+ *
+ * 用法:
+ * npm run android:publish # 自动递增补丁版本并发布
+ * npm run android:publish -- --version=1.0.1
+ * npm run android:publish -- --notes="扫码上报更稳" --keep=5
+ * npm run android:build # 只构建,不上传(--dry-run)
+ * npm run android:publish -- --skip-nginx # 不改 nginx
+ */
+
+const fs = require('node:fs');
+const path = require('node:path');
+const {
+ ROOT,
+ ensureCommandAvailable,
+ getNowStamp,
+ loadDeployConfig,
+ quoteForBash,
+ refreshNginx,
+ runCommand,
+ runScp,
+ runSsh,
+} = require('./deploy-lib.cjs');
+
+function parseArgs(argv) {
+ const options = {
+ envName: 'production',
+ version: '',
+ notes: '',
+ keep: 0,
+ dryRun: false,
+ skipNginx: false,
+ };
+
+ for (const item of argv) {
+ if (!item) continue;
+ if (!item.startsWith('--') && !options.envNameExplicit) {
+ options.envName = item;
+ options.envNameExplicit = true;
+ continue;
+ }
+ if (item === '--dry-run') {
+ options.dryRun = true;
+ } else if (item === '--skip-nginx') {
+ options.skipNginx = true;
+ } else if (item.startsWith('--version=')) {
+ options.version = item.slice('--version='.length).trim().replace(/^v/i, '');
+ } else if (item.startsWith('--notes=')) {
+ options.notes = item.slice('--notes='.length);
+ } else if (item.startsWith('--keep=')) {
+ options.keep = Number(item.slice('--keep='.length)) || 0;
+ }
+ }
+
+ if (options.version && !/^\d+\.\d+\.\d+$/.test(options.version)) {
+ throw new Error(`版本号格式应为 x.y.z:${options.version}`);
+ }
+ return options;
+}
+
+function compareVersion(a, b) {
+ const pa = a.split('.').map(Number);
+ const pb = b.split('.').map(Number);
+ for (let i = 0; i < 3; i++) {
+ if (pa[i] !== pb[i]) return pa[i] - pb[i];
+ }
+ return 0;
+}
+
+/** 取本地已有 APK / version.json 中最高的版本,并默认 +1 补丁号 */
+function nextVersion(outDir) {
+ const versions = [];
+
+ if (fs.existsSync(outDir)) {
+ for (const name of fs.readdirSync(outDir)) {
+ const match = name.match(/^YuncangScan-(\d+\.\d+\.\d+)\.apk$/);
+ if (match) versions.push(match[1]);
+ }
+ }
+
+ const versionFile = path.join(outDir, 'version.json');
+ if (fs.existsSync(versionFile)) {
+ try {
+ const data = JSON.parse(fs.readFileSync(versionFile, 'utf8'));
+ if (data && /^\d+\.\d+\.\d+$/.test(String(data.version || ''))) {
+ versions.push(String(data.version));
+ }
+ } catch (error) {
+ // 忽略损坏的本地 version.json
+ }
+ }
+
+ if (!versions.length) return '1.0.0';
+ versions.sort(compareVersion);
+ const [ major, minor, patch ] = versions[versions.length - 1].split('.').map(Number);
+ return `${major}.${minor}.${patch + 1}`;
+}
+
+/** 用 android_client/build.ps1 构建 Production 包 */
+function buildAndroid(config, { version, notes, baseUrl }) {
+ const buildScript = path.resolve(ROOT, config.androidBuildScript);
+ if (!fs.existsSync(buildScript)) {
+ throw new Error(`找不到 Android 构建脚本: ${buildScript}`);
+ }
+
+ const shell = process.platform === 'win32' ? 'powershell.exe' : 'pwsh';
+ const args = [
+ '-NoProfile',
+ '-ExecutionPolicy', 'Bypass',
+ '-File', buildScript,
+ '-Environment', 'Production',
+ '-Version', version,
+ '-ServerBaseUrl', baseUrl,
+ ];
+ if (notes) {
+ args.push('-ReleaseNotes', notes);
+ }
+
+ console.log(`构建 Android 正式包: ${version}(${baseUrl})`);
+ runCommand(shell, args, { cwd: path.dirname(buildScript), stdio: 'inherit' });
+}
+
+function main() {
+ const options = parseArgs(process.argv.slice(2));
+ const config = loadDeployConfig(options.envName);
+
+ const outDir = path.resolve(ROOT, config.androidOutDir);
+ const remoteDir = config.androidDownloadDir;
+ const remoteVersionDir = config.androidVersionDir || remoteDir;
+ const baseUrl = String(config.androidBaseUrl || `http://${config.serverName}`).replace(/\/+$/, '');
+ const keep = options.keep > 0 ? options.keep : Number(config.androidKeepVersions || 5);
+ const version = options.version || nextVersion(outDir);
+
+ if (!remoteDir) {
+ throw new Error('未配置 androidDownloadDir(Android 安装包发布目录)。');
+ }
+ if (!remoteVersionDir) {
+ throw new Error('未配置 androidVersionDir(Android version.json 发布目录)。');
+ }
+
+ buildAndroid(config, { version, notes: options.notes, baseUrl });
+
+ const apkName = `YuncangScan-${version}.apk`;
+ const apkPath = path.join(outDir, apkName);
+ const versionPath = path.join(outDir, 'version.json');
+
+ if (!fs.existsSync(apkPath)) {
+ throw new Error(`构建完成但 APK 不存在: ${apkPath}`);
+ }
+ if (!fs.existsSync(versionPath)) {
+ throw new Error(`构建完成但 version.json 不存在: ${versionPath}`);
+ }
+
+ const versionJson = JSON.parse(fs.readFileSync(versionPath, 'utf8'));
+ console.log(`安装包: ${apkPath}(${(fs.statSync(apkPath).size / 1024 / 1024).toFixed(1)} MB)`);
+ console.log(`版本文件: ${versionPath}`);
+ console.log(`下载地址: ${versionJson.downloadUrl}`);
+ console.log(`发布目录: ${config.username}@${config.host}:${remoteDir}`);
+ console.log(`版本目录: ${config.username}@${config.host}:${remoteVersionDir}`);
+
+ if (options.dryRun) {
+ console.log('DRY-RUN:只构建,不上传。');
+ return;
+ }
+
+ ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。');
+ ensureCommandAvailable('scp', '请先安装 OpenSSH Client 并确保 scp 在 PATH 中。');
+
+ const stamp = getNowStamp();
+ const remoteApkTmp = `${remoteDir}/.${apkName}.upload-${stamp}`;
+ const remoteVersionTmp = `${remoteVersionDir}/.version.json.upload-${stamp}`;
+
+ runSsh(config, [
+ 'set -euo pipefail',
+ `DIR=${quoteForBash(remoteDir)}`,
+ `VDIR=${quoteForBash(remoteVersionDir)}`,
+ 'mkdir -p "$DIR" "$VDIR"',
+ // 清理上次中断留下的隐藏临时文件
+ 'find "$DIR" "$VDIR" -maxdepth 1 -type f -name ".*.upload-*" -delete',
+ ].join('\n'), { stdio: 'pipe' });
+
+ console.log(`上传安装包(${(fs.statSync(apkPath).size / 1024 / 1024).toFixed(1)} MB)…`);
+ runScp(config, apkPath, remoteApkTmp);
+
+ runSsh(config, [
+ 'set -euo pipefail',
+ `DIR=${quoteForBash(remoteDir)}`,
+ `TMP=${quoteForBash(remoteApkTmp)}`,
+ `FINAL=${quoteForBash(`${remoteDir}/${apkName}`)}`,
+ 'mv "$TMP" "$FINAL"',
+ 'chmod 644 "$FINAL"',
+ `chown ${quoteForBash(config.androidOwner || 'www:www')} "$FINAL" || true`,
+ 'echo "APK_UPLOADED"',
+ ].join('\n'), { stdio: 'pipe' });
+ console.log(`安装包已发布: ${remoteDir}/${apkName}`);
+
+ // APK 就位后再更新 version.json,避免客户端拿到指向不存在文件的版本信息
+ runScp(config, versionPath, remoteVersionTmp);
+ runSsh(config, [
+ 'set -euo pipefail',
+ `DIR=${quoteForBash(remoteDir)}`,
+ `VDIR=${quoteForBash(remoteVersionDir)}`,
+ `TMP=${quoteForBash(remoteVersionTmp)}`,
+ 'mv "$TMP" "$VDIR/version.json"',
+ 'chmod 644 "$VDIR/version.json"',
+ `chown ${quoteForBash(config.androidOwner || 'www:www')} "$VDIR/version.json" || true`,
+ 'echo "VERSION_JSON_UPLOADED"',
+ // 只保留最近 N 个安装包
+ 'COUNT=0',
+ `for FILE in $(ls -1t "$DIR"/YuncangScan-*.apk 2>/dev/null || true); do`,
+ ' COUNT=$((COUNT + 1))',
+ ` if [ "$COUNT" -gt ${Number(keep)} ]; then rm -f "$FILE"; fi`,
+ 'done',
+ 'ls -1t "$DIR" | head -20',
+ ].join('\n'), { stdio: 'pipe' });
+
+ if (!options.skipNginx) {
+ refreshNginx(config);
+ }
+
+ console.log('');
+ console.log('Android 设备端发布完成:');
+ console.log(` 版本: ${version}`);
+ console.log(` 安装包: ${baseUrl}/download/android_client/${apkName}`);
+ console.log(` 更新信息: ${baseUrl}/download/android_client/version.json`);
+}
+
+try {
+ main();
+} catch (err) {
+ console.error(`[ANDROID] ${err && err.message ? err.message : err}`);
+ process.exit(1);
+}
diff --git a/backend/scripts/deploy/publish-desktop.cjs b/backend/scripts/deploy/publish-desktop.cjs
new file mode 100644
index 0000000..ea8cda6
--- /dev/null
+++ b/backend/scripts/deploy/publish-desktop.cjs
@@ -0,0 +1,245 @@
+'use strict';
+
+/**
+ * 桌面端正式包:构建 MSI + version.json,并单独发布到 nginx 静态目录
+ *
+ * 特点:
+ * - 只动桌面端产物,不重新发布后端、不重启 Egg、不跑数据库迁移;
+ * - 构建复用 desktop/installer/build.ps1(Production 环境);
+ * - 安装包上传到 deploy.config.local.cjs 里的 desktopDownloadDir(deployRoot/download/desktop);
+ * - version.json 上传到 desktopVersionDir(默认 deployRoot/download,nginx 对 /download/version.json 关缓存);
+ * - 同时刷新 front.conf 里的 /download/ 静态托管配置并 reload nginx。
+ *
+ * 用法:
+ * npm run desktop:publish # 自动递增补丁版本并发布
+ * npm run desktop:publish -- --version=1.0.90
+ * npm run desktop:publish -- --notes="修复 xxx" --keep=10
+ * npm run desktop:build # 只构建,不上传(--dry-run)
+ * npm run desktop:publish -- --skip-nginx # 不改 nginx
+ */
+
+const fs = require('node:fs');
+const path = require('node:path');
+const {
+ ROOT,
+ ensureCommandAvailable,
+ getNowStamp,
+ loadDeployConfig,
+ quoteForBash,
+ refreshNginx,
+ runCommand,
+ runScp,
+ runSsh,
+} = require('./deploy-lib.cjs');
+
+function parseArgs(argv) {
+ const options = {
+ envName: 'production',
+ version: '',
+ notes: '',
+ keep: 0,
+ dryRun: false,
+ skipNginx: false,
+ };
+
+ for (const item of argv) {
+ if (!item) continue;
+ if (!item.startsWith('--') && !options.envNameExplicit) {
+ options.envName = item;
+ options.envNameExplicit = true;
+ continue;
+ }
+ if (item === '--dry-run') {
+ options.dryRun = true;
+ } else if (item === '--skip-nginx') {
+ options.skipNginx = true;
+ } else if (item.startsWith('--version=')) {
+ options.version = item.slice('--version='.length).trim().replace(/^v/i, '');
+ } else if (item.startsWith('--notes=')) {
+ options.notes = item.slice('--notes='.length);
+ } else if (item.startsWith('--keep=')) {
+ options.keep = Number(item.slice('--keep='.length)) || 0;
+ }
+ }
+
+ if (options.version && !/^\d+\.\d+\.\d+$/.test(options.version)) {
+ throw new Error(`版本号格式应为 x.y.z:${options.version}`);
+ }
+ return options;
+}
+
+function compareVersion(a, b) {
+ const pa = a.split('.').map(Number);
+ const pb = b.split('.').map(Number);
+ for (let i = 0; i < 3; i++) {
+ if (pa[i] !== pb[i]) return pa[i] - pb[i];
+ }
+ return 0;
+}
+
+/** 取本地已有 MSI / version.json 中最高的版本,并默认 +1 补丁号 */
+function nextVersion(outDir) {
+ const versions = [];
+
+ if (fs.existsSync(outDir)) {
+ for (const name of fs.readdirSync(outDir)) {
+ const match = name.match(/^YuncangTraceSetup-(\d+\.\d+\.\d+)\.msi$/);
+ if (match) versions.push(match[1]);
+ }
+ }
+
+ const versionFile = path.join(outDir, 'version.json');
+ if (fs.existsSync(versionFile)) {
+ try {
+ const data = JSON.parse(fs.readFileSync(versionFile, 'utf8'));
+ if (data && /^\d+\.\d+\.\d+$/.test(String(data.version || ''))) {
+ versions.push(String(data.version));
+ }
+ } catch (error) {
+ // 忽略损坏的本地 version.json
+ }
+ }
+
+ if (!versions.length) return '1.0.0';
+ versions.sort(compareVersion);
+ const [ major, minor, patch ] = versions[versions.length - 1].split('.').map(Number);
+ return `${major}.${minor}.${patch + 1}`;
+}
+
+/** 用 build.ps1 构建 Production 包 */
+function buildDesktop(config, { version, notes, baseUrl }) {
+ const buildScript = path.resolve(ROOT, config.desktopBuildScript);
+ if (!fs.existsSync(buildScript)) {
+ throw new Error(`找不到桌面端构建脚本: ${buildScript}`);
+ }
+
+ const shell = process.platform === 'win32' ? 'powershell.exe' : 'pwsh';
+ const args = [
+ '-NoProfile',
+ '-ExecutionPolicy', 'Bypass',
+ '-File', buildScript,
+ '-Environment', 'Production',
+ '-Version', version,
+ '-ServerBaseUrl', baseUrl,
+ ];
+ if (notes) {
+ args.push('-ReleaseNotes', notes);
+ }
+
+ console.log(`构建桌面端正式包: ${version}(${baseUrl})`);
+ runCommand(shell, args, { cwd: path.dirname(buildScript), stdio: 'inherit' });
+}
+
+/** 写 front.conf(静态 /download + /api 反代)并 reload nginx */
+function main() {
+ const options = parseArgs(process.argv.slice(2));
+ const config = loadDeployConfig(options.envName);
+
+ const outDir = path.resolve(ROOT, config.desktopOutDir);
+ const remoteDir = config.desktopDownloadDir;
+ // version.json 不放安装包目录里:nginx 对 /download/version.json 单独关缓存,安装包目录走长缓存
+ const remoteVersionDir = config.desktopVersionDir || path.posix.dirname(String(remoteDir || ''));
+ const baseUrl = String(config.desktopBaseUrl || `http://${config.serverName}`).replace(/\/+$/, '');
+ const keep = options.keep > 0 ? options.keep : Number(config.desktopKeepVersions || 5);
+ const version = options.version || nextVersion(outDir);
+
+ if (!remoteDir) {
+ throw new Error('未配置 desktopDownloadDir(桌面安装包发布目录)。');
+ }
+ if (!remoteVersionDir || remoteVersionDir === '.' || remoteVersionDir === '/') {
+ throw new Error('未配置 desktopVersionDir(version.json 发布目录)。');
+ }
+
+ buildDesktop(config, { version, notes: options.notes, baseUrl });
+
+ const msiName = `YuncangTraceSetup-${version}.msi`;
+ const msiPath = path.join(outDir, msiName);
+ const versionPath = path.join(outDir, 'version.json');
+
+ if (!fs.existsSync(msiPath)) {
+ throw new Error(`构建完成但 MSI 不存在: ${msiPath}`);
+ }
+ if (!fs.existsSync(versionPath)) {
+ throw new Error(`构建完成但 version.json 不存在: ${versionPath}`);
+ }
+
+ const versionJson = JSON.parse(fs.readFileSync(versionPath, 'utf8'));
+ console.log(`安装包: ${msiPath}(${(fs.statSync(msiPath).size / 1024 / 1024).toFixed(1)} MB)`);
+ console.log(`版本文件: ${versionPath}`);
+ console.log(`下载地址: ${versionJson.downloadUrl}`);
+ console.log(`发布目录: ${config.username}@${config.host}:${remoteDir}`);
+ console.log(`版本目录: ${config.username}@${config.host}:${remoteVersionDir}`);
+
+ if (options.dryRun) {
+ console.log('DRY-RUN:只构建,不上传。');
+ return;
+ }
+
+ ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。');
+ ensureCommandAvailable('scp', '请先安装 OpenSSH Client 并确保 scp 在 PATH 中。');
+
+ const stamp = getNowStamp();
+ const remoteMsiTmp = `${remoteDir}/.${msiName}.upload-${stamp}`;
+ const remoteVersionTmp = `${remoteVersionDir}/.version.json.upload-${stamp}`;
+
+ runSsh(config, [
+ 'set -euo pipefail',
+ `DIR=${quoteForBash(remoteDir)}`,
+ `VDIR=${quoteForBash(remoteVersionDir)}`,
+ 'mkdir -p "$DIR" "$VDIR"',
+ // 清理上次中断留下的隐藏临时文件
+ 'find "$DIR" "$VDIR" -maxdepth 1 -type f -name ".*.upload-*" -delete',
+ ].join('\n'), { stdio: 'pipe' });
+
+ console.log(`上传安装包(${(fs.statSync(msiPath).size / 1024 / 1024).toFixed(1)} MB)…`);
+ runScp(config, msiPath, remoteMsiTmp);
+
+ runSsh(config, [
+ 'set -euo pipefail',
+ `DIR=${quoteForBash(remoteDir)}`,
+ `TMP=${quoteForBash(remoteMsiTmp)}`,
+ `FINAL=${quoteForBash(`${remoteDir}/${msiName}`)}`,
+ 'mv "$TMP" "$FINAL"',
+ 'chmod 644 "$FINAL"',
+ `chown ${quoteForBash(config.desktopOwner || 'www:www')} "$FINAL" || true`,
+ 'echo "MSI_UPLOADED"',
+ ].join('\n'), { stdio: 'pipe' });
+ console.log(`安装包已发布: ${remoteDir}/${msiName}`);
+
+ // MSI 就位后再更新 version.json,避免客户端拿到指向不存在文件的版本信息
+ runScp(config, versionPath, remoteVersionTmp);
+ runSsh(config, [
+ 'set -euo pipefail',
+ `DIR=${quoteForBash(remoteDir)}`,
+ `VDIR=${quoteForBash(remoteVersionDir)}`,
+ `TMP=${quoteForBash(remoteVersionTmp)}`,
+ 'mv "$TMP" "$VDIR/version.json"',
+ 'chmod 644 "$VDIR/version.json"',
+ `chown ${quoteForBash(config.desktopOwner || 'www:www')} "$VDIR/version.json" || true`,
+ 'echo "VERSION_JSON_UPLOADED"',
+ // 只保留最近 N 个安装包
+ 'COUNT=0',
+ `for FILE in $(ls -1t "$DIR"/YuncangTraceSetup-*.msi 2>/dev/null || true); do`,
+ ' COUNT=$((COUNT + 1))',
+ ` if [ "$COUNT" -gt ${Number(keep)} ]; then rm -f "$FILE"; fi`,
+ 'done',
+ 'ls -1t "$DIR" | head -20',
+ ].join('\n'), { stdio: 'pipe' });
+
+ if (!options.skipNginx) {
+ refreshNginx(config);
+ }
+
+ console.log('');
+ console.log('桌面端发布完成:');
+ console.log(` 版本: ${version}`);
+ console.log(` 安装包: ${baseUrl}/download/desktop/${msiName}`);
+ console.log(` 更新信息: ${baseUrl}/download/version.json`);
+}
+
+try {
+ main();
+} catch (err) {
+ console.error(`[DESKTOP] ${err && err.message ? err.message : err}`);
+ process.exit(1);
+}
diff --git a/backend/scripts/deploy/rollback-remote.cjs b/backend/scripts/deploy/rollback-remote.cjs
new file mode 100644
index 0000000..e7d507a
--- /dev/null
+++ b/backend/scripts/deploy/rollback-remote.cjs
@@ -0,0 +1,404 @@
+'use strict';
+
+const {
+ buildHealthCheckScript,
+ buildKillPortScript,
+ buildNginxSwitchScript,
+ buildPinnedPathGuardLines,
+ buildRemoteCleanupGuard,
+ buildRemoteJsonWriteLines,
+ buildStartScript,
+ buildStopDirScript,
+ ensureCommandAvailable,
+ getRemoteEnvFile,
+ loadDeployConfig,
+ quoteForBash,
+ runSsh,
+} = require('./deploy-lib.cjs');
+const { recordVersionUpdate } = require('./version-registry.cjs');
+
+function readRemoteCurrentVersion(config) {
+ const currentMdPath = `${config.deployRoot}/current.md`;
+ const output = runSsh(config, `cat ${quoteForBash(currentMdPath)} 2>/dev/null || true`, { stdio: 'pipe' });
+ const rawVersion = String(output || '').trim();
+
+ if (!rawVersion) {
+ throw new Error(`无法读取远端当前版本文件: ${currentMdPath}。`);
+ }
+
+ const normalized = rawVersion.replace(/\r/g, '').trim();
+ if (normalized !== 'v1' && normalized !== 'v2') {
+ throw new Error(`远端 current.md 内容无效: "${rawVersion}",期望值为 v1 或 v2。`);
+ }
+ return normalized;
+}
+
+function otherVersion(version) {
+ return version === 'v1' ? 'v2' : 'v1';
+}
+
+function parseBackupArg(argv) {
+ const backupArg = argv.find(item => item.startsWith('--backup='));
+ if (!backupArg) {
+ return '';
+ }
+ return backupArg.slice('--backup='.length).trim();
+}
+
+/**
+ * 读取目标版本的 package.json 版本号与历史发布记录(用于回退后保留 releaseVersion 等信息)
+ *
+ * @param {object} config - 部署配置
+ * @param {string} version - 版本标识 v1 / v2
+ * @param {string} dir - 版本目录
+ * @return {object} 可合并进发布状态的字段
+ */
+function readReleaseContext(config, version, dir) {
+ const script = [
+ 'set -euo pipefail',
+ `PKG=${quoteForBash(`${dir}/package.json`)}`,
+ `HIST=${quoteForBash(`${config.stateDir}/release-history.jsonl`)}`,
+ 'echo "__PKG__"',
+ 'if [ -f "$PKG" ]; then node -e "console.log(require(process.argv[1]).version)" "$PKG" 2>/dev/null || true; fi',
+ 'echo "__HIST__"',
+ 'if [ -f "$HIST" ]; then tail -n 50 "$HIST"; fi',
+ ].join('\n');
+
+ try {
+ const output = runSsh(config, script, { stdio: 'pipe' });
+ const [ pkgPart, histPart ] = output.split('__HIST__');
+ const packageVersion = String(pkgPart || '').replace('__PKG__', '').trim();
+ const entries = String(histPart || '')
+ .split(/\r?\n/)
+ .map(line => line.trim())
+ .filter(Boolean)
+ .map(line => {
+ try {
+ return JSON.parse(line);
+ } catch (error) {
+ return null;
+ }
+ })
+ .filter(entry => entry && entry.activeVersion === version);
+
+ const context = entries.reduce((acc, entry) => ({ ...acc, ...entry }), {});
+ return { ...context, packageVersion: packageVersion || context.packageVersion || '' };
+ } catch (error) {
+ return {};
+ }
+}
+
+function writeRemoteState(config, record) {
+ runSsh(config, [
+ 'set -euo pipefail',
+ `STATE_DIR=${quoteForBash(config.stateDir)}`,
+ 'mkdir -p "$STATE_DIR"',
+ ...buildRemoteJsonWriteLines(config.stateDir, 'current-release.json', record, false),
+ ...buildRemoteJsonWriteLines(config.stateDir, 'release-history.jsonl', record, true),
+ ].join('\n'), { stdio: 'pipe' });
+}
+
+function recordLocally(config, note) {
+ try {
+ recordVersionUpdate({ source: 'rollback', note, deployRoot: config.deployRoot });
+ } catch (err) {
+ console.warn(`[WARN] 本地版本记录失败: ${err.message}`);
+ }
+}
+
+/** 蓝绿回退:切回另一个版本目录(上一个发布版本) */
+function rollbackBySwitch(config, currentVersion) {
+ const targetVersion = otherVersion(currentVersion);
+ const targetDir = `${config.deployRoot}/${targetVersion}`;
+ const targetPort = config.ports[targetVersion];
+ const startLogPath = `/tmp/pack-service-${targetVersion}-rollback.log`;
+ const currentMdPath = `${config.deployRoot}/current.md`;
+
+ const exists = runSsh(config, [
+ 'set -euo pipefail',
+ `if [ -f ${quoteForBash(`${targetDir}/package.json`)} ]; then echo TARGET_OK; else echo TARGET_MISSING; fi`,
+ ].join('\n'), { stdio: 'pipe' }).trim();
+
+ if (exists !== 'TARGET_OK') {
+ throw new Error(
+ `上一个版本目录不可用: ${targetDir}。如需用备份包回退,请执行: npm run rollback -- --backup=backup-<时间戳>.tar.gz`
+ );
+ }
+
+ console.log(`蓝绿回退: ${currentVersion} -> ${targetVersion}(${targetDir},端口 ${targetPort})`);
+
+ runSsh(config, [
+ 'set -euo pipefail',
+ `TARGET_DIR=${quoteForBash(targetDir)}`,
+ `SHARED_CONFIG_DIR=${quoteForBash(config.sharedConfigDir)}`,
+ 'if [ -n "$SHARED_CONFIG_DIR" ] && [ -d "$SHARED_CONFIG_DIR" ]; then',
+ ' for FILE_NAME in config.prod.js config.local.js; do',
+ ' if [ -f "$SHARED_CONFIG_DIR/$FILE_NAME" ]; then',
+ ' mkdir -p "$TARGET_DIR/config"',
+ ' cp -a "$SHARED_CONFIG_DIR/$FILE_NAME" "$TARGET_DIR/config/$FILE_NAME"',
+ ' fi',
+ ' done',
+ 'fi',
+ ].join('\n'), { stdio: 'pipe' });
+
+ try {
+ const killPortOutput = runSsh(config, buildKillPortScript(targetPort), { stdio: 'pipe' });
+ console.log(String(killPortOutput || '').trim());
+ } catch (err) {
+ console.warn(`[WARN] 端口 ${targetPort} 清理失败: ${err.message}`);
+ }
+
+ runSsh(config, buildStartScript({
+ dir: targetDir,
+ port: targetPort,
+ envFile: getRemoteEnvFile(config),
+ logPath: startLogPath,
+ }), { stdio: 'pipe' });
+
+ try {
+ const healthOutput = runSsh(config, buildHealthCheckScript({
+ port: targetPort,
+ healthPath: config.healthCheckPath,
+ attempts: config.healthCheckAttempts,
+ interval: config.healthCheckInterval,
+ }), { stdio: 'pipe' });
+ console.log(String(healthOutput || '').trim());
+ } catch (err) {
+ console.error(`[ERROR] 回退目标实例健康检查失败: ${err.message}`);
+ try {
+ runSsh(config, buildStopDirScript(targetDir, `回退目标 (${targetVersion})`), { stdio: 'pipe' });
+ } catch (killErr) {
+ console.error(`[ERROR] 清理回退目标失败: ${killErr.message}`);
+ }
+ console.error(`[ERROR] current.md 未修改,旧实例 (${currentVersion}) 仍在提供服务`);
+ process.exit(1);
+ }
+
+ const switchOutput = runSsh(config, [
+ 'set -euo pipefail',
+ `printf '%s\\n' ${quoteForBash(targetVersion)} > ${quoteForBash(currentMdPath)}`,
+ `echo "已更新 current.md -> ${targetVersion}"`,
+ ].join('\n'), { stdio: 'pipe' });
+ console.log(String(switchOutput || '').trim());
+
+ try {
+ rollbackFrontend(config);
+ } catch (err) {
+ console.warn(`[WARN] 前端回退失败: ${err.message}`);
+ }
+
+ let nginxSwitched = true;
+ if (config.nginxUpstreamFile) {
+ try {
+ const nginxOutput = runSsh(config, buildNginxSwitchScript(config.nginxUpstreamFile, targetPort), { stdio: 'pipe' });
+ console.log(String(nginxOutput || '').trim());
+ } catch (err) {
+ nginxSwitched = false;
+ console.warn(`[WARN] Nginx upstream 切换失败: ${err.message}`);
+ console.warn(`[WARN] 为保留线上服务,暂不停止原实例 (${currentVersion});请修复 Nginx 后执行 nginx -t && nginx -s reload`);
+ }
+ }
+
+ if (!nginxSwitched) {
+ console.warn(`[WARN] 当前同时运行 ${currentVersion} / ${targetVersion},确认 Nginx 指到 ${targetPort} 后再停旧实例`);
+ } else {
+ try {
+ const stopOutput = runSsh(config, buildStopDirScript(
+ `${config.deployRoot}/${currentVersion}`,
+ `原实例 (${currentVersion})`
+ ), { stdio: 'pipe' });
+ console.log(String(stopOutput || '').trim());
+ } catch (err) {
+ console.warn(`[WARN] 停止原实例失败: ${err.message}`);
+ }
+ }
+
+ const record = {
+ ...readReleaseContext(config, targetVersion, targetDir),
+ rolledBackAt: new Date().toISOString(),
+ source: 'rollback',
+ activeVersion: targetVersion,
+ port: targetPort,
+ dir: targetDir,
+ previousVersion: currentVersion,
+ rolledBackBy: process.env.USERNAME || process.env.USER || '',
+ };
+ try {
+ writeRemoteState(config, record);
+ } catch (err) {
+ console.warn(`[WARN] 远端回退状态记录失败: ${err.message}`);
+ }
+ recordLocally(config, `rollback ${currentVersion} -> ${targetVersion}`);
+
+ console.log(`回退完成:当前活跃版本 ${targetVersion}(端口 ${targetPort})`);
+}
+
+/** 备份包回退:把指定备份解压回当前活跃目录并重启 */
+function rollbackByBackup(config, currentVersion, currentPort, backupName) {
+ const currentDir = `${config.deployRoot}/${currentVersion}`;
+ const startLogPath = `/tmp/pack-service-${currentVersion}-rollback.log`;
+ const latestBackupFile = `${config.stateDir}/latest-backup.txt`;
+
+ const selectBackupScript = [
+ 'set -euo pipefail',
+ `BACKUP_DIR=${quoteForBash(config.backupDir)}`,
+ `LATEST_BACKUP_FILE=${quoteForBash(latestBackupFile)}`,
+ `REQUESTED_BACKUP=${quoteForBash(backupName)}`,
+ 'if [ -n "$REQUESTED_BACKUP" ]; then',
+ ' TARGET_BACKUP="$REQUESTED_BACKUP"',
+ 'elif [ -f "$LATEST_BACKUP_FILE" ]; then',
+ ' TARGET_BACKUP="$(cat "$LATEST_BACKUP_FILE")"',
+ 'else',
+ ' echo "ERROR: 未找到最近一次发布备份,请通过 --backup=backup-时间戳.tar.gz 指定回退包。" >&2',
+ ' exit 1',
+ 'fi',
+ 'if [ ! -f "$BACKUP_DIR/$TARGET_BACKUP" ]; then',
+ ' echo "ERROR: 回退包不存在: $BACKUP_DIR/$TARGET_BACKUP" >&2',
+ ' exit 1',
+ 'fi',
+ 'echo "$TARGET_BACKUP"',
+ ].join('\n');
+
+ const targetBackup = runSsh(config, selectBackupScript, { stdio: 'pipe' }).trim();
+ console.log(`备份包回退: ${targetBackup} -> ${currentDir}`);
+
+ try {
+ const stopOutput = runSsh(config, buildStopDirScript(currentDir, `当前实例 (${currentVersion})`), { stdio: 'pipe' });
+ console.log(String(stopOutput || '').trim());
+ } catch (err) {
+ console.warn(`[WARN] 停止当前实例失败: ${err.message}`);
+ }
+
+ const pinnedStashDir = `/tmp/pack-service-pinned-rollback-${currentVersion}`;
+ const pinnedGuard = buildPinnedPathGuardLines('CURRENT_DIR', 'PINNED_DIR', config.preservePaths);
+ const cleanupGuard = buildRemoteCleanupGuard(config.sharedDirs);
+
+ runSsh(config, [
+ 'set -euo pipefail',
+ `CURRENT_DIR=${quoteForBash(currentDir)}`,
+ `BACKUP_DIR=${quoteForBash(config.backupDir)}`,
+ `TARGET_BACKUP=${quoteForBash(targetBackup)}`,
+ `PINNED_DIR=${quoteForBash(pinnedStashDir)}`,
+ `SHARED_CONFIG_DIR=${quoteForBash(config.sharedConfigDir)}`,
+ ...pinnedGuard.stash,
+ 'cd "$CURRENT_DIR"',
+ `find . -mindepth 1 -maxdepth 1 ${cleanupGuard} -exec rm -rf {} +`,
+ 'echo "旧代码已清理完成"',
+ 'tar -xzf "$BACKUP_DIR/$TARGET_BACKUP" -C "$CURRENT_DIR"',
+ 'echo "备份包已解压到 $CURRENT_DIR"',
+ ...pinnedGuard.restore,
+ 'if [ -n "$SHARED_CONFIG_DIR" ] && [ -d "$SHARED_CONFIG_DIR" ]; then',
+ ' for FILE_NAME in config.prod.js config.local.js; do',
+ ' if [ -f "$SHARED_CONFIG_DIR/$FILE_NAME" ]; then',
+ ' mkdir -p "$CURRENT_DIR/config"',
+ ' cp -a "$SHARED_CONFIG_DIR/$FILE_NAME" "$CURRENT_DIR/config/$FILE_NAME"',
+ ' echo "SHARED_CONFIG_APPLIED $FILE_NAME"',
+ ' fi',
+ ' done',
+ 'fi',
+ 'mkdir -p "$CURRENT_DIR/app/public/download" "$CURRENT_DIR/app/public/version"',
+ 'mkdir -p "$CURRENT_DIR/logs" "$CURRENT_DIR/run" "$CURRENT_DIR/temp"',
+ 'npm install --production',
+ 'echo "生产依赖安装完成"',
+ ].join('\n'));
+
+ runSsh(config, buildStartScript({
+ dir: currentDir,
+ port: currentPort,
+ envFile: getRemoteEnvFile(config),
+ logPath: startLogPath,
+ }), { stdio: 'pipe' });
+
+ try {
+ const healthOutput = runSsh(config, buildHealthCheckScript({
+ port: currentPort,
+ healthPath: config.healthCheckPath,
+ attempts: config.healthCheckAttempts,
+ interval: config.healthCheckInterval,
+ }), { stdio: 'pipe' });
+ console.log(String(healthOutput || '').trim());
+ } catch (err) {
+ console.error(`[ERROR] 备份包回退后健康检查失败: ${err.message}`);
+ console.error(`[ERROR] 请检查启动日志: ${startLogPath}`);
+ process.exit(1);
+ }
+
+ if (config.nginxUpstreamFile) {
+ try {
+ const nginxOutput = runSsh(config, buildNginxSwitchScript(config.nginxUpstreamFile, currentPort), { stdio: 'pipe' });
+ console.log(String(nginxOutput || '').trim());
+ } catch (err) {
+ console.warn(`[WARN] Nginx upstream 切换失败: ${err.message}`);
+ }
+ }
+
+ const record = {
+ ...readReleaseContext(config, currentVersion, currentDir),
+ rolledBackAt: new Date().toISOString(),
+ source: 'rollback-backup',
+ activeVersion: currentVersion,
+ port: currentPort,
+ dir: currentDir,
+ backup: targetBackup,
+ rolledBackBy: process.env.USERNAME || process.env.USER || '',
+ };
+ try {
+ writeRemoteState(config, record);
+ } catch (err) {
+ console.warn(`[WARN] 远端回退状态记录失败: ${err.message}`);
+ }
+ recordLocally(config, `rollback-backup ${targetBackup}`);
+
+ console.log(`回退完成:${currentVersion} 已恢复为备份包 ${targetBackup} 的内容`);
+}
+
+/** 回退前端静态目录:frontend ↔ frontend.prev 互换 */
+function rollbackFrontend(config) {
+ if (!config.buildFrontend) {
+ return;
+ }
+
+ runSsh(config, [
+ 'set -euo pipefail',
+ `FRONTEND_DIR=${quoteForBash(config.frontendDeployDir)}`,
+ `PREV_DIR=${quoteForBash(config.frontendPrevDir)}`,
+ 'if [ -d "$PREV_DIR" ]; then',
+ ' TMP_DIR="${FRONTEND_DIR}.rollback-$$"',
+ ' rm -rf "$TMP_DIR"',
+ ' if [ -d "$FRONTEND_DIR" ]; then mv "$FRONTEND_DIR" "$TMP_DIR"; fi',
+ ' mv "$PREV_DIR" "$FRONTEND_DIR"',
+ ' if [ -d "$TMP_DIR" ]; then mv "$TMP_DIR" "$PREV_DIR"; fi',
+ ' find "$FRONTEND_DIR" -type d -exec chmod 755 {} +',
+ ' find "$FRONTEND_DIR" -type f -exec chmod 644 {} +',
+ ' echo "FRONTEND_ROLLED_BACK $FRONTEND_DIR"',
+ 'else',
+ ' echo "FRONTEND_PREV_MISSING 跳过前端回退"',
+ 'fi',
+ ].join('\n'), { stdio: 'pipe' });
+}
+
+function main() {
+ const envName = process.argv[2] || 'production';
+ const config = loadDeployConfig(envName);
+ const backupName = parseBackupArg(process.argv.slice(3));
+
+ ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。');
+
+ const currentVersion = readRemoteCurrentVersion(config);
+ const currentPort = config.ports[currentVersion];
+ console.log(`远端当前活跃版本: ${currentVersion}(端口 ${currentPort})`);
+
+ if (backupName) {
+ rollbackByBackup(config, currentVersion, currentPort, backupName);
+ return;
+ }
+
+ rollbackBySwitch(config, currentVersion);
+}
+
+try {
+ main();
+} catch (err) {
+ console.error(`[ERROR] ${err && err.message ? err.message : err}`);
+ process.exit(1);
+}
diff --git a/backend/scripts/deploy/setup-git-hooks.cjs b/backend/scripts/deploy/setup-git-hooks.cjs
new file mode 100644
index 0000000..bc1038a
--- /dev/null
+++ b/backend/scripts/deploy/setup-git-hooks.cjs
@@ -0,0 +1,24 @@
+'use strict';
+
+const fs = require('node:fs');
+const path = require('node:path');
+const { REPO_ROOT, runCommand } = require('./deploy-lib.cjs');
+
+const HOOKS_DIR = '.githooks';
+const HOOK_PATH = path.join(REPO_ROOT, HOOKS_DIR, 'pre-commit');
+
+function main() {
+ if (!fs.existsSync(HOOK_PATH)) {
+ throw new Error(`缺少提交钩子文件: ${HOOK_PATH}`);
+ }
+
+ runCommand('git', [ 'config', 'core.hooksPath', HOOKS_DIR ], { cwd: REPO_ROOT, stdio: 'inherit' });
+ console.log(`已设置 core.hooksPath=${HOOKS_DIR}(仓库根: ${REPO_ROOT})`);
+}
+
+try {
+ main();
+} catch (err) {
+ console.error(`[ERROR] ${err && err.message ? err.message : err}`);
+ process.exit(1);
+}
diff --git a/backend/scripts/deploy/version-history.cjs b/backend/scripts/deploy/version-history.cjs
new file mode 100644
index 0000000..7a19a7b
--- /dev/null
+++ b/backend/scripts/deploy/version-history.cjs
@@ -0,0 +1,32 @@
+'use strict';
+
+const { readVersionHistory } = require('./version-registry.cjs');
+
+function parseLimit(argv) {
+ for (const item of argv) {
+ if (item.startsWith('--limit=')) {
+ const value = Number(item.slice('--limit='.length));
+ if (Number.isFinite(value) && value > 0) {
+ return Math.floor(value);
+ }
+ }
+ }
+ return 20;
+}
+
+function main() {
+ const limit = parseLimit(process.argv.slice(2));
+ const records = readVersionHistory(limit);
+ if (records.length === 0) {
+ console.log('LOCAL_VERSION_HISTORY_EMPTY');
+ return;
+ }
+ console.log(JSON.stringify(records, null, 2));
+}
+
+try {
+ main();
+} catch (err) {
+ console.error(`[ERROR] ${err && err.message ? err.message : err}`);
+ process.exit(1);
+}
diff --git a/backend/scripts/deploy/version-record.cjs b/backend/scripts/deploy/version-record.cjs
new file mode 100644
index 0000000..7237364
--- /dev/null
+++ b/backend/scripts/deploy/version-record.cjs
@@ -0,0 +1,29 @@
+'use strict';
+
+const { recordVersionUpdate } = require('./version-registry.cjs');
+
+function parseArgs(argv) {
+ let note = '';
+ for (const item of argv) {
+ if (item.startsWith('--note=')) {
+ note = item.slice('--note='.length).trim();
+ }
+ }
+ return { note };
+}
+
+function main() {
+ const options = parseArgs(process.argv.slice(2));
+ const entry = recordVersionUpdate({
+ source: 'version:record',
+ note: options.note || 'package-version-update',
+ });
+ console.log(JSON.stringify(entry, null, 2));
+}
+
+try {
+ main();
+} catch (err) {
+ console.error(`[ERROR] ${err && err.message ? err.message : err}`);
+ process.exit(1);
+}
diff --git a/backend/scripts/deploy/version-registry.cjs b/backend/scripts/deploy/version-registry.cjs
new file mode 100644
index 0000000..0872051
--- /dev/null
+++ b/backend/scripts/deploy/version-registry.cjs
@@ -0,0 +1,89 @@
+'use strict';
+
+const fs = require('node:fs');
+const path = require('node:path');
+const { ROOT, runCommand } = require('./deploy-lib.cjs');
+
+const VERSION_DIR = path.join(ROOT, 'versioning');
+const VERSION_HISTORY_FILE = path.join(VERSION_DIR, 'package-version-history.jsonl');
+const VERSION_CURRENT_FILE = path.join(VERSION_DIR, 'package-version-current.json');
+
+function ensureVersionDir() {
+ fs.mkdirSync(VERSION_DIR, { recursive: true });
+}
+
+function getPackageMeta() {
+ const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8'));
+ const packageVersion = String(pkg.version || '0.0.0');
+
+ let gitCommit = '';
+ let gitCommitShort = '';
+ let gitBranch = '';
+ try {
+ gitCommit = runCommand('git', [ 'rev-parse', 'HEAD' ]);
+ gitCommitShort = runCommand('git', [ 'rev-parse', '--short', 'HEAD' ]);
+ gitBranch = runCommand('git', [ 'rev-parse', '--abbrev-ref', 'HEAD' ]);
+ } catch (error) {
+ gitCommit = '';
+ gitCommitShort = '';
+ gitBranch = '';
+ }
+
+ return {
+ packageVersion,
+ gitCommit,
+ gitCommitShort,
+ gitBranch,
+ };
+}
+
+function recordVersionUpdate(options = {}) {
+ ensureVersionDir();
+
+ const meta = getPackageMeta();
+ const entry = {
+ recordedAt: new Date().toISOString(),
+ source: options.source || 'manual',
+ note: options.note || '',
+ packageVersion: meta.packageVersion,
+ gitCommit: meta.gitCommit,
+ gitCommitShort: meta.gitCommitShort,
+ gitBranch: meta.gitBranch,
+ releaseVersion: options.releaseVersion || '',
+ deployRoot: options.deployRoot || '',
+ };
+
+ fs.appendFileSync(VERSION_HISTORY_FILE, `${JSON.stringify(entry)}\n`, 'utf8');
+ fs.writeFileSync(VERSION_CURRENT_FILE, `${JSON.stringify(entry, null, 2)}\n`, 'utf8');
+ return entry;
+}
+
+function readVersionHistory(limit = 20) {
+ if (!fs.existsSync(VERSION_HISTORY_FILE)) {
+ return [];
+ }
+
+ const lines = fs.readFileSync(VERSION_HISTORY_FILE, 'utf8')
+ .split(/\r?\n/)
+ .map(item => item.trim())
+ .filter(Boolean);
+
+ const take = Math.max(1, Number(limit || 20));
+ const records = [];
+ for (const line of lines.slice(-take)) {
+ try {
+ records.push(JSON.parse(line));
+ } catch (error) {
+ records.push({ raw: line });
+ }
+ }
+ return records;
+}
+
+module.exports = {
+ VERSION_CURRENT_FILE,
+ VERSION_DIR,
+ VERSION_HISTORY_FILE,
+ readVersionHistory,
+ recordVersionUpdate,
+};
diff --git a/backend/scripts/init-db.js b/backend/scripts/init-db.js
index a27e6f3..fe62dd9 100644
--- a/backend/scripts/init-db.js
+++ b/backend/scripts/init-db.js
@@ -7,7 +7,7 @@
* npm run db:init # 执行 sql/schema.sql
* node scripts/init-db.js sql/xxx.sql # 执行指定 SQL 文件
*
- * 连接信息来源:环境变量 > config/config.local.js > 内置默认值
+ * 连接信息来源:环境变量 > config/config.prod.js(EGG_SERVER_ENV=prod)> config/config.local.js > 内置默认值
*/
const fs = require('fs');
@@ -15,7 +15,7 @@ const path = require('path');
const mysql = require('mysql2/promise');
// 数据库连接信息统一在 scripts/db-config.js 里解析
-// (环境变量 > config/config.local.js > 默认值)
+// (环境变量 > config/config.prod.js(EGG_SERVER_ENV=prod)> config/config.local.js > 默认值)
const resolveDbConfig = require('./db-config');
/** 去掉 -- 行注释,再按分号切分成可逐条执行的语句 */
diff --git a/backend/versioning/.gitkeep b/backend/versioning/.gitkeep
new file mode 100644
index 0000000..e69de29
diff --git a/desktop/App.xaml.cs b/desktop/App.xaml.cs
index 4925d81..32481aa 100644
--- a/desktop/App.xaml.cs
+++ b/desktop/App.xaml.cs
@@ -43,6 +43,12 @@ public partial class App : Application
private bool _exiting;
private bool _trayHintShown;
+ /// 启动时那次自动检查更新是否已成功完成(失败时登录后再补一次)
+ private bool _updateCheckDone;
+
+ /// 正在检查 / 正在弹更新窗:避免自动检查与菜单「检查更新」并发弹两个窗
+ private bool _updatePrompting;
+
/// NTP 定时校时(运行期间周期性把本机时钟校准到 NTP)
private System.Threading.Timer? _ntpTimer;
@@ -158,7 +164,11 @@ public partial class App : Application
AppLog.Write($"本机服务:{_server.BaseUrl}({(_server.IsRunning ? "运行中" : "未启动")})");
AppLog.Write($"环境:{BuildInfo.EnvironmentLabel},后端:{_settings.ServerBaseUrl}");
- // ④ 登录 → 主窗口
+ // ④ 检查更新:**不依赖登录**。登录窗是 ShowDialog 模态,等登录完再查的话,
+ // 老版本用户卡在登录页就永远收不到更新提示,所以这里先发起,网络请求与登录同时进行。
+ _ = CheckUpdatesAsync();
+
+ // ⑤ 登录 → 主窗口
if (!ShowLogin())
{
ExitApplication();
@@ -167,9 +177,8 @@ public partial class App : Application
ShowMainWindow();
- // ⑤ 检查更新(**不依赖登录**状态,但仍要等主窗口起来之后):
- // 登录窗是 ShowDialog 模态,先查的话更新窗会被它挡在后面 —— 就是「没有提示更新」的典型现象。
- _ = CheckUpdatesAsync();
+ // 启动那次检查失败(断网 / 服务未就绪)就在登录后补一次;成功过就不再重复弹窗
+ if (!_updateCheckDone) _ = CheckUpdatesAsync();
}
///
@@ -178,10 +187,16 @@ public partial class App : Application
///
private async Task CheckUpdatesAsync()
{
+ if (_updatePrompting) return;
+ _updatePrompting = true;
+
try
{
var current = GetType().Assembly.GetName().Version ?? new Version(1, 0, 0, 0);
var info = await UpdateChecker.CheckAsync(_settings.ServerBaseUrl, current);
+
+ // 请求本身成功(有没有新版本另说):登录后不用再补查一次
+ _updateCheckDone = true;
if (info is null) return;
AppLog.Write($"发现新版本 {info.Version}(当前 {current}):{info.DownloadUrl}");
@@ -194,9 +209,22 @@ public partial class App : Application
AutoStart = Environment.GetEnvironmentVariable("YUNCANG_AUTO_UPDATE") == "1",
};
+ // 登录窗是模态 ShowDialog,正开着就挂它做 Owner + Topmost:
+ // 否则更新窗会被登录页压在后面,表现就是「卡在登录页收不到更新提示」。
+ if (_loginWindow is { IsVisible: true } login)
+ {
+ update.Owner = login;
+ update.Topmost = true;
+ }
// 主窗口在显示时才挂 Owner(托盘隐藏状态下挂 Owner,子窗口也会被一起藏掉)
- if (_main is { IsVisible: true } main) update.Owner = main;
- else update.Topmost = true;
+ else if (_main is { IsVisible: true } main)
+ {
+ update.Owner = main;
+ }
+ else
+ {
+ update.Topmost = true;
+ }
var result = update.ShowDialog();
AppLog.Write($"更新窗口返回:{result}");
@@ -210,6 +238,10 @@ public partial class App : Application
{
AppLog.Write($"检查更新失败:{ex.Message}");
}
+ finally
+ {
+ _updatePrompting = false;
+ }
}
///
@@ -281,8 +313,18 @@ public partial class App : Application
if (saved is not null
&& !string.Equals(saved.ServerBaseUrl, _settings.ServerBaseUrl, StringComparison.OrdinalIgnoreCase))
{
- AppLog.Write("服务器地址已变更,需要重新登录");
- saved = null;
+ // 只是 http → https(同一台服务器,强制 HTTPS 之前落盘的地址):沿用令牌,只把地址换掉
+ if (AppSettings.IsSameHostAsDefault(saved.ServerBaseUrl))
+ {
+ AppLog.Write($"服务器地址已升级为 {_settings.ServerBaseUrl},继续使用本地登录态");
+ saved.ServerBaseUrl = _settings.ServerBaseUrl;
+ SessionStore.Save(saved);
+ }
+ else
+ {
+ AppLog.Write("服务器地址已变更,需要重新登录");
+ saved = null;
+ }
}
var login = new LoginWindow(_settings, saved);
diff --git a/desktop/LoginWindow.xaml b/desktop/LoginWindow.xaml
index 3e9f33e..49e8bd4 100644
--- a/desktop/LoginWindow.xaml
+++ b/desktop/LoginWindow.xaml
@@ -19,15 +19,7 @@
-
-
-
-
-
-
-
-
+
diff --git a/desktop/LoginWindow.xaml.cs b/desktop/LoginWindow.xaml.cs
index 8819745..5a590be 100644
--- a/desktop/LoginWindow.xaml.cs
+++ b/desktop/LoginWindow.xaml.cs
@@ -44,14 +44,9 @@ public partial class LoginWindow : Window
_settings = settings;
_saved = saved;
- ServerBox.Text = settings.ServerBaseUrl;
AccountBox.Text = settings.LastAccount;
RememberBox.IsChecked = settings.RememberAccount;
- // 环境由构建决定(Debug = 开发环境,Release = 生产环境),默认地址也来自构建
- EnvText.Text = BuildInfo.EnvironmentLabel;
- ServerBox.ToolTip = $"留空即使用{BuildInfo.EnvironmentLabel}默认地址:{BuildInfo.DefaultServer}\n启动时可用 --server=http://x.x.x.x:7300 临时指定";
-
Loaded += OnLoaded;
Closed += (_, _) => StopWechatPolling();
}
@@ -113,7 +108,8 @@ public partial class LoginWindow : Window
{
if (_busy) return;
- var server = AppSettings.Normalize(ServerBox.Text);
+ // 服务地址是内部实现(构建时注入的默认值 / 启动参数 --server 覆盖),不在界面上暴露
+ var server = AppSettings.Normalize(_settings.ServerBaseUrl);
var account = AccountBox.Text.Trim();
var password = PasswordBox.Password;
@@ -203,7 +199,7 @@ public partial class LoginWindow : Window
try
{
- var api = new ApiClient(AppSettings.Normalize(ServerBox.Text));
+ var api = new ApiClient(AppSettings.Normalize(_settings.ServerBaseUrl));
var ticket = await api.StartWechatLoginAsync(cts.Token);
// WPF 不能渲染 SVG,这里拿同一张二维码的 GIF
@@ -344,7 +340,6 @@ public partial class LoginWindow : Window
LoginButton.IsEnabled = !busy;
WechatButton.IsEnabled = !busy;
ExitButton.IsEnabled = !busy;
- ServerBox.IsEnabled = !busy;
AccountBox.IsEnabled = !busy;
PasswordBox.IsEnabled = !busy;
RememberBox.IsEnabled = !busy;
diff --git a/desktop/MainWindow.xaml b/desktop/MainWindow.xaml
index dc51148..edad33e 100644
--- a/desktop/MainWindow.xaml
+++ b/desktop/MainWindow.xaml
@@ -25,6 +25,8 @@
+
+
diff --git a/desktop/MainWindow.xaml.cs b/desktop/MainWindow.xaml.cs
index 06b56d4..4825622 100644
--- a/desktop/MainWindow.xaml.cs
+++ b/desktop/MainWindow.xaml.cs
@@ -125,7 +125,6 @@ public partial class MainWindow : Window
// 用户看到的现象就是「没点查询,打包查询却一直在自动查」。运单查询只允许用户主动发起
// (输入框回车 / 点查询 / 网页或插件用 yuncang:// 协议叫醒)。
UserText.Text = $"已登录:{session.DisplayName}";
- UserText.ToolTip = $"服务器:{settings.ServerBaseUrl}";
Loaded += async (_, _) =>
{
@@ -775,6 +774,37 @@ public partial class MainWindow : Window
}
}
+ ///
+ /// 「工具 → 复制谷歌插件地址」:插件随安装包释放到 <安装目录>\extension,
+ /// 复制这个 Windows 路径,再到 chrome://extensions「加载已解压的扩展程序」里粘进去。
+ ///
+ private void CopyExtensionPath_Click(object sender, RoutedEventArgs e)
+ {
+ var path = Path.Combine(AppContext.BaseDirectory, "extension");
+ try
+ {
+ if (!Directory.Exists(path))
+ {
+ MessageBox.Show(this,
+ $"没有找到谷歌插件目录:\n\n{path}\n\n请安装最新版本后再试。",
+ "复制谷歌插件地址", MessageBoxButton.OK, MessageBoxImage.Warning);
+ return;
+ }
+
+ Clipboard.SetText(path);
+ AppLog.Write($"已复制谷歌插件地址:{path}");
+ MessageBox.Show(this,
+ $"已复制插件路径:\n\n{path}\n\n打开 chrome://extensions → 打开「开发者模式」→「加载已解压的扩展程序」→ 粘贴该路径。",
+ "复制谷歌插件地址", MessageBoxButton.OK, MessageBoxImage.Information);
+ }
+ catch (Exception ex)
+ {
+ AppLog.Write($"复制谷歌插件地址失败:{ex.Message}");
+ MessageBox.Show(this, $"复制插件路径失败:{ex.Message}\n\n{path}",
+ "复制谷歌插件地址", MessageBoxButton.OK, MessageBoxImage.Warning);
+ }
+ }
+
private void ClearLogs_Click(object sender, RoutedEventArgs e)
{
var answer = MessageBox.Show(this,
diff --git a/desktop/README.md b/desktop/README.md
index b3ce71e..4a80ec6 100644
--- a/desktop/README.md
+++ b/desktop/README.md
@@ -7,9 +7,10 @@ Windows 桌面端,用**前端 `/local` 公共页**和 **Chrome 插件**做对
- 在 `127.0.0.1:17300` 起一个本机 HTTP 服务,浏览器里的页面直接查询本机数据;
- 注册 `yuncang://` 启动协议,网页可以「叫醒」本软件(前提是已安装);
- **托盘图标**:关窗口只是缩到托盘(本机服务不能因关窗断掉),双击托盘恢复窗口,
- 右键菜单有「打开主界面 / 重启软件 / 服务地址(只读)/ 退出」;
-- **主界面不展示服务地址**:端口/地址属于内部实现细节,用户只需知道「能用」;
- 状态点 + 「运行中 · http://localhost:17300」已经够判断死活。
+ 右键菜单有「打开主界面 / 重启软件 / 退出」;
+- **界面不展示服务地址**:登录页和主界面都不显示后端地址 / 本机端口,它们属于内部实现细节;
+ 后端地址由构建注入(`package.config.json` 的 `serverBaseUrl`),需要临时指向别处时用启动参数
+ `--server=http://x.x.x.x:7300`(只对本次运行生效,不写进界面)。
- **防多开**:全局互斥体 + 命名管道 —— 第二个实例不会抢 17300 端口,而是把
`yuncang://open?code=xxx` 转给已运行的实例(在托盘里也会被叫出来并直接查询),然后自己退出。
@@ -19,7 +20,7 @@ desktop/
├── app.manifest # 高 DPI / 兼容性声明
├── Assets/app.ico # 程序/托盘图标(tools/make-icon.ps1 生成)
├── App.xaml / App.xaml.cs # 防多开 + 托盘 + 登录流程 + 本机服务生命周期
-├── LoginWindow.xaml / .xaml.cs # 服务器地址 / 账号 / 密码 / 记住账号 / 自动恢复登录
+├── LoginWindow.xaml / .xaml.cs # 账号 / 密码 / 记住账号 / 自动恢复登录(不展示服务地址)
├── MainWindow.xaml / .xaml.cs # 服务状态、测试查询、菜单、退出登录
└── Services/
├── LocalHttpServer.cs # HttpListener(17300):查询 / 唤起登录 / 下载录像
@@ -40,6 +41,7 @@ desktop/
| 场景 | 行为 |
| --- | --- |
| 首次启动 | 先起本机服务(17300 HTTP + 17301 WS)与托盘,再弹登录页 → 登录成功才出主窗口 |
+| 启动时检查更新 | **不等登录**:进入登录页的同时就开始查 `GET /download/version.json`,有新版本会把更新窗盖在登录页上(否则老版本用户永远卡在登录页收不到更新) |
| 已有令牌 | 登录窗一闪而过:`/api/web/me` 通过就直接进主窗口;失效则清掉令牌留在登录页 |
| 关窗口(X) | 隐藏到托盘,本机服务继续跑(第一次会冒一个气泡提示) |
| 再次双击 exe / 点网页「启动本机软件」 | 不会开第二个:把 `yuncang://open?code=…` 通过命名管道转给已运行实例 |
@@ -211,13 +213,26 @@ cd desktop\installer
### 脚本做了什么
1. `dotnet publish`(自包含单文件,不依赖 .NET 运行时;版本号一起注入程序集);
- **同时把 `native\HCNetSDK\**`、`native\ffmpeg\**` 作为独立文件输出**(不走单文件自解压);
+ **同时把 `native\HCNetSDK\**`、`native\ffmpeg\**`、`..\extension\**` 作为独立文件输出**(不走单文件自解压);
缺 `publish\native\ffmpeg\ffmpeg.exe` 会直接报错中止;
-2. `wix build` 生成 MSI(`Product.wxs` 用 `` 递归收集,保持目录结构);
+2. `wix build` 生成 MSI(`Product.wxs` 用 ``、``
+ 递归收集,保持目录结构;`extension\test` / `extension\tools` 这类调试文件不打进包);
3. 算 MD5 → 写 `version.json`;
-4. 复制到后端:MSI → `backend/app/public/download/`,`version.json` → `backend/app/public/version/`;
+4. 复制到后端:MSI → `backend/app/public/download/desktop/`,`version.json` → `backend/app/public/version/desktop/`;
5. 本地 `out/` 与后端目录**各只保留最近 5 个**安装包(`keepVersions` 可配)。
+> 安装包与版本信息都归到后端 `desktop` 子目录:下载地址 `<域名>/download/desktop/YuncangTraceSetup-x.y.z.msi`,
+> 版本信息仍是 `<域名>/download/version.json`(老客户端写死了这个地址,不能改)。
+
+### 谷歌浏览器插件随包安装
+
+仓库根目录的 `extension/` 会一起打进 MSI,安装后固定在 **`<安装目录>\extension`**
+(perUser 安装即 `%LOCALAPPDATA%\Programs\YuncangTrace\extension`):
+
+- 菜单「工具 → 复制谷歌插件地址」直接把该目录的 **Windows 路径**(如 `C:\Users\xxx\AppData\Local\Programs\YuncangTrace\extension`)复制到剪贴板;
+- 用户打开 `chrome://extensions` → 打开「开发者模式」→「加载已解压的扩展程序」→ 粘贴路径即可;
+- 卸载时该目录随 MSI 组件一起删除;
+
### 自动更新怎么工作
```
@@ -240,7 +255,7 @@ cd desktop\installer
```json
{
"version": "1.0.1",
- "downloadUrl": "https://正式域名/download/YuncangTraceSetup-1.0.1.msi",
+ "downloadUrl": "https://正式域名/download/desktop/YuncangTraceSetup-1.0.1.msi",
"md5": "7a93b4…",
"size": 56786944,
"publishedAt": "2026-10-17T12:00:58+08:00",
@@ -258,7 +273,7 @@ Egg 的 `static` 在生产默认**强缓存一年**。如果 `version.json` 也
| 层 | 做法 |
| --- | --- |
-| 文件位置 | `version.json` 放在 `app/public/version/`,**不在静态目录里** |
+| 文件位置 | `version.json` 放在 `app/public/version/desktop/`,**不在静态目录里** |
| 后端路由 | `GET /download/version.json` 由 `controller/download.js` 返回,显式 `Cache-Control: no-store`、去掉 `ETag`/`Last-Modified`(连 304 都不走) |
| 前端中间件 | `middleware/frontend.js` 放行 `/download/*`,否则会被 SPA 入口接管 |
| 客户端 | 请求带 `?t=毫秒时间戳` + `Cache-Control: no-cache` |
diff --git a/desktop/Services/AppSettings.cs b/desktop/Services/AppSettings.cs
index b83415b..3709031 100644
--- a/desktop/Services/AppSettings.cs
+++ b/desktop/Services/AppSettings.cs
@@ -123,8 +123,9 @@ public sealed class AppSettings
// 文件里存的是空串 = 用户没改过,用当前构建的默认值;
// 老版本会把默认地址直接落盘,所以「等于任何已知默认值」也当作没改过,跟随当前构建。
+ // 同一个域名只换了协议(http → https 强制跳转后 POST 会被降级成 GET)也按默认值处理。
var stored = Normalize(settings.ServerBaseUrl);
- settings.ServerBaseUrl = IsKnownDefault(stored) ? DefaultServer : stored;
+ settings.ServerBaseUrl = IsKnownDefault(stored) || IsSameHostAsDefault(stored) ? DefaultServer : stored;
return settings;
}
catch (Exception ex)
@@ -206,6 +207,22 @@ public sealed class AppSettings
|| url.Equals(Normalize(BuildInfo.ProdServerPlaceholder), StringComparison.OrdinalIgnoreCase);
}
+ /// 和默认地址是同一台服务器,只是协议不同(例如强制 HTTPS 之前落盘的 http 地址)
+ public static bool IsSameHostAsDefault(string? url)
+ {
+ if (!Uri.TryCreate(Normalize(url), UriKind.Absolute, out var stored)
+ || !Uri.TryCreate(DefaultServer, UriKind.Absolute, out var current))
+ {
+ return false;
+ }
+
+ if (!string.Equals(stored.Host, current.Host, StringComparison.OrdinalIgnoreCase)) return false;
+ if (current.Scheme != Uri.UriSchemeHttps || stored.Scheme != Uri.UriSchemeHttp) return false;
+
+ // 只认「默认端口」的旧地址(http://host 与 https://host),不碰用户自己加的端口
+ return stored.Port == current.Port || (stored.Port == 80 && current.Port == 443);
+ }
+
/// 落盘用的结构(和本类的可读属性一一对应)
private sealed class StoredSettings
{
diff --git a/desktop/YuncangTrace.LocalService.csproj b/desktop/YuncangTrace.LocalService.csproj
index 8517711..6ce2a4d 100644
--- a/desktop/YuncangTrace.LocalService.csproj
+++ b/desktop/YuncangTrace.LocalService.csproj
@@ -96,6 +96,19 @@
PreserveNewest
true
+
+
+
+ extension\%(RecursiveDir)%(Filename)%(Extension)
+ PreserveNewest
+ PreserveNewest
+ true
+
diff --git a/desktop/installer/Product.wxs b/desktop/installer/Product.wxs
index 360ff4b..43cae9f 100644
--- a/desktop/installer/Product.wxs
+++ b/desktop/installer/Product.wxs
@@ -32,6 +32,8 @@
+
+
@@ -45,6 +47,8 @@
+
+
@@ -98,4 +102,14 @@
+
+
+
+
+
+
+
diff --git a/desktop/installer/build.ps1 b/desktop/installer/build.ps1
index 4b6d312..df09169 100644
--- a/desktop/installer/build.ps1
+++ b/desktop/installer/build.ps1
@@ -8,8 +8,9 @@
2. dotnet publish(自包含单文件,不依赖 .NET 运行时);
3. wix build 生成 MSI;
4. 计算 MD5 → 写 version.json(version / downloadUrl / md5 / size / publishedAt / buildId);
- 5. 把 version.json + MSI 复制到后端静态目录(默认 backend/app/public/download/),
- 供软件启动时 GET /download/version.json 检测更新;
+ 5. 把 version.json + MSI 复制到后端目录(MSI → backend/app/public/download/desktop/、
+ version.json → backend/app/public/version/desktop/),供软件启动时
+ GET /download/version.json 检测更新;
6. 本地 out/ 与后端目录各只保留最近 keepVersions(默认 5)个安装包。
.PARAMETER Environment
@@ -53,14 +54,19 @@ $ErrorActionPreference = 'Stop'
# dotnet 可能装在用户目录(免管理员安装):wix 是 dotnet 全局工具(apphost),
# **只认 DOTNET_ROOT / 默认安装路径,不认 PATH** —— 不设置会报「You must install .NET」。
$dotnetRoot = Join-Path $env:LOCALAPPDATA 'Microsoft\dotnet'
-if (Test-Path (Join-Path $dotnetRoot 'dotnet.exe')) {
+$dotnetExe = Join-Path $dotnetRoot 'dotnet.exe'
+if (Test-Path $dotnetExe) {
$env:DOTNET_ROOT = $dotnetRoot
if (($env:Path -split ';') -notcontains $dotnetRoot) {
$env:Path = "$dotnetRoot;$env:Path"
}
Write-Host "DOTNET_ROOT=$dotnetRoot"
}
-if (-not (Get-Command dotnet -ErrorAction SilentlyContinue)) {
+else {
+ # 兜底:用 PATH 里的 dotnet
+ $dotnetExe = 'dotnet'
+}
+if (-not (Get-Command $dotnetExe -ErrorAction SilentlyContinue)) {
throw "找不到 dotnet。请先安装 .NET 8 SDK,或设置 DOTNET_ROOT。"
}
@@ -108,7 +114,7 @@ Write-Host "后端:$ServerBaseUrl"
# ---------------- 3. 发布 ----------------
Push-Location $desktop
try {
- dotnet publish $project -c Release -r win-x64 `
+ & $dotnetExe publish $project -c Release -r win-x64 `
--self-contained true `
-p:PublishSingleFile=true `
-p:IncludeNativeLibrariesForSelfExtract=true `
@@ -156,7 +162,7 @@ finally {
# ---------------- 5. version.json ----------------
$hash = (Get-FileHash -Algorithm MD5 -Path $msi).Hash.ToLowerInvariant()
$size = (Get-Item $msi).Length
-$downloadUrl = "$ServerBaseUrl/download/$msiName"
+$downloadUrl = "$ServerBaseUrl/download/desktop/$msiName"
$now = Get-Date
$versionJson = [ordered]@{
@@ -176,8 +182,8 @@ Write-Utf8NoBom $versionFile $versionJson
Write-Host "MD5:$hash($([math]::Round($size / 1MB, 1)) MB)"
# ---------------- 6. 复制到后端 ----------------
-# MSI → 静态目录(/download/xxx.msi,长缓存)
-# version.json → 非静态目录(/download/version.json 由路由提供,绝不能缓存)
+# MSI → app/public/download/desktop/(/download/desktop/xxx.msi,长缓存)
+# version.json → app/public/version/desktop/(/download/version.json 由路由提供,绝不能缓存)
$skipVersionJson = $false
$downloadDir = $null
$versionDir = $null
@@ -190,13 +196,17 @@ if ($envCfg.copyToServer -ne $false) {
New-Item -ItemType Directory -Force -Path $versionDir | Out-Null
# 后端已经有更新版本:说明这次是在补打旧版本,不能把 version.json 降回去
+ # (旧版本打包脚本把 version.json 放在 app/public/version/ 根目录,这里两个位置都看)
$existingVj = Join-Path $versionDir 'version.json'
- if (Test-Path $existingVj) {
+ $legacyVj = Join-Path (Split-Path -Parent $versionDir) 'version.json'
+ foreach ($candidate in @($existingVj, $legacyVj)) {
+ if (-not (Test-Path $candidate)) { continue }
try {
- $old = (Read-Utf8 $existingVj) | ConvertFrom-Json
+ $old = (Read-Utf8 $candidate) | ConvertFrom-Json
if ($old.version -and ([version]$old.version -gt [version]$Version)) {
$skipVersionJson = $true
Write-Warning "后端 version.json 已是更新版本($($old.version)),本次不覆盖它"
+ break
}
}
catch { /* 旧文件坏了就当没有 */ }
@@ -210,9 +220,11 @@ if ($envCfg.copyToServer -ne $false) {
if (-not $skipVersionJson) {
Write-Utf8NoBom $existingVj $versionJson
(Get-Item $existingVj).LastWriteTime = $now
+ # 旧版本打包时把 version.json 放在 app/public/version/ 根目录,顺手清掉(避免两份不一致)
+ if (Test-Path $legacyVj) { Remove-Item $legacyVj -Force }
}
- # 旧版本打包时把 version.json 放在静态目录里,顺手清掉(避免两份不一致)
+ # 更早的版本把 version.json 放在静态目录里,顺手清掉(避免两份不一致)
$staleVj = Join-Path $downloadDir 'version.json'
if (Test-Path $staleVj) { Remove-Item $staleVj -Force }
diff --git a/desktop/installer/package.config.json b/desktop/installer/package.config.json
index 6c6207e..fe87712 100644
--- a/desktop/installer/package.config.json
+++ b/desktop/installer/package.config.json
@@ -1,21 +1,21 @@
{
- "$comment": "打包配置:build.ps1 -Environment Development|Production 读取对应环境。版本号默认取 csproj 的 ,可用 -Version 覆盖。",
+ "$comment": "打包配置:build.ps1 -Environment Development|Production 读取对应环境。版本号默认取 csproj 的 ,可用 -Version 覆盖。安装包与版本信息统一放进后端的 desktop 子目录:下载地址 /download/desktop/*.msi,版本信息仍由 /download/version.json 提供。",
"keepVersions": 5,
"environments": {
"Development": {
"$comment": "开发环境:后端本机 7300。打包后会把 version.json + MSI 复制到后端,本机即可测自动更新。",
"serverBaseUrl": "http://127.0.0.1:7300",
- "downloadFolder": "../../backend/app/public/download",
- "versionFolder": "../../backend/app/public/version",
+ "downloadFolder": "../../backend/app/public/download/desktop",
+ "versionFolder": "../../backend/app/public/version/desktop",
"copyToServer": true
},
"Production": {
"$comment": "生产环境:把 serverBaseUrl 换成正式域名(协议登录 + 更新下载都走它)。",
- "serverBaseUrl": "https://packs.example.com",
- "downloadFolder": "../../backend/app/public/download",
- "versionFolder": "../../backend/app/public/version",
+ "serverBaseUrl": "https://pack.wms.gztbyc.com",
+ "downloadFolder": "../../backend/app/public/download/desktop",
+ "versionFolder": "../../backend/app/public/version/desktop",
"copyToServer": true
}
}
diff --git a/extension/README.md b/extension/README.md
index 4b20a66..450c863 100644
--- a/extension/README.md
+++ b/extension/README.md
@@ -24,6 +24,18 @@ Chrome / Edge 扩展(**Manifest V3 + 原生 JS,零构建**)。
## 1. 安装
+### 客户机:从桌面端安装包直接加载(推荐)
+
+桌面端 MSI 已经把这个 `extension/` 目录一起装好,路径固定为
+`%LOCALAPPDATA%\Programs\YuncangTrace\extension`:
+
+1. 桌面端软件菜单「**工具 → 复制谷歌插件地址**」(复制的是 Windows 路径,可直接粘进选择框)。
+2. 打开 `chrome://extensions`(Edge 是 `edge://extensions`)→ 右上角打开 **开发者模式**。
+3. 点 **加载已解压的扩展程序**,把刚复制的路径粘进去。
+4. 刷新一下已经打开的 WMS 页面(扩展只对**安装之后**加载的页面生效)。
+
+### 开发:直接加载仓库目录
+
1. 打开 `chrome://extensions`(Edge 是 `edge://extensions`)。
2. 右上角打开 **开发者模式**。
3. 点 **加载已解压的扩展程序**,选择本目录 `extension/`。
diff --git a/frontend/.env.production b/frontend/.env.production
new file mode 100644
index 0000000..c2b6c09
--- /dev/null
+++ b/frontend/.env.production
@@ -0,0 +1,12 @@
+# 生产构建环境变量(npm run build / vite build 自动读取,提交到仓库)
+#
+# 生产由后端同源托管页面与 /api,所以 API_BASE 留空即可。
+VITE_API_BASE=
+
+# 本机桌面端约定:yuncang:// 协议 + HTTP 17300 + WebSocket 17301
+VITE_APP_PROTOCOL=yuncang
+VITE_LOCAL_SERVICE=http://localhost:17300
+VITE_LOCAL_WS=ws://127.0.0.1:17301/
+
+# /download/version.json 取不到时的兜底安装包地址(留空则只依赖 version.json)
+VITE_SOFTWARE_DOWNLOAD_URL=
diff --git a/frontend/src/components/AppLayout.vue b/frontend/src/components/AppLayout.vue
index 426c233..a8e32aa 100644
--- a/frontend/src/components/AppLayout.vue
+++ b/frontend/src/components/AppLayout.vue
@@ -30,7 +30,8 @@ const allMenus = [
{ to: '/records', label: '扫码记录', subject: true },
{ to: '/subjects', label: '主体 / 成员', subject: false },
{ to: '/profile', label: '个人中心', subject: false },
- { to: '/test', label: '测试页', subject: true },
+ // 测试页只在开发构建里出现(生产构建不会产出该页面)
+ ...(import.meta.env.DEV ? [{ to: '/test', label: '测试页', subject: true }] : []),
];
/** 没有主体时只留首页 / 主体 / 个人中心(要求:先建主体才出现业务菜单) */
diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts
index ab5ef9b..c8a53cf 100644
--- a/frontend/src/router/index.ts
+++ b/frontend/src/router/index.ts
@@ -10,7 +10,7 @@ import { ensureSubjects, hasSubject } from '@/composables/useSubject';
const routes: RouteRecordRaw[] = [
{ path: '/login', name: 'login', component: () => import('@/views/LoginView.vue'), meta: { public: true, bare: true } },
{ path: '/forgot', name: 'forgot', component: () => import('@/views/ForgotView.vue'), meta: { public: true, bare: true } },
- { path: '/reset', name: 'reset', component: () => import('@/views/ResetView.vue'), meta: { public: true, bare: true } },
+ { path: '/reset', name: 'reset', component: () => import('@/views/ResetView.vue'), meta: { public: true, bare: true, alwaysShow: true } },
// 手机扫码后打开:确认登录(公开)
{ path: '/wechat', name: 'wechat-confirm', component: () => import('@/views/WechatConfirmView.vue'), meta: { public: true, bare: true } },
// 本机软件(打印服务)公共页:**不需要登录**,Chrome 插件打开 `/local?code=<运单号>`
@@ -34,7 +34,10 @@ const routes: RouteRecordRaw[] = [
{ path: '/workstations', name: 'workstations', component: () => import('@/views/WorkstationsView.vue') },
{ path: '/records', name: 'records', component: () => import('@/views/RecordsView.vue') },
{ path: '/profile', name: 'profile', component: () => import('@/views/ProfileView.vue'), meta: { allowNoSubject: true } },
- { path: '/test', name: 'test', component: () => import('@/views/TestView.vue') },
+ // 测试页只在开发构建里存在:生产包不包含该路由,也不会产出它的 chunk
+ ...(import.meta.env.DEV
+ ? [{ path: '/test', name: 'test', component: () => import('@/views/TestView.vue') } as RouteRecordRaw]
+ : []),
{ path: '/:pathMatch(.*)*', redirect: '/' },
];
@@ -45,9 +48,11 @@ export const router = createRouter({
});
router.beforeEach(async (to) => {
+ const isPublic = Boolean(to.meta.public);
// 桌面端「工具 → 打开配置页」:`?token=<用户 JWT>` 直接登录,并把 token 从地址栏去掉
+ // ⚠️ 只对需要登录的页面生效:`/reset?token=…` 里的 token 是重置令牌,不是 SSO JWT
const ssoToken = typeof to.query.token === 'string' ? to.query.token : (typeof to.query.sso === 'string' ? to.query.sso : '');
- if (ssoToken) {
+ if (!isPublic && ssoToken) {
localStorage.setItem('packs_token', ssoToken);
const query = { ...to.query };
delete query.token;
@@ -56,18 +61,20 @@ router.beforeEach(async (to) => {
}
const logged = Boolean(getToken());
- if (!to.meta.public && !logged) {
+ if (!isPublic && !logged) {
return { name: 'login', query: { redirect: to.fullPath } };
}
- // 已登录时这些公开页也照常显示(扫码确认页 / 本机软件页:由插件或手机直接打开,
- // 不该被踢回首页)
- const alwaysShow = to.name === 'wechat-confirm' || to.name === 'local-service';
- if (to.meta.public && logged && !alwaysShow) {
+ // 已登录时这些公开页也照常显示(扫码确认页 / 本机软件页 / 重置密码页):
+ // 它们可能由外部链接直接打开,不该被踢回首页
+ const alwaysShow = to.meta.alwaysShow === true
+ || to.name === 'wechat-confirm'
+ || to.name === 'local-service';
+ if (isPublic && logged && !alwaysShow) {
return { name: 'home' };
}
// 业务页都要主体:没拉过列表先拉一次,没有可用主体就去「主体 / 成员」页创建
- if (logged && !to.meta.public) {
+ if (logged && !isPublic) {
try {
await ensureSubjects();
} catch {
diff --git a/frontend/src/views/ForgotView.vue b/frontend/src/views/ForgotView.vue
index ab88dc0..8c53305 100644
--- a/frontend/src/views/ForgotView.vue
+++ b/frontend/src/views/ForgotView.vue
@@ -19,7 +19,8 @@ async function submit() {
{ auth: false },
);
sent.value = data.sent;
- devUrl.value = data.url || '';
+ // 只有本地开发构建才展示回显的重置链接
+ devUrl.value = import.meta.env.DEV && data.devMode ? (data.url || '') : '';
} catch (err) {
error.value = err instanceof ApiError ? err.message : '发送失败,请稍后再试';
} finally {
diff --git a/frontend/src/views/HomeView.vue b/frontend/src/views/HomeView.vue
index b050473..aec9a68 100644
--- a/frontend/src/views/HomeView.vue
+++ b/frontend/src/views/HomeView.vue
@@ -13,6 +13,10 @@ const stats = ref(null);
const error = ref('');
const loading = ref(true);
const noSubject = ref(!hasSubject.value);
+/** 测试页只在开发构建里存在,所以生产环境的提示文案不再提它(编译期就折掉 dev 文案) */
+const emptyHint = import.meta.env.DEV
+ ? '还没有扫码记录。设备扫码登录后,用「测试页」可以模拟上报一条。'
+ : '还没有扫码记录。设备扫码登录后会出现在这里。';
onMounted(async () => {
if (noSubject.value) {
@@ -87,7 +91,7 @@ onMounted(async () => {
- 还没有扫码记录。设备扫码登录后,用「测试页」可以模拟上报一条。
+ {{ emptyHint }}
diff --git a/frontend/src/views/LoginView.vue b/frontend/src/views/LoginView.vue
index c1316eb..4eccbaa 100644
--- a/frontend/src/views/LoginView.vue
+++ b/frontend/src/views/LoginView.vue
@@ -83,7 +83,9 @@ async function sendCode() {
{ auth: false },
);
codeSent.value = true;
- ok.value = data.devMode && data.code ? `验证码已生成(开发模式):${data.code}` : '验证码已发送到邮箱,10 分钟内有效';
+ // 只有本地开发构建才展示回显验证码;生产构建始终按“已发送到邮箱”提示
+ const showDevCode = import.meta.env.DEV && data.devMode && Boolean(data.code);
+ ok.value = showDevCode ? `验证码已生成(开发模式):${data.code}` : '验证码已发送到邮箱,10 分钟内有效';
} catch (err) {
error.value = err instanceof ApiError ? err.message : '验证码发送失败';
} finally {
diff --git a/frontend/src/views/ResetView.vue b/frontend/src/views/ResetView.vue
index c576888..d763f8f 100644
--- a/frontend/src/views/ResetView.vue
+++ b/frontend/src/views/ResetView.vue
@@ -3,6 +3,7 @@
import { computed, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { api, ApiError } from '@/api/client';
+import { clearToken } from '@/composables/useAuth';
const route = useRoute();
const router = useRouter();
@@ -23,6 +24,8 @@ async function submit() {
busy.value = true;
try {
await api.post('/api/web/auth/reset', { token: token.value, password: password.value }, { auth: false });
+ // 密码已改:清掉当前浏览器里的旧登录态,避免跳登录页时又被守卫送回首页
+ clearToken();
done.value = true;
setTimeout(() => router.replace({ name: 'login', query: { ok: '密码已重置,请用新密码登录' } }), 1200);
} catch (err) {
diff --git a/frontend/src/views/WorkstationsView.vue b/frontend/src/views/WorkstationsView.vue
index b63b778..06986d4 100644
--- a/frontend/src/views/WorkstationsView.vue
+++ b/frontend/src/views/WorkstationsView.vue
@@ -41,6 +41,10 @@ const typeFilter = ref('');
const loading = ref(false);
const error = ref('');
const okMsg = ref('');
+/** 测试页只在开发构建里存在,所以生产环境的提示文案不再提它(编译期就折掉 dev 文案) */
+const scanEmptyHint = import.meta.env.DEV
+ ? '还没有中控上报的通道(可先在「测试页」模拟上报)。'
+ : '还没有中控上报的通道。设备接入并上报后,通道会出现在这里。';
// ---------------- 新增 / 编辑 ----------------
const formOpen = ref(false);
@@ -554,7 +558,7 @@ onMounted(() => load(1));
已被「{{ item.boundWorkstation?.name || item.boundWorkstation?.code }}」绑定
- 还没有中控上报的通道(可先在「测试页」模拟上报)。
+ {{ scanEmptyHint }}
没有可添加的扫码通道(已全部绑定)。