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

mirror-play-apk.cjs

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