示例工程 56-auto-update

56-auto-update/app/main/index.ts

typescript · 11 KB

import { app, BrowserWindow, ipcMain } from "electron";
import fsSync from "node:fs";
import os from "node:os";
import path from "node:path";
import {
  CH,
  type Check,
  type EventRow,
  type FeedRow,
  type Snapshot,
} from "../shared/ipc";
import {
  SCHEMES,
  compareVersions,
  decideUpdate,
  officialEligible,
  storeInAppUpdate,
  type Feed,
  type FeedKind,
} from "../shared/feed";

app.setName("Update Lab");

const isSmoke =
  process.argv.includes("--smoke") || process.env.DEMO_SMOKE === "1";
const isShots = process.argv.includes("--shots");
const tempData =
  isSmoke || isShots ? path.join(os.tmpdir(), `upd56-${process.pid}`) : "";
if (tempData) app.setPath("userData", tempData);

const appRoot = app.getAppPath();
const fixtureRoot = path.join(appRoot, "fixtures");
const currentVersion = "1.0.0";

let win: BrowserWindow | null = null;
let events: EventRow[] = [];
let feeds: FeedRow[] = [];

const FILES: Array<{
  id: string;
  label: string;
  kind: FeedKind;
  file: string;
}> = [
  {
    id: "mac",
    label: "macOS releases.json",
    kind: "mac",
    file: "releases.json",
  },
  { id: "win", label: "Windows RELEASES", kind: "win", file: "RELEASES" },
  {
    id: "none",
    label: "无更新 feed",
    kind: "mac",
    file: "no-update.json",
  },
  { id: "invalid", label: "损坏 feed", kind: "invalid", file: "invalid.txt" },
];

function log(kind: string, detail: string): void {
  events = [{ at: Date.now(), kind, detail }, ...events].slice(0, 40);
  broadcast();
}

function broadcast(): void {
  if (win && !win.isDestroyed()) {
    win.webContents.send("update:event", { at: Date.now() });
  }
}

function loadFeeds(): void {
  feeds = FILES.map((file) => {
    let raw = "";
    try {
      raw = fsSync.readFileSync(path.join(fixtureRoot, file.file), "utf8");
    } catch {
      raw = "";
    }
    const feed: Feed = {
      id: file.id,
      label: file.label,
      kind: file.kind,
      raw,
    };
    return { ...feed, decision: decideUpdate(currentVersion, feed) };
  });
  log(
    "feeds",
    feeds.map((row) => `${row.id}:${row.decision.status}`).join(" "),
  );
}

function checks(): Check[] {
  const find = (id: string) => feeds.find((row) => row.id === id);
  const mac = find("mac");
  const win = find("win");
  const none = find("none");
  const invalid = find("invalid");
  return [
    {
      id: "schemes",
      label: "四类更新方案完整",
      pass: SCHEMES.length === 4,
      detail: SCHEMES.map((row) => row.id).join(","),
    },
    {
      id: "feeds",
      label: "四个 feed fixture 已加载",
      pass: feeds.length === 4,
      detail: String(feeds.length),
    },
    {
      id: "mac",
      label: "macOS feed 选出 1.2.0",
      pass:
        mac?.decision.status === "update" && mac.decision.latest === "1.2.0",
      detail: mac?.decision.latest ?? "",
    },
    {
      id: "win",
      label: "Windows feed 选出 1.2.0",
      pass:
        win?.decision.status === "update" && win.decision.latest === "1.2.0",
      detail: win?.decision.latest ?? "",
    },
    {
      id: "none",
      label: "无更新 feed 返回 none",
      pass: none?.decision.status === "none",
      detail: none?.decision.status ?? "",
    },
    {
      id: "invalid",
      label: "损坏 feed 返回 error 而不是崩溃",
      pass: invalid?.decision.status === "error",
      detail: invalid?.decision.reason ?? "",
    },
    {
      id: "semver",
      label: "版本比较 1.10.0 > 1.9.0",
      pass: compareVersions("1.10.0", "1.9.0") > 0,
      detail: "1.10.0 > 1.9.0",
    },
    {
      id: "official",
      label: "官方服务门槛:macOS 可、Linux 不可",
      pass:
        officialEligible({
          platform: "macos",
          publicRepo: true,
          signed: true,
        }).ok &&
        !officialEligible({
          platform: "linux",
          publicRepo: true,
          signed: true,
        }).ok,
      detail: "mac/linux",
    },
    {
      id: "store",
      label: "商店渠道关闭应用内自更新",
      pass: storeInAppUpdate() === false,
      detail: "false",
    },
    {
      id: "no-install",
      label: "只做 feed/决策/提示,不执行安装替换",
      pass: true,
      detail: "no install",
    },
  ];
}

function snapshot(): Snapshot {
  const list = checks();
  const passed = list.filter((check) => check.pass).length;
  return {
    platform: process.platform,
    electronVersion: process.versions.electron,
    nodeVersion: process.versions.node,
    schemes: SCHEMES.map((row) => ({ ...row })),
    feeds: feeds.map((row) => ({
      ...row,
      decision: { ...row.decision },
    })),
    currentVersion,
    checks: list,
    score: Math.round((passed / list.length) * 100),
    events: events.map((row) => ({ ...row })),
  };
}

function resolvePreload(): string {
  const candidates = [
    path.join(__dirname, "preload.cjs"),
    path.join(__dirname, "../preload/index.cjs"),
    path.join(__dirname, "preload.js"),
  ];
  return (
    candidates.find((candidate) => fsSync.existsSync(candidate)) ??
    candidates[0] ??
    ""
  );
}

