storebound/cli/play/client.ts

68 lines
3.5 KiB
TypeScript

// Google Play Developer API (androidpublisher v3) client: JSON + media calls with retry, and the edit lifecycle.
import { playServiceAccount } from '../lib/credentials';
import { tokenSource } from '../lib/google-auth';
import { log } from '../lib/log';
export type PlayClient = Awaited<ReturnType<typeof playClient>>;
export async function playClient(root: string, packageName: string) {
const token = tokenSource(playServiceAccount(root));
const API = `https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${packageName}`;
const UPLOAD = `https://androidpublisher.googleapis.com/upload/androidpublisher/v3/applications/${packageName}`;
/** JSON call (object body) or media upload (Uint8Array body + Content-Type). Throws with the API's text. */
async function call<T = unknown>(method: string, url: string, body?: unknown, headers: Record<string, string> = {}): Promise<T> {
const bin = body instanceof Uint8Array;
for (let attempt = 0; ; attempt++) {
const r = await fetch(url, {
method,
headers: { Authorization: 'Bearer ' + (await token()), ...(body === undefined || bin ? {} : { 'Content-Type': 'application/json' }), ...headers },
body: body === undefined ? undefined : bin ? (body as unknown as BodyInit) : JSON.stringify(body),
});
const text = await r.text();
if (r.ok) return (text ? JSON.parse(text) : {}) as T;
if ((r.status === 429 || r.status >= 500) && attempt < 4) { await Bun.sleep(2000 * (attempt + 1)); continue; }
const short = url.replace(API, '').replace(UPLOAD, '');
// A wrong path casing answers with an HTML 404 page, not JSON: say so instead of dumping the HTML.
const msg = /^\s*</.test(text) ? `(HTML ${r.status} page: wrong path or casing?)` : text.slice(0, 1500);
throw new Error(`${method} ${short} -> ${r.status} ${msg}`);
}
}
async function editOnce<T>(fn: (id: string) => Promise<T>, o: { dry?: boolean; commitQuery?: string }): Promise<T> {
const e = await call<{ id: string }>('POST', `${API}/edits`, {});
log('play', `edit ${e.id} opened`);
try {
const out = await fn(e.id);
if (o.dry) {
await call('POST', `${API}/edits/${e.id}:validate`);
log('play', 'dry run: edit validated, discarding');
await call('DELETE', `${API}/edits/${e.id}`);
} else {
await call('POST', `${API}/edits/${e.id}:commit${o.commitQuery ?? ''}`);
log('play', `edit ${e.id} committed`);
}
return out;
} catch (err) {
await call('DELETE', `${API}/edits/${e.id}`).catch(() => {});
throw err;
}
}
return {
API, UPLOAD, packageName, call,
/**
* Opens an edit, runs fn, then commits (or validates and discards when dry). Any Console save or other edit commit
* invalidates an open edit ("A change was made to the application outside of this Edit"); then the whole edit is
* redone, up to `retries` times. Keep edits small (e.g. one per language for images) so a retry is cheap.
*/
async edit<T>(fn: (id: string) => Promise<T>, o: { dry?: boolean; commitQuery?: string; retries?: number } = {}): Promise<T> {
for (let left = o.retries ?? 3; ; left--) {
try { return await editOnce(fn, o); } catch (err) {
if (left <= 0 || !/outside of this Edit|Edit has been deleted|edit.*(expired|not found)/i.test(String(err))) throw err;
log('play', `app changed outside the edit (Console?), redoing it (${left} retries left)`);
}
}
},
};
}