Repository Public
1#!/usr/bin/env python32# =============================================================================3# SP BOUCHER | SOFTWARE & RESEARCH4# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# PROJECT METADATA8# -----------------------------------------------------------------------------9# Project : SP Search iOS10# File : Scripts/asc.py11# Description : State of a build on App Store Connect and test groups,12# with the team key already on this Mac13# (~/.appstoreconnect/private_keys). No secret in the14# repository. Read only, except "group", which attaches a15# build to the internal group; nothing is ever submitted to16# a review. usage: asc.py app | build [number] | wait17# [number] | group [number] | status [number]18# Module : Scripts19# Repository : https://git.spboucher.ai/sp-search-ios20# Project Website : https://search.spboucher.ai21# Created : 2026-12-0122# Last Modified : 2026-12-0123#24# =============================================================================25# AUTHOR & PROFESSIONAL AFFILIATION26# =============================================================================27#28# Author : Simon-Pierre Boucher29# Position : Professor of Finance30# Institution : Université du Québec en Outaouais (UQO)31# Department : Département des sciences administratives32# Organization : SP Boucher33#34# Website : https://spboucher.ai35# Git : https://git.spboucher.ai36#37# =============================================================================38# OFFICIAL CONTACT DIRECTORY39# =============================================================================40#41# General : info@spboucher.ai42# Professional : contact@spboucher.ai43# Direct : simon@spboucher.ai44# Research : research@spboucher.ai45# Development : dev@spboucher.ai46# Support : support@spboucher.ai47# Security/Admin : admin@spboucher.ai48# Notifications : notifications@spboucher.ai49#50# Preferred Contact: support@spboucher.ai51#52# =============================================================================53# COPYRIGHT & INTELLECTUAL PROPERTY54# =============================================================================55#56# Copyright (c) 202657# Simon-Pierre Boucher58#59# All rights reserved where applicable.60#61# This file is governed by the applicable project license,62# copyright notices, institutional agreements and relevant law.63#64# Unless expressly authorized by the applicable license or65# rights holder, copying, redistribution, sublicensing,66# publication and commercial exploitation are not permitted.67#68# Existing third-party rights and notices remain unaffected.69#70# =============================================================================71# CONFIDENTIALITY & SECURITY72# =============================================================================73#74# Classification : Public75# Distribution : Public repository; use is governed by the project license76# Security Contact : admin@spboucher.ai77#78# Access to this source does not independently grant permission79# to redistribute or disclose confidential materials.80#81# Do not embed credentials, private keys, access tokens,82# certificates or confidential personal information.83#84# =============================================================================85# LICENSE & MAINTENANCE86# =============================================================================87#88# License : None specified (no license file in this repository)89# Maintainer : Simon-Pierre Boucher90# Technical Contact: dev@spboucher.ai91#92# =============================================================================93# END OF SP BOUCHER SOURCE HEADER94# =============================================================================9596import json97import os98import sys99import time100import urllib.error101import urllib.request102103import jwt # PyJWT104105KEY_ID = os.environ.get("ASC_KEY_ID", "L379BDKR69")106ISSUER = os.environ.get("ASC_ISSUER_ID", "013e761f-e05c-4d93-a50b-f3d960adae4a")107APP = os.environ.get("SPSEARCH_ASC_APP", "6841331008") # « SP Search », ai.spboucher.spsearch.ios, SKU spsearch-ios-001108VERSION = os.environ.get("SPSEARCH_VERSION", "1.0.0")109BUNDLE = "ai.spboucher.spsearch.ios"110GROUP = "Test"111MODEL_APP = "6836172581" # SP Music iOS: its internal group holds the team's internal tester112113114def token():115 key = open(os.path.expanduser(f"~/.appstoreconnect/private_keys/AuthKey_{KEY_ID}.p8")).read()116 now = int(time.time())117 return jwt.encode({"iss": ISSUER, "iat": now, "exp": now + 900, "aud": "appstoreconnect-v1"}, key,118 algorithm="ES256", headers={"kid": KEY_ID})119120121def call(method, path, body=None):122 req = urllib.request.Request("https://api.appstoreconnect.apple.com" + path, method=method,123 data=json.dumps(body).encode() if body else None,124 headers={"Authorization": "Bearer " + token(), "Content-Type": "application/json"})125 try:126 with urllib.request.urlopen(req, timeout=40) as r:127 return r.status, json.loads(r.read() or b"{}")128 except urllib.error.HTTPError as e:129 return e.code, json.loads(e.read() or b"{}")130131132def resolve_app():133 """The record's id: SPSEARCH_ASC_APP when set, otherwise looked up by bundle id."""134 global APP135 if APP:136 return APP137 s, j = call("GET", f"/v1/apps?filter[bundleId]={BUNDLE}&fields[apps]=name,bundleId,sku,primaryLocale")138 data = [a for a in j.get("data", []) if a["attributes"]["bundleId"] == BUNDLE]139 if not data:140 print(f"no App Store Connect record for {BUNDLE} (HTTP {s}) - create it with Scripts/portal/create-asc-record.js")141 sys.exit(1)142 APP = data[0]["id"]143 return APP144145146def build(number=None):147 q = f"/v1/builds?filter[app]={APP}&filter[preReleaseVersion.version]={VERSION}&sort=-uploadedDate&limit=5"148 if number:149 q += f"&filter[version]={number}"150 s, j = call("GET", q)151 data = j.get("data", [])152 return data[0] if data else None153154155def groups():156 s, j = call("GET", f"/v1/apps/{APP}/betaGroups?fields[betaGroups]=name,isInternalGroup,hasAccessToAllBuilds&limit=50")157 return j.get("data", [])158159160def describe(b):161 a = b["attributes"]162 return f"{b['id']} {VERSION} ({a['version']}) {a['processingState']} encryption={a.get('usesNonExemptEncryption')} iOS min={a.get('minOsVersion')} expires={a.get('expirationDate')}"163164165def main():166 cmd = sys.argv[1] if len(sys.argv) > 1 else "build"167 number = sys.argv[2] if len(sys.argv) > 2 else None168 resolve_app()169 if cmd == "app":170 s, j = call("GET", f"/v1/apps/{APP}?fields[apps]=name,bundleId,sku,primaryLocale")171 print(APP, json.dumps(j.get("data", {}).get("attributes", {}), ensure_ascii=False))172 return 0173 if cmd == "build":174 b = build(number)175 print(describe(b) if b else f"no build {VERSION} {number or ''}")176 return 0 if b else 1177 if cmd == "wait":178 # the build shows up a few minutes after the upload, then goes from PROCESSING to VALID179 for _ in range(90):180 b = build(number)181 state = b["attributes"]["processingState"] if b else "not visible yet"182 print(time.strftime("%H:%M:%S"), state, flush=True)183 if state in ("VALID", "INVALID", "FAILED"):184 return 0 if state == "VALID" else 1185 time.sleep(20)186 return 1187 if cmd == "group":188 b = build(number)189 if not b:190 print("no build to attach")191 return 1192 internal = [g for g in groups() if g["attributes"]["isInternalGroup"]]193 if not internal:194 # First build of the app: the internal group is created, with the internal tester(s) of the model app's195 # internal group (people of the team; no external tester, no review).196 s, j = call("POST", "/v1/betaGroups", {"data": {"type": "betaGroups",197 "attributes": {"name": GROUP, "isInternalGroup": True, "hasAccessToAllBuilds": True},198 "relationships": {"app": {"data": {"type": "apps", "id": APP}}}}})199 if s >= 300:200 print("group creation refused:", s, json.dumps(j, ensure_ascii=False)[:600])201 return 1202 gid = j["data"]["id"]203 print(f"internal group « {GROUP} » created")204 s, j = call("GET", f"/v1/apps/{MODEL_APP}/betaGroups?fields[betaGroups]=isInternalGroup")205 model = next((g["id"] for g in j.get("data", []) if g["attributes"]["isInternalGroup"]), None)206 if model:207 s, j = call("GET", f"/v1/betaGroups/{model}/betaTesters?limit=50")208 for t in j.get("data", []):209 a = t["attributes"]210 s2, j2 = call("POST", "/v1/betaTesters", {"data": {"type": "betaTesters",211 "attributes": {"email": a["email"], "firstName": a.get("firstName"), "lastName": a.get("lastName")},212 "relationships": {"betaGroups": {"data": [{"type": "betaGroups", "id": gid}]}}}})213 print("internal tester added" if s2 < 300 else f"tester refused: {s2} {json.dumps(j2, ensure_ascii=False)[:300]}")214 internal = [g for g in groups() if g["attributes"]["isInternalGroup"]]215 for g in internal:216 a = g["attributes"]217 if a.get("hasAccessToAllBuilds"):218 print(f"internal group « {a['name']} »: access to all builds, nothing to attach")219 continue220 s, j = call("POST", f"/v1/betaGroups/{g['id']}/relationships/builds", {"data": [{"type": "builds", "id": b["id"]}]})221 print(f"internal group « {a['name']} »: build attached" if s < 300 else f"attachment refused: {s} {json.dumps(j, ensure_ascii=False)[:400]}")222 return 0223 if cmd == "status":224 b = build(number)225 if not b:226 print(f"no build {VERSION} {number or ''}")227 return 1228 print(describe(b))229 s, j = call("GET", f"/v1/builds/{b['id']}/buildBetaDetail")230 d = j.get("data", {}).get("attributes", {})231 print("internal testing:", d.get("internalBuildState"), "| external testing:", d.get("externalBuildState"))232 s, j = call("GET", f"/v1/builds/{b['id']}/betaAppReviewSubmission")233 print("beta review:", (j.get("data") or {}).get("attributes", {}).get("betaReviewState", "no submission"))234 for g in groups():235 a = g["attributes"]236 s, j = call("GET", f"/v1/betaGroups/{g['id']}/builds?limit=200&fields[builds]=version")237 has = any(x["id"] == b["id"] for x in j.get("data", []))238 s, t = call("GET", f"/v1/betaGroups/{g['id']}/betaTesters?limit=50")239 print(f"group « {a['name']} » ({'internal' if a['isInternalGroup'] else 'external'}): "240 f"{'all builds' if a.get('hasAccessToAllBuilds') else ('has this build' if has else 'does not have this build')}, {len(t.get('data', []))} tester(s)")241 return 0242 print("usage: asc.py app | build [number] | wait [number] | group [number] | status [number]")243 return 2244245246if __name__ == "__main__":247 sys.exit(main())248