SPB Git

Repository Public

asc.py 11.1 KB 247 lines python

1#!/usr/bin/env python32# =============================================================================3#                  SP BOUCHER | SOFTWARE & RESEARCH4#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# PROJECT METADATA8# -----------------------------------------------------------------------------9# Project          : SP Keyboard10# 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-keyboard20# Created          : 2026-12-0121# Last Modified    : 2026-12-0122#23# =============================================================================24# AUTHOR & PROFESSIONAL AFFILIATION25# =============================================================================26#27# Author           : Simon-Pierre Boucher28# Position         : Professor of Finance29# Institution      : Université du Québec en Outaouais (UQO)30# Department       : Département des sciences administratives31# Organization     : SP Boucher32#33# Website          : https://spboucher.ai34# Git              : https://git.spboucher.ai35#36# =============================================================================37# OFFICIAL CONTACT DIRECTORY38# =============================================================================39#40# General          : info@spboucher.ai41# Professional     : contact@spboucher.ai42# Direct           : simon@spboucher.ai43# Research         : research@spboucher.ai44# Development      : dev@spboucher.ai45# Support          : support@spboucher.ai46# Security/Admin   : admin@spboucher.ai47# Notifications    : notifications@spboucher.ai48#49# Preferred Contact: support@spboucher.ai50#51# =============================================================================52# COPYRIGHT & INTELLECTUAL PROPERTY53# =============================================================================54#55# Copyright (c) 202656# Simon-Pierre Boucher57#58# All rights reserved where applicable.59#60# This file is governed by the applicable project license,61# copyright notices, institutional agreements and relevant law.62#63# Unless expressly authorized by the applicable license or64# rights holder, copying, redistribution, sublicensing,65# publication and commercial exploitation are not permitted.66#67# Existing third-party rights and notices remain unaffected.68#69# =============================================================================70# CONFIDENTIALITY & SECURITY71# =============================================================================72#73# Classification   : Public74# Distribution     : Public repository; use is governed by the project license75# Security Contact : admin@spboucher.ai76#77# Access to this source does not independently grant permission78# to redistribute or disclose confidential materials.79#80# Do not embed credentials, private keys, access tokens,81# certificates or confidential personal information.82#83# =============================================================================84# LICENSE & MAINTENANCE85# =============================================================================86#87# License          : None specified (no license file in this repository)88# Maintainer       : Simon-Pierre Boucher89# Technical Contact: dev@spboucher.ai90#91# =============================================================================92# END OF SP BOUCHER SOURCE HEADER93# =============================================================================9495import json96import os97import sys98import time99import urllib.error100import urllib.request101102import jwt  # PyJWT103104KEY_ID = os.environ.get("ASC_KEY_ID", "L379BDKR69")105ISSUER = os.environ.get("ASC_ISSUER_ID", "013e761f-e05c-4d93-a50b-f3d960adae4a")106APP = os.environ.get("SPK_ASC_APP", "6841658614")   # « SP Keyboard », ai.spboucher.keyboard, SKU spkeyboard-ios-001107VERSION = os.environ.get("SPK_VERSION", "1.0.0")108BUNDLE = "ai.spboucher.keyboard"109GROUP = "Test"110MODEL_APP = "6836172581"   # SP Music iOS: its internal group holds the team's internal tester111112113def token():114    key = open(os.path.expanduser(f"~/.appstoreconnect/private_keys/AuthKey_{KEY_ID}.p8")).read()115    now = int(time.time())116    return jwt.encode({"iss": ISSUER, "iat": now, "exp": now + 900, "aud": "appstoreconnect-v1"}, key,117                      algorithm="ES256", headers={"kid": KEY_ID})118119120def call(method, path, body=None):121    req = urllib.request.Request("https://api.appstoreconnect.apple.com" + path, method=method,122                                 data=json.dumps(body).encode() if body else None,123                                 headers={"Authorization": "Bearer " + token(), "Content-Type": "application/json"})124    try:125        with urllib.request.urlopen(req, timeout=40) as r:126            return r.status, json.loads(r.read() or b"{}")127    except urllib.error.HTTPError as e:128        return e.code, json.loads(e.read() or b"{}")129130131def resolve_app():132    """The record's id: SPK_ASC_APP when set, otherwise looked up by bundle id."""133    global APP134    if APP:135        return APP136    s, j = call("GET", f"/v1/apps?filter[bundleId]={BUNDLE}&fields[apps]=name,bundleId,sku,primaryLocale")137    data = [a for a in j.get("data", []) if a["attributes"]["bundleId"] == BUNDLE]138    if not data:139        print(f"no App Store Connect record for {BUNDLE} (HTTP {s}) - create it with Scripts/portal/create-asc-record.js")140        sys.exit(1)141    APP = data[0]["id"]142    return APP143144145def build(number=None):146    q = f"/v1/builds?filter[app]={APP}&filter[preReleaseVersion.version]={VERSION}&sort=-uploadedDate&limit=5"147    if number:148        q += f"&filter[version]={number}"149    s, j = call("GET", q)150    data = j.get("data", [])151    return data[0] if data else None152153154def groups():155    s, j = call("GET", f"/v1/apps/{APP}/betaGroups?fields[betaGroups]=name,isInternalGroup,hasAccessToAllBuilds&limit=50")156    return j.get("data", [])157158159def describe(b):160    a = b["attributes"]161    return f"{b['id']} {VERSION} ({a['version']}) {a['processingState']} encryption={a.get('usesNonExemptEncryption')} iOS min={a.get('minOsVersion')} expires={a.get('expirationDate')}"162163164def main():165    cmd = sys.argv[1] if len(sys.argv) > 1 else "build"166    number = sys.argv[2] if len(sys.argv) > 2 else None167    resolve_app()168    if cmd == "app":169        s, j = call("GET", f"/v1/apps/{APP}?fields[apps]=name,bundleId,sku,primaryLocale")170        print(APP, json.dumps(j.get("data", {}).get("attributes", {}), ensure_ascii=False))171        return 0172    if cmd == "build":173        b = build(number)174        print(describe(b) if b else f"no build {VERSION} {number or ''}")175        return 0 if b else 1176    if cmd == "wait":177        # the build shows up a few minutes after the upload, then goes from PROCESSING to VALID178        for _ in range(90):179            b = build(number)180            state = b["attributes"]["processingState"] if b else "not visible yet"181            print(time.strftime("%H:%M:%S"), state, flush=True)182            if state in ("VALID", "INVALID", "FAILED"):183                return 0 if state == "VALID" else 1184            time.sleep(20)185        return 1186    if cmd == "group":187        b = build(number)188        if not b:189            print("no build to attach")190            return 1191        internal = [g for g in groups() if g["attributes"]["isInternalGroup"]]192        if not internal:193            # First build of the app: the internal group is created, with the internal tester(s) of the model app's194            # internal group (people of the team; no external tester, no review).195            s, j = call("POST", "/v1/betaGroups", {"data": {"type": "betaGroups",196                        "attributes": {"name": GROUP, "isInternalGroup": True, "hasAccessToAllBuilds": True},197                        "relationships": {"app": {"data": {"type": "apps", "id": APP}}}}})198            if s >= 300:199                print("group creation refused:", s, json.dumps(j, ensure_ascii=False)[:600])200                return 1201            gid = j["data"]["id"]202            print(f"internal group « {GROUP} » created")203            s, j = call("GET", f"/v1/apps/{MODEL_APP}/betaGroups?fields[betaGroups]=isInternalGroup")204            model = next((g["id"] for g in j.get("data", []) if g["attributes"]["isInternalGroup"]), None)205            if model:206                s, j = call("GET", f"/v1/betaGroups/{model}/betaTesters?limit=50")207                for t in j.get("data", []):208                    a = t["attributes"]209                    s2, j2 = call("POST", "/v1/betaTesters", {"data": {"type": "betaTesters",210                                  "attributes": {"email": a["email"], "firstName": a.get("firstName"), "lastName": a.get("lastName")},211                                  "relationships": {"betaGroups": {"data": [{"type": "betaGroups", "id": gid}]}}}})212                    print("internal tester added" if s2 < 300 else f"tester refused: {s2} {json.dumps(j2, ensure_ascii=False)[:300]}")213            internal = [g for g in groups() if g["attributes"]["isInternalGroup"]]214        for g in internal:215            a = g["attributes"]216            if a.get("hasAccessToAllBuilds"):217                print(f"internal group « {a['name']} »: access to all builds, nothing to attach")218                continue219            s, j = call("POST", f"/v1/betaGroups/{g['id']}/relationships/builds", {"data": [{"type": "builds", "id": b["id"]}]})220            print(f"internal group « {a['name']} »: build attached" if s < 300 else f"attachment refused: {s} {json.dumps(j, ensure_ascii=False)[:400]}")221        return 0222    if cmd == "status":223        b = build(number)224        if not b:225            print(f"no build {VERSION} {number or ''}")226            return 1227        print(describe(b))228        s, j = call("GET", f"/v1/builds/{b['id']}/buildBetaDetail")229        d = j.get("data", {}).get("attributes", {})230        print("internal testing:", d.get("internalBuildState"), "| external testing:", d.get("externalBuildState"))231        s, j = call("GET", f"/v1/builds/{b['id']}/betaAppReviewSubmission")232        print("beta review:", (j.get("data") or {}).get("attributes", {}).get("betaReviewState", "no submission"))233        for g in groups():234            a = g["attributes"]235            s, j = call("GET", f"/v1/betaGroups/{g['id']}/builds?limit=200&fields[builds]=version")236            has = any(x["id"] == b["id"] for x in j.get("data", []))237            s, t = call("GET", f"/v1/betaGroups/{g['id']}/betaTesters?limit=50")238            print(f"group « {a['name']} » ({'internal' if a['isInternalGroup'] else 'external'}): "239                  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)")240        return 0241    print("usage: asc.py app | build [number] | wait [number] | group [number] | status [number]")242    return 2243244245if __name__ == "__main__":246    sys.exit(main())247
Files main
Menu

Theme