Branchwell

Bucksley / app · bucksley.ai / scripts / asc.py

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