publish-apk.mjs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. #!/usr/bin/env node
  2. /**
  3. * APK + 下载官网发布(ai.fmode.cn/download/)
  4. *
  5. * 用法:
  6. * node scripts/publish-apk.mjs # 完整:上传 APK → 更新官网 → 刷 CDN → 探活
  7. * node scripts/publish-apk.mjs --dry-run # 只打印将要执行的动作,不执行
  8. * node scripts/publish-apk.mjs --skip-apk # 不上传 APK,只更新官网与清单
  9. * node scripts/publish-apk.mjs --force # 允许覆盖已存在的同名 APK 对象
  10. * node scripts/publish-apk.mjs --channel=正式版 # 渠道标注(默认「测试版」,写进官网与清单)
  11. *
  12. * 设计(2026-11-23,用户裁决):
  13. * · APK 走 S3(OBS)上传,版本号进文件名 `fmode-app-v{versionName}.apk`——
  14. * 永不覆盖同名对象,天然免刷 CDN 缓存
  15. * · 官网放 ai.fmode.cn/download/(Web App 在根路径,两边不互踩)
  16. * · 官网源是 prototypes/fmode-download-20261120(暗色产品官网),
  17. * 本脚本把 APK 信息写进 site.js 的 FMODE_SITE 后跑它的 build.mjs 重新产出
  18. *
  19. * 与 deploy.mjs 的分工:deploy.mjs 管 Web App(根路径),本脚本管 /download/。
  20. * 🔴 桶里还有 2025-08 遗留构建与 assets/,全程只用 obsutil cp 逐对象上传,
  21. * 禁止 sync -delete / rm(与 deploy.mjs、deploy-kit 同一铁律)。
  22. *
  23. * 凭据:obsutil 用 `~/.obsutilconfig`(43 位 AK);CDN 刷新用下方 KooCLI 专用
  24. * 20 位 AK/SK(与 deploy.mjs 同一对,黄金规则 9 用户裁决可明文、集中存放)。
  25. */
  26. import { createHash } from 'node:crypto';
  27. import { execFileSync, execSync } from 'node:child_process';
  28. import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
  29. import { dirname, join, resolve } from 'node:path';
  30. import { fileURLToPath } from 'node:url';
  31. const here = dirname(fileURLToPath(import.meta.url));
  32. const projectRoot = resolve(here, '..');
  33. const BUCKET = 'obs://www-ai.fmode.cn';
  34. const CDN_BASE = 'https://ai.fmode.cn';
  35. const OBS_EP = 'obs.cn-south-1.myhuaweicloud.com';
  36. const CDN_REGION = 'cn-north-1';
  37. const APK_DIR = join(projectRoot, 'android/app/build/outputs/apk/debug');
  38. const SITE_DIR = join(projectRoot, 'prototypes/fmode-download-20261120');
  39. const TMP_DIR = join(projectRoot, 'scripts/.tmp-publish');
  40. // 与 deploy.mjs 同一对 KooCLI 凭证(见 deploy.mjs 顶部注释:不是 obsutil 那套)
  41. const HW_AK = process.env.HW_AK || '2BFF7JWXAIJ0UGNJ0OSB';
  42. const HW_SK = process.env.HW_SK || 'NaPCiJCGmD3nklCzX65s8mSK1Py13ueyhgepa0s1';
  43. const args = new Set(process.argv.slice(2));
  44. const dryRun = args.has('--dry-run');
  45. const skipApk = args.has('--skip-apk');
  46. const force = args.has('--force');
  47. const channelArg = process.argv.find((a) => a.startsWith('--channel='));
  48. const channel = channelArg ? channelArg.split('=')[1] : '测试版';
  49. /** Windows 上 npm/npx 是 .cmd,必须走 shell(同 deploy.mjs 2026-11-18 修复) */
  50. function needsShell(cmd) {
  51. if (process.platform !== 'win32') return false;
  52. return /\.(cmd|bat)$/i.test(cmd) || cmd === 'npm' || cmd === 'npx';
  53. }
  54. function run(cmd, argv, opts = {}) {
  55. const printable = `${cmd} ${argv.join(' ')}`;
  56. console.log(`\n$ ${printable}`);
  57. if (dryRun) return '';
  58. try {
  59. return execFileSync(cmd, argv, {
  60. cwd: projectRoot,
  61. stdio: 'inherit',
  62. ...(needsShell(cmd) ? { shell: true } : {}),
  63. ...opts,
  64. });
  65. } catch {
  66. console.error(`\n❌ 命令失败:${printable}`);
  67. process.exit(1);
  68. }
  69. }
  70. /** 探测型命令:失败返回 null 而不是退出(用于 stat 检查对象是否存在) */
  71. function tryRun(cmd, argv) {
  72. try {
  73. return execSync(`${cmd} ${argv.join(' ')}`, { cwd: projectRoot, stdio: 'pipe' }).toString();
  74. } catch {
  75. return null;
  76. }
  77. }
  78. async function probe(url, timeoutMs = 30_000) {
  79. const ac = new AbortController();
  80. const timer = setTimeout(() => ac.abort(), timeoutMs);
  81. try {
  82. const res = await fetch(url, { signal: ac.signal, redirect: 'follow' });
  83. return { status: res.status, headers: res.headers, body: await res.text() };
  84. } catch {
  85. return { status: 0, headers: new Headers(), body: '' };
  86. } finally {
  87. clearTimeout(timer);
  88. }
  89. }
  90. /** 华为云 KooCLI 探测(同 deploy.mjs:PATH 里的 hcloud 可能是 Hetzner 同名 CLI) */
  91. function resolveHcloud() {
  92. const candidates = [
  93. process.env.HCLOUD_BIN,
  94. 'E:\\coding-environment\\huaweicloud-koocli\\hcloud.exe',
  95. `${process.env.LOCALAPPDATA}\\huaweicloud\\hcloud.exe`,
  96. `${process.env.USERPROFILE}\\tools\\hcloud\\hcloud.exe`,
  97. '/usr/local/bin/hcloud',
  98. 'hcloud',
  99. ].filter(Boolean);
  100. for (const bin of candidates) {
  101. try {
  102. const out = execFileSync(bin, ['version'], { encoding: 'utf8', timeout: 15_000 });
  103. if (/KooCLI/i.test(out)) return bin;
  104. } catch { /* 下一个 */ }
  105. }
  106. return null;
  107. }
  108. // ── 1. APK 元信息 ──────────────────────────────────────────────────────────
  109. console.log('\n=== [1/6] 读取 APK 元信息 ===');
  110. const apkPath = join(APK_DIR, 'app-debug.apk');
  111. const metaPath = join(APK_DIR, 'output-metadata.json');
  112. if (!existsSync(apkPath) || !existsSync(metaPath)) {
  113. console.error('❌ 找不到 APK 产物,请先构建:cd android && gradle assembleDebug');
  114. process.exit(1);
  115. }
  116. const meta = JSON.parse(readFileSync(metaPath, 'utf8'));
  117. const versionName = meta.elements?.[0]?.versionName;
  118. if (!versionName) {
  119. console.error('❌ output-metadata.json 中没有 versionName');
  120. process.exit(1);
  121. }
  122. const { size, mtimeMs } = statSync(apkPath);
  123. const md5 = createHash('md5').update(readFileSync(apkPath)).digest('hex');
  124. const fileName = `fmode-app-v${versionName}.apk`;
  125. const fileSizeText = `${(size / 1024 / 1024).toFixed(1)} MB`;
  126. const today = new Date().toLocaleDateString('sv-SE'); // YYYY-MM-DD
  127. const apkUrl = `${CDN_BASE}/download/${fileName}`;
  128. console.log(` 版本 ${versionName} · ${fileSizeText} · md5 ${md5.slice(0, 8)}… · 渠道「${channel}」`);
  129. console.log(` 构建时间 ${new Date(mtimeMs).toLocaleString('zh-CN')}`);
  130. // ── 2. 防覆盖检查 + 上传 APK ────────────────────────────────────────────────
  131. console.log('\n=== [2/6] 上传 APK 到 OBS ===');
  132. const remoteApk = `${BUCKET}/download/${fileName}`;
  133. if (!skipApk) {
  134. const stat = tryRun('obsutil', ['stat', remoteApk, `-e=${OBS_EP}`]);
  135. if (stat && !force) {
  136. console.error(`❌ ${fileName} 已存在于桶中。同名对象不覆盖(防误盖历史版本)。`);
  137. console.error(' 确认要覆盖请加 --force;发新版本请先递增 versionName。');
  138. process.exit(1);
  139. }
  140. // -meta 偶发不生效,chattri REPLACE_NEW 双保险(deploy-kit apk-publish.sh 实测写法)
  141. run('obsutil', ['cp', apkPath, remoteApk, '-acl=public-read',
  142. '-meta=Content-Type:application/vnd.android.package-archive', `-e=${OBS_EP}`]);
  143. run('obsutil', ['chattri', remoteApk,
  144. '-meta=Content-Type:application/vnd.android.package-archive', '-direct=REPLACE_NEW', `-e=${OBS_EP}`]);
  145. run('obsutil', ['chattri', remoteApk, '-acl=public-read', `-e=${OBS_EP}`]);
  146. } else {
  147. console.log(' 跳过 APK 上传(--skip-apk)');
  148. }
  149. // ── 3. 更新官网配置并重新打包 ───────────────────────────────────────────────
  150. console.log('\n=== [3/6] 写入 FMODE_SITE 并重新构建官网 ===');
  151. const siteJsPath = join(SITE_DIR, 'site.js');
  152. const siteJs = readFileSync(siteJsPath, 'utf8');
  153. const fmodeSite = `const FMODE_SITE = { apkUrl: '${apkUrl}', version: '${versionName}', fileSize: '${fileSizeText}', updatedAt: '${today}', channel: '${channel}' };`;
  154. if (!/const FMODE_SITE = \{[^}]*\};/.test(siteJs)) {
  155. console.error('❌ site.js 里找不到 FMODE_SITE 配置行');
  156. process.exit(1);
  157. }
  158. if (!dryRun) writeFileSync(siteJsPath, siteJs.replace(/const FMODE_SITE = \{[^}]*\};/, fmodeSite));
  159. console.log(` ${fmodeSite}`);
  160. run('node', [join(SITE_DIR, 'build.mjs')]);
  161. // ── 4. 上传官网 + 清单 ──────────────────────────────────────────────────────
  162. console.log('\n=== [4/6] 上传 download/index.html 与 manifest.json ===');
  163. const indexPath = join(SITE_DIR, 'index.html');
  164. if (!existsSync(indexPath) && !dryRun) {
  165. console.error('❌ build.mjs 未产出 index.html');
  166. process.exit(1);
  167. }
  168. mkdirSync(TMP_DIR, { recursive: true });
  169. run('obsutil', ['cp', indexPath, `${BUCKET}/download/index.html`, '-acl=public-read',
  170. '-meta=Content-Type:text/html;charset=utf-8', `-e=${OBS_EP}`]);
  171. run('obsutil', ['chattri', `${BUCKET}/download/index.html`,
  172. '-meta=Content-Type:text/html;charset=utf-8', '-direct=REPLACE_NEW', `-e=${OBS_EP}`]);
  173. // 清单沿用 deploy-kit apk-publish.sh 的格式:按 file 去重、新条目插最前
  174. let manifest = { apps: [] };
  175. const current = await probe(`${CDN_BASE}/download/manifest.json?cb=${Date.now()}`);
  176. if (current.status === 200) {
  177. try { manifest = JSON.parse(current.body); } catch { /* 用空清单 */ }
  178. if (!Array.isArray(manifest.apps)) manifest.apps = [];
  179. } else {
  180. console.log(' (线上暂无 manifest.json,新建)');
  181. }
  182. manifest.apps = manifest.apps.filter((a) => a.file !== fileName);
  183. manifest.apps.unshift({
  184. file: fileName, name: 'Fmode 客户端', version: versionName, note: channel,
  185. size, md5, url: `download/${fileName}`, time: today,
  186. });
  187. manifest.updated = new Date().toLocaleString('sv-SE').replace('T', ' ').slice(0, 16);
  188. const manifestPath = join(TMP_DIR, 'manifest.json');
  189. if (!dryRun) writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));
  190. console.log(` 清单条目:${manifest.apps.map((a) => a.file).join(', ')}`);
  191. run('obsutil', ['cp', manifestPath, `${BUCKET}/download/manifest.json`, '-acl=public-read',
  192. '-meta=Content-Type:application/json;charset=utf-8', `-e=${OBS_EP}`]);
  193. // ── 5. 刷 CDN(固定名文件才需要;APK 是新对象不刷) ─────────────────────────
  194. console.log('\n=== [5/6] 刷新 CDN ===');
  195. const refreshUrls = [`${CDN_BASE}/download/`, `${CDN_BASE}/download/index.html`, `${CDN_BASE}/download/manifest.json`];
  196. for (const u of refreshUrls) console.log(` ${u}`);
  197. const HCLOUD_BIN = resolveHcloud();
  198. if (!HCLOUD_BIN) {
  199. // 同 deploy.mjs:找不到不静默跳过(OBS 已上传,CDN 没刷用户拿旧版)
  200. console.error('\n❌ 未找到华为云 KooCLI(hcloud)。文件已上传,但 CDN 未刷新。');
  201. console.error(' 安装后重跑,或用 HCLOUD_BIN=<完整路径> 指定;也可在 CDN 控制台手动刷新以上 URL。');
  202. process.exit(1);
  203. }
  204. // KooCLI 首跑会交互询问隐私声明,stdin 喂 y(同 deploy.mjs)
  205. run(HCLOUD_BIN, [
  206. 'CDN', 'CreateRefreshTasks/v2',
  207. `--cli-region=${CDN_REGION}`,
  208. '--refresh_task.type=file',
  209. ...refreshUrls.map((u, i) => `--refresh_task.urls.${i + 1}=${u}`),
  210. `--cli-access-key=${HW_AK}`,
  211. `--cli-secret-key=${HW_SK}`,
  212. ], { input: 'y\ny\ny\n' });
  213. // ── 6. 探活 ────────────────────────────────────────────────────────────────
  214. console.log('\n=== [6/6] 线上探活 ===');
  215. if (dryRun) {
  216. console.log(' (dry-run,跳过)');
  217. } else {
  218. let allOk = true;
  219. if (!skipApk) {
  220. // APK:状态 200 + 大小一致(Content-Type 也可能经 CDN 归一化,以大小为准)
  221. let apkOk = false;
  222. for (let i = 0; i < 12 && !apkOk; i++) {
  223. const r = await probe(apkUrl, 15_000);
  224. const len = Number(r.headers.get('content-length') || 0);
  225. apkOk = r.status === 200 && len === size;
  226. if (!apkOk) await new Promise((r2) => setTimeout(r2, 5_000));
  227. }
  228. console.log(apkOk ? ` ✓ APK 直链 200 · ${fileSizeText}` : ` ❌ APK 直链未就绪:${apkUrl}`);
  229. allOk &&= apkOk;
  230. }
  231. // 官网:CDN 刷新有延迟,以「响应含本次版本号」为准(不看 200)
  232. let siteOk = false;
  233. for (let i = 0; i < 18 && !siteOk; i++) {
  234. const r = await probe(`${CDN_BASE}/download/?cb=${Date.now()}`, 15_000);
  235. siteOk = r.body.includes(versionName) && r.body.includes(fileName);
  236. if (!siteOk) await new Promise((r2) => setTimeout(r2, 10_000));
  237. }
  238. console.log(siteOk ? ' ✓ 下载页含本次版本与 APK 直链' : ' ❌ 下载页 3 分钟后仍非本次内容,请手动确认 CDN');
  239. allOk &&= siteOk;
  240. // Web App 不受影响(回归哨兵)
  241. const app = await probe(`${CDN_BASE}/`, 15_000);
  242. const appOk = app.body.includes('app-root');
  243. console.log(appOk ? ' ✓ 根路径 Web App 正常(未受影响)' : ' ❌ 根路径 Web App 异常,立即检查!');
  244. allOk &&= appOk;
  245. if (!allOk) {
  246. console.error('\n❌ 发布完成但线上校验未全部通过,见上方 ❌ 项');
  247. process.exit(1);
  248. }
  249. }
  250. console.log('\n' + '─'.repeat(56));
  251. console.log(` 安装包直链 : ${apkUrl}`);
  252. console.log(` 下载页 : ${CDN_BASE}/download/`);
  253. console.log('─'.repeat(56));
  254. console.log('\n✅ 发布完成\n');