function createWindow(): BrowserWindow {
  const window = new BrowserWindow({
    width: 1100,
    height: 860,
    show: false,
    title: "自动更新决策台",
    backgroundColor: "#ffffff",
    webPreferences: {
      preload: resolvePreload(),
      contextIsolation: true,
      sandbox: true,
      nodeIntegration: false,
      webSecurity: true,
      allowRunningInsecureContent: false,
      experimentalFeatures: false,
      webviewTag: false,
      spellcheck: false,
      backgroundThrottling: true,
    },
  });
  const contents = window.webContents;
  contents.setWindowOpenHandler(() => ({ action: "deny" }));
  contents.on("will-navigate", (event, url) => {
    if (!url.startsWith("file://")) event.preventDefault();
  });
  contents.on("will-attach-webview", (event) => event.preventDefault());
  window.once("ready-to-show", () => window.show());
  contents.once("did-finish-load", () => {
    if (!window.isDestroyed() && !window.isVisible()) window.show();
    log("ready", "自动更新界面已加载");
  });
  if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {
    void window.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL);
  } else {
    void window.loadFile(
      path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`),
    );
  }
  win = window;
  return window;
}

function delay(ms: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function evalRenderer<T>(
  window: BrowserWindow,
  code: string,
): Promise<T> {
  let lastCaught: unknown = null;
  for (let attempt = 0; attempt < 3; attempt += 1) {
    try {
      return (await window.webContents.executeJavaScript(code)) as T;
    } catch (caught) {
      lastCaught = caught;
      await delay(150);
    }
  }
  throw lastCaught instanceof Error
    ? lastCaught
    : new Error(String(lastCaught));
}

async function waitForRenderer(window: BrowserWindow): Promise<void> {
  for (let attempt = 0; attempt < 160; attempt += 1) {
    if (window.isDestroyed()) return;
    try {
      const ready = await evalRenderer<boolean>(
        window,
        "typeof window.__demo === 'function'",
      );
      if (ready) return;
    } catch {
      // 页面仍在加载。
    }
    await delay(100);
  }
  throw new Error("renderer did not become ready");
}

type DemoState = {
  score: number;
  checks: number;
  passed: number;
  schemes: number;
  feeds: number;
  macStatus: string;
  macLatest: string;
  winStatus: string;
  winLatest: string;
  noneStatus: string;
  invalidStatus: string;
  noInstall: boolean;
};

async function runSmoke(window: BrowserWindow): Promise<void> {
  try {
    await waitForRenderer(window);
    await delay(600);
    await waitForRenderer(window);
    const state = await evalRenderer<DemoState>(window, "window.__demo()");
    process.stdout.write(
      `${JSON.stringify({
        evt: "smoke",
        ok:
          state.score === 100 &&
          state.checks === 10 &&
          state.passed === 10 &&
          state.schemes === 4 &&
          state.feeds === 4 &&
          state.macStatus === "update" &&
          state.macLatest === "1.2.0" &&
          state.winStatus === "update" &&
          state.winLatest === "1.2.0" &&
          state.noneStatus === "none" &&
          state.invalidStatus === "error" &&
          state.noInstall,
        ...state,
      })}\n`,
    );
    app.quit();
  } catch (caught) {
    process.stdout.write(
      `${JSON.stringify({ evt: "smoke", ok: false, message: String(caught) })}\n`,
    );
    app.exit(1);
  }
}

async function capture(
  window: BrowserWindow,
  dir: string,
  file: string,
): Promise<void> {
  const image = await window.webContents.capturePage();
  if (image.isEmpty()) throw new Error(`empty capture: ${file}`);
  const png = image.toPNG();
  fsSync.writeFileSync(path.join(dir, file), png);
  fsSync.writeFileSync(path.join(dir, "raw", file), png);
}

async function runShots(window: BrowserWindow): Promise<void> {
  try {
    const dir = path.resolve(
      process.cwd(),
      "../../../docs/assets/images/56-auto-update",
    );
    fsSync.mkdirSync(path.join(dir, "raw"), { recursive: true });
    await waitForRenderer(window);
    await delay(600);
    await waitForRenderer(window);
    await evalRenderer(window, `window.__prepareShots("schemes")`);
    await delay(250);
    await capture(window, dir, "56-01-schemes.png");
    await evalRenderer(window, `window.__prepareShots("available")`);
    await delay(250);
    await capture(window, dir, "56-02-available.png");
    await evalRenderer(window, `window.__prepareShots("limits")`);
    await delay(250);
    await capture(window, dir, "56-03-limits.png");
    app.quit();
  } catch (caught) {
    process.stdout.write(
      `${JSON.stringify({ evt: "shots-error", message: String(caught) })}\n`,
    );
    app.exit(1);
  }
}

ipcMain.handle(CH.snapshot, () => snapshot());

ipcMain.handle(CH.refresh, () => {
  loadFeeds();
  log("refresh", "重新解析 feed 并决策");
  return snapshot();
});

app.whenReady().then(() => {
  loadFeeds();
  log("load", `${SCHEMES.length} 方案 / ${feeds.length} feeds`);
  const window = createWindow();
  if (isSmoke) {
    void runSmoke(window);
  } else if (isShots) {
    void runShots(window);
  }
  app.on("activate", () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow();
    } else {
      win?.show();
      win?.focus();
    }
  });
});

app.on("will-quit", () => {
  if (tempData) {
    try {
      fsSync.rmSync(tempData, { recursive: true, force: true });
    } catch {
      // 清理失败不影响退出。
    }
  }
});

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") app.quit();
});