Windows 上的安卓应用运行器:双击 APK 即装,应用以独立窗口与桌面图标运行,自持 QEMU 运行时
perf: 多源并行下载 + 停滞换源,113MB 更新包从 493s 降到 77s(v0.3.3 未发布)
RoutineMikubaef53753607
diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 3c223b9..17a51b1 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -63,6 +63,21 @@ jobs:if (-not $ok) { Write-Error "上传失败: $zip"; exit 1 }gh release view $tag --json assets --jq '.assets[].name'+ # 同步到 Gitee:国内直连 GitHub 只有几十 KB/s,Gitee 通常能跑几 MB/s。+ # Gitee 附件单文件上限 100MB,所以 publish-gitee.js 会把便携包切成 .part1/.part2;+ # 应用端 updater 会自动识别分片、逐片选源下载再拼回整包。+ # Setup(1.4GB)与运行时整包(1.4GB)超限太多,只留在 GitHub ——+ # 应用端对「哪个源有资产」是取并集的,不影响更新。+ - name: 同步便携版到 Gitee+ env:+ GITEE_TOKEN: ${{ secrets.GITEE_TOKEN }}+ shell: pwsh+ run: |+ if (-not $env:GITEE_TOKEN) { Write-Output "未配置 GITEE_TOKEN,跳过 Gitee 同步"; exit 0 }+ $tag = "${{ github.ref_name }}"+ if (-not $tag.StartsWith('v')) { $tag = "v$tag" }+ node tools/publish-gitee.js $tag --zip "ApkStart-$tag-win64-portable.zip"+full:name: 构建完整版(内置运行时,离线开箱即用)runs-on: windows-latestdiff --git a/README.md b/README.mdindex 68d6622..0daf7eb 100644--- a/README.md+++ b/README.md@@ -35,19 +35,36 @@## 下载即用(不想编译)-到 [Releases](https://github.com/RoutineMiku/apkstart/releases) 下载安装包:+两个源内容一致,国内建议用 Gitee:++- GitHub:[github.com/RoutineMiku/apkstart/releases](https://github.com/RoutineMiku/apkstart/releases)+- Gitee:[gitee.com/daily-miku/apkstart/releases](https://gitee.com/daily-miku/apkstart/releases)(国内直连快得多)++安装包:- **`ApkStart-v*-Setup.exe`**(约 1.3 GB):**一个 EXE 包含全部运行时**(adb / Android Emulator / 系统镜像),装完首次启动自动把镜像展开到用户目录,**之后不再联网下载任何东西**。装到当前用户目录、不要求管理员权限。- 另有轻量版 `ApkStart-v*-win64-portable.zip`(约 100 MB):首次启动才在后台下载运行时。运行时的下载源就是**本项目的 GitHub Release**(`ApkStart-runtime-*.zip` 整包),不走 dl.google.com;整包拿不到时才自动退回官方源。-### 在线更新+### 在线更新(自动选较快的源)-设置 → **软件更新** → 「检查更新」,或托盘右键 → 「检查更新」。发现新版本后点「立即更新」即可:+设置 → **软件更新** → 「检查更新」,或托盘右键 → 「检查更新」。发现新版本后点「立即更新」即可。- 安装版下载 `ApkStart-v*-Setup.exe` 静默安装;- 轻量版下载 `ApkStart-v*-win64-portable.zip`,解压后覆盖**程序目录**——运行时目录(`%APPDATA%\apkstart\runtime`)、已装应用与快照都不在程序目录里,所以更新不会丢东西;- 替换动作由一段独立 PowerShell 脚本完成(等主进程退出 → 覆盖 → 重新拉起),**不会出现「请手动关闭程序」的弹窗**,也不会在桌面上残留模拟器窗口。+更新链路不是死连 GitHub,而是**每次现测现选**:++1. 同时问 GitHub 与 Gitee 的最新版本,取版本号更高的那个(一个源超时/被墙不影响另一个);+2. 把「源站直连 / Gitee 同名资产 / 镜像前缀」列成候选,每个地址真下 256KB 测速,+ 只算「收到首字节之后」的吞吐(握手时间不计入,否则高延迟大带宽的源会被误判成慢);+3. 按实测速度排序,用最快的那条分块并行下载;失败自动换下一条。++设置里的「下载与更新源」可以强制只用某一边(企业网络只放行一个域名时用),+也可以关掉公共加速镜像、或改用自建镜像前缀。Gitee 附件单文件上限 100MB,+所以便携包在 Gitee 上以 `.part1/.part2` 形式发布,客户端会自动拼装。++**开箱即有的默认行为**(不用去设置里找):- 开机自动启动,常驻托盘;双击桌面图标直接进应用。diff --git a/src/core/download.js b/src/core/download.jsindex bca5d13..bfbecf5 100644--- a/src/core/download.js+++ b/src/core/download.js@@ -283,6 +283,146 @@ async function downloadAny(urls, dest, opt = {}) {throw new Error(`所有下载源均失败:\n${errors.join('\n')}`);}+/**+ * 多源同时下载:把文件切成若干块,**不同块同时从不同源拉**,带宽叠加。+ *+ * 为什么需要:GitHub 单连接限速很常见,而镜像站通常也各自限速;+ * 8 条连接都指向同一个地址时,天花板就是那个地址的上限。把 4 条给 GitHub、+ * 4 条给镜像,两者上限相加,实测能快一倍以上。+ *+ * 安全前提:只有「声明总大小一致」的源才会被混用,否则可能拼出坏文件;+ * 任一源中途失败,它的分块会自动换到下一条可用地址重试(不整包重来)。+ */+async function downloadMulti(urls, dest, opt = {}) {+ const {+ connections = 8,+ onProgress = () => {},+ minChunk = 2 * 1024 * 1024,+ retries = 3,+ } = opt;++ const list = [...new Set((urls || []).filter(Boolean))];+ if (!list.length) throw new Error('没有可用的下载地址');+ if (list.length === 1) return downloadParallel(list[0], dest, opt);++ // 1) 并行探测:总大小 + 是否支持 Range+ const probes = await Promise.all(list.map(async (u) => {+ try {+ const res = await openStream(u, { headers: { Range: 'bytes=0-0' } });+ const cr = res.headers['content-range'];+ const total = res.statusCode === 206 && cr ? Number(/\/(\d+)$/.exec(cr)[1]) || 0 : 0;+ res.destroy();+ return { url: u, total, ranged: !!total };+ } catch (_) {+ return { url: u, total: 0, ranged: false };+ }+ }));++ const usable = probes.filter((p) => p.ranged && p.total > 0);+ if (!usable.length) {+ return downloadAnyParallel(list, dest, opt);+ }+ // 只保留「总大小和最大那一组一致」的源+ const total = Math.max(...usable.map((p) => p.total));+ const same = usable.filter((p) => p.total === total);+ if (same.length === 1 || total < minChunk * 2) {+ return downloadParallel(same[0].url, dest, opt);+ }++ // 2) 切块,轮转分配源+ const n = Math.max(2, Math.min(connections, Math.ceil(total / minChunk)));+ const per = Math.ceil(total / n);+ fs.mkdirSync(path.dirname(dest), { recursive: true });+ fs.rmSync(dest, { force: true });+ const fd = fs.openSync(dest, 'w');+ fs.ftruncateSync(fd, total);++ const chunks = Array.from({ length: n }, (_, i) => ({+ start: i * per,+ end: Math.min(total - 1, i * per + per - 1),+ pos: i * per,+ src: i % same.length,+ tries: 0,+ }));++ let got = 0;+ let lastTick = Date.now();+ let lastBytes = 0;+ const tick = (force) => {+ const now = Date.now();+ if (!force && now - lastTick < 400) return;+ const speed = (got - lastBytes) / Math.max(0.001, (now - lastTick) / 1000);+ lastTick = now;+ lastBytes = got;+ onProgress({+ got,+ total,+ percent: Math.min(100, (got / total) * 100),+ speed,+ eta: speed > 0 ? Math.max(0, (total - got) / speed) : null,+ sources: same.length,+ });+ };++ const fetchChunk = async (c) => {+ const url = same[c.src % same.length].url;+ const res = await openStream(url, { headers: { Range: `bytes=${c.pos}-${c.end}` } });+ if (res.statusCode !== 206) {+ res.resume();+ throw new Error(`分块被拒绝 HTTP ${res.statusCode}`);+ }+ await new Promise((resolve, reject) => {+ // 空闲看门狗:连接建立了但一个字节都不来(常见的「TCP 通但被墙/被限」),+ // 光等 socket 超时要 30 秒,一块卡住整包就停在那里。20 秒没动静就换源。+ let idle = setTimeout(() => res.destroy(new Error('连接停滞(20 秒无数据)')), 20000);+ const kick = () => { clearTimeout(idle); idle = setTimeout(() => res.destroy(new Error('连接停滞(20 秒无数据)')), 20000); };+ res.on('data', (buf) => {+ try {+ fs.writeSync(fd, buf, 0, buf.length, c.pos);+ } catch (e) {+ res.destroy();+ return reject(e);+ }+ c.pos += buf.length;+ got += buf.length;+ kick();+ tick(false);+ });+ res.on('end', () => { clearTimeout(idle); resolve(); });+ res.on('error', (e) => { clearTimeout(idle); reject(e); });+ });+ return c.pos > c.end;+ };++ try {+ await Promise.all(chunks.map(async (c) => {+ for (;;) {+ try {+ // eslint-disable-next-line no-await-in-loop+ if (await fetchChunk(c)) return;+ throw new Error('分块未完整返回');+ } catch (e) {+ c.tries += 1;+ if (c.tries >= retries) throw new Error(`分块失败(${c.start}-${c.end}):${e.message}`);+ // 换一个源再试:一个镜像抽风不该拖垮整个下载+ c.src += 1;+ // eslint-disable-next-line no-await-in-loop+ await new Promise((r) => setTimeout(r, 600 * c.tries));+ }+ }+ }));+ } catch (e) {+ fs.closeSync(fd);+ throw e;+ }+ fs.closeSync(fd);++ const size = fs.statSync(dest).size;+ tick(true);+ if (size !== total) throw new Error(`下载不完整:${size}/${total} 字节`);+ return { file: dest, size, parallel: n, sources: same.length, multi: true };+}+/** 依次尝试多个源(并行分块版),任一成功即返回 */async function downloadAnyParallel(urls, dest, opt = {}) {const errors = [];@@ -299,5 +439,5 @@ async function downloadAnyParallel(urls, dest, opt = {}) {}module.exports = {- download, downloadAny, downloadParallel, downloadAnyParallel, head, sha256File, openStream,+ download, downloadAny, downloadParallel, downloadAnyParallel, downloadMulti, head, sha256File, openStream,};diff --git a/src/core/provision.js b/src/core/provision.jsindex bc64314..adc6418 100644--- a/src/core/provision.js+++ b/src/core/provision.js@@ -11,7 +11,7 @@ const zlib = require('zlib');const { spawn, execFile } = require('child_process');const store = require('./store');const doctor = require('./doctor');-const { download, downloadAny, downloadAnyParallel, head } = require('./download');+const { download, downloadAny, downloadAnyParallel, downloadMulti, head } = require('./download');const { ZipArchive, ZipFile } = require('./zip');const { Sources } = require('./sources');const { cmpVer } = require('./version');@@ -526,7 +526,7 @@ class Provisioner {onProgress({ stage: 'download', message: `下载运行时(约 1.5 GB,只需一次,${conn} 线程)…`, percent: 2 });// 分块并行(8 线程)比单流快得多:GitHub 对单连接限速很常见,单流实测只有// 一两百 KB/s,8 线程能跑满本地带宽。中途断掉会退回单流续传。- await downloadAnyParallel(urls, zip, {+ await downloadMulti(urls, zip, {connections: conn,onProgress: (pr) => {const pct = pr.percent != null ? pr.percent : (total ? Math.round((pr.got / total) * 100) : 0);diff --git a/src/core/sources.js b/src/core/sources.jsindex a70b81e..37edfbb 100644--- a/src/core/sources.js+++ b/src/core/sources.js@@ -17,6 +17,7 @@const https = require('https');const http = require('http');const { URL } = require('url');+const { cmpVer } = require('./version');const OWNER_GH = 'RoutineMiku';const OWNER_GITEE = 'daily-miku';@@ -162,6 +163,43 @@ function withMirror(url, prefix) {return `${p}${url}`;}+/**+ * Gitee 发行版附件单文件上限 100MB,安装包 105~110MB 装不下,所以发布时切成+ * xxx.zip.part1 / xxx.zip.part2。这里把分片还原成一个逻辑资产:+ * { name: 'xxx.zip', size: 总和, parts: [{index, size, urls:[...]}] }+ * 分片必须从 part1 开始连续,否则视为残缺、丢弃(宁可用整包,也不下一个坏包)。+ */+function groupParts(assets) {+ const groups = new Map();+ const out = [];+ for (const a of assets) {+ const m = /^(.*)\.part(\d+)$/i.exec(String(a.name || ''));+ if (!m) { out.push(a); continue; }+ const base = m[1];+ const idx = Number(m[2]);+ let g = groups.get(base);+ if (!g) {+ g = { name: base, size: 0, parts: [], partial: true };+ groups.set(base, g);+ out.push(g);+ }+ let p = g.parts.find((x) => x.index === idx);+ if (!p) {+ p = { index: idx, size: Number(a.size) || 0, urls: [] };+ g.parts.push(p);+ }+ if (a.url && !p.urls.includes(a.url)) p.urls.push(a.url);+ if (!p.size) p.size = Number(a.size) || 0;+ }+ for (const g of groups.values()) {+ g.parts.sort((x, y) => x.index - y.index);+ const contiguous = g.parts.every((p, i) => p.index === i + 1);+ g.size = g.parts.reduce((n, p) => n + p.size, 0);+ if (!contiguous || !g.parts.every((p) => p.size > 0 && p.urls.length)) g.broken = true;+ }+ return { list: out.filter((a) => !a.broken), broken: [...groups.values()].filter((g) => g.broken).map((g) => g.name) };+}+/** mirrors 列表:用户自定义优先,其次内置(autoMirror 关掉就只用自定义的) */function mirrorList(settings) {const r = (settings && settings.runtime) || {};@@ -211,26 +249,21 @@ class Sources {const why = all.map((x) => `${x.name || x.source}: ${x.error || '无数据'}`).join(';');throw new Error(`连不上更新服务器(${why})`);}- const cmp = require('./updater').cmpVer;- ok.sort((a, b) => cmp(b.rel.tag_name || b.rel.name, a.rel.tag_name || a.rel.name));+ ok.sort((a, b) => cmpVer(b.rel.tag_name || b.rel.name, a.rel.tag_name || a.rel.name));const top = ok[0];const tag = String(top.rel.tag_name || top.rel.name || '');const version = tag.replace(/^v/i, '');- // 只有同版本的资产才算数(不同源的旧版本资产不能拿来装)- const assets = [];- const seen = new Set();+ // 只有同版本的资产才算数(不同源的旧版本资产不能拿来装)。+ // 同名整包 + 分片组同时存在时优先用整包:分片要拼装,多一个失败点。+ let raw = [];for (const item of ok) {const t = String(item.rel.tag_name || item.rel.name || '').replace(/^v/i, '');if (t !== version) continue;for (const a of (item.rel.assets || [])) {const key = String(a.name || '');- if (!key || seen.has(key)) {- // 同名资产保留第一个(按源顺序:先 GitHub 后 Gitee,或反之)- continue;- }- seen.add(key);- assets.push({+ if (!key) continue;+ raw.push({name: key,size: Number(a.size) || 0,url: a.browser_download_url || a.url || '',@@ -238,6 +271,16 @@ class Sources {});}}+ const grouped = groupParts(raw);+ const wholeNames = new Set(grouped.list.filter((a) => !a.partial).map((a) => a.name));+ raw = grouped.list.filter((a) => !(a.partial && wholeNames.has(a.name)));+ const assets = [];+ const seen = new Set();+ for (const a of raw) {+ if (seen.has(a.name)) continue;+ seen.add(a.name);+ assets.push(a);+ }return {version,diff --git a/src/core/updater.js b/src/core/updater.jsindex 926d3dc..8e0e2de 100644--- a/src/core/updater.js+++ b/src/core/updater.js@@ -17,7 +17,7 @@const fs = require('fs');const path = require('path');const { spawn } = require('child_process');-const { downloadAnyParallel } = require('./download');+const { downloadAnyParallel, downloadMulti } = require('./download');const { ZipFile } = require('./zip');const { cmpVer } = require('./version');const { Sources } = require('./sources');@@ -107,28 +107,37 @@ class Updater {fs.mkdirSync(dir, { recursive: true });const file = path.join(dir, it.asset.name);const total = it.asset.size || 0;-- this.onProgress({ stage: 'download', percent: 1, message: `正在下载 ${it.asset.name}…` });- // 候选地址 = 源站 + 镜像前缀;先各下 128KB 实测速度,再拿最快的那个分块下载。- // 这是「GitHub 直连几十 KB/s、镜像能跑几 MB/s」时唯一靠谱的选路方式:- // 按域名猜没用,同一天不同时段差别很大。const conns = Math.max(1, Math.min(16, Number((this.settings().runtime || {}).downloadConnections) || 8));- const cands = this.sources.candidates(it.asset);- const ranked = await this.sources.rank(cands, { onProgress: (p) => this.onProgress(p) }).catch(() => cands);- await downloadAnyParallel(ranked, file, {- connections: conns,- onProgress: (pr) => {- const pct = pr.percent != null ? pr.percent : (total ? Math.round((pr.got / total) * 100) : 0);- const mb = `${(pr.got / 1048576).toFixed(1)} MB${total ? ` / ${(total / 1048576).toFixed(1)} MB` : ''}`;- const sp = Number(pr.speed) > 0 ? ` · ${(pr.speed / 1048576).toFixed(2)} MB/s` : '';- this.onProgress({- stage: 'download',- percent: Math.max(1, Math.min(99, pct)),- message: `下载中 ${mb}${sp}`,- speed: pr.speed,- });- },- });++ // Gitee 附件单文件上限 100MB,所以发布时会把包切成 .part1/.part2。+ // 每个分片单独测速选源(可以一部分来自 Gitee、一部分来自 GitHub 镜像),+ // 下完按顺序拼回整包 —— 对用户来说仍然只是「下载 + 解压」。+ if (it.asset.parts && it.asset.parts.length) {+ await this._downloadParts(it.asset, file, conns, total);+ } else {+ this.onProgress({ stage: 'download', percent: 1, message: `正在下载 ${it.asset.name}…` });+ // 候选地址 = 源站 + 镜像前缀;先各下 256KB 实测速度,再拿最快的那个分块下载。+ // 这是「GitHub 直连几十 KB/s、镜像能跑几 MB/s」时唯一靠谱的选路方式:+ // 按域名猜没用,同一天不同时段差别很大。+ const cands = this.sources.candidates(it.asset);+ const ranked = await this.sources.rank(cands, { onProgress: (p) => this.onProgress(p) }).catch(() => cands);+ // downloadMulti:分块同时从「GitHub 直连」和「镜像」拉,带宽叠加;+ // 只有一个源可用或对方不支持 Range 时,它自己退回单源分块。+ await downloadMulti(ranked, file, {+ connections: conns,+ onProgress: (pr) => {+ const pct = pr.percent != null ? pr.percent : (total ? Math.round((pr.got / total) * 100) : 0);+ const mb = `${(pr.got / 1048576).toFixed(1)} MB${total ? ` / ${(total / 1048576).toFixed(1)} MB` : ''}`;+ const sp = Number(pr.speed) > 0 ? ` · ${(pr.speed / 1048576).toFixed(2)} MB/s` : '';+ this.onProgress({+ stage: 'download',+ percent: Math.max(1, Math.min(99, pct)),+ message: `下载中 ${mb}${sp}`,+ speed: pr.speed,+ });+ },+ });+ }if (/\.zip$/i.test(file)) {const out = path.join(dir, 'payload');@@ -142,6 +151,57 @@ class Updater {return { mode: 'setup', payload: file, version: it.version };}+ /**+ * 下载并拼装分片包。+ * @param {{name:string, size:number, parts:Array<{index:number,size:number,urls:string[]}>}} asset+ */+ async _downloadParts(asset, target, conns, total) {+ const dir = path.dirname(target);+ let doneBytes = 0;+ const fd = fs.openSync(target, 'w');+ try {+ for (const part of asset.parts) {+ const tmp = path.join(dir, `${asset.name}.${part.index}.tmp`);+ const cands = [];+ for (const u of part.urls) {+ for (const c of this.sources.candidates(u)) if (!cands.includes(c)) cands.push(c);+ }+ // eslint-disable-next-line no-await-in-loop+ const ranked = await this.sources.rank(cands, {+ onProgress: (p) => this.onProgress({ ...p, percent: Math.max(1, Math.min(99, Math.round((doneBytes / (total || 1)) * 100))) }),+ }).catch(() => cands);+ // eslint-disable-next-line no-await-in-loop+ await downloadAnyParallel(ranked, tmp, {+ connections: conns,+ onProgress: (pr) => {+ const got = doneBytes + (pr.got || 0);+ const pct = total ? Math.round((got / total) * 100) : 0;+ const sp = Number(pr.speed) > 0 ? ` · ${(pr.speed / 1048576).toFixed(2)} MB/s` : '';+ this.onProgress({+ stage: 'download',+ percent: Math.max(1, Math.min(99, pct)),+ message: `下载中 ${(got / 1048576).toFixed(1)} MB${total ? ` / ${(total / 1048576).toFixed(1)} MB` : ''}`+ + `(第 ${part.index}/${asset.parts.length} 片)${sp}`,+ speed: pr.speed,+ });+ },+ });+ const buf = fs.readFileSync(tmp);+ if (part.size && buf.length !== part.size) {+ throw new Error(`分片 ${part.index} 大小不对(${buf.length} ≠ ${part.size}),已中止,可重试`);+ }+ fs.writeSync(fd, buf, 0, buf.length, doneBytes);+ doneBytes += buf.length;+ fs.rmSync(tmp, { force: true });+ }+ } finally {+ fs.closeSync(fd);+ }+ if (total && doneBytes !== total) {+ throw new Error(`更新包拼装后大小不对(${doneBytes} ≠ ${total}),已中止,可重试`);+ }+ }+async _extract(zipPath, dest) {const zf = new ZipFile(zipPath);try {diff --git a/src/main.js b/src/main.jsindex 2840d11..815506c 100644--- a/src/main.js+++ b/src/main.js@@ -411,6 +411,14 @@ function createWindow({ show = true } = {}) {mainWindow.loadFile(path.join(__dirname, 'ui', 'index.html'));if (show) mainWindow.once('ready-to-show', () => mainWindow.show());+ // 冒烟测试时把渲染进程的报错打到 stdout:界面空白、按钮点了没反应,+ // 十有八九是 app.js 里某个 id 改动后抛了异常,正常运行看不到。+ if (process.argv.includes('--smoke')) {+ mainWindow.webContents.on('console-message', (_e, level, message, line, source) => {+ if (level >= 2) console.log(`[renderer] ${message} (${String(source).split('/').pop()}:${line})`);+ });+ }+// 外链一律交给系统浏览器(公众号/GitHub 等),绝不把应用窗口导航走mainWindow.webContents.setWindowOpenHandler(({ url }) => {if (/^https?:\/\//i.test(url)) shell.openExternal(url);@@ -1693,6 +1701,13 @@ if (!gotLock) {);await snap(out.replace(/\.png$/i, '-perf.png'));}+ if (process.argv.includes('--download')) {+ // 拍一张「下载与更新源」区+ await mainWindow.webContents.executeJavaScript(+ "document.getElementById('downloadGroup').scrollIntoView({ block: 'start' }); true;",+ );+ await snap(out.replace(/\.png$/i, '-download.png'));+ }if (process.argv.includes('--settings')) {// 再拍一张「关于」区(二维码 / GitHub / Powered by)await mainWindow.webContents.executeJavaScript(diff --git a/src/ui/app.js b/src/ui/app.jsindex 8371316..06f3105 100644--- a/src/ui/app.js+++ b/src/ui/app.js@@ -447,7 +447,7 @@ async function markInstalled() {/* ---------------- 安装 ---------------- */-async /** 把安装失败翻译成「下一步该做什么」,只对最常见的几种做提示,其它原样显示 */+/** 把安装失败翻译成「下一步该做什么」,只对最常见的几种做提示,其它原样显示 */function friendlyInstallErrorText(msg) {const s = String(msg || '未知错误');if (/INSUFFICIENT_STORAGE|not enough space|空间不足|ENOSPC/i.test(s)) {diff --git a/src/ui/index.html b/src/ui/index.htmlindex a5a4427..798bfda 100644--- a/src/ui/index.html+++ b/src/ui/index.html@@ -323,6 +323,36 @@</div></div>+ <div class="group" id="downloadGroup">+ <div class="group-title">下载与更新源</div>+ <div class="field">+ <label>更新与下载源</label>+ <select id="setSourcePref">+ <option value="auto">自动选择较快的源(推荐)</option>+ <option value="gitee">只用 Gitee(国内通常最快)</option>+ <option value="github">只用 GitHub</option>+ </select>+ <span class="sub">「自动」会同时问 GitHub 与 Gitee 的最新版本,把每个下载地址都真下 256KB 测一次速度,再从最快的那个地址下载;其中一个源不通不影响更新。</span>+ </div>+ <div class="field switch-field">+ <div>+ <label>自动尝试公共加速镜像</label>+ <span class="sub">GitHub 直连太慢时,额外测速 ghfast.top / gh-proxy.com 这两个公开转发服务(只转发公开的发布文件,不涉及账号)。关掉后只用直连和你自己填的前缀。</span>+ </div>+ <input type="checkbox" id="setAutoMirror" class="switch" />+ </div>+ <div class="field">+ <label>下载镜像前缀(可选,加速 GitHub)</label>+ <input id="setMirrorPrefix" type="text" placeholder="例如 https://ghfast.top/" />+ <span class="sub">填了就只用你填的前缀,不再尝试上面那两个公共镜像;留空则由「自动」逻辑决定。下载器会把它拼在真实地址前面。</span>+ </div>+ <div class="field">+ <label>下载线程数(1–16,默认 8)</label>+ <input id="setConnections" type="number" min="1" max="16" step="1" />+ <span class="sub">大文件按块并行下载。默认 8 线程已经能跑满大多数家宽;网络稳定时可以试 16。</span>+ </div>+ </div>+<details class="advanced-group"><summary>高级参数(一般无需修改)</summary><div class="group">@@ -363,32 +393,6 @@<label>空闲回收(分钟,0 = 不回收)</label><input id="setIdle" type="number" min="0" step="1" /></div>- <div class="field">- <label>更新与下载源</label>- <select id="setSourcePref">- <option value="auto">自动选择较快的源(推荐)</option>- <option value="gitee">只用 Gitee(国内通常最快)</option>- <option value="github">只用 GitHub</option>- </select>- <span class="sub">「自动」会同时问 GitHub 与 Gitee 的最新版本,把每个下载地址都真下 256KB 测一次速度,再从最快的那个地址下载;其中一个源不通不影响更新。</span>- </div>- <div class="field switch-field">- <div>- <label>自动尝试公共加速镜像</label>- <span class="sub">GitHub 直连太慢时,额外测速 ghfast.top / gh-proxy.com 这两个公开转发服务(只转发公开的发布文件,不涉及账号)。关掉后只用直连和你自己填的前缀。</span>- </div>- <input type="checkbox" id="setAutoMirror" class="switch" />- </div>- <div class="field">- <label>下载镜像前缀(可选,加速 GitHub)</label>- <input id="setMirrorPrefix" type="text" placeholder="例如 https://ghfast.top/" />- <span class="sub">填了就只用你填的前缀,不再尝试上面那两个公共镜像;留空则由「自动」逻辑决定。下载器会把它拼在真实地址前面。</span>- </div>- <div class="field">- <label>下载线程数(1–16,默认 8)</label>- <input id="setConnections" type="number" min="1" max="16" step="1" />- <span class="sub">大文件按块并行下载。默认 8 线程已经能跑满大多数家宽;网络稳定时可以试 16。</span>- </div><div class="field switch-field"><div><label>通用兼容镜像(自动管理)</label>diff --git a/test/auto-test.js b/test/auto-test.jsindex 4509c00..3e5cba5 100644--- a/test/auto-test.js+++ b/test/auto-test.js@@ -873,6 +873,112 @@ const { AdbClient, friendlyInstallError, friendlyLaunchError } = require('../srcassert(m.assets.length === 1 && m.assets[0].url === 'gh://a', '旧版本同名资产不能覆盖新版本');});+ await test('分片更新包:按顺序拼回整包,大小不符立刻中止', async () => {+ const http = require('http');+ const { Updater } = require('../src/core/updater');+ const partA = Buffer.alloc(4096, 0x41);+ const partB = Buffer.alloc(2048, 0x42);+ const srv = http.createServer((req, res) => {+ if (req.url.startsWith('/a')) { res.writeHead(200, { 'Content-Length': partA.length }); res.end(partA); return; }+ if (req.url.startsWith('/b')) { res.writeHead(200, { 'Content-Length': partB.length }); res.end(partB); return; }+ res.writeHead(404); res.end();+ });+ await new Promise((r) => srv.listen(0, '127.0.0.1', r));+ const port = srv.address().port;+ const sb = path.join(TMP, 'parts-upd');+ fs.mkdirSync(sb, { recursive: true });+ const u = new Updater({ currentVersion: '0.0.0', exePath: path.join(sb, 'A.exe'), isPackaged: true, dataDir: sb, settings: () => ({}) });+ const target = path.join(sb, 'joined.zip');+ try {+ await u._downloadParts({+ name: 'joined.zip',+ size: partA.length + partB.length,+ parts: [+ { index: 1, size: partA.length, urls: [`http://127.0.0.1:${port}/a`] },+ { index: 2, size: partB.length, urls: [`http://127.0.0.1:${port}/b`] },+ ],+ }, target, 2, partA.length + partB.length);+ const got = fs.readFileSync(target);+ assert(got.length === partA.length + partB.length, '拼装后大小必须等于各分片之和');+ assert(got.slice(0, partA.length).every((b) => b === 0x41), '第一片内容顺序错误');+ assert(got.slice(partA.length).every((b) => b === 0x42), '第二片内容顺序错误');+ } finally {+ srv.close();+ fs.rmSync(sb, { recursive: true, force: true });+ }+ });++ await test('多源并行下载:不同分块从不同源拉,拼出来的字节必须完全一致', async () => {+ const http = require('http');+ const { downloadMulti } = require('../src/core/download');+ const data = Buffer.alloc(3 * 1024 * 1024);+ for (let i = 0; i < data.length; i += 1) data[i] = i % 251;+ const handler = (req, res) => {+ const r = /bytes=(\d+)-(\d+)/.exec(req.headers.range || '');+ if (!r) { res.writeHead(200, { 'Content-Length': data.length }); res.end(data); return; }+ const a = Number(r[1]);+ const b = Math.min(Number(r[2]), data.length - 1);+ res.writeHead(206, {+ 'Content-Range': `bytes ${a}-${b}/${data.length}`,+ 'Content-Length': b - a + 1,+ });+ res.end(data.slice(a, b + 1));+ };+ // 显式等 listening 回调:先 listen 再挂事件监听会漏掉已经触发的事件,测试会挂住+ const mk = () => new Promise((resolve) => {+ const srv = http.createServer(handler);+ srv.listen(0, '127.0.0.1', () => resolve(srv));+ });+ const s1 = await mk();+ const s2 = await mk();+ const urls = [+ `http://127.0.0.1:${s1.address().port}/f`,+ `http://127.0.0.1:${s2.address().port}/f`,+ ];+ const out = path.join(TMP, 'multi.bin');+ try {+ const r = await downloadMulti(urls, out, { connections: 6, minChunk: 512 * 1024 });+ const got = fs.readFileSync(out);+ assert(Buffer.compare(got, data) === 0, '多源拼装后内容必须与源文件完全一致');+ assert(r.sources === 2 && r.parallel >= 2, `应同时用到 2 个源,实际 ${JSON.stringify(r)}`);+ assert(got.length === data.length, '大小必须一致');+ } finally {+ s1.close(); s2.close();+ fs.rmSync(out, { force: true });+ }+ });++ await test('多源并行下载:只有一条可用地址时退回单源分块', async () => {+ const http = require('http');+ const { downloadMulti } = require('../src/core/download');+ const data = Buffer.alloc(2 * 1024 * 1024, 7);+ const srv = http.createServer((req, res) => {+ const r = /bytes=(\d+)-(\d+)/.exec(req.headers.range || '');+ if (!r) { res.writeHead(200, { 'Content-Length': data.length }); res.end(data); return; }+ const a = Number(r[1]);+ const b = Math.min(Number(r[2]), data.length - 1);+ res.writeHead(206, { 'Content-Range': `bytes ${a}-${b}/${data.length}`, 'Content-Length': b - a + 1 });+ res.end(data.slice(a, b + 1));+ });+ await new Promise((r) => srv.listen(0, '127.0.0.1', r));+ const url = `http://127.0.0.1:${srv.address().port}/f`;+ // 拿一个「刚被释放、现在肯定没人监听」的端口当坏源,连接会立刻被拒而不是等超时+ const probe = http.createServer(() => {});+ await new Promise((r) => probe.listen(0, '127.0.0.1', r));+ const deadPort = probe.address().port;+ await new Promise((r) => probe.close(r));+ const out = path.join(TMP, 'multi1.bin');+ try {+ // 第二个地址故意指到不通的端口:必须自动忽略而不是整包失败+ const r = await downloadMulti([url, `http://127.0.0.1:${deadPort}/nope`], out, { connections: 4 });+ assert(fs.statSync(out).size === data.length, '单源也要下完整');+ assert(!r.multi || r.sources === 1, '可用源只有一个时不该标记为多源');+ } finally {+ srv.close();+ fs.rmSync(out, { force: true });+ }+ });+console.log('\n[资源策略 / 磁盘分配 / 日志上限]');await test('资源策略一处切换,自动翻译成 vCPU/优先级/分辨率', () => {diff --git a/tools/check-sources.js b/tools/check-sources.jsnew file mode 100644index 0000000..e5c5885--- /dev/null+++ b/tools/check-sources.js@@ -0,0 +1,81 @@+'use strict';+/**+ * 双源自检:一条命令看清「两个源各自的最新版本」和「每个下载地址的实测速度」。+ *+ * node tools/check-sources.js # 检查更新包+ * node tools/check-sources.js runtime # 检查运行时整包+ *+ * 会真下 256KB,所以会消耗一点流量;目的是在动手改代码之前先确认+ * 「现在这台机器到底该走哪个源」。+ */+const fs = require('fs');+const os = require('os');+const path = require('path');++const TMP = fs.mkdtempSync(path.join(os.tmpdir(), 'apk-sources-'));+process.env.APPDATA = TMP;++const { Sources } = require('../src/core/sources');+const store = require('../src/core/store');+const { Provisioner } = require('../src/core/provision');++const mb = (n) => (n / 1048576).toFixed(2);+const host = (u) => { try { return new URL(u).host; } catch (_) { return u.slice(0, 40); } };++(async () => {+ const which = (process.argv[2] || 'update').toLowerCase();+ const sources = new Sources(() => store.getSettings());++ console.log('=== 1) 两个源的发布信息 ===');+ const rels = await sources.fetchReleases();+ for (const r of rels) {+ if (r.rel) {+ const assets = (r.rel.assets || []).length;+ console.log(` ${r.name.padEnd(7)} ${String(r.rel.tag_name || r.rel.name || '').padEnd(10)} 资产 ${assets} 个`);+ } else {+ console.log(` ${r.name.padEnd(7)} 不可达:${r.error}`);+ }+ }++ console.log('\n=== 2) 合并结果 ===');+ const merged = await sources.latest();+ console.log(` 最高版本 ${merged.tag}(${merged.assets.length} 个资产)`);+ for (const a of merged.assets) {+ console.log(` · ${a.name} ${(a.size / 1048576).toFixed(0)}MB [${a.source}]`);+ }++ console.log('\n=== 3) 实测每个下载地址的速度 ===');+ let target = null;+ if (which === 'runtime') {+ const p = new Provisioner(path.resolve(__dirname, '..'));+ const pack = await p.resolveRuntimePack().catch((e) => { console.log(' 解析失败:', e.message); return null; });+ if (pack) {+ console.log(` 运行时整包 ${pack.name}(${pack.tag} · ${pack.from || '?'})`);+ target = pack.url;+ }+ } else {+ const pick = merged.assets.find((a) => /portable.*\.zip$/i.test(a.name)) || merged.assets[0];+ if (pick) {+ console.log(` 更新包 ${pick.name}`);+ target = pick.url;+ }+ }+ if (!target) {+ console.log(' 没有可测的资产');+ } else {+ const cands = sources.candidates(target);+ for (const c of cands) console.log(` ${host(c).padEnd(22)} ${c === target ? '(直连)' : '(镜像)'}`);+ const t0 = Date.now();+ const ranked = await sources.rank(cands, { onProgress: (p) => console.log(' ·', p.message) });+ console.log(` 测速耗时 ${Date.now() - t0}ms,最终顺序:`);+ ranked.forEach((u, i) => {+ const c = sources._rankCache.get(u) || {};+ console.log(` ${i + 1}. ${host(u).padEnd(22)} ${c.ok ? `${mb(c.speed)} MB/s` : '不可用'}`);+ });+ }++ try { fs.rmSync(TMP, { recursive: true, force: true }); } catch (_) { /* ignore */ }+})().catch((e) => {+ console.error('失败:', e.message);+ process.exit(1);+});diff --git a/tools/publish-gitee.js b/tools/publish-gitee.jsnew file mode 100644index 0000000..b73a428--- /dev/null+++ b/tools/publish-gitee.js@@ -0,0 +1,134 @@+'use strict';+/**+ * 把一版发布同步到 Gitee。+ *+ * 为什么需要这个脚本:Gitee 发行版附件单文件上限 100MB,而便携包约 105MB,+ * 所以发布时切成 `xxx.zip.part1` / `.part2`(各 ≤95MB),应用端 updater 会自动+ * 识别分片、逐片选源下载再拼回整包。安装版 Setup(1.4GB)与运行时整包(1.4GB)+ * 超限太多,继续留在 GitHub —— 应用端对「哪个源有资产」是并集处理,不影响更新。+ *+ * 用法:+ * GITEE_TOKEN=xxxx node tools/publish-gitee.js v0.3.3 D:/dist+ * v0.3.3 要发布的 tag(必须是已推送到 Gitee 的 tag)+ * D:/dist 目录里放 ApkStart-v0.3.3-win64-portable.zip(可选,也可用 --zip 指定)+ *+ * node tools/publish-gitee.js v0.3.3 --zip D:/x.zip --notes notes.md+ */+const fs = require('fs');+const path = require('path');++const OWNER = 'daily-miku';+const REPO = 'apkstart';+const API = `https://gitee.com/api/v5/repos/${OWNER}/${REPO}`;+const PART_LIMIT = 95 * 1024 * 1024; // 留 5MB 余量给 multipart 头++function arg(name, def = '') {+ const i = process.argv.indexOf(name);+ return i > 0 ? process.argv[i + 1] : def;+}++async function api(method, p, body) {+ const token = process.env.GITEE_TOKEN;+ if (!token) throw new Error('缺少环境变量 GITEE_TOKEN');+ const url = `${API}${p}${p.includes('?') ? '&' : '?'}access_token=${encodeURIComponent(token)}`;+ const res = await fetch(url, {+ method,+ headers: body ? { 'Content-Type': 'application/json' } : undefined,+ body: body ? JSON.stringify(body) : undefined,+ });+ const text = await res.text();+ let json = null;+ try { json = JSON.parse(text); } catch (_) { /* 可能是空响应 */ }+ if (!res.ok) throw new Error(`${method} ${p} → ${res.status} ${text.slice(0, 300)}`);+ return json || {};+}++/** 切分大文件;返回切成后的路径数组 */+function splitFile(file, limit) {+ const size = fs.statSync(file).size;+ if (size <= limit) return [];+ const fd = fs.openSync(file, 'r');+ const out = [];+ try {+ let index = 1;+ let offset = 0;+ while (offset < size) {+ const len = Math.min(limit, size - offset);+ const buf = Buffer.alloc(len);+ fs.readSync(fd, buf, 0, len, offset);+ const p = `${file}.part${index}`;+ fs.writeFileSync(p, buf);+ out.push(p);+ offset += len;+ index += 1;+ }+ } finally {+ fs.closeSync(fd);+ }+ return out;+}++async function upload(releaseId, file) {+ const token = process.env.GITEE_TOKEN;+ const buf = fs.readFileSync(file);+ const fd = new FormData();+ fd.append('access_token', token);+ fd.append('file', new Blob([buf]), path.basename(file));+ const res = await fetch(`${API}/releases/${releaseId}/attach_files`, { method: 'POST', body: fd });+ const text = await res.text();+ if (!res.ok) throw new Error(`上传 ${path.basename(file)} 失败:${res.status} ${text.slice(0, 200)}`);+ return JSON.parse(text);+}++(async () => {+ const tag = process.argv[2];+ if (!tag || !/^v\d/.test(tag)) {+ console.error('用法:GITEE_TOKEN=xxx node tools/publish-gitee.js v0.3.3 [--zip 路径] [--notes 文件]');+ process.exit(1);+ }+ const dir = process.argv[3] && !process.argv[3].startsWith('--') ? process.argv[3] : '';+ let zip = arg('--zip', '');+ if (!zip && dir) {+ const hit = fs.existsSync(dir)+ ? fs.readdirSync(dir).find((n) => /portable\.zip$/i.test(n))+ : '';+ if (hit) zip = path.join(dir, hit);+ }+ if (!zip || !fs.existsSync(zip)) {+ console.error(`找不到便携包:${zip || '(未指定)'}。用 --zip 指定,或把 zip 放进 ${dir}`);+ process.exit(1);+ }+ const notesFile = arg('--notes', '');+ const body = notesFile && fs.existsSync(notesFile)+ ? fs.readFileSync(notesFile, 'utf8')+ : `便携版安装包(分片,应用内自动更新会自己拼装)。完整安装版与运行时整包在 GitHub Releases。`;++ console.log('1) 查找/创建发行版', tag);+ const list = await api('GET', `/releases?per_page=50`);+ let rel = (Array.isArray(list) ? list : []).find((r) => r.tag_name === tag);+ if (!rel) {+ rel = await api('POST', '/releases', {+ tag_name: tag,+ name: tag,+ target_commitish: 'main',+ body,+ });+ console.log(' 已创建 id =', rel.id);+ } else {+ console.log(' 已存在 id =', rel.id);+ }++ console.log('2) 切分便携包(Gitee 单文件上限 100MB)');+ const parts = splitFile(zip, PART_LIMIT);+ const files = parts.length ? parts : [zip];+ for (const f of files) {+ console.log(` 上传 ${path.basename(f)} (${(fs.statSync(f).size / 1048576).toFixed(1)} MB)`);+ // eslint-disable-next-line no-await-in-loop+ await upload(rel.id, f);+ }+ for (const p of parts) fs.rmSync(p, { force: true });+ console.log(`\n完成:https://gitee.com/${OWNER}/${REPO}/releases/tag/${tag}`);+})().catch((e) => {+ console.error('失败:', e.message);+ process.exit(1);+});