| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233 |
- import { Injectable, signal, computed, inject } from '@angular/core';
- import { App } from '@capacitor/app';
- import { Capacitor } from '@capacitor/core';
- /**
- * 版本与更新服务(2026-11-23 新建)
- *
- * 背景:这个 App 之前**完全没有**更新检查能力 —— 用户装上去之后,
- * 除非自己去下载页重装,否则永远停留在旧版本。
- *
- * 设计要点:
- *
- * 1. **版本单一事实源**
- * 原生 versionName / versionCode 从 `@capacitor/app` 的 getInfo() 读,
- * 不在前端硬编码。读不到(纯浏览器)时回退到构建期注入的常量。
- *
- * 2. **更新元数据走平台云函数**
- * `app_update?appId=<包名>` 返回最新版本信息。这个接口是平台既有的,
- * 和 nova-admin 那套完全一致,不需要新增后端。
- *
- * 3. **更新日志内嵌在返回体**
- * `App` 表 record 里有 `content` 字段存更新说明,
- * 所以「查看更新了什么」不需要额外请求。
- *
- * 4. **强制更新能力**
- * `isForce` 为真时弹窗不可关闭,必须更新才能继续用。
- */
- export interface UpdateInfo {
- /** 最新版本名,如 1.0.2 */
- version: string;
- /** 最新版本号,用于数值比较 */
- versionCode: number;
- /** APK 直链 */
- url: string;
- /** 更新说明(纯文本或简单 markdown) */
- content: string;
- /** 是否强制更新 */
- isForce: boolean;
- /** 更新说明详情页(可选,更丰富的排版) */
- changelogUrl?: string;
- /** APK 体积(字节,可选,用于展示) */
- size?: number;
- }
- export interface LocalVersion {
- versionName: string;
- versionCode: number;
- appName: string;
- packageName: string;
- }
- /** 包名 —— 与 capacitor.config.ts 保持一致 */
- const APP_ID = 'cn.fmode.app';
- /**
- * 更新服务接口(2026-11-23)
- *
- * 走自建云函数 `fmode-app-update`(Fmode Module API,代码存在数据库里动态执行)。
- * 老接口 `app_update` 在当前集群已不存在(实测 404),是更新整体失效的根因。
- *
- * 为什么不再直连 App 表:
- * 直连会把客户端绑死在 Parse 的 REST 格式、class 名、字段名上。
- * 将来加灰度、改字段、换存储都要发新版客户端 —— 而更新功能本身失效时,
- * 用户根本升不上来,形成死锁。云函数这层契约解耦了这个风险。
- *
- * 调用方式用 **函数 id** 而非 path:
- * 实测按 path 调用返回「云函数不存在」,按 id 稳定可用。
- * 函数 id 由部署时生成,写死在这里(服务端换实现不需要改这个 id)。
- */
- const UPDATE_FN_URL = 'https://server.fmode.cn/api/functions';
- const UPDATE_FN_ID = 'kTPtIM9YTQ';
- @Injectable({ providedIn: 'root' })
- export class AppUpdateService {
- /** 本机当前版本 */
- readonly local = signal<LocalVersion | null>(null);
- /** 服务端返回的最新版本(null = 还没查到或已是最新) */
- readonly remote = signal<UpdateInfo | null>(null);
- /** 网络/解析错误信息 */
- readonly error = signal<string | null>(null);
- /** 是否正在检查 */
- readonly checking = signal(false);
- /** 是否有可用更新 —— 只比较 versionCode,这是唯一可靠依据 */
- readonly hasUpdate = computed(() => {
- const l = this.local();
- const r = this.remote();
- if (!l || !r) return false;
- return r.versionCode > l.versionCode;
- });
- /** 更新是否为强制 */
- readonly isForce = computed(() => this.remote()?.isForce === true);
- private infoLoaded = false;
- /**
- * 读本机版本。
- *
- * 原生环境走 Capacitor App.getInfo(),拿真实的 versionName/versionCode;
- * 浏览器环境没有这些,用构建期常量兜底,保证页面不崩。
- */
- async loadLocalVersion(): Promise<LocalVersion> {
- if (this.infoLoaded && this.local()) return this.local()!;
- let info: LocalVersion = {
- versionName: '1.0.1',
- versionCode: 101,
- appName: '飞马SI',
- packageName: APP_ID,
- };
- if (Capacitor.isNativePlatform()) {
- try {
- const v = await App.getInfo();
- info = {
- versionName: v.version || info.versionName,
- /*
- * getInfo() 的 build 字段就是 Android 的 versionCode,
- * 但它是字符串。解析失败就退回默认值,绝不 NaN。
- */
- versionCode: Number.parseInt(v.build, 10) || info.versionCode,
- appName: v.name || info.appName,
- packageName: v.id || APP_ID,
- };
- } catch {
- /* 读不到就用兜底值,不阻塞 */
- }
- }
- this.local.set(info);
- this.infoLoaded = true;
- return info;
- }
- /**
- * 检查更新。
- *
- * 返回 true 表示有更新。调用方据此决定是否弹窗 ——
- * 服务本身不弹窗,保持无 UI 副作用,方便在启动、进「我的」页、
- * 用户手动点击等多种时机复用。
- */
- async check(): Promise<boolean> {
- this.checking.set(true);
- this.error.set(null);
- try {
- const local = await this.loadLocalVersion();
- /*
- * 调用云函数(POST,参数在 params 里)。
- *
- * 带上 currentVersionCode:服务端可据此判断是否低于 minVersionCode,
- * 从而把某次更新升级为强制更新 —— 服务端改字段即可,不用发新版客户端。
- */
- const res = await fetch(UPDATE_FN_URL, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- id: UPDATE_FN_ID,
- params: {
- appid: APP_ID,
- currentVersionCode: local.versionCode,
- currentVersion: local.versionName,
- },
- }),
- /* 更新检查绝不能命中任何缓存,否则发了新版用户永远查不到 */
- cache: 'no-store',
- });
- if (!res.ok) {
- this.error.set(`更新服务返回 ${res.status}`);
- return false;
- }
- const json = await res.json();
- /*
- * 云函数返回 { code: 200, data: {...} }。
- * code 404 = 这个包还没在 App 表登记,视为「无更新」而不是错误。
- */
- if (json?.code !== 200 || !json.data) {
- this.remote.set(null);
- return false;
- }
- const row = json.data;
- const info: UpdateInfo = {
- version: String(row.version ?? ''),
- /*
- * 云函数已把 versionCode 补齐;万一缺失,
- * 用 version 解析出数字来比较,否则没法判断新旧。
- */
- versionCode: Number(row.versionCode) || this.parseVersionCode(String(row.version ?? '')),
- url: row.url ?? '',
- content: row.changelog ?? '',
- isForce: row.isForce === true,
- changelogUrl: row.changelogUrl || undefined,
- size: Number(row.size) || undefined,
- };
- if (!info.url || !info.version) {
- this.remote.set(null);
- return false;
- }
- this.remote.set(info);
- return info.versionCode > local.versionCode;
- } catch (e: unknown) {
- this.error.set(e instanceof Error ? e.message : '检查更新失败');
- return false;
- } finally {
- this.checking.set(false);
- }
- }
- /**
- * 把 "1.0.12" 解析成可用于比较的整数 10012。
- *
- * 规则:主.次.修订 → 主*10000 + 次*100 + 修订。
- * 这样 1.0.9 < 1.0.10 能正确比较(字符串比较会判错)。
- * 服务端没给 versionCode 时用这个兜底。
- */
- private parseVersionCode(v: string): number {
- const m = v.match(/(\d+)\.(\d+)\.(\d+)/);
- if (!m) return 0;
- return Number(m[1]) * 10000 + Number(m[2]) * 100 + Number(m[3]);
- }
- }
|