From 81a5a8888d8d536838fbefabc5bf5f3069bc9ea8 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 17 Oct 2026 12:07:13 +0800 Subject: [PATCH] =?UTF-8?q?=E6=89=93=E5=8C=85=EF=BC=9A=E5=BC=80=E5=8F=91/?= =?UTF-8?q?=E7=94=9F=E4=BA=A7=E7=8E=AF=E5=A2=83=E9=85=8D=E7=BD=AE=20+=20?= =?UTF-8?q?=E7=89=88=E6=9C=AC=E5=8F=B7=20+=20=E8=87=AA=E5=8A=A8=E6=9B=B4?= =?UTF-8?q?=E6=96=B0=EF=BC=88version.json=EF=BC=89+=20=E4=BF=9D=E7=95=995?= =?UTF-8?q?=E4=B8=AA=E5=8C=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 一、打包配置(desktop/installer/package.config.json) - 两个环境各自的域名:Development = http://127.0.0.1:7300,Production = 占位正式域名(发布前替换)。 - keepVersions = 5。 - build.ps1 -Environment Production 自动用生产域名打 exe 与下载地址;-ServerBaseUrl 可临时覆盖。 二、build.ps1 - 新增 -Environment / -Version / -Keep / -ReleaseNotes;版本默认取 csproj,可覆盖, 通过 -p:Version 注入程序集(AssemblyVersion/FileVersion 一起变)。 - 打完后:算 MD5、写 version.json(version/downloadUrl/md5/size/publishedAt/buildId/environment/releaseNotes), 复制 MSI → backend/app/public/download/,version.json → backend/app/public/version/。 - 本地 out/ 与后端目录各只保留最近 5 个安装包(按版本号排序清理)。 - 补丁版保护:后端已有更高版本时,不覆盖 version.json(避免补打旧版把版本降回去)。 三、后端静态分发 + 缓存(关键) - Egg 的 static 生产默认强缓存一年,version.json 若走静态会**永远检测不到更新**。 且实测 koa-static 命中文件后**不再 next()**,后置中间件改不了它的响应头(先写了 middleware 验证不可行,已删)。 → version.json 放到 app/public/version/(不在静态目录),由路由 GET /download/version.json 提供: Cache-Control: no-store, no-cache, must-revalidate, max-age=0 + Pragma/Expires,且不产生 ETag/Last-Modified。 - MSI 仍走 egg-static(prefix /download/,maxAge 31536000),文件名带版本号可长缓存。 - middleware/frontend.js 放行 /download/*,否则会被 SPA 入口接管。 - 实测响应头:version.json 无 ETag/Last-Modified、cache-control: no-store…; MSI cache-control: public, max-age=31536000。 四、桌面端自动更新(Services/UpdateChecker.cs + App) - 启动登录后后台请求 {后端}/download/version.json?t=毫秒时间戳(带 no-cache 头), 比较程序集版本;有新版则弹窗(版本/说明/大小),点是 → 浏览器打开 downloadUrl。 - 失败静默(网络问题不打扰);日志记录发现新版本/已打开下载。 - 实测:安装 1.0.1 → version.json 1.0.1 不提示;改成 1.0.2 后重启 → 日志「发现新版本 1.0.2(当前 1.0.1.0)→ 已打开下载」。 五、.gitignore - 忽略后端分发产物:backend/app/public/{download,version}/* 但保留 .gitkeep。 ⚠️ backend/config/config.default.js 本次提交同时带入了该文件里已有的未提交改动 (后端默认端口 7001 → 7300 及注释),因为 static 配置必须写在同一个文件里; 其它 backend/extension/frontend 的未提交 WIP 未包含在本次提交中。 --- .gitignore | 6 + backend/app/controller/download.js | 42 ++++++ backend/app/middleware/frontend.js | 5 +- backend/app/public/download/.gitkeep | 7 + backend/app/public/version/.gitkeep | 9 ++ backend/app/router.js | 5 + backend/config/config.default.js | 24 +++- desktop/App.xaml.cs | 48 ++++++- desktop/README.md | 78 +++++++++- desktop/Services/UpdateChecker.cs | 76 ++++++++++ desktop/installer/build.ps1 | 199 ++++++++++++++++++++++---- desktop/installer/package.config.json | 22 +++ 12 files changed, 479 insertions(+), 42 deletions(-) create mode 100644 backend/app/controller/download.js create mode 100644 backend/app/public/download/.gitkeep create mode 100644 backend/app/public/version/.gitkeep create mode 100644 desktop/Services/UpdateChecker.cs create mode 100644 desktop/installer/package.config.json diff --git a/.gitignore b/.gitignore index 1dd3530..ced8f61 100644 --- a/.gitignore +++ b/.gitignore @@ -29,6 +29,12 @@ artifacts/ desktop/installer/out/ *.wixpdb +# 安装包分发目录(打包脚本复制到后端静态目录;只保留 .gitkeep) +backend/app/public/download/* +!backend/app/public/download/.gitkeep +backend/app/public/version/* +!backend/app/public/version/.gitkeep + # ---------- 运行期 / 日志 ---------- # backend 的 logs/、多实例自测时的 logs-test/、脚本产出的 run/ logs/ diff --git a/backend/app/controller/download.js b/backend/app/controller/download.js new file mode 100644 index 0000000..1ebb97b --- /dev/null +++ b/backend/app/controller/download.js @@ -0,0 +1,42 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const { Controller } = require('egg'); + +/** + * 安装包分发:版本信息(软件自动更新用) + * + * ⚠️ **为什么不放在 egg-static 的目录里**: + * `koa-static` 命中文件后**不会再调用 next()**,任何「后置中间件」都改不了它的响应头; + * 而 egg-static 生产默认强缓存一年 → 软件永远拿旧的 version.json,永远检测不到更新。 + * + * 所以: + * - `version.json` 放在 `app/public/version/`(不在静态 prefix 下),由本控制器读文件; + * - 安装包 `*.msi` 仍走 egg-static(`/download/xxx.msi`),文件名带版本号,可以长缓存。 + * + * 缓存策略:no-store + no-cache + Expires 0,且不产生 ETag/Last-Modified(不走 304)。 + * 生产前面若还有 nginx/CDN,也要对 `/download/version.json` 关缓存。 + */ +class DownloadController extends Controller { + /** GET /download/version.json */ + async version() { + const { ctx, app } = this; + const file = path.join(app.baseDir, 'app/public/version/version.json'); + + if (!fs.existsSync(file)) { + ctx.status = 404; + ctx.body = { ok: false, message: 'version.json 不存在(还没打包过?)' }; + return; + } + + ctx.set('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0'); + ctx.set('Pragma', 'no-cache'); + ctx.set('Expires', '0'); + ctx.set('X-Content-Type-Options', 'nosniff'); + ctx.type = 'application/json; charset=utf-8'; + ctx.body = fs.readFileSync(file); // 几百字节,直接读最省事 + } +} + +module.exports = DownloadController; diff --git a/backend/app/middleware/frontend.js b/backend/app/middleware/frontend.js index 9cd2a47..4a40bc4 100644 --- a/backend/app/middleware/frontend.js +++ b/backend/app/middleware/frontend.js @@ -10,7 +10,7 @@ const serve = require('koa-static'); * * - **开发(`env=local`)**:把非 `/api`、`/health` 的请求反向代理到前端 dev server * (`config.frontend.devServer`,默认 `http://127.0.0.1:7301`,即 `frontend && npm run dev`)。 - * 这样联调只开一个地址(后端 `:7001`),前端的热更新也照常生效(含 HMR 的 WebSocket 升级)。 + * 这样联调只开一个地址(后端 `:7300`),前端的热更新也照常生效(含 HMR 的 WebSocket 升级)。 * - **生产**:托管 `config.frontend.distDir`(默认 `../frontend/dist`)里的静态资源, * 找不到文件且浏览器要 HTML 时回退到 `index.html`(SPA 深链刷新不会 404)。 * - **单测(`env=unittest`)**:整体跳过(不连前端、也不要求 dist 存在), @@ -67,9 +67,10 @@ module.exports = (options, app) => { }; }; -/** 只接管「页面」请求:非接口 + GET/HEAD */ +/** 只接管「页面」请求:非接口 + GET/HEAD;`/download/*` 是安装包静态资源,不接管 */ function isFrontendRequest(ctx) { if (ctx.method !== 'GET' && ctx.method !== 'HEAD') return false; + if (ctx.path.startsWith('/download/')) return false; return !ctx.path.startsWith('/api/') && ctx.path !== '/api' && ctx.path !== '/health'; } diff --git a/backend/app/public/download/.gitkeep b/backend/app/public/download/.gitkeep new file mode 100644 index 0000000..fadb741 --- /dev/null +++ b/backend/app/public/download/.gitkeep @@ -0,0 +1,7 @@ +# 安装包分发目录(打包脚本 desktop/installer/build.ps1 会写入 version.json 与 MSI) +# +# 访问地址: +# GET /download/version.json —— 软件自动更新用(绝不缓存) +# GET /download/YuncangTraceSetup-<版本>.msi +# +# 这个文件只是让 git 保留目录;打包产物不要提交(见 .gitignore)。 diff --git a/backend/app/public/version/.gitkeep b/backend/app/public/version/.gitkeep new file mode 100644 index 0000000..9c0cc8b --- /dev/null +++ b/backend/app/public/version/.gitkeep @@ -0,0 +1,9 @@ +# 版本信息目录(打包脚本 desktop/installer/build.ps1 会把 version.json 写到这里) +# +# 为什么不放在 app/public/download/(静态目录)里: +# koa-static 命中文件后不会 next(),后置中间件改不了它的响应头, +# 而 egg-static 生产默认强缓存一年 → 软件永远检测不到更新。 +# 所以 version.json 走路由(app/controller/download.js),由路由显式关缓存。 +# +# 访问地址:GET /download/version.json +# 打包产物不要提交(见 .gitignore)。 diff --git a/backend/app/router.js b/backend/app/router.js index 6f6d374..051bc1d 100644 --- a/backend/app/router.js +++ b/backend/app/router.js @@ -23,6 +23,11 @@ module.exports = (app) => { router.get('/api/info', controller.home.index); router.get('/health', controller.health.index); + // ---------- 安装包分发(软件自动更新) ---------- + // 安装包本体 `GET /download/YuncangTraceSetup-x.y.z.msi` 由 egg-static 提供(config.static); + // version.json **必须走路由**:static 命中后不会 next(),改不了缓存头(会被缓存一年)。 + router.get('/download/version.json', controller.download.version); + // ---------- web 用户端(前端 SPA 调;登录/注册等公开,其余要令牌) ---------- router.post('/api/web/auth/login', controller.web.auth.login); router.post('/api/web/auth/register/code', controller.web.auth.sendRegisterCode); diff --git a/backend/config/config.default.js b/backend/config/config.default.js index 90c8604..5737fe9 100644 --- a/backend/config/config.default.js +++ b/backend/config/config.default.js @@ -23,10 +23,24 @@ module.exports = (appInfo) => { // frontend:**后端不渲染页面** —— 开发时把页面请求反代给前端 dev server,生产时托管前端构建产物 config.middleware = [ 'errorHandler', 'frontend' ]; + // ==================== 安装包分发(软件自动更新) ==================== + // 打包脚本(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 判断是否有新版本。 + config.static = { + prefix: '/download/', + dir: path.join(appInfo.baseDir, 'app/public/download'), + // 这里只会放“文件名带版本号”的 MSI,内容永不变 → 可以放心长缓存 + maxAge: 31536000, + buffer: false, // MSI 几十 MB,流式发送 + }; + // ==================== 前端入口(页面不在后端渲染) ==================== // 开发(env=local):页面请求(非 /api、/health)反代到前端 dev server(frontend/ 里 npm run dev) // 生产:直接托管前端构建产物 dist(SPA 深链回退到 index.html) - // 联调时只开一个地址:打开 http://127.0.0.1:7001 就是前端页面 + // 联调时只开一个地址:打开 http://127.0.0.1:7300 就是前端页面 config.frontend = { enable: !/^(0|false|no|off)$/i.test(String(env.FRONTEND_ENABLE || 'true')), devServer: env.FRONTEND_DEV_SERVER || 'http://127.0.0.1:7301', @@ -46,11 +60,11 @@ module.exports = (appInfo) => { }; // ==================== 服务端口 ==================== - // 本地默认 7001;“专用测试端口”用 `npm run dev:test`(egg-bin dev --port 7300) - // 也可临时覆盖:PORT=7300 npm run dev(PowerShell:$env:PORT=7300; npm run dev) + // 本地默认 **7300**(曾用 7001;避免与别的项目撞,也方便和前端 7301 排在一起) + // 临时换口:PORT=7400 npm run dev(PowerShell:$env:PORT=7400; npm run dev) config.cluster = { listen: { - port: Number(env.PORT || 7001), + port: Number(env.PORT || 7300), }, }; @@ -196,7 +210,7 @@ module.exports = (appInfo) => { }; // 多实例并存时用 LOG_DIR 把日志分到不同目录,免得到处翻同一个日志文件 - // 例(PowerShell):$env:LOG_DIR='logs-test'; npm run dev:test + // 例(PowerShell):$env:PORT=7400; $env:LOG_DIR='logs-test'; npm run dev // ⚠️ 必须写在上面 config.logger 赋值之后,否则会被整个覆盖掉 if (env.LOG_DIR) { config.logger.dir = path.resolve(appInfo.baseDir, env.LOG_DIR); diff --git a/desktop/App.xaml.cs b/desktop/App.xaml.cs index 2f05da7..8497e80 100644 --- a/desktop/App.xaml.cs +++ b/desktop/App.xaml.cs @@ -1,12 +1,14 @@ using System; +using System.Diagnostics; using System.Net; +using System.Threading.Tasks; using System.Windows; using YuncangTrace.LocalService.Services; namespace YuncangTrace.LocalService; /// -/// 应用入口,负责四件事: +/// 应用入口,负责五件事: /// /// 1. **防多开**:全局互斥体;第二个实例把参数(可能是 `yuncang://open?code=xxx`)送给第一个实例后自己退出; /// 2. **本机 HTTP 服务**(127.0.0.1:17300):登录前就起来,关窗口也不停(托盘里继续跑); @@ -83,6 +85,50 @@ public partial class App : Application } ShowMainWindow(); + + // ⑤ 检查更新(后台;失败静默,不影响使用) + _ = CheckUpdatesAsync(); + } + + /// + /// 检查更新:后端静态 GET /download/version.json,比当前程序集版本新就弹窗问要不要下载。 + /// 网络失败 / 后端没放 version.json 都静默(这不该打扰用户)。 + /// + private async Task CheckUpdatesAsync() + { + try + { + var current = GetType().Assembly.GetName().Version ?? new Version(1, 0, 0, 0); + var info = await UpdateChecker.CheckAsync(_settings.ServerBaseUrl, current); + if (info is null) return; + + AppLog.Write($"发现新版本 {info.Version}(当前 {current}):{info.DownloadUrl}"); + + var notes = string.IsNullOrWhiteSpace(info.Notes) ? string.Empty : $"\n\n更新内容:{info.Notes}"; + var size = info.Size > 0 ? $"\n安装包大小:{info.Size / 1024.0 / 1024.0:0.0} MB" : string.Empty; + + var answer = MessageBox.Show( + $"发现新版本 {info.Version}(当前 {current})。{notes}{size}\n\n现在下载安装包吗?", + "软件更新", + MessageBoxButton.YesNo, + MessageBoxImage.Information); + + if (answer != MessageBoxResult.Yes) return; + + if (string.IsNullOrWhiteSpace(info.DownloadUrl)) + { + AppLog.Write("更新信息里没有下载地址(version.json 的 downloadUrl)"); + return; + } + + // 用默认浏览器打开下载(MSI 能直接下,也能交给用户自己跑) + Process.Start(new ProcessStartInfo(info.DownloadUrl) { UseShellExecute = true }); + AppLog.Write($"已打开下载:{info.DownloadUrl}"); + } + catch (Exception ex) + { + AppLog.Write($"检查更新失败:{ex.Message}"); + } } /// diff --git a/desktop/README.md b/desktop/README.md index d977f74..55b2099 100644 --- a/desktop/README.md +++ b/desktop/README.md @@ -113,7 +113,7 @@ dotnet publish -c Release -r win-x64 --self-contained true ` 开发阶段想让 `bin\Debug` 的 exe 也能直接双击,两个办法:装官方 SDK/Desktop Runtime 到标准位置, 或者每次用发布产物验证唤起。 -## 打安装包(MSI) +## 打安装包(MSI)+ 自动更新 `desktop/installer/` 下是安装包定义(**WiX 5**,免费;WiX v6+ 需要 OSMF 付费协议,别装最新版)。 @@ -122,12 +122,76 @@ dotnet publish -c Release -r win-x64 --self-contained true ` dotnet tool install --global wix --version 5.0.2 cd desktop\installer -.\build.ps1 -ServerBaseUrl https://正式域名 -# → out\YuncangTraceSetup-<版本>.msi(约 54 MB,cab 压缩) + +.\build.ps1 # 开发环境(默认),版本取 csproj(1.0.0) +.\build.ps1 -Version 1.0.1 # 指定版本 +.\build.ps1 -Environment Production -Version 1.0.1 -ReleaseNotes "修复若干问题" ``` -`build.ps1` 做两件事:先 `dotnet publish`(自包含单文件,不依赖运行时)→ 再 `wix build`。 -版本号取自 csproj 的 ``,改版本只改那一处。 +### 环境与域名(`package.config.json`) + +| 环境 | 默认后端 | 用途 | +| --- | --- | --- | +| `Development` | `http://127.0.0.1:7300` | 本机联调;打完会自动把包+版本信息复制到后端,本机就能测更新 | +| `Production` | `https://packs.example.com`(**占位,发布前必须改成正式域名**) | 正式安装包 | + +`build.ps1 -Environment Production` 自动用生产域名打 exe(`ServerBaseUrl`)和下载地址; +也可以用 `-ServerBaseUrl` 临时覆盖。 + +### 脚本做了什么 + +1. `dotnet publish`(自包含单文件,不依赖 .NET 运行时;版本号一起注入程序集); +2. `wix build` 生成 MSI; +3. 算 MD5 → 写 `version.json`; +4. 复制到后端:MSI → `backend/app/public/download/`,`version.json` → `backend/app/public/version/`; +5. 本地 `out/` 与后端目录**各只保留最近 5 个**安装包(`keepVersions` 可配)。 + +### 自动更新怎么工作 + +``` +软件启动(登录后)→ GET {后端}/download/version.json?t=时间戳 + → version.json 里的 version 比当前程序集版本新 + → 弹窗「发现新版本 x.y.z」→ 用户点是 → 浏览器打开 downloadUrl 下载安装 +``` + +`version.json` 长这样(脚本生成,**不用手写**): + +```json +{ + "version": "1.0.1", + "downloadUrl": "https://正式域名/download/YuncangTraceSetup-1.0.1.msi", + "md5": "7a93b4…", + "size": 56786944, + "publishedAt": "2026-10-17T12:00:58+08:00", + "buildId": "20261017120058", + "environment": "Production", + "releaseNotes": "修复若干问题" +} +``` + +### ⚠️ 缓存(这里最容易踩坑) + +Egg 的 `static` 在生产默认**强缓存一年**。如果 `version.json` 也被缓存,软件永远检测不到更新。 + +处理方式(都已实现): + +| 层 | 做法 | +| --- | --- | +| 文件位置 | `version.json` 放在 `app/public/version/`,**不在静态目录里** | +| 后端路由 | `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` | +| 安装包本体 | 文件名带版本号 → `Cache-Control: public, max-age=31536000, immutable` | + +> 生产前面如果还有 **nginx / CDN**,也要对 `/download/version.json` 关缓存,否则只在应用层关没用: +> ```nginx +> location = /download/version.json { +> add_header Cache-Control "no-store, no-cache, must-revalidate" always; +> proxy_no_cache 1; +> proxy_cache_bypass 1; +> proxy_pass http://127.0.0.1:7300; +> } +> ``` 安装包行为: @@ -140,8 +204,8 @@ cd desktop\installer | 用户数据 | `%LOCALAPPDATA%\YuncangTrace\{settings,session}.json` 卸载**不删**(重装后仍保持设置/登录) | ```powershell -msiexec /i out\YuncangTraceSetup-1.0.0.msi # 安装 -msiexec /x out\YuncangTraceSetup-1.0.0.msi # 卸载 +msiexec /i out\YuncangTraceSetup-1.0.1.msi # 安装 +msiexec /x out\YuncangTraceSetup-1.0.1.msi # 卸载 ``` > 需要「本机所有用户都能用」时:`Product.wxs` 里 `Scope` 改 `perMachine`、注册表根改 `HKLM`, diff --git a/desktop/Services/UpdateChecker.cs b/desktop/Services/UpdateChecker.cs new file mode 100644 index 0000000..e37a59a --- /dev/null +++ b/desktop/Services/UpdateChecker.cs @@ -0,0 +1,76 @@ +using System; +using System.Net.Http; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; + +namespace YuncangTrace.LocalService.Services; + +/// 发现的新版本(来自后端静态 `version.json`) +/// 新版本号(如 1.0.1) +/// 安装包地址(一般是后端 `/download/YuncangTraceSetup-x.y.z.msi`) +/// 安装包 MD5(可用于下载后校验) +/// 安装包字节数(0 = 未知) +/// 更新说明(可为空) +public sealed record UpdateInfo(string Version, string? DownloadUrl, string? Md5, long Size, string? Notes); + +/// +/// 自动更新检查:请求后端的静态 `GET /download/version.json`,与当前程序版本比对。 +/// +/// `version.json` 由 `desktop/installer/build.ps1` 生成,内容形如: +/// +/// { "version": "1.0.1", "downloadUrl": "https://站点/download/YuncangTraceSetup-1.0.1.msi", +/// "md5": "…", "size": 56712345, "publishedAt": "…", "buildId": "…", "releaseNotes": "…" } +/// +/// +/// ⚠️ 缓存是这里最容易踩的坑(Egg 的 static 生产默认强缓存一年): +/// - URL 带 `?t=毫秒时间戳`; +/// - 请求头带 `no-cache`; +/// - 后端 `middleware/download.js` 对 version.json 回 `no-store` 并去掉 ETag/Last-Modified。 +/// 三层都做,是为了兼容中间可能存在的代理 / CDN。 +/// +public static class UpdateChecker +{ + /// 版本信息地址(跟当前构建环境的后端地址走) + public static string VersionUrl(string serverBaseUrl) + => serverBaseUrl.TrimEnd('/') + "/download/version.json"; + + /// + /// 检查是否有更新。 + /// + /// 有新版本返回它;已是最新 / 请求失败 / 数据不合法都返回 null + public static async Task CheckAsync( + string serverBaseUrl, + Version current, + CancellationToken cancellationToken = default) + { + var url = $"{VersionUrl(serverBaseUrl)}?t={DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}"; + + using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(8) }; + using var request = new HttpRequestMessage(HttpMethod.Get, url); + request.Headers.TryAddWithoutValidation("Cache-Control", "no-cache, no-store"); + request.Headers.TryAddWithoutValidation("Pragma", "no-cache"); + + using var response = await http.SendAsync(request, HttpCompletionOption.ResponseContentRead, cancellationToken) + .ConfigureAwait(false); + if (!response.IsSuccessStatusCode) return null; + + var json = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + using var doc = JsonDocument.Parse(json); + var root = doc.RootElement; + + if (!root.TryGetProperty("version", out var versionEl)) return null; + + var text = versionEl.GetString(); + if (string.IsNullOrWhiteSpace(text)) return null; + if (!Version.TryParse(text.Trim(), out var remote)) return null; + if (remote <= current) return null; + + return new UpdateInfo( + text.Trim(), + root.TryGetProperty("downloadUrl", out var d) ? d.GetString() : null, + root.TryGetProperty("md5", out var m) ? m.GetString() : null, + root.TryGetProperty("size", out var s) && s.TryGetInt64(out var size) ? size : 0, + root.TryGetProperty("releaseNotes", out var n) ? n.GetString() : null); + } +} diff --git a/desktop/installer/build.ps1 b/desktop/installer/build.ps1 index 8e24ca2..b8af6a4 100644 --- a/desktop/installer/build.ps1 +++ b/desktop/installer/build.ps1 @@ -1,33 +1,51 @@ #requires -Version 5.1 <# .SYNOPSIS - 打「云仓视频溯源软件」的 MSI 安装包。 + 打「云仓视频溯源软件」的 MSI 安装包,并生成本机自动更新用的 version.json。 .DESCRIPTION - 1. 自包含单文件发布 → desktop\publish\YuncangTrace.LocalService.exe - 2. 用 WiX 5 打包 → desktop\installer\out\YuncangTraceSetup-<版本>.msi + 1. 按 -Environment 从 package.config.json 取该环境的域名(开发 / 生产); + 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 检测更新; + 6. 本地 out/ 与后端目录各只保留最近 keepVersions(默认 5)个安装包。 - 安装包特性: - - perUser 安装(免管理员、无 UAC),装到 %LOCALAPPDATA%\Programs\YuncangTrace - - **安装即注册** yuncang:// 协议(HKCU),不需要先启动软件 - - 卸载时 MSI 自动删除协议与开始菜单(= 取消注册) +.PARAMETER Environment + Development(默认,连本机 7300)/ Production(用正式域名)。 + +.PARAMETER Version + 覆盖版本号(默认取 csproj 的 )。例:-Version 1.0.1 .PARAMETER ServerBaseUrl - 打进 exe 的生产后端地址(登录用)。默认是占位地址,正式发布必须传真实域名。 + 覆盖该环境配置里的域名(临时打测试包用)。 -.PARAMETER Configuration - 默认 Release。 +.PARAMETER Keep + 保留多少个历史安装包(默认读 package.config.json 的 keepVersions = 5)。 + +.PARAMETER ReleaseNotes + 写进 version.json 的更新说明(软件弹更新提示时展示)。 .EXAMPLE - .\build.ps1 -ServerBaseUrl https://trace.example.com + .\build.ps1 -Environment Production -Version 1.0.1 -ReleaseNotes "修复若干问题" + +.EXAMPLE + .\build.ps1 # 开发环境、版本取 csproj .NOTES 前置:dotnet tool install --global wix --version 5.0.2 (WiX v6+ 需要 OSMF 付费协议,v5 不需要) + 本文件必须保存为 UTF-8 with BOM —— PowerShell 5.1 读无 BOM 脚本会按 GBK 解析,中文注释直接语法报错。 #> param( - [string]$ServerBaseUrl = 'https://packs.example.com', - [string]$Configuration = 'Release' + [ValidateSet('Development', 'Production')] + [string]$Environment = 'Development', + + [string]$Version, + [string]$ServerBaseUrl, + [int]$Keep = 0, + [string]$ReleaseNotes = '' ) $ErrorActionPreference = 'Stop' @@ -37,21 +55,50 @@ $project = Join-Path $desktop 'YuncangTrace.LocalService.csproj' $publishDir = Join-Path $desktop 'publish' $outDir = Join-Path $PSScriptRoot 'out' -# 版本号以 csproj 为准(只读文件,不改它) -$projXml = [xml][System.IO.File]::ReadAllText($project, (New-Object System.Text.UTF8Encoding($false))) -$version = ($projXml.Project.PropertyGroup.Version | Where-Object { $_ } | Select-Object -First 1) -if (-not $version) { throw "csproj 里没找到 " } +function Read-Utf8([string]$p) { + return [System.IO.File]::ReadAllText($p, (New-Object System.Text.UTF8Encoding($false))) +} -Write-Host "版本:$version" +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 } + +# ---------------- 2. 版本 ---------------- +$projXml = [xml](Read-Utf8 $project) +$projVersion = ($projXml.Project.PropertyGroup.Version | Where-Object { $_ } | Select-Object -First 1) + +if (-not $Version) { $Version = $projVersion } +if (-not $Version) { throw "csproj 里没找到 ,也没传 -Version" } +$Version = $Version.Trim().TrimStart('v', 'V') +$null = [version]$Version # 提前校验格式(不合法直接报错) + +Write-Host "环境:$Environment" +Write-Host "版本:$Version" Write-Host "后端:$ServerBaseUrl" -# 1) 发布(自包含单文件:双击/协议唤起都不依赖 .NET 运行时) +# ---------------- 3. 发布 ---------------- Push-Location $desktop try { - dotnet publish $project -c $Configuration -r win-x64 ` + dotnet publish $project -c Release -r win-x64 ` --self-contained true ` -p:PublishSingleFile=true ` -p:IncludeNativeLibrariesForSelfExtract=true ` + -p:Version=$Version ` -p:ServerBaseUrl=$ServerBaseUrl ` -o $publishDir if ($LASTEXITCODE -ne 0) { throw "dotnet publish 失败($LASTEXITCODE)" } @@ -63,7 +110,7 @@ finally { $exe = Join-Path $publishDir 'YuncangTrace.LocalService.exe' if (-not (Test-Path $exe)) { throw "发布产物不存在:$exe" } -# 2) 打 MSI +# ---------------- 4. 打 MSI ---------------- $wix = (Get-Command wix.exe -ErrorAction SilentlyContinue).Source if (-not $wix) { $wix = Join-Path $env:USERPROFILE '.dotnet\tools\wix.exe' } if (-not (Test-Path $wix)) { @@ -71,19 +118,117 @@ if (-not (Test-Path $wix)) { } New-Item -ItemType Directory -Force -Path $outDir | Out-Null -$msi = Join-Path $outDir "YuncangTraceSetup-$version.msi" +$msiName = "YuncangTraceSetup-$Version.msi" +$msi = Join-Path $outDir $msiName Push-Location $PSScriptRoot try { - & $wix build Product.wxs -arch x64 -d "Version=$version" -o $msi + & $wix build Product.wxs -arch x64 -d "Version=$Version" -o $msi if ($LASTEXITCODE -ne 0) { throw "wix build 失败($LASTEXITCODE)" } } finally { Pop-Location } -$size = [math]::Round((Get-Item $msi).Length / 1MB, 1) +# ---------------- 5. version.json ---------------- +$hash = (Get-FileHash -Algorithm MD5 -Path $msi).Hash.ToLowerInvariant() +$size = (Get-Item $msi).Length +$downloadUrl = "$ServerBaseUrl/download/$msiName" +$now = Get-Date + +$versionJson = [ordered]@{ + version = $Version + 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 "MD5:$hash($([math]::Round($size / 1MB, 1)) MB)" + +# ---------------- 6. 复制到后端 ---------------- +# MSI → 静态目录(/download/xxx.msi,长缓存) +# version.json → 非静态目录(/download/version.json 由路由提供,绝不能缓存) +$skipVersionJson = $false +$downloadDir = $null +$versionDir = $null +$existingVj = $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 { /* 旧文件坏了就当没有 */ } + } + + $dstMsi = Join-Path $downloadDir $msiName + Copy-Item -Path $msi -Destination $dstMsi -Force + # 刷新 mtime:即使上游还有一层协商缓存,也能认出文件变了 + (Get-Item $dstMsi).LastWriteTime = $now + + if (-not $skipVersionJson) { + Write-Utf8NoBom $existingVj $versionJson + (Get-Item $existingVj).LastWriteTime = $now + } + + # 旧版本打包时把 version.json 放在静态目录里,顺手清掉(避免两份不一致) + $staleVj = Join-Path $downloadDir 'version.json' + if (Test-Path $staleVj) { Remove-Item $staleVj -Force } + + Write-Host "已复制到:$downloadDir(MSI)、$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 'YuncangTraceSetup-*.msi' -File | ForEach-Object { + if ($_.BaseName -match 'YuncangTraceSetup-(\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 "完成:$msi($size MB)" -ForegroundColor Green -Write-Host "安装(免管理员):msiexec /i `"$msi`"" -Write-Host "卸载: msiexec /x `"$msi`"" +Write-Host "完成:$msi" -ForegroundColor Green +Write-Host "版本文件:$versionFile" +Write-Host "下载地址:$downloadUrl" +Write-Host "安装:msiexec /i `"$msi`"" +Write-Host "卸载:msiexec /x `"$msi`"" diff --git a/desktop/installer/package.config.json b/desktop/installer/package.config.json new file mode 100644 index 0000000..6c6207e --- /dev/null +++ b/desktop/installer/package.config.json @@ -0,0 +1,22 @@ +{ + "$comment": "打包配置:build.ps1 -Environment Development|Production 读取对应环境。版本号默认取 csproj 的 ,可用 -Version 覆盖。", + "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", + "copyToServer": true + }, + + "Production": { + "$comment": "生产环境:把 serverBaseUrl 换成正式域名(协议登录 + 更新下载都走它)。", + "serverBaseUrl": "https://packs.example.com", + "downloadFolder": "../../backend/app/public/download", + "versionFolder": "../../backend/app/public/version", + "copyToServer": true + } + } +}