Branchwell

Jobley / app · jobley.ai / scripts / asc.py

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