Repository Public
1#!/usr/bin/env python32"""TestFlight follow-up for the iOS app of MacLustr Command Center (after apps/ios/Scripts/release.sh upload).34 ASC_KEY_ID=L379BDKR69 ASC_ISSUER_ID=… python3 infra/apple/testflight.py report only5 ASC_KEY_ID=L379BDKR69 ASC_ISSUER_ID=… python3 infra/apple/testflight.py --apply also:6 - declares export compliance on builds that miss it (usesNonExemptEncryption = false: HTTPS / system crypto only)7 - makes sure an INTERNAL beta group exists (reuses the first one; otherwise creates "Interne")8 - makes sure the account holder is a tester of that group9 - adds the processed (VALID) builds to the group when the group does not already receive every build1011It touches nothing but the app with bundle id ai.spboucher.clustr.ios. Nothing secret is printed.12"""13import json, os, sys1415HERE = os.path.dirname(os.path.abspath(__file__))16sys.path.insert(0, HERE)17os.environ.setdefault("ASC_KEY_ID", "L379BDKR69")18import asc # noqa: E4021920BUNDLE_ID = "ai.spboucher.clustr.ios"21GROUP_NAME = "Interne"22APPLY = "--apply" in sys.argv[1:]23changes, problems = [], []242526def api(method, path, body=None, ok=(200, 201, 204)):27 status, data = asc.call(method, path, body)28 if status not in ok:29 errs = [f"{e.get('code')}: {e.get('detail') or e.get('title')}" for e in data.get("errors", [])] if isinstance(data, dict) else []30 raise RuntimeError(f"{method} {path.split('?')[0]} -> HTTP {status} {'; '.join(errs) or str(data)[:300]}")31 return data323334def attempt(description, fn):35 """Applies a change; a refusal by the API is reported, not fatal."""36 if not APPLY:37 changes.append("(pending) " + description)38 return None39 try:40 out = fn()41 changes.append(description)42 return out43 except RuntimeError as e:44 problems.append(f"{description}: {e}")45 return None464748def main():49 apps = [a for a in api("GET", f"/v1/apps?filter[bundleId]={BUNDLE_ID}&limit=200")["data"] if a["attributes"]["bundleId"] == BUNDLE_ID]50 if not apps:51 print(json.dumps({"app_record": "missing", "bundle_id": BUNDLE_ID}, indent=1))52 sys.exit(3)53 app = apps[0]54 out = {"mode": "apply" if APPLY else "report", "app": {"id": app["id"], "name": app["attributes"]["name"], "sku": app["attributes"]["sku"],55 "primary_locale": app["attributes"]["primaryLocale"]}}56 builds = api("GET", f"/v1/builds?filter[app]={app['id']}&sort=-uploadedDate&limit=20"57 "&fields[builds]=version,processingState,usesNonExemptEncryption,uploadedDate,expired,minOsVersion,preReleaseVersion,buildBetaDetail"58 "&include=preReleaseVersion,buildBetaDetail&fields[preReleaseVersions]=version&fields[buildBetaDetails]=internalBuildState,externalBuildState")59 inc = {(i["type"], i["id"]): i["attributes"] for i in builds.get("included", [])}60 out["builds"] = []61 for b in builds["data"]:62 a = b["attributes"]63 rel = b.get("relationships", {})64 pre = (rel.get("preReleaseVersion", {}).get("data") or {})65 beta = (rel.get("buildBetaDetail", {}).get("data") or {})66 if a.get("usesNonExemptEncryption") is None and a.get("processingState") == "VALID":67 r = attempt(f"declare export compliance (usesNonExemptEncryption=false) on build {a['version']}", lambda b=b: api("PATCH", f"/v1/builds/{b['id']}", {68 "data": {"type": "builds", "id": b["id"], "attributes": {"usesNonExemptEncryption": False}}}))69 if r is not None:70 a["usesNonExemptEncryption"] = False71 out["builds"].append({"id": b["id"], "marketing_version": inc.get(("preReleaseVersions", pre.get("id")), {}).get("version"), "build": a["version"],72 "processing_state": a["processingState"], "uses_non_exempt_encryption": a.get("usesNonExemptEncryption"),73 "uploaded": a.get("uploadedDate"), "expired": a.get("expired"), "min_os": a.get("minOsVersion"),74 "internal_state": inc.get(("buildBetaDetails", beta.get("id")), {}).get("internalBuildState")})7576 groups = api("GET", f"/v1/apps/{app['id']}/betaGroups?limit=200")["data"]77 internal = [g for g in groups if g["attributes"].get("isInternalGroup")]78 group = internal[0] if internal else None79 if group is None:80 res = attempt(f"create internal beta group '{GROUP_NAME}'", lambda: api("POST", "/v1/betaGroups", {"data": {81 "type": "betaGroups", "attributes": {"name": GROUP_NAME, "isInternalGroup": True, "hasAccessToAllBuilds": True},82 "relationships": {"app": {"data": {"type": "apps", "id": app["id"]}}}}}))83 group = res["data"] if res else None84 if group is None:85 out["internal_group"] = None86 else:87 ga = group["attributes"]88 testers = api("GET", f"/v1/betaGroups/{group['id']}/betaTesters?limit=200")["data"]89 emails = {(t["attributes"].get("email") or "").lower() for t in testers}90 holders = [u for u in api("GET", "/v1/users?limit=200")["data"] if "ACCOUNT_HOLDER" in (u["attributes"].get("roles") or [])]91 holder_in_group = None92 for u in holders:93 ua = u["attributes"]94 email = (ua.get("username") or "").lower()95 holder_in_group = email in emails96 if not holder_in_group:97 r = attempt("add the account holder to the internal group", lambda ua=ua: api("POST", "/v1/betaTesters", {"data": {98 "type": "betaTesters", "attributes": {"email": ua.get("username"), "firstName": ua.get("firstName"), "lastName": ua.get("lastName")},99 "relationships": {"betaGroups": {"data": [{"type": "betaGroups", "id": group["id"]}]}}}}))100 holder_in_group = r is not None101 group_builds = {b["id"] for b in api("GET", f"/v1/betaGroups/{group['id']}/builds?limit=200&fields[builds]=version")["data"]}102 for b in builds["data"]:103 if b["attributes"]["processingState"] == "VALID" and b["id"] not in group_builds and not ga.get("hasAccessToAllBuilds"):104 r = attempt(f"add build {b['attributes']['version']} to group '{ga['name']}'", lambda b=b: api(105 "POST", f"/v1/betaGroups/{group['id']}/relationships/builds", {"data": [{"type": "builds", "id": b["id"]}]}))106 if r is not None:107 group_builds.add(b["id"])108 out["internal_group"] = {"id": group["id"], "name": ga["name"], "is_internal": ga.get("isInternalGroup"),109 "has_access_to_all_builds": ga.get("hasAccessToAllBuilds"), "testers": len(testers) + (0 if not changes else 0),110 "account_holder_is_tester": holder_in_group,111 "builds_in_group": sorted(b["attributes"]["version"] for b in builds["data"] if b["id"] in group_builds)}112 out["changes"], out["problems"] = changes, problems113 print(json.dumps(out, indent=1, default=str))114 sys.exit(1 if problems else 0)115116117if __name__ == "__main__":118 try:119 main()120 except RuntimeError as e:121 print(json.dumps({"fatal": str(e), "changes": changes}, indent=1))122 sys.exit(2)123