SPB Git

Repository Public

asc.py 6.1 KB 137 lines python

1#!/usr/bin/env python32# Food-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  # PyJWT1819KEY_ID = os.environ.get("ASC_KEY_ID", "L379BDKR69")20ISSUER = os.environ.get("ASC_ISSUER_ID", "013e761f-e05c-4d93-a50b-f3d960adae4a")21BUNDLE = "com.spboucher.foodka.v2"22VERSION = "2.0.0"23GROUP = "Test"                      # groupe interne, comme pour les autres apps de l'équipe24MODEL_APP = "6839382600"            # Lou-Ka v2 : son groupe interne donne le testeur à reprendre252627def token():28    key = open(os.path.expanduser(f"~/.appstoreconnect/private_keys/AuthKey_{KEY_ID}.p8")).read()29    now = int(time.time())30    return jwt.encode({"iss": ISSUER, "iat": now, "exp": now + 900, "aud": "appstoreconnect-v1"}, key,31                      algorithm="ES256", headers={"kid": KEY_ID})323334def call(method, path, body=None):35    req = urllib.request.Request("https://api.appstoreconnect.apple.com" + path, method=method,36                                 data=json.dumps(body).encode() if body else None,37                                 headers={"Authorization": "Bearer " + token(), "Content-Type": "application/json"})38    try:39        with urllib.request.urlopen(req, timeout=40) as r:40            return r.status, json.loads(r.read() or b"{}")41    except urllib.error.HTTPError as e:42        return e.code, json.loads(e.read() or b"{}")434445def app_id():46    s, j = call("GET", f"/v1/apps?filter[bundleId]={BUNDLE}&fields[apps]=name,bundleId,sku")47    for d in j.get("data", []):48        if d["attributes"]["bundleId"] == BUNDLE:49            return d["id"], d["attributes"]50    return None, None515253def build(app, number=None):54    q = f"/v1/builds?filter[app]={app}&filter[preReleaseVersion.version]={VERSION}&sort=-uploadedDate&limit=5"55    if number:56        q += f"&filter[version]={number}"57    s, j = call("GET", q)58    data = j.get("data", [])59    return data[0] if data else None606162def main():63    cmd = sys.argv[1] if len(sys.argv) > 1 else "app"64    if cmd == "raw":65        s, j = call(sys.argv[2], sys.argv[3], json.loads(sys.argv[4]) if len(sys.argv) > 4 else None)66        print(s, json.dumps(j, ensure_ascii=False)[:3000])67        return 068    app, attrs = app_id()69    if cmd == "app":70        if not app:71            print("ABSENTE : aucune fiche App Store Connect pour", BUNDLE)72            return 173        print(app, attrs["name"], attrs["sku"])74        return 075    if not app:76        print("ABSENTE : aucune fiche App Store Connect pour", BUNDLE)77        return 178    number = sys.argv[2] if len(sys.argv) > 2 else None79    if cmd == "build":80        b = build(app, number)81        if not b:82            print("aucun build", VERSION, number or "")83            return 184        a = b["attributes"]85        print(b["id"], f"{VERSION} ({a['version']})", a["processingState"], "chiffrement:", a.get("usesNonExemptEncryption"),86              "iOS min:", a.get("minOsVersion"), "expire:", a.get("expirationDate"))87        return 088    if cmd == "wait":89        # le build apparaît quelques minutes après l'envoi, puis passe de PROCESSING à VALID90        for _ in range(90):91            b = build(app, number)92            state = b["attributes"]["processingState"] if b else "pas encore visible"93            print(time.strftime("%H:%M:%S"), state, flush=True)94            if state in ("VALID", "INVALID", "FAILED"):95                return 0 if state == "VALID" else 196            time.sleep(20)97        return 198    if cmd == "group":99        # groupe interne (membres de l'équipe seulement) avec accès à tous les builds : rien n'est soumis à la100        # revue bêta, aucun testeur externe101        s, j = call("GET", f"/v1/apps/{app}/betaGroups?fields[betaGroups]=name,isInternalGroup,hasAccessToAllBuilds")102        group = next((g for g in j.get("data", []) if g["attributes"]["isInternalGroup"]), None)103        if not group:104            s, j = call("POST", "/v1/betaGroups", {"data": {"type": "betaGroups",105                        "attributes": {"name": GROUP, "isInternalGroup": True, "hasAccessToAllBuilds": True},106                        "relationships": {"app": {"data": {"type": "apps", "id": app}}}}})107            if s >= 300:108                print("création du groupe refusée :", s, json.dumps(j, ensure_ascii=False)[:600])109                return 1110            group = j["data"]111        gid = group["id"]112        s, j = call("GET", f"/v1/betaGroups/{gid}/betaTesters?limit=50")113        testers = j.get("data", [])114        if not testers:115            # même testeur interne que le groupe interne de l'app modèle (compte de l'équipe)116            s, j = call("GET", f"/v1/apps/{MODEL_APP}/betaGroups?fields[betaGroups]=isInternalGroup")117            model = next((g["id"] for g in j.get("data", []) if g["attributes"]["isInternalGroup"]), None)118            if model:119                s, j = call("GET", f"/v1/betaGroups/{model}/betaTesters?limit=50")120                for t in j.get("data", []):121                    a = t["attributes"]122                    s2, j2 = call("POST", "/v1/betaTesters", {"data": {"type": "betaTesters",123                                  "attributes": {"email": a["email"], "firstName": a.get("firstName"), "lastName": a.get("lastName")},124                                  "relationships": {"betaGroups": {"data": [{"type": "betaGroups", "id": gid}]}}}})125                    if s2 >= 300:126                        print("ajout du testeur refusé :", s2, json.dumps(j2, ensure_ascii=False)[:400])127            s, j = call("GET", f"/v1/betaGroups/{gid}/betaTesters?limit=50")128            testers = j.get("data", [])129        print(gid, group["attributes"]["name"], "interne, tous les builds ;", len(testers), "testeur(s)")130        return 0131    print("usage: asc.py app | build [numéro] | wait [numéro] | group | raw MÉTHODE CHEMIN [JSON]")132    return 2133134135if __name__ == "__main__":136    sys.exit(main())137
Files main
Menu

Theme