fix(V0.2): OTA 发布说明改为 commit message, sha 单独展示; 版本附构建时间
Docker Build and Push / build-image (push) Successful in 1m2s

- CI: notes 取 git log -1 的 commit message (标题+正文, 截断 400 字),
  commit sha 经 --commit 写入 manifest (不再把裸 sha 塞进发布说明)
- build-ota: 新增 --commit 参数; latest.json 增加 commit 字段
- 服务端 /ota/check 与 /manifest-web 透传 commit 与 sequence
- 我的页: 当前版本/新版本后附 seq 时间戳 (MM-dd HH:mm),
  发布说明下方新增「提交」行显示短 sha
This commit is contained in:
jif2.zhang
2026-10-25 11:56:04 +08:00
parent 74e1e7dd13
commit e3ac00a641
5 changed files with 781 additions and 757 deletions
+5 -2
View File
@@ -85,13 +85,16 @@ jobs:
- name: Build & sign OTA package - name: Build & sign OTA package
# 每次主分支提交生成 OTA 升级包, sequence 默认时间戳 (单调递增) # 每次主分支提交生成 OTA 升级包, sequence 默认时间戳 (单调递增)
# 发布说明 = 触发构建的 commit message (标题+正文, 截断 400 字),
# commit sha 通过 --commit 单独写入 manifest, 前端分行展示
# 产物 ota-package/ (tar.gz + latest.json + .minisig) 进入 docker build context, 由 Dockerfile COPY 进镜像 # 产物 ota-package/ (tar.gz + latest.json + .minisig) 进入 docker build context, 由 Dockerfile COPY 进镜像
env: env:
MINISIGN_PRIVATE_KEY: ${{ secrets.MINISIGN_PRIVATE_KEY }} MINISIGN_PRIVATE_KEY: ${{ secrets.MINISIGN_PRIVATE_KEY }}
OTA_NOTES: ${{ github.sha }}
run: | run: |
set -euo pipefail set -euo pipefail
node scripts/build-ota.mjs --out ota-package --notes ${OTA_NOTES} --min-binary ${OTA_MIN_BINARY} MSG="$(git log -1 --pretty=format:%B | sed -e '/^[[:space:]]*$/d' | head -c 400)"
echo "notes: ${MSG}"
node scripts/build-ota.mjs --out ota-package --notes "${MSG}" --commit "${GITHUB_SHA}" --min-binary ${OTA_MIN_BINARY}
echo "===== latest.json =====" echo "===== latest.json ====="
cat ota-package/latest.json cat ota-package/latest.json
echo "===== bundle sha256 =====" echo "===== bundle sha256 ====="
+150 -147
View File
@@ -1,147 +1,150 @@
#!/usr/bin/env node #!/usr/bin/env node
// OTA 升级包生成脚本 (兼容 tauri-plugin-hotswap) // OTA 升级包生成脚本 (兼容 tauri-plugin-hotswap)
// 用法: // 用法:
// node scripts/build-ota.mjs [--out <dir>] [--sequence <n>] [--min-binary <x>] [--notes <s>] [--no-sign] [--key <path>] // node scripts/build-ota.mjs [--out <dir>] [--sequence <n>] [--min-binary <x>] [--notes <s>] [--no-sign] [--key <path>]
// 流程: // 流程:
// 1) 校验 dist/ 已构建 // 1) 校验 dist/ 已构建
// 2) 生成 bundle.tar.gz (dist/ 内容) // 2) 生成 bundle.tar.gz (dist/ 内容)
// 3) minisign 签名 (除非 --no-sign; 私钥优先读 MINISIGN_PRIVATE_KEY 环境变量) // 3) minisign 签名 (除非 --no-sign; 私钥优先读 MINISIGN_PRIVATE_KEY 环境变量)
// 4) 写 latest.json (manifest, 含 sequence/version/signature/bundle_size/notes/...) // 4) 写 latest.json (manifest, 含 sequence/version/signature/bundle_size/notes/...)
// 5) 全部产物输出到 out 目录 (默认 ota-package/) // 5) 全部产物输出到 out 目录 (默认 ota-package/)
// //
// minisign 安装: 见 readme "OTA 升级" 章节 // minisign 安装: 见 readme "OTA 升级" 章节
import fs from 'node:fs' import fs from 'node:fs'
import path from 'node:path' import path from 'node:path'
import crypto from 'node:crypto' import crypto from 'node:crypto'
import { fileURLToPath } from 'node:url' import { fileURLToPath } from 'node:url'
import { spawnSync } from 'node:child_process' import { spawnSync } from 'node:child_process'
const __filename = fileURLToPath(import.meta.url) const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename) const __dirname = path.dirname(__filename)
const ROOT = path.resolve(__dirname, '..') const ROOT = path.resolve(__dirname, '..')
const args = process.argv.slice(2) const args = process.argv.slice(2)
function getArg(name, def) { function getArg(name, def) {
const i = args.indexOf(name) const i = args.indexOf(name)
return i >= 0 && args[i + 1] ? args[i + 1] : def return i >= 0 && args[i + 1] ? args[i + 1] : def
} }
const OUT_DIR = path.resolve(getArg('--out', 'ota-package')) const OUT_DIR = path.resolve(getArg('--out', 'ota-package'))
const SEQUENCE = Number(getArg('--sequence', String(Date.now()))) // 默认用时间戳做单调计数 const SEQUENCE = Number(getArg('--sequence', String(Date.now()))) // 默认用时间戳做单调计数
const MIN_BINARY = getArg('--min-binary', '') const MIN_BINARY = getArg('--min-binary', '')
const NOTES = getArg('--notes', '') const NOTES = getArg('--notes', '')
const NO_SIGN = args.includes('--no-sign') // 构建对应的 git commit sha (发布说明=commit message, sha 单独一行展示)
// 私钥优先来源: MINISIGN_PRIVATE_KEY 环境变量 (CI 注入) → 文件 (--key 路径) const COMMIT = getArg('--commit', '')
const KEY_PATH = path.resolve(getArg('--key', path.join(OUT_DIR, 'hotswap.key'))) const NO_SIGN = args.includes('--no-sign')
const KEY_FROM_ENV = !!process.env.MINISIGN_PRIVATE_KEY // 私钥优先来源: MINISIGN_PRIVATE_KEY 环境变量 (CI 注入) → 文件 (--key 路径)
// 旧版 tauri.conf.json 里的 pubkey (自动同步过去, 方便用户复制) const KEY_PATH = path.resolve(getArg('--key', path.join(OUT_DIR, 'hotswap.key')))
const TAURI_CONF = path.join(ROOT, 'src-tauri', 'tauri.conf.json') const KEY_FROM_ENV = !!process.env.MINISIGN_PRIVATE_KEY
// 旧版 tauri.conf.json 里的 pubkey (自动同步过去, 方便用户复制)
const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')) const TAURI_CONF = path.join(ROOT, 'src-tauri', 'tauri.conf.json')
const APP_VERSION = pkg.version || '0.0.0'
const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8'))
const DIST = path.join(ROOT, 'dist') const APP_VERSION = pkg.version || '0.0.0'
if (!fs.existsSync(path.join(DIST, 'index.html'))) {
console.error('[build-ota] 错误: dist/index.html 不存在, 请先执行 npm run build') const DIST = path.join(ROOT, 'dist')
process.exit(1) if (!fs.existsSync(path.join(DIST, 'index.html'))) {
} console.error('[build-ota] 错误: dist/index.html 不存在, 请先执行 npm run build')
process.exit(1)
// 准备输出目录 }
fs.mkdirSync(OUT_DIR, { recursive: true })
// 准备输出目录
// 1) 生成 bundle.tar.gz fs.mkdirSync(OUT_DIR, { recursive: true })
const BUNDLE_NAME = 'iboard-ota.tar.gz'
const BUNDLE_PATH = path.join(OUT_DIR, BUNDLE_NAME) // 1) 生成 bundle.tar.gz
const r = spawnSync('tar', ['-czf', BUNDLE_PATH, '-C', DIST, '.'], { stdio: 'inherit' }) const BUNDLE_NAME = 'iboard-ota.tar.gz'
if (r.status !== 0) { const BUNDLE_PATH = path.join(OUT_DIR, BUNDLE_NAME)
console.error('[build-ota] tar 打包失败') const r = spawnSync('tar', ['-czf', BUNDLE_PATH, '-C', DIST, '.'], { stdio: 'inherit' })
process.exit(1) if (r.status !== 0) {
} console.error('[build-ota] tar 打包失败')
const bundleStat = fs.statSync(BUNDLE_PATH) process.exit(1)
const bundleSha256 = crypto.createHash('sha256').update(fs.readFileSync(BUNDLE_PATH)).digest('hex') }
const bundleStat = fs.statSync(BUNDLE_PATH)
// 2) 签名 (minisign) const bundleSha256 = crypto.createHash('sha256').update(fs.readFileSync(BUNDLE_PATH)).digest('hex')
let signature = ''
let pubkey = '' // 2) 签名 (minisign)
if (!NO_SIGN) { let signature = ''
// CI 注入: 私钥走环境变量, 写到临时文件, 签名后立即删除 (避免落盘) let pubkey = ''
let KEY_PATH_TMP = null if (!NO_SIGN) {
let KEY_PATH_USE = KEY_PATH // CI 注入: 私钥走环境变量, 写到临时文件, 签名后立即删除 (避免落盘)
if (KEY_FROM_ENV) { let KEY_PATH_TMP = null
KEY_PATH_TMP = path.join(OUT_DIR, `.hotswap.key.${process.pid}`) let KEY_PATH_USE = KEY_PATH
fs.writeFileSync(KEY_PATH_TMP, process.env.MINISIGN_PRIVATE_KEY, { mode: 0o600 }) if (KEY_FROM_ENV) {
KEY_PATH_USE = KEY_PATH_TMP KEY_PATH_TMP = path.join(OUT_DIR, `.hotswap.key.${process.pid}`)
} fs.writeFileSync(KEY_PATH_TMP, process.env.MINISIGN_PRIVATE_KEY, { mode: 0o600 })
if (!fs.existsSync(KEY_PATH_USE)) { KEY_PATH_USE = KEY_PATH_TMP
console.error('[build-ota] 私钥不存在:', KEY_PATH_USE) }
console.error(' 注入方式二选一:') if (!fs.existsSync(KEY_PATH_USE)) {
console.error(' 1) CI: 设环境变量 MINISIGN_PRIVATE_KEY (整段 .key 文件内容, 含首行 untrusted comment)') console.error('[build-ota] 私钥不存在:', KEY_PATH_USE)
console.error(' 2) 本机: 放 ' + KEY_PATH + ', 或用 --key <path>') console.error(' 注入方式二选一:')
console.error(' 生成方法: minisign -G -W -p ota-package/hotswap.pub -s ota-package/hotswap.key') console.error(' 1) CI: 设环境变量 MINISIGN_PRIVATE_KEY (整段 .key 文件内容, 含首行 untrusted comment)')
process.exit(1) console.error(' 2) 本机: 放 ' + KEY_PATH + ', 或用 --key <path>')
} console.error(' 生成方法: minisign -G -W -p ota-package/hotswap.pub -s ota-package/hotswap.key')
// minisign -Sm <file> -s <key> 生成 detached signature process.exit(1)
const sigArgs = ['-Sm', BUNDLE_PATH, '-s', KEY_PATH_USE] }
const sigR = spawnSync('minisign', sigArgs, { stdio: 'inherit' }) // minisign -Sm <file> -s <key> 生成 detached signature
// 清理 CI 临时私钥 (无论成功失败都删) const sigArgs = ['-Sm', BUNDLE_PATH, '-s', KEY_PATH_USE]
if (KEY_PATH_TMP) { const sigR = spawnSync('minisign', sigArgs, { stdio: 'inherit' })
try { fs.unlinkSync(KEY_PATH_TMP) } catch { /* ignore */ } // 清理 CI 临时私钥 (无论成功失败都删)
KEY_PATH_TMP = null if (KEY_PATH_TMP) {
} try { fs.unlinkSync(KEY_PATH_TMP) } catch { /* ignore */ }
if (sigR.status !== 0) { KEY_PATH_TMP = null
console.error('[build-ota] minisign 签名失败') }
process.exit(1) if (sigR.status !== 0) {
} console.error('[build-ota] minisign 签名失败')
const sigPath = BUNDLE_PATH + '.minisig' process.exit(1)
signature = fs.readFileSync(sigPath, 'utf8').trim() }
const sigPath = BUNDLE_PATH + '.minisig'
// 尝试同步 pubkey 到 tauri.conf.json (如果存在) signature = fs.readFileSync(sigPath, 'utf8').trim()
const PUB_PATH = path.join(path.dirname(KEY_PATH), 'hotswap.pub')
if (fs.existsSync(PUB_PATH)) { // 尝试同步 pubkey 到 tauri.conf.json (如果存在)
pubkey = fs.readFileSync(PUB_PATH, 'utf8').trim() const PUB_PATH = path.join(path.dirname(KEY_PATH), 'hotswap.pub')
const lines = pubkey.split(/\r?\n/) if (fs.existsSync(PUB_PATH)) {
pubkey = (lines.find((l) => l.startsWith('RWR') || l.startsWith('RWT') || l.startsWith('RWQ')) || '').trim() pubkey = fs.readFileSync(PUB_PATH, 'utf8').trim()
} const lines = pubkey.split(/\r?\n/)
} pubkey = (lines.find((l) => l.startsWith('RWR') || l.startsWith('RWT') || l.startsWith('RWQ')) || '').trim()
}
// 3) 写 latest.json }
const minBinary = MIN_BINARY || (() => {
// 默认从 src-tauri/tauri.conf.json 读 version // 3) 写 latest.json
try { return JSON.parse(fs.readFileSync(TAURI_CONF, 'utf8')).version || APP_VERSION } const minBinary = MIN_BINARY || (() => {
catch { return APP_VERSION } // 默认从 src-tauri/tauri.conf.json 读 version
})() try { return JSON.parse(fs.readFileSync(TAURI_CONF, 'utf8')).version || APP_VERSION }
const manifest = { catch { return APP_VERSION }
version: APP_VERSION + '-ota', })()
sequence: SEQUENCE, const manifest = {
min_binary_version: minBinary, version: APP_VERSION + '-ota',
bundle: BUNDLE_NAME, sequence: SEQUENCE,
bundle_size: bundleStat.size, min_binary_version: minBinary,
bundle_sha256: bundleSha256, bundle: BUNDLE_NAME,
signature, bundle_size: bundleStat.size,
notes: NOTES, bundle_sha256: bundleSha256,
pub_date: new Date().toISOString(), signature,
mandatory: false, notes: String(NOTES).slice(0, 400),
// 内部用: 前端 web 模式比对 build_id commit: COMMIT || undefined,
build_id: 'seq-' + SEQUENCE, pub_date: new Date().toISOString(),
} mandatory: false,
fs.writeFileSync(path.join(OUT_DIR, 'latest.json'), JSON.stringify(manifest, null, 2)) // 内部用: 前端 web 模式比对 build_id
build_id: 'seq-' + SEQUENCE,
// 4) 提示 }
console.log('') fs.writeFileSync(path.join(OUT_DIR, 'latest.json'), JSON.stringify(manifest, null, 2))
console.log('=== OTA 包生成完成 ===')
console.log('输出目录: ', OUT_DIR) // 4) 提示
console.log('版本: ', manifest.version) console.log('')
console.log('sequence: ', manifest.sequence) console.log('=== OTA 包生成完成 ===')
console.log('bundle 大小: ', (bundleStat.size / 1024).toFixed(1) + ' KB') console.log('输出目录: ', OUT_DIR)
console.log('bundle sha256:', bundleSha256) console.log('版本: ', manifest.version)
console.log('签名: ', signature ? '(已生成, 写入 latest.json)' : '(未签名, --no-sign)') console.log('sequence: ', manifest.sequence)
if (pubkey) { console.log('bundle 大小: ', (bundleStat.size / 1024).toFixed(1) + ' KB')
console.log('') console.log('bundle sha256:', bundleSha256)
console.log('请将下面这一行 pubkey 写到 src-tauri/tauri.conf.json -> plugins.hotswap.pubkey:') console.log('签名: ', signature ? '(已生成, 写入 latest.json)' : '(未签名, --no-sign)')
console.log(' ' + pubkey) if (pubkey) {
} console.log('')
console.log('请将下面这一行 pubkey 写到 src-tauri/tauri.conf.json -> plugins.hotswap.pubkey:')
console.log('') console.log(' ' + pubkey)
console.log('下一步: 把这两个文件发布到 OTA 存储:') }
console.log(' ' + BUNDLE_NAME)
console.log(' latest.json') console.log('')
console.log('并确保 server 进程环境变量 OTA_PACKAGE_DIR 指向该目录。') console.log('下一步: 把这两个文件发布到 OTA 存储:')
console.log(' ' + BUNDLE_NAME)
console.log(' latest.json')
console.log('并确保 server 进程环境变量 OTA_PACKAGE_DIR 指向该目录。')
+105 -102
View File
@@ -1,102 +1,105 @@
// OTA 升级接口 (兼容 tauri-plugin-hotswap 服务端约定) // OTA 升级接口 (兼容 tauri-plugin-hotswap 服务端约定)
// GET /api/ota/check/:current_sequence // GET /api/ota/check/:current_sequence
// - 客户端传当前 sequence, 服务端判断是否有更新 // - 客户端传当前 sequence, 服务端判断是否有更新
// - 有: 200 + manifest JSON // - 有: 200 + manifest JSON
// - 无: 204 No Content // - 无: 204 No Content
// GET /api/ota/bundle/:filename // GET /api/ota/bundle/:filename
// - 下载前端 bundle (tar.gz), 供 manifest.url 引用 // - 下载前端 bundle (tar.gz), 供 manifest.url 引用
// GET /api/ota/manifest-web // GET /api/ota/manifest-web
// - 给 Web 浏览器用的简化版 manifest (无签名, 仅展示用) // - 给 Web 浏览器用的简化版 manifest (无签名, 仅展示用)
// //
// 数据源: 环境变量 OTA_PACKAGE_DIR 指向的目录, 里面要放: // 数据源: 环境变量 OTA_PACKAGE_DIR 指向的目录, 里面要放:
// - latest.json (由 scripts/build-ota.mjs 生成) // - latest.json (由 scripts/build-ota.mjs 生成)
// { sequence, version, min_binary_version, signature, notes, bundle, mandatory, pub_date, bundle_size } // { sequence, version, min_binary_version, signature, notes, bundle, mandatory, pub_date, bundle_size }
// - <filename> (tar.gz 升级包) // - <filename> (tar.gz 升级包)
import { Router } from 'express' import { Router } from 'express'
import fs from 'node:fs' import fs from 'node:fs'
import path from 'node:path' import path from 'node:path'
const router = Router() const router = Router()
function resolveOtaDir() { function resolveOtaDir() {
const dir = process.env.OTA_PACKAGE_DIR const dir = process.env.OTA_PACKAGE_DIR
? path.resolve(process.env.OTA_PACKAGE_DIR) ? path.resolve(process.env.OTA_PACKAGE_DIR)
: path.resolve(process.cwd(), 'ota-package') : path.resolve(process.cwd(), 'ota-package')
return dir return dir
} }
function readLatest() { function readLatest() {
const p = path.join(resolveOtaDir(), 'latest.json') const p = path.join(resolveOtaDir(), 'latest.json')
if (!fs.existsSync(p)) return null if (!fs.existsSync(p)) return null
try { try {
return JSON.parse(fs.readFileSync(p, 'utf8')) return JSON.parse(fs.readFileSync(p, 'utf8'))
} catch (e) { } catch (e) {
console.error('[ota] latest.json 解析失败:', e.message) console.error('[ota] latest.json 解析失败:', e.message)
return null return null
} }
} }
// GET /api/ota/check/:current_sequence // GET /api/ota/check/:current_sequence
// 客户端实际请求 URL 是 endpoint 中 {{current_sequence}} 替换后的形式 // 客户端实际请求 URL 是 endpoint 中 {{current_sequence}} 替换后的形式
router.get('/ota/check/:current_sequence', (req, res) => { router.get('/ota/check/:current_sequence', (req, res) => {
const currentSeq = Number(req.params.current_sequence) const currentSeq = Number(req.params.current_sequence)
if (!Number.isFinite(currentSeq) || currentSeq < 0) { if (!Number.isFinite(currentSeq) || currentSeq < 0) {
return res.status(400).json({ error: '无效的 sequence' }) return res.status(400).json({ error: '无效的 sequence' })
} }
const latest = readLatest() const latest = readLatest()
if (!latest) { if (!latest) {
// 无可用包, 按约定返回 204 // 无可用包, 按约定返回 204
return res.status(204).end() return res.status(204).end()
} }
// 不新于当前则 204 // 不新于当前则 204
if (typeof latest.sequence === 'number' && latest.sequence <= currentSeq) { if (typeof latest.sequence === 'number' && latest.sequence <= currentSeq) {
return res.status(204).end() return res.status(204).end()
} }
// 检查 binary_version 兼容性 (客户端会再校验一次, 这里只做参考过滤) // 检查 binary_version 兼容性 (客户端会再校验一次, 这里只做参考过滤)
// 客户端传 binary_version query: 暂不强制, 让客户端兜底 // 客户端传 binary_version query: 暂不强制, 让客户端兜底
const dir = resolveOtaDir() const dir = resolveOtaDir()
const base = process.env.OTA_PUBLIC_BASE || '' const base = process.env.OTA_PUBLIC_BASE || ''
res.json({ res.json({
version: latest.version, version: latest.version,
sequence: latest.sequence, sequence: latest.sequence,
min_binary_version: latest.min_binary_version || '0.0.0', min_binary_version: latest.min_binary_version || '0.0.0',
url: (base ? base : '') + '/api/ota/bundle/' + encodeURIComponent(latest.bundle), url: (base ? base : '') + '/api/ota/bundle/' + encodeURIComponent(latest.bundle),
signature: latest.signature, signature: latest.signature,
notes: latest.notes || '', notes: latest.notes || '',
pub_date: latest.pub_date || new Date().toISOString(), commit: latest.commit || '',
mandatory: !!latest.mandatory, pub_date: latest.pub_date || new Date().toISOString(),
bundle_size: latest.bundle_size || 0, mandatory: !!latest.mandatory,
}) bundle_size: latest.bundle_size || 0,
}) })
})
// GET /api/ota/bundle/:filename - 流式下载 bundle
router.get('/ota/bundle/:filename', (req, res) => { // GET /api/ota/bundle/:filename - 流式下载 bundle
const dir = resolveOtaDir() router.get('/ota/bundle/:filename', (req, res) => {
// 防越界: 只取 basename const dir = resolveOtaDir()
const name = path.basename(req.params.filename) // 防越界: 只取 basename
const p = path.join(dir, name) const name = path.basename(req.params.filename)
if (!fs.existsSync(p)) return res.status(404).json({ error: 'bundle 不存在' }) const p = path.join(dir, name)
const stat = fs.statSync(p) if (!fs.existsSync(p)) return res.status(404).json({ error: 'bundle 不存在' })
res.setHeader('Content-Type', 'application/gzip') const stat = fs.statSync(p)
res.setHeader('Content-Length', stat.size) res.setHeader('Content-Type', 'application/gzip')
res.setHeader('Content-Disposition', 'attachment; filename="' + name + '"') res.setHeader('Content-Length', stat.size)
fs.createReadStream(p).pipe(res) res.setHeader('Content-Disposition', 'attachment; filename="' + name + '"')
}) fs.createReadStream(p).pipe(res)
})
// GET /api/ota/manifest-web - Web 浏览器用的简化版
// 客户端会拿这个跟当前 build_id 比较, 有新版本就提示用户刷新 // GET /api/ota/manifest-web - Web 浏览器用的简化版
router.get('/ota/manifest-web', (_req, res) => { // 客户端会拿这个跟当前 build_id 比较, 有新版本就提示用户刷新
const latest = readLatest() router.get('/ota/manifest-web', (_req, res) => {
if (!latest) return res.json({ available: false }) const latest = readLatest()
res.json({ if (!latest) return res.json({ available: false })
available: true, res.json({
version: latest.version, available: true,
build_id: latest.build_id || latest.version, version: latest.version,
note: latest.notes || '', sequence: latest.sequence,
size: latest.bundle_size || 0, commit: latest.commit || '',
}) build_id: latest.build_id || latest.version,
}) note: latest.notes || '',
size: latest.bundle_size || 0,
// GET /api/ota/info 已删除: 诊断接口会暴露服务器路径与签名, 且无调用方 })
})
export default router
// GET /api/ota/info 已删除: 诊断接口会暴露服务器路径与签名, 且无调用方
export default router
+262 -259
View File
@@ -1,259 +1,262 @@
// 前端 OTA 封装 // 前端 OTA 封装
// - Tauri 客户端: 直接用 tauri-plugin-hotswap-api (checkUpdate / applyUpdate / ...) // - Tauri 客户端: 直接用 tauri-plugin-hotswap-api (checkUpdate / applyUpdate / ...)
// - Web 浏览器: 只走我们自己的 /api/ota/manifest, 提示用户手动刷新 (Vite 资源指纹会失效) // - Web 浏览器: 只走我们自己的 /api/ota/manifest, 提示用户手动刷新 (Vite 资源指纹会失效)
// //
// 设计原则: // 设计原则:
// - Web 端只能"查 + 提示", 不能真下载应用, 避免误导 // - Web 端只能"查 + 提示", 不能真下载应用, 避免误导
// - Tauri 端走 hotswap 插件的官方 API, 签名校验/回滚/资源替换全交给插件 // - Tauri 端走 hotswap 插件的官方 API, 签名校验/回滚/资源替换全交给插件
import { getApiBase } from './client.js' import { getApiBase } from './client.js'
import { APP_VERSION, BUILD_ID } from '../version.js' import { APP_VERSION, BUILD_ID } from '../version.js'
// 判断是否在 Tauri WebView 内 (有 __TAURI_INTERNALS__ 即 Tauri 环境) // 判断是否在 Tauri WebView 内 (有 __TAURI_INTERNALS__ 即 Tauri 环境)
const inTauri = typeof window !== 'undefined' && '__TAURI_INTERNALS__' in window const inTauri = typeof window !== 'undefined' && '__TAURI_INTERNALS__' in window
// 拼接绝对 URL: 在 Tauri (VITE_API_BASE 有值) 时直连, 否则同源 // 拼接绝对 URL: 在 Tauri (VITE_API_BASE 有值) 时直连, 否则同源
function resolveUrl(p) { function resolveUrl(p) {
const base = getApiBase() const base = getApiBase()
return base ? base + p : p return base ? base + p : p
} }
// 当前版本信息 (前端展示用) // 当前版本信息 (前端展示用)
export function getCurrentVersionInfo() { export function getCurrentVersionInfo() {
return { version: APP_VERSION, build: BUILD_ID } return { version: APP_VERSION, build: BUILD_ID }
} }
// 启动时: 确认当前资源可用 (Tauri only) // 启动时: 确认当前资源可用 (Tauri only)
// 失败/异常都不抛, 仅 console.warn // 失败/异常都不抛, 仅 console.warn
export function initOta() { export function initOta() {
if (!inTauri) return if (!inTauri) return
// 动态 import: web 模式根本不打这个 chunk // 动态 import: web 模式根本不打这个 chunk
import('tauri-plugin-hotswap-api') import('tauri-plugin-hotswap-api')
.then((mod) => mod.notifyReady()) .then((mod) => mod.notifyReady())
.then(() => console.log('[ota] notifyReady ok')) .then(() => console.log('[ota] notifyReady ok'))
.catch((e) => console.warn('[ota] notifyReady failed:', e)) .catch((e) => console.warn('[ota] notifyReady failed:', e))
} }
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// 判新模式 (V0.2) // 判新模式 (V0.2)
// 「开发版本」开关 (我的页 OTA 组内, 默认关闭), 值持久化在设备端 localStorage: // 「开发版本」开关 (我的页 OTA 组内, 默认关闭), 值持久化在设备端 localStorage:
// 开关 关闭 (默认 / 生产口径): 用**版本号**判新 —— 取服务端 manifest 的 version, // 开关 关闭 (默认 / 生产口径): 用**版本号**判新 —— 取服务端 manifest 的 version,
// 与当前运行版本按数字字段逐段比较大小 (0.2.0 > 0.1.0)。 // 与当前运行版本按数字字段逐段比较大小 (0.2.0 > 0.1.0)。
// 这样即使某个旧版本分支被重新构建 (sequence 变大但版本号更小), 也不会把新设备拉回旧版。 // 这样即使某个旧版本分支被重新构建 (sequence 变大但版本号更小), 也不会把新设备拉回旧版。
// 开关 打开 (开发口径): 用 **build sequence** 判新 —— 直接走插件 checkUpdate(), // 开关 打开 (开发口径): 用 **build sequence** 判新 —— 直接走插件 checkUpdate(),
// 只要服务端 sequence 比本地大就算新, 每次提交都能推到设备上, 便于联调。 // 只要服务端 sequence 比本地大就算新, 每次提交都能推到设备上, 便于联调。
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
const OTA_DEV_MODE_KEY = 'iboard_ota_dev_mode' const OTA_DEV_MODE_KEY = 'iboard_ota_dev_mode'
export function getOtaDevMode() { export function getOtaDevMode() {
try { try {
return localStorage.getItem(OTA_DEV_MODE_KEY) === '1' return localStorage.getItem(OTA_DEV_MODE_KEY) === '1'
} catch { /* ignore */ } } catch { /* ignore */ }
return false return false
} }
export function setOtaDevMode(v) { export function setOtaDevMode(v) {
try { localStorage.setItem(OTA_DEV_MODE_KEY, v ? '1' : '0') } catch { /* ignore */ } try { localStorage.setItem(OTA_DEV_MODE_KEY, v ? '1' : '0') } catch { /* ignore */ }
} }
// 版本号 → 数字字段数组 / 比较函数 (纯函数放在 utils, 便于单测) // 版本号 → 数字字段数组 / 比较函数 (纯函数放在 utils, 便于单测)
import { compareVersion, parseVersionFields } from '../utils/version.js' import { compareVersion, parseVersionFields } from '../utils/version.js'
export { compareVersion, parseVersionFields } export { compareVersion, parseVersionFields }
// 拉服务端最新 manifest (不分平台) // 拉服务端最新 manifest (不分平台)
// /api/ota/check/0: current_sequence 传 0, 只要有 OTA 包就一定返回 200 + manifest // /api/ota/check/0: current_sequence 传 0, 只要有 OTA 包就一定返回 200 + manifest
export async function fetchOtaManifest() { export async function fetchOtaManifest() {
try { try {
const res = await fetch(resolveUrl('/api/ota/check/0'), { method: 'GET' }) const res = await fetch(resolveUrl('/api/ota/check/0'), { method: 'GET' })
if (res.status === 204) return null if (res.status === 204) return null
if (!res.ok) return null if (!res.ok) return null
return await res.json() return await res.json()
} catch (e) { } catch (e) {
console.warn('[ota] manifest 拉取失败:', e) console.warn('[ota] manifest 拉取失败:', e)
return null return null
} }
} }
// 检查更新 // 检查更新
// 返回统一结构, 调用方不关心是 Tauri 还是 web: // 返回统一结构, 调用方不关心是 Tauri 还是 web:
// { // {
// available: boolean, // available: boolean,
// reason: 'no_package' | 'same_version' | 'ota_disabled' | 'unsupported' | 'ok', // reason: 'no_package' | 'same_version' | 'ota_disabled' | 'unsupported' | 'ok',
// info: { version, sequence, notes, mandatory, bundle_size } // info: { version, sequence, notes, mandatory, bundle_size }
// } // }
// opts.devMode: true=按 build sequence 判新, false=按版本号判新 (默认) // opts.devMode: true=按 build sequence 判新, false=按版本号判新 (默认)
export async function checkOtaUpdate(opts) { export async function checkOtaUpdate(opts) {
const devMode = !!(opts && opts.devMode) const devMode = !!(opts && opts.devMode)
if (!inTauri) { if (!inTauri) {
return checkOtaUpdateWeb(devMode) return checkOtaUpdateWeb(devMode)
} }
return checkOtaUpdateTauri(devMode) return checkOtaUpdateTauri(devMode)
} }
// 取"当前运行版本": 已应用 OTA 覆盖包则用覆盖包版本, 否则用内置包版本 // 取"当前运行版本": 已应用 OTA 覆盖包则用覆盖包版本, 否则用内置包版本
async function currentRunningVersion() { async function currentRunningVersion() {
try { try {
const v = await getOtaVersionInfo() const v = await getOtaVersionInfo()
if (v?.active && v.version) return v.version if (v?.active && v.version) return v.version
} catch { /* ignore */ } } catch { /* ignore */ }
return APP_VERSION return APP_VERSION
} }
// 版本号口径判新 (Tauri + Web 共用): 服务端 version 比当前运行版本大才算新 // 版本号口径判新 (Tauri + Web 共用): 服务端 version 比当前运行版本大才算新
async function checkByVersion() { async function checkByVersion() {
const [manifest, current] = await Promise.all([fetchOtaManifest(), currentRunningVersion()]) const [manifest, current] = await Promise.all([fetchOtaManifest(), currentRunningVersion()])
if (!manifest || !manifest.version) { if (!manifest || !manifest.version) {
return { available: false, reason: 'no_package', info: null } return { available: false, reason: 'no_package', info: null }
} }
if (compareVersion(manifest.version, current) <= 0) { if (compareVersion(manifest.version, current) <= 0) {
return { available: false, reason: 'same_version', info: manifest } return { available: false, reason: 'same_version', info: manifest }
} }
return { return {
available: true, available: true,
reason: 'ok', reason: 'ok',
info: { info: {
version: manifest.version, version: manifest.version,
sequence: manifest.sequence, sequence: manifest.sequence,
notes: manifest.notes || '', notes: manifest.notes || '',
mandatory: !!manifest.mandatory, commit: manifest.commit || '',
bundle_size: manifest.bundle_size || 0, mandatory: !!manifest.mandatory,
}, bundle_size: manifest.bundle_size || 0,
} },
} }
}
async function checkOtaUpdateTauri(devMode) {
// 开发口径: sequence 判新, 直接走插件 (插件内部用当前 sequence 请求 /api/ota/check/:seq) async function checkOtaUpdateTauri(devMode) {
if (devMode) { // 开发口径: sequence 判新, 直接走插件 (插件内部用当前 sequence 请求 /api/ota/check/:seq)
const { checkUpdate } = await import('tauri-plugin-hotswap-api') if (devMode) {
const r = await checkUpdate() const { checkUpdate } = await import('tauri-plugin-hotswap-api')
if (!r.available) { const r = await checkUpdate()
return { available: false, reason: 'no_package', info: r } if (!r.available) {
} return { available: false, reason: 'no_package', info: r }
return { }
available: true, return {
reason: 'ok', available: true,
info: { reason: 'ok',
version: r.version, info: {
sequence: r.sequence, version: r.version,
notes: r.notes, sequence: r.sequence,
mandatory: r.mandatory, notes: r.notes,
bundle_size: r.bundle_size, mandatory: r.mandatory,
}, bundle_size: r.bundle_size,
} },
} }
// 生产口径: 版本号判新 }
return checkByVersion() // 生产口径: 版本号判新
} return checkByVersion()
}
async function checkOtaUpdateWeb(devMode) {
// Web 端不能下载, 只能拿到版本号/构建号做比对, 提示用户刷新 async function checkOtaUpdateWeb(devMode) {
try { // Web 端不能下载, 只能拿到版本号/构建号做比对, 提示用户刷新
const res = await fetch(resolveUrl('/api/ota/manifest-web'), { method: 'GET' }) try {
if (!res.ok) { const res = await fetch(resolveUrl('/api/ota/manifest-web'), { method: 'GET' })
return { available: false, reason: 'unsupported', info: null } if (!res.ok) {
} return { available: false, reason: 'unsupported', info: null }
const data = await res.json() }
if (!data.available) return { available: false, reason: 'no_package', info: data } const data = await res.json()
// Web 端拿不到本地 sequence: if (!data.available) return { available: false, reason: 'no_package', info: data }
// 开发口径 (devMode) → 只要服务端版本与本地不同就算新 (近似 sequence 语义, 含回退) // Web 端拿不到本地 sequence:
// 生产口径 → 严格比较版本号大小, 只有更高版本才算新 // 开发口径 (devMode) → 只要服务端版本与本地不同就算新 (近似 sequence 语义, 含回退)
const cmp = compareVersion(data.version, APP_VERSION) // 生产口径 → 严格比较版本号大小, 只有更高版本才算新
if (devMode ? cmp === 0 : cmp <= 0) { const cmp = compareVersion(data.version, APP_VERSION)
return { available: false, reason: 'same_version', info: data } if (devMode ? cmp === 0 : cmp <= 0) {
} return { available: false, reason: 'same_version', info: data }
return { }
available: true, return {
reason: 'ok', available: true,
info: { reason: 'ok',
version: data.version, info: {
notes: data.note || '', version: data.version,
// web 端没有强制/mandatory 等字段, 仅展示 sequence: data.sequence,
mandatory: false, notes: data.note || '',
bundle_size: data.size || 0, commit: data.commit || '',
}, // web 端没有强制/mandatory 等字段, 仅展示
} mandatory: false,
} catch (e) { bundle_size: data.size || 0,
console.warn('[ota] web check failed:', e) },
return { available: false, reason: 'unsupported', info: null } }
} } catch (e) {
} console.warn('[ota] web check failed:', e)
return { available: false, reason: 'unsupported', info: null }
// 下载并应用更新 (Tauri only). 调用方负责 UI 提示和错误处理 }
// onProgress(received, total) 进度回调 }
// 成功后必须 reload, 新资源才会生效
export async function applyOtaUpdate(onProgress) { // 下载并应用更新 (Tauri only). 调用方负责 UI 提示和错误处理
if (!inTauri) { // onProgress(received, total) 进度回调
throw new Error('OTA 升级仅在 Tauri 客户端可用, Web 端请直接刷新页面') // 成功后必须 reload, 新资源才会生效
} export async function applyOtaUpdate(onProgress) {
const mod = await import('tauri-plugin-hotswap-api') if (!inTauri) {
throw new Error('OTA 升级仅在 Tauri 客户端可用, Web 端请直接刷新页面')
// 注册一次性进度监听 (applyUpdate 期间触发) }
let unlisten = null const mod = await import('tauri-plugin-hotswap-api')
let unlistenLifecycle = null
if (onProgress) { // 注册一次性进度监听 (applyUpdate 期间触发)
try { let unlisten = null
unlisten = await mod.onDownloadProgress((p) => onProgress(p.downloaded, p.total)) let unlistenLifecycle = null
} catch (e) { if (onProgress) {
console.warn('[ota] onDownloadProgress 监听失败:', e) try {
} unlisten = await mod.onDownloadProgress((p) => onProgress(p.downloaded, p.total))
} } catch (e) {
console.warn('[ota] onDownloadProgress 监听失败:', e)
// 监听 lifecycle 事件, 捕获失败详情 (download-error / apply 失败时 error 字段带具体原因) }
// applyUpdate() 抛出的错误往往只有泛化信息, 细节藏在 lifecycle 事件里 }
let lifecycleError = ''
try { // 监听 lifecycle 事件, 捕获失败详情 (download-error / apply 失败时 error 字段带具体原因)
unlistenLifecycle = await mod.onLifecycle((ev) => { // applyUpdate() 抛出的错误往往只有泛化信息, 细节藏在 lifecycle 事件里
if (ev.event === 'download-error' || ev.event === 'apply' || ev.event === 'check-error') { let lifecycleError = ''
if (ev.error) { try {
lifecycleError = ev.error unlistenLifecycle = await mod.onLifecycle((ev) => {
console.error('[ota] lifecycle', ev.event, 'error:', ev.error) if (ev.event === 'download-error' || ev.event === 'apply' || ev.event === 'check-error') {
} if (ev.error) {
} lifecycleError = ev.error
}) console.error('[ota] lifecycle', ev.event, 'error:', ev.error)
} catch (e) { }
console.warn('[ota] onLifecycle 监听失败:', e) }
} })
} catch (e) {
try { console.warn('[ota] onLifecycle 监听失败:', e)
const newVersion = await mod.applyUpdate() }
return newVersion
} catch (e) { try {
// 把 lifecycle 里的详细错误拼进抛出的异常, 方便前端展示真实原因 const newVersion = await mod.applyUpdate()
const base = e?.message || '升级失败' return newVersion
const detail = lifecycleError ? ` (${lifecycleError})` : '' } catch (e) {
const err = new Error(base + detail) // 把 lifecycle 里的详细错误拼进抛出的异常, 方便前端展示真实原因
err.cause = e const base = e?.message || '升级失败'
throw err const detail = lifecycleError ? ` (${lifecycleError})` : ''
} finally { const err = new Error(base + detail)
if (unlisten) { err.cause = e
try { unlisten() } catch { /* ignore */ } throw err
} } finally {
if (unlistenLifecycle) { if (unlisten) {
try { unlistenLifecycle() } catch { /* ignore */ } try { unlisten() } catch { /* ignore */ }
} }
} if (unlistenLifecycle) {
} try { unlistenLifecycle() } catch { /* ignore */ }
}
// 回滚到内置 dist (Tauri only, 一般用于 OTA 出错时手动恢复) }
export async function rollbackOta() { }
if (!inTauri) throw new Error('仅 Tauri 客户端可用')
const mod = await import('tauri-plugin-hotswap-api') // 回滚到内置 dist (Tauri only, 一般用于 OTA 出错时手动恢复)
return mod.rollback() export async function rollbackOta() {
} if (!inTauri) throw new Error('仅 Tauri 客户端可用')
const mod = await import('tauri-plugin-hotswap-api')
// 取当前 OTA 状态 (Tauri only) return mod.rollback()
export async function getOtaVersionInfo() { }
if (!inTauri) return null
try { // 取当前 OTA 状态 (Tauri only)
const mod = await import('tauri-plugin-hotswap-api') export async function getOtaVersionInfo() {
return await mod.getVersionInfo() if (!inTauri) return null
} catch (e) { try {
console.warn('[ota] getVersionInfo failed:', e) const mod = await import('tauri-plugin-hotswap-api')
return null return await mod.getVersionInfo()
} } catch (e) {
} console.warn('[ota] getVersionInfo failed:', e)
return null
// reload 当前页 (新资源生效) }
export function reloadApp() { }
window.location.reload()
} // reload 当前页 (新资源生效)
export function reloadApp() {
window.location.reload()
}
+259 -247
View File
@@ -1,247 +1,259 @@
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom' import { useNavigate } from 'react-router-dom'
import { Avatar, Button, List, ProgressBar, Switch, Toast } from 'antd-mobile' import { Avatar, Button, List, ProgressBar, Switch, Toast } from 'antd-mobile'
import { useAuth } from '../auth/AuthContext.jsx' import { useAuth } from '../auth/AuthContext.jsx'
import { APP_VERSION, BUILD_ID } from '../version.js' import { APP_VERSION, BUILD_ID } from '../version.js'
import { import {
applyOtaUpdate, applyOtaUpdate,
checkOtaUpdate, checkOtaUpdate,
getCurrentVersionInfo, getCurrentVersionInfo,
getOtaDevMode, getOtaDevMode,
getOtaVersionInfo, getOtaVersionInfo,
reloadApp, reloadApp,
rollbackOta, rollbackOta,
setOtaDevMode, setOtaDevMode,
} from '../api/ota.js' } from '../api/ota.js'
// "我" 页: 顶部 NavBar + 用户头像卡片 + 信息列表 + OTA 升级区 // seq/build 时间戳 → 'MM-dd HH:mm' (sequence 为毫秒时间戳, build_id 形如 seq-<ms>)
// OTA 区: export function fmtSeqTime(v) {
// - 显示当前 APP_VERSION (前端包, 对应内置 dist) const ms = typeof v === 'string' && v.startsWith('seq-') ? Number(v.slice(4)) : Number(v)
// - 显示当前 hotswap 状态 (是否已应用覆盖包) if (!Number.isFinite(ms) || ms <= 0) return ''
// - [检查更新]: 走 checkOtaUpdate() const p = (n) => String(n).padStart(2, '0')
// - [立即升级]: 走 applyOtaUpdate(), 完成后 reload const d = new Date(ms)
// - [回滚]: 清除覆盖包, 回到内置 dist return `${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`
export default function MePage() { }
const { user, logout } = useAuth()
const navigate = useNavigate() // "我" 页: 顶部 NavBar + 用户头像卡片 + 信息列表 + OTA 升级区
// OTA 区:
// 顶部安全区与「我」页蓝色渐变头部无缝衔接: 给 body 打标记, // - 显示当前 APP_VERSION (前端包, 对应内置 dist)
// 由 CSS 让 .app-safe-top 也使用同一条渐变, 避免出现一条白边/色块把蓝色割断. // - 显示当前 hotswap 状态 (是否已应用覆盖包)
// 离开本页时移除标记, 其他页恢复默认底色. // - [检查更新]: 走 checkOtaUpdate()
useEffect(() => { // - [立即升级]: 走 applyOtaUpdate(), 完成后 reload
document.body.classList.add('me-safe-top') // - [回滚]: 清除覆盖包, 回到内置 dist
return () => { document.body.classList.remove('me-safe-top') } export default function MePage() {
}, []) const { user, logout } = useAuth()
const navigate = useNavigate()
// OTA 状态
const [otaState, setOtaState] = useState('idle') // idle | checking | available | none | downloading | ready | error // 顶部安全区与「我」页蓝色渐变头部无缝衔接: 给 body 打标记,
const [otaInfo, setOtaInfo] = useState(null) // 检查结果中的 info // 由 CSS 让 .app-safe-top 也使用同一条渐变, 避免出现一条白边/色块把蓝色割断.
const [otaVersion, setOtaVersion] = useState(null) // hotswap 当前激活的覆盖包版本 // 离开本页时移除标记, 其他页恢复默认底色.
const [progress, setProgress] = useState({ received: 0, total: 0 }) useEffect(() => {
const [error, setError] = useState('') document.body.classList.add('me-safe-top')
// 判新模式: false(默认)=版本号比较, true=build sequence 比较; 值持久化在设备端 return () => { document.body.classList.remove('me-safe-top') }
const [devMode, setDevMode] = useState(() => getOtaDevMode()) }, [])
// 进入页面时拉一次 hotswap 状态 (Tauri 内才需要, web 下 null 也无所谓) // OTA 状态
useEffect(() => { const [otaState, setOtaState] = useState('idle') // idle | checking | available | none | downloading | ready | error
let cancelled = false const [otaInfo, setOtaInfo] = useState(null) // 检查结果中的 info
getOtaVersionInfo().then((v) => { const [otaVersion, setOtaVersion] = useState(null) // hotswap 当前激活的覆盖包版本
if (!cancelled) setOtaVersion(v) const [progress, setProgress] = useState({ received: 0, total: 0 })
}) const [error, setError] = useState('')
return () => { cancelled = true } // 判新模式: false(默认)=版本号比较, true=build sequence 比较; 值持久化在设备端
}, []) const [devMode, setDevMode] = useState(() => getOtaDevMode())
async function onCheck() { // 进入页面时拉一次 hotswap 状态 (Tauri 内才需要, web 下 null 也无所谓)
setError('') useEffect(() => {
setOtaState('checking') let cancelled = false
try { getOtaVersionInfo().then((v) => {
const r = await checkOtaUpdate({ devMode }) if (!cancelled) setOtaVersion(v)
if (r.available) { })
setOtaInfo(r.info) return () => { cancelled = true }
setOtaState('available') }, [])
Toast.show({ icon: 'success', content: '发现新版本 v' + (r.info?.version || '') })
} else { async function onCheck() {
setOtaInfo(null) setError('')
setOtaState('none') setOtaState('checking')
if (r.reason === 'same_version') { try {
Toast.show({ content: '已是最新版本' }) const r = await checkOtaUpdate({ devMode })
} else if (r.reason === 'no_package') { if (r.available) {
Toast.show({ content: '当前没有可用更新' }) setOtaInfo(r.info)
} else { setOtaState('available')
Toast.show({ content: '当前没有可用更新' }) Toast.show({ icon: 'success', content: '发现新版本 v' + (r.info?.version || '') })
} } else {
} setOtaInfo(null)
} catch (e) { setOtaState('none')
setError(e?.message || '检查失败') if (r.reason === 'same_version') {
setOtaState('error') Toast.show({ content: '已是最新版本' })
Toast.show({ icon: 'fail', content: '检查失败: ' + (e?.message || '') }) } else if (r.reason === 'no_package') {
} Toast.show({ content: '当前没有可用更新' })
} } else {
Toast.show({ content: '当前没有可用更新' })
async function onApply() { }
setError('') }
setOtaState('downloading') } catch (e) {
setProgress({ received: 0, total: 0 }) setError(e?.message || '检查失败')
try { setOtaState('error')
const newVer = await applyOtaUpdate((received, total) => { Toast.show({ icon: 'fail', content: '检查失败: ' + (e?.message || '') })
setProgress({ received, total }) }
}) }
Toast.show({ icon: 'success', content: '已下载 v' + newVer + ', 即将重启' })
setOtaState('ready') async function onApply() {
// 给用户 1s 看提示, 然后 reload setError('')
setTimeout(() => reloadApp(), 1000) setOtaState('downloading')
} catch (e) { setProgress({ received: 0, total: 0 })
setError(e?.message || '升级失败') try {
setOtaState('error') const newVer = await applyOtaUpdate((received, total) => {
Toast.show({ icon: 'fail', content: '升级失败: ' + (e?.message || '') }) setProgress({ received, total })
} })
} Toast.show({ icon: 'success', content: '已下载 v' + newVer + ', 即将重启' })
setOtaState('ready')
async function onRollback() { // 给用户 1s 看提示, 然后 reload
if (!window.confirm('确认回滚到内置版本?')) return setTimeout(() => reloadApp(), 1000)
try { } catch (e) {
await rollbackOta() setError(e?.message || '升级失败')
Toast.show({ icon: 'success', content: '已回滚, 正在重启' }) setOtaState('error')
setTimeout(() => reloadApp(), 800) Toast.show({ icon: 'fail', content: '升级失败: ' + (e?.message || '') })
} catch (e) { }
Toast.show({ icon: 'fail', content: '回滚失败: ' + (e?.message || '') }) }
}
} async function onRollback() {
if (!window.confirm('确认回滚到内置版本?')) return
async function onLogout() { try {
const confirmed = window.confirm('确定退出登录?') await rollbackOta()
if (!confirmed) return Toast.show({ icon: 'success', content: '已回滚, 正在重启' })
await logout() setTimeout(() => reloadApp(), 800)
Toast.show({ icon: 'success', content: '已退出' }) } catch (e) {
navigate('/login', { replace: true }) Toast.show({ icon: 'fail', content: '回滚失败: ' + (e?.message || '') })
} }
}
const cur = getCurrentVersionInfo()
const isTauri = typeof window !== 'undefined' && '__TAURI_INTERNALS__' in window async function onLogout() {
const showProgress = otaState === 'downloading' && progress.total > 0 const confirmed = window.confirm('确定退出登录?')
const progressPct = showProgress ? Math.min(100, Math.round((progress.received / progress.total) * 100)) : 0 if (!confirmed) return
await logout()
return ( Toast.show({ icon: 'success', content: '已退出' })
<div className="me-page"> navigate('/login', { replace: true })
<div className="me-profile"> }
<Avatar
className="me-avatar" const cur = getCurrentVersionInfo()
src={user?.avatar} const isTauri = typeof window !== 'undefined' && '__TAURI_INTERNALS__' in window
style={{ '--size': '64px', '--border-radius': '50%' }} const showProgress = otaState === 'downloading' && progress.total > 0
> const progressPct = showProgress ? Math.min(100, Math.round((progress.received / progress.total) * 100)) : 0
{(user?.name || '?').slice(0, 1).toUpperCase()}
</Avatar> return (
<div className="me-name">{user?.name || '用户'}</div> <div className="me-page">
<div className="me-email">{user?.email}</div> <div className="me-profile">
</div> <Avatar
className="me-avatar"
{/* OTA 升级区 */} src={user?.avatar}
<List className="me-list" mode="card" header="前端升级 (OTA)"> style={{ '--size': '64px', '--border-radius': '50%' }}
<List.Item extra={'v' + cur.version + ' · ' + cur.build}>当前版本</List.Item> >
<List.Item extra={otaVersion?.active ? 'v' + (otaVersion.version || '?') : '内置'}> {(user?.name || '?').slice(0, 1).toUpperCase()}
运行资源 </Avatar>
</List.Item> <div className="me-name">{user?.name || '用户'}</div>
{/* 判新口径开关: 默认关(版本号比较), 打开后按 build sequence 比较 */} <div className="me-email">{user?.email}</div>
<List.Item </div>
extra={
<Switch {/* OTA 升级区 */}
checked={devMode} <List className="me-list" mode="card" header="前端升级 (OTA)">
onChange={(v) => { <List.Item extra={'v' + cur.version + (fmtSeqTime(cur.build) ? ' · ' + fmtSeqTime(cur.build) : '')}>当前版本</List.Item>
setDevMode(v) <List.Item extra={otaVersion?.active ? 'v' + (otaVersion.version || '?') : '内置'}>
setOtaDevMode(v) 运行资源
// 切换口径后旧检查结果失效, 重置避免误导 </List.Item>
setOtaState('idle') {/* 判新口径开关: 默认关(版本号比较), 打开后按 build sequence 比较 */}
setOtaInfo(null) <List.Item
setError('') extra={
Toast.show({ content: v ? '开发版本: 按构建号判新' : '正式口径: 按版本号判新' }) <Switch
}} checked={devMode}
/> onChange={(v) => {
} setDevMode(v)
description={ setOtaDevMode(v)
devMode // 切换口径后旧检查结果失效, 重置避免误导
? '按 build sequence 判新:每次构建都算新版本,便于开发联调' setOtaState('idle')
: '按版本号判新:仅当服务端版本号更高时才提示更新' setOtaInfo(null)
} setError('')
> Toast.show({ content: v ? '开发版本: 按构建号判新' : '正式口径: 按版本号判新' })
开发版本 }}
</List.Item> />
<List.Item> }
<div className="me-ota-actions"> description={
<Button devMode
size="small" ? '按 build sequence 判新:每次构建都算新版本,便于开发联调'
color="primary" : '按版本号判新:仅当服务端版本号更高时才提示更新'
loading={otaState === 'checking'} }
disabled={otaState === 'downloading'} >
onClick={onCheck} 开发版本
> </List.Item>
检查更新 <List.Item>
</Button> <div className="me-ota-actions">
<Button <Button
size="small" size="small"
color="danger" color="primary"
disabled={otaState !== 'available' || otaState === 'downloading'} loading={otaState === 'checking'}
onClick={onApply} disabled={otaState === 'downloading'}
> onClick={onCheck}
立即升级 >
</Button> 检查更新
{isTauri && otaVersion?.active && ( </Button>
<Button <Button
size="small" size="small"
fill="outline" color="danger"
onClick={onRollback} disabled={otaState !== 'available' || otaState === 'downloading'}
disabled={otaState === 'downloading'} onClick={onApply}
> >
回滚 立即升级
</Button> </Button>
)} {isTauri && otaVersion?.active && (
</div> <Button
</List.Item> size="small"
{otaState === 'available' && otaInfo && ( fill="outline"
<List.Item extra={'v' + otaInfo.version}> onClick={onRollback}
新版本 disabled={otaState === 'downloading'}
{otaInfo.bundle_size ? ` (${(otaInfo.bundle_size / 1024).toFixed(0)} KB)` : ''} >
</List.Item> 回滚
)} </Button>
{otaState === 'downloading' && ( )}
<List.Item> </div>
<div className="me-ota-progress"> </List.Item>
<div className="me-ota-progress-text"> {otaState === 'available' && otaInfo && (
正在下载 {showProgress ? progressPct + '%' : ''} <List.Item extra={'v' + otaInfo.version + (fmtSeqTime(otaInfo.sequence) ? ' · ' + fmtSeqTime(otaInfo.sequence) : '')}>
{' '}({(progress.received / 1024).toFixed(0)} KB 新版本
{progress.total ? ' / ' + (progress.total / 1024).toFixed(0) + ' KB' : ''}) {otaInfo.bundle_size ? ` (${(otaInfo.bundle_size / 1024).toFixed(0)} KB)` : ''}
</div> </List.Item>
<ProgressBar percent={progressPct || undefined} /> )}
</div> {otaState === 'downloading' && (
</List.Item> <List.Item>
)} <div className="me-ota-progress">
{otaInfo?.notes && ( <div className="me-ota-progress-text">
<List.Item description={otaInfo.notes}>发布说明</List.Item> 正在下载 {showProgress ? progressPct + '%' : ''}
)} {' '}({(progress.received / 1024).toFixed(0)} KB
{error && ( {progress.total ? ' / ' + (progress.total / 1024).toFixed(0) + ' KB' : ''})
<List.Item> </div>
<span className="me-ota-error">{error}</span> <ProgressBar percent={progressPct || undefined} />
</List.Item> </div>
)} </List.Item>
{!isTauri && ( )}
<List.Item description="Web 端仅展示提示, 实际升级需在 Tauri 客户端进行">提示</List.Item> {otaInfo?.notes && (
)} <List.Item description={otaInfo.notes}>发布说明</List.Item>
</List> )}
{otaInfo?.commit && (
<List className="me-list" mode="card"> <List.Item extra={String(otaInfo.commit).slice(0, 10)}>提交</List.Item>
<List.Item extra={'#' + (user?.id || '-')}>用户 ID</List.Item> )}
<List.Item extra={user?.createdAt ? new Date(user.createdAt).toLocaleDateString() : '-'}> {error && (
注册时间 <List.Item>
</List.Item> <span className="me-ota-error">{error}</span>
<List.Item </List.Item>
onClick={onLogout} )}
clickable {!isTauri && (
arrowIcon={false} <List.Item description="Web 端仅展示提示, 实际升级需在 Tauri 客户端进行">提示</List.Item>
className="me-logout" )}
> </List>
退出登录
</List.Item> <List className="me-list" mode="card">
</List> <List.Item extra={'#' + (user?.id || '-')}>用户 ID</List.Item>
<div className="me-version">v{APP_VERSION} · build {BUILD_ID}</div> <List.Item extra={user?.createdAt ? new Date(user.createdAt).toLocaleDateString() : '-'}>
</div> 注册时间
) </List.Item>
} <List.Item
onClick={onLogout}
clickable
arrowIcon={false}
className="me-logout"
>
退出登录
</List.Item>
</List>
<div className="me-version">v{APP_VERSION} · build {BUILD_ID}</div>
</div>
)
}