Branchwell

Glimmer / app / native / scripts / asc.py

1#!/usr/bin/env python3
2"""Small App Store Connect helper for the TestFlight release script.
3
4Reads APPLE_API_KEY_ID, APPLE_API_ISSUER and APPLE_API_KEY_FILE from the environment.
5
6 asc.py latest-build <app-id> <version> prints the newest build number for that version (0 if none)
7 asc.py wait-build <app-id> <version> <build> waits until Apple finishes processing the build
8 asc.py internal-group <app-id> <version> <build> puts the build in an internal tester group
9"""
10import base64, json, os, subprocess, sys, time, urllib.error, urllib.parse, urllib.request
11
12GROUP_NAME = "Glimmer Internal"
13
14
15def token():
16 def b64(raw):
17 return base64.urlsafe_b64encode(raw).rstrip(b"=")
18 header = b64(json.dumps({"alg": "ES256", "kid": os.environ["APPLE_API_KEY_ID"], "typ": "JWT"}).encode())
19 now = int(time.time())
20 claims = b64(json.dumps({"iss": os.environ["APPLE_API_ISSUER"], "iat": now, "exp": now + 900,
21 "aud": "appstoreconnect-v1"}).encode())
22 message = header + b"." + claims
23 der = subprocess.run(["openssl", "dgst", "-sha256", "-sign", os.environ["APPLE_API_KEY_FILE"]],
24 input=message, capture_output=True, check=True).stdout
25 # openssl returns a DER signature; the token needs the raw r and s values.
26 r_length = der[3]
27 r = der[4:4 + r_length]
28 s = der[6 + r_length:6 + r_length + der[5 + r_length]]
29 return (message + b"." + b64(r[-32:].rjust(32, b"\0") + s[-32:].rjust(32, b"\0"))).decode()
30
31
32def call(path, method="GET", body=None):
33 request = urllib.request.Request(
34 "https://api.appstoreconnect.apple.com/v1/" + path, method=method,
35 data=json.dumps(body).encode() if body is not None else None,
36 headers={"Authorization": "Bearer " + token(), "Content-Type": "application/json"})
37 try:
38 with urllib.request.urlopen(request) as response:
39 text = response.read()
40 return json.loads(text) if text else {}
41 except urllib.error.HTTPError as error:
42 detail = error.read().decode(errors="replace")
43 raise SystemExit(f"App Store Connect answered {error.code} for {method} {path}: {detail[:400]}")
44
45
46def builds(app, version):
47 query = urllib.parse.urlencode({"filter[app]": app, "filter[preReleaseVersion.version]": version,
48 "limit": 200, "fields[builds]": "version,processingState"})
49 return call("builds?" + query)["data"]
50
51
52def latest_build(app, version):
53 numbers = [int(row["attributes"]["version"]) for row in builds(app, version) if row["attributes"]["version"].isdigit()]
54 print(max(numbers, default=0))
55
56
57def find_build(app, version, build):
58 return next((row for row in builds(app, version) if row["attributes"]["version"] == str(build)), None)
59
60
61def wait_build(app, version, build):
62 deadline = time.time() + 40 * 60
63 while time.time() < deadline:
64 row = find_build(app, version, build)
65 state = row["attributes"]["processingState"] if row else "not listed yet"
66 print(f"Build {version} ({build}): {state}", flush=True)
67 if state == "VALID":
68 return
69 if state in ("INVALID", "FAILED"):
70 raise SystemExit("Apple rejected the build during processing. Check the email from App Store Connect.")
71 time.sleep(45)
72 raise SystemExit("Apple is still processing after 40 minutes. Run `asc.py wait-build` again later.")
73
74
75def internal_group(app, version, build):
76 row = find_build(app, version, build)
77 if not row:
78 raise SystemExit("The build is not in App Store Connect.")
79 groups = call(f"apps/{app}/betaGroups?limit=200")["data"]
80 group = next((g for g in groups if g["attributes"].get("isInternalGroup")), None)
81 if not group:
82 group = call("betaGroups", "POST", {"data": {
83 "type": "betaGroups",
84 "attributes": {"name": GROUP_NAME, "isInternalGroup": True, "hasAccessToAllBuilds": True},
85 "relationships": {"app": {"data": {"type": "apps", "id": app}}}}})["data"]
86 print(f"Created the internal group “{GROUP_NAME}”.")
87 if not group["attributes"].get("hasAccessToAllBuilds"):
88 call(f"betaGroups/{group['id']}/relationships/builds", "POST", {"data": [{"type": "builds", "id": row["id"]}]})
89 testers = call(f"betaGroups/{group['id']}/betaTesters?limit=200")["data"]
90 print(f"Group “{group['attributes']['name']}” has the build and {len(testers)} tester(s).")
91 if not testers:
92 print("Add testers in App Store Connect: TestFlight, Internal Testing, then the + next to Testers.")
93 # Apple only notifies a tester about builds after they accept the invitation email.
94 waiting = [t["attributes"].get("firstName") or "a tester" for t in testers if t["attributes"].get("state") == "INVITED"]
95 if waiting:
96 print(f"Not accepted yet: {', '.join(waiting)}. They get no build notifications until they open the "
97 "TestFlight invitation email and tap View in TestFlight.")
98
99
100if __name__ == "__main__":
101 commands = {"latest-build": latest_build, "wait-build": wait_build, "internal-group": internal_group}
102 if len(sys.argv) < 2 or sys.argv[1] not in commands:
103 raise SystemExit(__doc__)
104 commands[sys.argv[1]](*sys.argv[2:])