Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

mirror-play-apk.cjs

231 lines7.9 KB

1// Publishes closed-testing betas, or downloads the internal APK for a normal
2// nightly release. Play generates and signs the APK from the
3// uploaded bundle with the app signing key, so it carries the same signature
4// as the Play Store install. Run by .github/workflows/mobile-android-apk.yml.
5const { execFileSync } = require("node:child_process");
6const crypto = require("node:crypto");
7const fs = require("node:fs");
8const os = require("node:os");
9const path = require("node:path");
10const { Readable } = require("node:stream");
11const { pipeline } = require("node:stream/promises");
12​
13const PLAY_API = "https://androidpublisher.googleapis.com/androidpublisher/v3/applications";
14​
15function requireEnv(name) {
16 const value = process.env[name];
17 if (!value) throw new Error(`${name} is required.`);
18 return value;
20​
21// Service account key -> OAuth access token via a self-signed JWT grant.
22async function playAccessToken(key) {
23 const now = Math.floor(Date.now() / 1000);
24 const encode = (value) => Buffer.from(JSON.stringify(value)).toString("base64url");
25 const unsigned = `${encode({ alg: "RS256", typ: "JWT" })}.${encode({
26 iss: key.client_email,
27 scope: "https://www.googleapis.com/auth/androidpublisher",
28 aud: key.token_uri,
29 iat: now,
30 exp: now + 600,
31 })}`;
32 const signature = crypto.sign("RSA-SHA256", Buffer.from(unsigned), key.private_key);
33 const response = await fetch(key.token_uri, {
34 method: "POST",
35 body: new URLSearchParams({
36 grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
37 assertion: `${unsigned}.${signature.toString("base64url")}`,
38 }),
39 });
40 if (!response.ok) {
41 throw new Error(`Google token exchange failed: ${response.status} ${await response.text()}`);
42 }
43 return (await response.json()).access_token;
45​
46async function play(token, method, url) {
47 const response = await fetch(url, { method, headers: { authorization: `Bearer ${token}` } });
48 if (!response.ok) {
49 throw new Error(`${method} ${url} failed: ${response.status} ${await response.text()}`);
50 }
51 return response;
53​
54// Highest version code the track serves, with its release name. Play names a
55// release after the bundle's versionName unless the uploader sets one. This
56// endpoint reads without opening an edit; an edit would invalidate any open
57// EAS Submit edit made with the same service account.
58async function newestTrackBuild(token, appUrl, trackName) {
59 const { releases = [] } = await (
60 await play(token, "GET", `${appUrl}/tracks/${trackName}/releases`)
61 ).json();
62 let newest;
63 for (const release of releases) {
64 if (release.releaseLifecycleState !== "RELEASE_LIFECYCLE_STATE_PUBLISHED") continue;
65 for (const { versionCode } of release.activeArtifacts ?? []) {
66 if (!newest || versionCode > newest.versionCode) {
67 newest = { versionCode, versionName: release.releaseName || String(versionCode) };
68 }
69 }
70 }
71 return newest;
73​
74function gh(...args) {
75 return execFileSync("gh", args, { encoding: "utf8", stdio: ["ignore", "pipe", "inherit"] });
77​
78function readRelease(tag) {
79 try {
80 return JSON.parse(gh("release", "view", tag, "--json", "assets,body,isDraft"));
81 } catch {
82 return undefined;
83 }
85​
86// Download to a temporary directory so a failed request cannot leave a partial
87// APK among the release assets.
88async function downloadApk({ token, appUrl, build, apkName }) {
89 const generated = await (
90 await play(token, "GET", `${appUrl}/generatedApks/${build.versionCode}`)
91 ).json();
92 const universal = (generated.generatedApks ?? []).filter((entry) => entry.generatedUniversalApk);
93 if (universal.length === 0) return undefined;
94 if (universal.length > 1) {
95 throw new Error(`Play returned ${universal.length} universal APKs, one per signing key.`);
96 }
97 const { downloadId } = universal[0].generatedUniversalApk;
98 const directory = fs.mkdtempSync(path.join(os.tmpdir(), "apk-"));
99 const apkPath = path.join(directory, apkName);
100 try {
101 const download = await play(
102 token,
103 "GET",
104 `${appUrl}/generatedApks/${build.versionCode}/downloads/${encodeURIComponent(downloadId)}:download?alt=media`,
105 );
106 await pipeline(Readable.fromWeb(download.body), fs.createWriteStream(apkPath));
107 return apkPath;
108 } catch (error) {
109 fs.rmSync(directory, { recursive: true, force: true });
110 throw error;
111 }
113​
114function publishBeta(tag, apkPath, notes, title) {
115 const release = readRelease(tag);
116 if (
117 release &&
118 !release.isDraft &&
119 release.assets.some(
120 (asset) =>
121 asset.name === path.basename(apkPath) && asset.state === "uploaded" && asset.size > 0,
122 )
123 )
124 return;
125 if (!release) {
126 gh(
127 "release",
128 "create",
129 tag,
130 "--draft",
131 "--prerelease",
132 "--latest=false",
133 "--title",
134 title,
135 "--notes",
136 notes,
137 );
138 }
139 gh("release", "upload", tag, apkPath, "--clobber");
140 gh(
141 "release",
142 "edit",
143 tag,
144 "--draft=false",
145 "--prerelease",
146 "--latest=false",
147 "--title",
148 title,
149 "--notes",
150 notes,
151 );
153​
154async function main() {
155 const packageName = requireEnv("PACKAGE_NAME");
156 const outputDirectory = process.env.APK_OUTPUT_DIR;
157 const channel = outputDirectory ? "internal" : "beta";
158 const track = outputDirectory ? "internal" : "alpha";
159 const token = await playAccessToken(JSON.parse(requireEnv("GOOGLE_PLAY_SERVICE_ACCOUNT_JSON")));
160 const appUrl = `${PLAY_API}/${packageName}`;
161 const build = await newestTrackBuild(token, appUrl, track);
162 if (!build) {
163 console.log(`The ${track} track has no live release.`);
164 return;
165 }
166 const safeName = build.versionName.replace(/[^0-9A-Za-z.]+/g, "-").replace(/^-|-$/g, "");
167 const apkName = `t3code-android-${channel}-${safeName}-${build.versionCode}.apk`;
168 const tag = outputDirectory ? undefined : requireEnv("RELEASE_TAG");
169 const snapshotTag = `android-beta-${build.versionCode}`;
170 const release = tag ? readRelease(tag) : undefined;
171 const snapshot = tag ? readRelease(snapshotTag) : undefined;
172 const hasApk = (value) =>
173 value &&
174 !value.isDraft &&
175 value.assets.some(
176 (asset) => asset.name === apkName && asset.state === "uploaded" && asset.size > 0,
177 );
178 const pruneBetaAssets = () => {
179 for (const stale of release?.assets ?? []) {
180 if (stale.name.endsWith(".apk") && stale.name !== apkName) {
181 gh("release", "delete-asset", tag, stale.name, "--yes");
182 }
183 }
184 };
185 if (hasApk(release) && hasApk(snapshot)) {
186 pruneBetaAssets();
187 console.log(`${apkName} is already published.`);
188 return;
189 }
190 const apkPath = await downloadApk({ token, appUrl, build, apkName });
191 if (!apkPath) {
192 console.log(`Play is still processing the ${track} APK for ${build.versionCode}.`);
193 return;
194 }
195 try {
196 if (outputDirectory) {
197 fs.mkdirSync(outputDirectory, { recursive: true });
198 const destination = path.join(outputDirectory, apkName);
199 const temporary = `${destination}.tmp`;
200 try {
201 fs.copyFileSync(apkPath, temporary);
202 fs.renameSync(temporary, destination);
203 } finally {
204 fs.rmSync(temporary, { force: true });
205 }
206 return;
207 }
208 const notes = [
209 `T3 Code for Android beta, mirrored from Google Play closed testing. Build: ${build.versionName} (${build.versionCode}).`,
210 "",
211 "These builds have been promoted for wider testing, but may still contain bugs. The beta is optional; the store app also works with Nightly servers.",
212 ].join("\n");
213 // Publish the versioned beta first, then advance the stable download page.
214 // The build number makes retries and unchanged hourly checks idempotent.
215 publishBeta(
216 snapshotTag,
217 apkPath,
218 notes,
219 `Android beta ${build.versionName} (${build.versionCode})`,
220 );
221 publishBeta(tag, apkPath, notes, "T3 Code for Android (beta)");
222 pruneBetaAssets();
223 } finally {
224 fs.rmSync(path.dirname(apkPath), { recursive: true, force: true });
225 }
227​
228main().catch((error) => {
229 console.error(error);
230 process.exit(1);
231});