app-update.service.ts 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. import { Injectable, signal, computed, inject } from '@angular/core';
  2. import { App } from '@capacitor/app';
  3. import { Capacitor } from '@capacitor/core';
  4. /**
  5. * 版本与更新服务(2026-11-23 新建)
  6. *
  7. * 背景:这个 App 之前**完全没有**更新检查能力 —— 用户装上去之后,
  8. * 除非自己去下载页重装,否则永远停留在旧版本。
  9. *
  10. * 设计要点:
  11. *
  12. * 1. **版本单一事实源**
  13. * 原生 versionName / versionCode 从 `@capacitor/app` 的 getInfo() 读,
  14. * 不在前端硬编码。读不到(纯浏览器)时回退到构建期注入的常量。
  15. *
  16. * 2. **更新元数据走平台云函数**
  17. * `app_update?appId=<包名>` 返回最新版本信息。这个接口是平台既有的,
  18. * 和 nova-admin 那套完全一致,不需要新增后端。
  19. *
  20. * 3. **更新日志内嵌在返回体**
  21. * `App` 表 record 里有 `content` 字段存更新说明,
  22. * 所以「查看更新了什么」不需要额外请求。
  23. *
  24. * 4. **强制更新能力**
  25. * `isForce` 为真时弹窗不可关闭,必须更新才能继续用。
  26. */
  27. export interface UpdateInfo {
  28. /** 最新版本名,如 1.0.2 */
  29. version: string;
  30. /** 最新版本号,用于数值比较 */
  31. versionCode: number;
  32. /** APK 直链 */
  33. url: string;
  34. /** 更新说明(纯文本或简单 markdown) */
  35. content: string;
  36. /** 是否强制更新 */
  37. isForce: boolean;
  38. /** 更新说明详情页(可选,更丰富的排版) */
  39. changelogUrl?: string;
  40. /** APK 体积(字节,可选,用于展示) */
  41. size?: number;
  42. }
  43. export interface LocalVersion {
  44. versionName: string;
  45. versionCode: number;
  46. appName: string;
  47. packageName: string;
  48. }
  49. /** 包名 —— 与 capacitor.config.ts 保持一致 */
  50. const APP_ID = 'cn.fmode.app';
  51. /**
  52. * 更新服务接口(2026-11-23)
  53. *
  54. * 走自建云函数 `fmode-app-update`(Fmode Module API,代码存在数据库里动态执行)。
  55. * 老接口 `app_update` 在当前集群已不存在(实测 404),是更新整体失效的根因。
  56. *
  57. * 为什么不再直连 App 表:
  58. * 直连会把客户端绑死在 Parse 的 REST 格式、class 名、字段名上。
  59. * 将来加灰度、改字段、换存储都要发新版客户端 —— 而更新功能本身失效时,
  60. * 用户根本升不上来,形成死锁。云函数这层契约解耦了这个风险。
  61. *
  62. * 调用方式用 **函数 id** 而非 path:
  63. * 实测按 path 调用返回「云函数不存在」,按 id 稳定可用。
  64. * 函数 id 由部署时生成,写死在这里(服务端换实现不需要改这个 id)。
  65. */
  66. const UPDATE_FN_URL = 'https://server.fmode.cn/api/functions';
  67. const UPDATE_FN_ID = 'kTPtIM9YTQ';
  68. @Injectable({ providedIn: 'root' })
  69. export class AppUpdateService {
  70. /** 本机当前版本 */
  71. readonly local = signal<LocalVersion | null>(null);
  72. /** 服务端返回的最新版本(null = 还没查到或已是最新) */
  73. readonly remote = signal<UpdateInfo | null>(null);
  74. /** 网络/解析错误信息 */
  75. readonly error = signal<string | null>(null);
  76. /** 是否正在检查 */
  77. readonly checking = signal(false);
  78. /** 是否有可用更新 —— 只比较 versionCode,这是唯一可靠依据 */
  79. readonly hasUpdate = computed(() => {
  80. const l = this.local();
  81. const r = this.remote();
  82. if (!l || !r) return false;
  83. return r.versionCode > l.versionCode;
  84. });
  85. /** 更新是否为强制 */
  86. readonly isForce = computed(() => this.remote()?.isForce === true);
  87. private infoLoaded = false;
  88. /**
  89. * 读本机版本。
  90. *
  91. * 原生环境走 Capacitor App.getInfo(),拿真实的 versionName/versionCode;
  92. * 浏览器环境没有这些,用构建期常量兜底,保证页面不崩。
  93. */
  94. async loadLocalVersion(): Promise<LocalVersion> {
  95. if (this.infoLoaded && this.local()) return this.local()!;
  96. let info: LocalVersion = {
  97. versionName: '1.0.1',
  98. versionCode: 101,
  99. appName: '飞马SI',
  100. packageName: APP_ID,
  101. };
  102. if (Capacitor.isNativePlatform()) {
  103. try {
  104. const v = await App.getInfo();
  105. info = {
  106. versionName: v.version || info.versionName,
  107. /*
  108. * getInfo() 的 build 字段就是 Android 的 versionCode,
  109. * 但它是字符串。解析失败就退回默认值,绝不 NaN。
  110. */
  111. versionCode: Number.parseInt(v.build, 10) || info.versionCode,
  112. appName: v.name || info.appName,
  113. packageName: v.id || APP_ID,
  114. };
  115. } catch {
  116. /* 读不到就用兜底值,不阻塞 */
  117. }
  118. }
  119. this.local.set(info);
  120. this.infoLoaded = true;
  121. return info;
  122. }
  123. /**
  124. * 检查更新。
  125. *
  126. * 返回 true 表示有更新。调用方据此决定是否弹窗 ——
  127. * 服务本身不弹窗,保持无 UI 副作用,方便在启动、进「我的」页、
  128. * 用户手动点击等多种时机复用。
  129. */
  130. async check(): Promise<boolean> {
  131. this.checking.set(true);
  132. this.error.set(null);
  133. try {
  134. const local = await this.loadLocalVersion();
  135. /*
  136. * 调用云函数(POST,参数在 params 里)。
  137. *
  138. * 带上 currentVersionCode:服务端可据此判断是否低于 minVersionCode,
  139. * 从而把某次更新升级为强制更新 —— 服务端改字段即可,不用发新版客户端。
  140. */
  141. const res = await fetch(UPDATE_FN_URL, {
  142. method: 'POST',
  143. headers: { 'Content-Type': 'application/json' },
  144. body: JSON.stringify({
  145. id: UPDATE_FN_ID,
  146. params: {
  147. appid: APP_ID,
  148. currentVersionCode: local.versionCode,
  149. currentVersion: local.versionName,
  150. },
  151. }),
  152. /* 更新检查绝不能命中任何缓存,否则发了新版用户永远查不到 */
  153. cache: 'no-store',
  154. });
  155. if (!res.ok) {
  156. this.error.set(`更新服务返回 ${res.status}`);
  157. return false;
  158. }
  159. const json = await res.json();
  160. /*
  161. * 云函数返回 { code: 200, data: {...} }。
  162. * code 404 = 这个包还没在 App 表登记,视为「无更新」而不是错误。
  163. */
  164. if (json?.code !== 200 || !json.data) {
  165. this.remote.set(null);
  166. return false;
  167. }
  168. const row = json.data;
  169. const info: UpdateInfo = {
  170. version: String(row.version ?? ''),
  171. /*
  172. * 云函数已把 versionCode 补齐;万一缺失,
  173. * 用 version 解析出数字来比较,否则没法判断新旧。
  174. */
  175. versionCode: Number(row.versionCode) || this.parseVersionCode(String(row.version ?? '')),
  176. url: row.url ?? '',
  177. content: row.changelog ?? '',
  178. isForce: row.isForce === true,
  179. changelogUrl: row.changelogUrl || undefined,
  180. size: Number(row.size) || undefined,
  181. };
  182. if (!info.url || !info.version) {
  183. this.remote.set(null);
  184. return false;
  185. }
  186. this.remote.set(info);
  187. return info.versionCode > local.versionCode;
  188. } catch (e: unknown) {
  189. this.error.set(e instanceof Error ? e.message : '检查更新失败');
  190. return false;
  191. } finally {
  192. this.checking.set(false);
  193. }
  194. }
  195. /**
  196. * 把 "1.0.12" 解析成可用于比较的整数 10012。
  197. *
  198. * 规则:主.次.修订 → 主*10000 + 次*100 + 修订。
  199. * 这样 1.0.9 < 1.0.10 能正确比较(字符串比较会判错)。
  200. * 服务端没给 versionCode 时用这个兜底。
  201. */
  202. private parseVersionCode(v: string): number {
  203. const m = v.match(/(\d+)\.(\d+)\.(\d+)/);
  204. if (!m) return 0;
  205. return Number(m[1]) * 10000 + Number(m[2]) * 100 + Number(m[3]);
  206. }
  207. }