Files
piik/scripts/mirror-release.mjs
T
AAA 815f1a07c4 fix(media): stabilize sharing recovery and remote input (#513)
## Problem and outcome

Connection recovery and packet repair could leave stale pictures, missing sound or unreliable remote input. This maintenance release repairs media/route ownership, H.264 negotiation, voice forwarding and Windows input recovery, and makes shared mobile controls and popovers easier to use.

## Release notes
**Piik, now in your pocket.**

Piik App supports Android screen sharing, with touch controls for a friend's computer.

**手机,也能开播。**

Piik App 支持 Android 屏幕分享,也能用手机控制朋友的电脑。

### English

Piik v2.5.1 improves sharing recovery, voice playback and remote control, with clearer mobile controls. It keeps the existing 2.x compatibility baseline.

- Improve H.264 selection and picture recovery after reconnecting, changing sources or recovering lost packets; keep a working share when a replacement source fails.
- Keep audio and room voice continuous, and prevent duplicate sound when switching playback windows.
- Improve Windows input recovery and release remote-control permissions when their connection ends.
- Keep mobile controls together and popovers usable after layout changes or in short viewports.
- Open the appropriate Android update download, including the Gitee ZIP containing the APK. Self-hosted SFU servers refresh public addresses for new connections without a restart.
- Add macOS source-thumbnail support.

Update the App and self-hosted site together to receive all fixes. Browser settings and existing room data are retained.

### 中文

Piik v2.5.1 改善分享恢复、语音播放与远程控制的稳定性,让手机操作更顺手,沿用现有 2.x 兼容基线。

- 改善 H.264 编码选择,以及重连、切换分享源和丢包后的画面恢复;新分享源切换失败时保留正常分享。
- 保持声音与房间语音连续,避免切换播放窗口时出现双重声音。
- 改善 Windows 输入恢复,并在连接结束时释放远程控制授权。
- 手机控件保持成组,浮层在布局变化或可见高度较小时仍可操作。
- Android 更新打开对应下载入口,Gitee 提供内含 APK 的 ZIP;自部署 SFU 为新连接刷新公网地址,无需重启服务。
- 补齐 macOS 选源缩略图支持。

请一起更新 App 与自部署站点,以获得全部修复。浏览器设置与已有房间数据保留。
## Validation

- Full frontend typecheck, test and production-build acceptance; current Windows App/Server packaging, extracted-file checks and exact served JavaScript verified locally.
- Existing Go, vulnerability, native media and controlled-network results retained at their tested revisions. The final production delta from the fully checked candidate is the shared short-viewport popover correction.
- The diagnostic report supplied for #502 informed the Windows input fixes. #500 sharing is confirmed working; its missing source previews are implemented. Original-device follow-up remains separate from this release's verified local fixes.

## Compatibility and scope

Preserves the published 2.x Browser/server, Native control, capture and SQLite contracts. No 3.0 or iOS implementation or external contributor patch is included. Related: #500, #502, #510, #512.
2026-10-31 16:34:12 -04:00

150 lines
7.7 KiB
JavaScript

import { execFileSync } from "node:child_process";
import { createHash } from "node:crypto";
import { openAsBlob } from "node:fs";
import { setTimeout as delay } from "node:timers/promises";
import { readReleaseArtifacts } from "./release-artifacts.mjs";
const [directory, version, revision, option] = process.argv.slice(2);
if (option && option !== "--dry-run") {
throw new Error("Use mirror-release.mjs <artifacts> <version> <full-SHA> [--dry-run]");
}
const { mirrorFiles: files } = readReleaseArtifacts(directory, version, revision);
if (files.some((file) => file.size > 100_000_000)) throw new Error("Gitee's 100 MB attachment limit is exceeded");
const repository = "TNTcraftHIM/Piik";
const api = `https://gitee.com/api/v5/repos/${repository}`;
const marker = `<!-- piik-source: ${revision} -->`;
const token = process.env.GITEE_TOKEN?.trim();
function requireLatestSource() {
const latest = JSON.parse(execFileSync("gh", ["api", `repos/${repository}/releases/latest`],
{ encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 30_000 }));
if (latest.tag_name !== version || latest.target_commitish !== revision ||
latest.draft !== false || latest.prerelease !== false) {
throw new Error("Only the latest GitHub release may create or complete a Gitee mirror");
}
}
async function fetchResponse(url, options, timeout, consume) {
const attempts = (options.method ?? "GET") === "GET" ? 3 : 1;
for (let attempt = 1; ; attempt++) {
const signal = AbortSignal.timeout(timeout);
let response;
try {
response = await fetch(url, { ...options, signal });
// Receiving headers is not a completed read. Keep JSON decoding and the
// entire anonymous package/hash verification inside the same retry bound.
if (attempt === attempts || ![408, 429, 500, 502, 503, 504].includes(response.status)) {
return await consume(response);
}
} catch (error) {
if (attempt === attempts || !(signal.aborted || error instanceof TypeError || error?.name === "TimeoutError")) {
throw new Error(`Gitee ${options.method ?? "GET"} ${new URL(url).pathname}: ${error.message}`);
}
} finally {
if (response?.body && !response.bodyUsed) await response.body.cancel().catch(() => {});
}
console.log(`Retry Gitee read ${new URL(url).pathname}: ${attempt + 1}/${attempts}`);
await delay(attempt * 1_000);
}
}
async function request(path, method = "GET", body) {
const multipart = body instanceof FormData;
console.log(`Gitee ${method} ${path}`);
// A timed-out upload may already exist. Retry only reads; a script rerun
// reconciles attachment identities before any subsequent write.
return fetchResponse(api + path, {
method, redirect: "error",
headers: { Accept: "application/json", Authorization: `Bearer ${token}`,
...(!body || multipart ? {} : { "Content-Type": "application/json" }) },
body: body ? multipart ? body : JSON.stringify(body) : undefined,
}, multipart ? 180_000 : 20_000, async response => {
if (response.status === 404 && method === "GET") return null;
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
});
}
// Verify anonymously: credentials are never forwarded to attachment redirects.
async function verifyDownload(uploaded, file) {
const expectedURL = `https://gitee.com/${repository}/releases/download/${version}/${file.name}`;
if (uploaded?.size !== file.size || uploaded.browser_download_url !== expectedURL) {
throw new Error(`Mirror attachment metadata mismatch: ${file.name}`);
}
console.log(`Verify Gitee package: ${file.name} (${file.size} bytes)`);
await fetchResponse(expectedURL, {}, 180_000, async response => {
if (!response.ok || !response.body) throw new Error(`Mirror attachment is not anonymously downloadable: ${file.name}`);
const hash = createHash("sha256");
let size = 0;
for await (const chunk of response.body) {
size += chunk.length;
if (size > file.size) throw new Error(`Mirror attachment size mismatch: ${file.name}`);
hash.update(chunk);
}
if (size !== file.size || hash.digest("hex") !== file.sha256) {
throw new Error(`Mirror attachment checksum mismatch: ${file.name}`);
}
});
}
if (option === "--dry-run") {
console.log(JSON.stringify({ version, revision, files: files.length, bytes: files.reduce((sum, file) => sum + file.size, 0) }));
} else {
if (!token) throw new Error("GITEE_TOKEN must be supplied by the publisher's environment");
const source = JSON.parse(execFileSync("gh", ["api", `repos/${repository}/releases/tags/${version}`],
{ encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }));
if (source.draft !== false || source.prerelease !== false || source.tag_name !== version || source.target_commitish !== revision ||
source.html_url !== `https://github.com/${repository}/releases/tag/${version}`) {
throw new Error("Only an already-published matching GitHub stable release can be mirrored");
}
// Compare every byte identity with GitHub before creating or changing the mirror.
for (const file of files) {
const asset = source.assets.find((asset) => asset.name === file.name);
if (asset?.state !== "uploaded" || asset.size !== file.size || asset.digest !== `sha256:${file.sha256}`) {
throw new Error(`GitHub attachment checksum mismatch or unavailable: ${file.name}`);
}
}
let release = await request(`/releases/tags/${version}`);
if (release && (release.tag_name !== version ||
(release.prerelease !== false && release.prerelease !== true) ||
!release.body?.split(/\r?\n/).includes(marker))) {
throw new Error("Existing mirror release belongs to a different or unknown source revision");
}
const body = `${source.body ?? ""}\n\nSource: https://github.com/${repository}/commit/${revision}\n\n${marker}\n`;
if (!release || release.prerelease) requireLatestSource();
if (!release) {
const repo = await request("");
if (!repo || repo.private || !repo.default_branch) throw new Error("A public initialized Gitee mirror is required");
release = await request("/releases", "POST", {
tag_name: version, name: source.name || `Piik ${version}`, body, prerelease: true,
target_commitish: repo.default_branch,
});
}
if (!Number.isSafeInteger(release.id) || release.id <= 0) throw new Error("Invalid Gitee release identity");
const attachments = await request(`/releases/${release.id}/attach_files?per_page=100`);
if (!Array.isArray(attachments) || attachments.length >= 100) throw new Error("Unexpected mirror attachment list");
for (const file of files) {
let uploaded = attachments.find((asset) => asset.name === file.name);
if (!uploaded) {
if (!release.prerelease) throw new Error("Published mirror is incomplete; publish a corrected new version");
console.log(`Upload Gitee package: ${file.name} (${file.size} bytes)`);
const form = new FormData();
form.append("file", await openAsBlob(file.path), file.name);
uploaded = await request(`/releases/${release.id}/attach_files`, "POST", form);
}
await verifyDownload(uploaded, file);
}
// Gitee has no draft API. Its preview flag fences incomplete uploads from checks.
if (release.prerelease) {
// Uploads may take minutes; a newer GitHub release must not be displaced.
requireLatestSource();
const completed = await request(`/releases/${release.id}`, "PATCH", {
tag_name: version, name: source.name || `Piik ${version}`, body, prerelease: false,
});
if (completed.prerelease !== false || completed.tag_name !== version) {
throw new Error("Gitee did not confirm the completed stable mirror");
}
}
console.log(`Verified Gitee mirror ${version} from ${revision} (${files.length} attachments).`);
}