Repository Public
1#!/usr/bin/env python32# =============================================================================3# SP BOUCHER | SOFTWARE & RESEARCH4# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# PROJECT METADATA8# -----------------------------------------------------------------------------9# Project : Valo-Plex iOS10# File : Scripts/asc.py11# Description : appels à l'API App Store Connect avec la clé d'équipe déjà12# présente sur ce Mac (~/.appstoreconnect/private_keys).13# Aucun secret dans le dépôt. usage : asc.py app | build14# [numéro] | wait [numéro] | group | raw MÉTHODE CHEMIN15# [JSON]16# Module : Scripts17# Repository : https://git.spboucher.ai/valo-plex-ios18# Project Website : https://www.valo-plex.com19# Created : 2026-12-0120# Last Modified : 2026-12-0121#22# =============================================================================23# AUTHOR & PROFESSIONAL AFFILIATION24# =============================================================================25#26# Author : Simon-Pierre Boucher27# Position : Professor of Finance28# Institution : Université du Québec en Outaouais (UQO)29# Department : Département des sciences administratives30# Organization : SP Boucher31#32# Website : https://spboucher.ai33# Git : https://git.spboucher.ai34#35# =============================================================================36# OFFICIAL CONTACT DIRECTORY37# =============================================================================38#39# General : info@spboucher.ai40# Professional : contact@spboucher.ai41# Direct : simon@spboucher.ai42# Research : research@spboucher.ai43# Development : dev@spboucher.ai44# Support : support@spboucher.ai45# Security/Admin : admin@spboucher.ai46# Notifications : notifications@spboucher.ai47#48# Preferred Contact: support@spboucher.ai49#50# =============================================================================51# COPYRIGHT & INTELLECTUAL PROPERTY52# =============================================================================53#54# Copyright (c) 202655# Simon-Pierre Boucher56#57# All rights reserved where applicable.58#59# This file is governed by the applicable project license,60# copyright notices, institutional agreements and relevant law.61#62# Unless expressly authorized by the applicable license or63# rights holder, copying, redistribution, sublicensing,64# publication and commercial exploitation are not permitted.65#66# Existing third-party rights and notices remain unaffected.67#68# =============================================================================69# CONFIDENTIALITY & SECURITY70# =============================================================================71#72# Classification : Public73# Distribution : Public repository; use is governed by the project license74# Security Contact : admin@spboucher.ai75#76# Access to this source does not independently grant permission77# to redistribute or disclose confidential materials.78#79# Do not embed credentials, private keys, access tokens,80# certificates or confidential personal information.81#82# =============================================================================83# LICENSE & MAINTENANCE84# =============================================================================85#86# License : None specified (no license file in this repository)87# Maintainer : Simon-Pierre Boucher88# Technical Contact: dev@spboucher.ai89#90# =============================================================================91# END OF SP BOUCHER SOURCE HEADER92# =============================================================================9394import json95import os96import sys97import time98import urllib.error99import urllib.request100101import jwt # PyJWT102103KEY_ID = os.environ.get("ASC_KEY_ID", "L379BDKR69")104ISSUER = os.environ.get("ASC_ISSUER_ID", "013e761f-e05c-4d93-a50b-f3d960adae4a")105BUNDLE = "com.spboucher.valoplex"106# version de la mise en marché : celle de project.yml107VERSION = next((l.split('"')[1] for l in open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "project.yml")) if "MARKETING_VERSION" in l), "1.0.0")108GROUP = "Test" # groupe interne, comme pour les autres apps de l'équipe109MODEL_APP = "6839382600" # Lou-Ka v2 : son groupe interne donne le testeur à reprendre110111112def token():113 key = open(os.path.expanduser(f"~/.appstoreconnect/private_keys/AuthKey_{KEY_ID}.p8")).read()114 now = int(time.time())115 return jwt.encode({"iss": ISSUER, "iat": now, "exp": now + 900, "aud": "appstoreconnect-v1"}, key,116 algorithm="ES256", headers={"kid": KEY_ID})117118119def call(method, path, body=None):120 req = urllib.request.Request("https://api.appstoreconnect.apple.com" + path, method=method,121 data=json.dumps(body).encode() if body else None,122 headers={"Authorization": "Bearer " + token(), "Content-Type": "application/json"})123 try:124 with urllib.request.urlopen(req, timeout=40) as r:125 return r.status, json.loads(r.read() or b"{}")126 except urllib.error.HTTPError as e:127 return e.code, json.loads(e.read() or b"{}")128129130def app_id():131 s, j = call("GET", f"/v1/apps?filter[bundleId]={BUNDLE}&fields[apps]=name,bundleId,sku")132 for d in j.get("data", []):133 if d["attributes"]["bundleId"] == BUNDLE:134 return d["id"], d["attributes"]135 return None, None136137138def build(app, number=None):139 q = f"/v1/builds?filter[app]={app}&filter[preReleaseVersion.version]={VERSION}&sort=-uploadedDate&limit=5"140 if number:141 q += f"&filter[version]={number}"142 s, j = call("GET", q)143 data = j.get("data", [])144 return data[0] if data else None145146147def main():148 cmd = sys.argv[1] if len(sys.argv) > 1 else "app"149 if cmd == "raw":150 s, j = call(sys.argv[2], sys.argv[3], json.loads(sys.argv[4]) if len(sys.argv) > 4 else None)151 print(s, json.dumps(j, ensure_ascii=False)[:3000])152 return 0153 app, attrs = app_id()154 if cmd == "app":155 if not app:156 print("ABSENTE : aucune fiche App Store Connect pour", BUNDLE)157 return 1158 print(app, attrs["name"], attrs["sku"])159 return 0160 if not app:161 print("ABSENTE : aucune fiche App Store Connect pour", BUNDLE)162 return 1163 number = sys.argv[2] if len(sys.argv) > 2 else None164 if cmd == "build":165 b = build(app, number)166 if not b:167 print("aucun build", VERSION, number or "")168 return 1169 a = b["attributes"]170 print(b["id"], f"{VERSION} ({a['version']})", a["processingState"], "chiffrement:", a.get("usesNonExemptEncryption"),171 "iOS min:", a.get("minOsVersion"), "expire:", a.get("expirationDate"))172 return 0173 if cmd == "wait":174 # le build apparaît quelques minutes après l'envoi, puis passe de PROCESSING à VALID175 for _ in range(90):176 b = build(app, number)177 state = b["attributes"]["processingState"] if b else "pas encore visible"178 print(time.strftime("%H:%M:%S"), state, flush=True)179 if state in ("VALID", "INVALID", "FAILED"):180 return 0 if state == "VALID" else 1181 time.sleep(20)182 return 1183 if cmd == "group":184 # groupe interne (membres de l'équipe seulement) avec accès à tous les builds : rien n'est soumis à la185 # revue bêta, aucun testeur externe186 s, j = call("GET", f"/v1/apps/{app}/betaGroups?fields[betaGroups]=name,isInternalGroup,hasAccessToAllBuilds")187 group = next((g for g in j.get("data", []) if g["attributes"]["isInternalGroup"]), None)188 if not group:189 s, j = call("POST", "/v1/betaGroups", {"data": {"type": "betaGroups",190 "attributes": {"name": GROUP, "isInternalGroup": True, "hasAccessToAllBuilds": True},191 "relationships": {"app": {"data": {"type": "apps", "id": app}}}}})192 if s >= 300:193 print("création du groupe refusée :", s, json.dumps(j, ensure_ascii=False)[:600])194 return 1195 group = j["data"]196 gid = group["id"]197 s, j = call("GET", f"/v1/betaGroups/{gid}/betaTesters?limit=50")198 testers = j.get("data", [])199 if not testers:200 # même testeur interne que le groupe interne de l'app modèle (compte de l'équipe)201 s, j = call("GET", f"/v1/apps/{MODEL_APP}/betaGroups?fields[betaGroups]=isInternalGroup")202 model = next((g["id"] for g in j.get("data", []) if g["attributes"]["isInternalGroup"]), None)203 if model:204 s, j = call("GET", f"/v1/betaGroups/{model}/betaTesters?limit=50")205 for t in j.get("data", []):206 a = t["attributes"]207 s2, j2 = call("POST", "/v1/betaTesters", {"data": {"type": "betaTesters",208 "attributes": {"email": a["email"], "firstName": a.get("firstName"), "lastName": a.get("lastName")},209 "relationships": {"betaGroups": {"data": [{"type": "betaGroups", "id": gid}]}}}})210 if s2 >= 300:211 print("ajout du testeur refusé :", s2, json.dumps(j2, ensure_ascii=False)[:400])212 s, j = call("GET", f"/v1/betaGroups/{gid}/betaTesters?limit=50")213 testers = j.get("data", [])214 print(gid, group["attributes"]["name"], "interne, tous les builds ;", len(testers), "testeur(s)")215 return 0216 print("usage: asc.py app | build [numéro] | wait [numéro] | group | raw MÉTHODE CHEMIN [JSON]")217 return 2218219220if __name__ == "__main__":221 sys.exit(main())222