Repository Public
1#!/usr/bin/env python32# Auto-Ka iOS v23# File: Scripts/asc.py4# Description: appels à l'API App Store Connect avec la clé d'équipe déjà présente sur ce Mac5# (~/.appstoreconnect/private_keys). Aucun secret dans le dépôt.6# usage : asc.py app | build [numéro] | wait [numéro] | group | raw MÉTHODE CHEMIN [JSON]7#8# Author: Simon-Pierre Boucher9# Contact: contact@spboucher.ai10import json11import os12import sys13import time14import urllib.error15import urllib.request1617import jwt # PyJWT18192021def _local(name):22 """Identifiants de la clé d'équipe : variable d'environnement, sinon Scripts/local.env (hors dépôt)."""23 if os.environ.get(name):24 return os.environ[name]25 path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "local.env")26 if os.path.exists(path):27 for line in open(path):28 k, _, v = line.strip().partition("=")29 if k == name:30 return v.strip().strip('"')31 sys.exit(f"{name} absent : le définir dans l'environnement ou dans Scripts/local.env")323334KEY_ID = _local("ASC_KEY_ID")35ISSUER = _local("ASC_ISSUER_ID")36BUNDLE = "com.spboucher.autoka.v2"37VERSION = "2.0.0"38GROUP = "Test" # groupe interne, comme pour les autres apps de l'équipe39MODEL_APP = "6839382600" # Lou-Ka v2 : son groupe interne donne le testeur à reprendre404142def token():43 key = open(os.path.expanduser(f"~/.appstoreconnect/private_keys/AuthKey_{KEY_ID}.p8")).read()44 now = int(time.time())45 return jwt.encode({"iss": ISSUER, "iat": now, "exp": now + 900, "aud": "appstoreconnect-v1"}, key,46 algorithm="ES256", headers={"kid": KEY_ID})474849def call(method, path, body=None):50 req = urllib.request.Request("https://api.appstoreconnect.apple.com" + path, method=method,51 data=json.dumps(body).encode() if body else None,52 headers={"Authorization": "Bearer " + token(), "Content-Type": "application/json"})53 try:54 with urllib.request.urlopen(req, timeout=40) as r:55 return r.status, json.loads(r.read() or b"{}")56 except urllib.error.HTTPError as e:57 return e.code, json.loads(e.read() or b"{}")585960def app_id():61 s, j = call("GET", f"/v1/apps?filter[bundleId]={BUNDLE}&fields[apps]=name,bundleId,sku")62 for d in j.get("data", []):63 if d["attributes"]["bundleId"] == BUNDLE:64 return d["id"], d["attributes"]65 return None, None666768def build(app, number=None):69 q = f"/v1/builds?filter[app]={app}&filter[preReleaseVersion.version]={VERSION}&sort=-uploadedDate&limit=5"70 if number:71 q += f"&filter[version]={number}"72 s, j = call("GET", q)73 data = j.get("data", [])74 return data[0] if data else None757677def main():78 cmd = sys.argv[1] if len(sys.argv) > 1 else "app"79 if cmd == "raw":80 s, j = call(sys.argv[2], sys.argv[3], json.loads(sys.argv[4]) if len(sys.argv) > 4 else None)81 print(s, json.dumps(j, ensure_ascii=False)[:3000])82 return 083 app, attrs = app_id()84 if cmd == "app":85 if not app:86 print("ABSENTE : aucune fiche App Store Connect pour", BUNDLE)87 return 188 print(app, attrs["name"], attrs["sku"])89 return 090 if not app:91 print("ABSENTE : aucune fiche App Store Connect pour", BUNDLE)92 return 193 number = sys.argv[2] if len(sys.argv) > 2 else None94 if cmd == "build":95 b = build(app, number)96 if not b:97 print("aucun build", VERSION, number or "")98 return 199 a = b["attributes"]100 print(b["id"], f"{VERSION} ({a['version']})", a["processingState"], "chiffrement:", a.get("usesNonExemptEncryption"),101 "iOS min:", a.get("minOsVersion"), "expire:", a.get("expirationDate"))102 return 0103 if cmd == "wait":104 # le build apparaît quelques minutes après l'envoi, puis passe de PROCESSING à VALID105 for _ in range(90):106 b = build(app, number)107 state = b["attributes"]["processingState"] if b else "pas encore visible"108 print(time.strftime("%H:%M:%S"), state, flush=True)109 if state in ("VALID", "INVALID", "FAILED"):110 return 0 if state == "VALID" else 1111 time.sleep(20)112 return 1113 if cmd == "group":114 # groupe interne (membres de l'équipe seulement) avec accès à tous les builds : rien n'est soumis à la115 # revue bêta, aucun testeur externe116 s, j = call("GET", f"/v1/apps/{app}/betaGroups?fields[betaGroups]=name,isInternalGroup,hasAccessToAllBuilds")117 group = next((g for g in j.get("data", []) if g["attributes"]["isInternalGroup"]), None)118 if not group:119 s, j = call("POST", "/v1/betaGroups", {"data": {"type": "betaGroups",120 "attributes": {"name": GROUP, "isInternalGroup": True, "hasAccessToAllBuilds": True},121 "relationships": {"app": {"data": {"type": "apps", "id": app}}}}})122 if s >= 300:123 print("création du groupe refusée :", s, json.dumps(j, ensure_ascii=False)[:600])124 return 1125 group = j["data"]126 gid = group["id"]127 s, j = call("GET", f"/v1/betaGroups/{gid}/betaTesters?limit=50")128 testers = j.get("data", [])129 if not testers:130 # même testeur interne que le groupe interne de l'app modèle (compte de l'équipe)131 s, j = call("GET", f"/v1/apps/{MODEL_APP}/betaGroups?fields[betaGroups]=isInternalGroup")132 model = next((g["id"] for g in j.get("data", []) if g["attributes"]["isInternalGroup"]), None)133 if model:134 s, j = call("GET", f"/v1/betaGroups/{model}/betaTesters?limit=50")135 for t in j.get("data", []):136 a = t["attributes"]137 s2, j2 = call("POST", "/v1/betaTesters", {"data": {"type": "betaTesters",138 "attributes": {"email": a["email"], "firstName": a.get("firstName"), "lastName": a.get("lastName")},139 "relationships": {"betaGroups": {"data": [{"type": "betaGroups", "id": gid}]}}}})140 if s2 >= 300:141 print("ajout du testeur refusé :", s2, json.dumps(j2, ensure_ascii=False)[:400])142 s, j = call("GET", f"/v1/betaGroups/{gid}/betaTesters?limit=50")143 testers = j.get("data", [])144 print(gid, group["attributes"]["name"], "interne, tous les builds ;", len(testers), "testeur(s)")145 return 0146 print("usage: asc.py app | build [numéro] | wait [numéro] | group | raw MÉTHODE CHEMIN [JSON]")147 return 2148149150if __name__ == "__main__":151 sys.exit(main())152