Repository Public
1#!/usr/bin/env python32# =============================================================================3# SP BOUCHER | SOFTWARE & RESEARCH4# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# PROJECT METADATA8# -----------------------------------------------------------------------------9# Project : Immo-Ka 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/immo-ka-ios-v318# Project Website : https://www.immo-ka.com19# Created : 2026-11-2520# 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.immoka.v2"106VERSION = "3.1.0"107GROUP = "Test" # groupe interne, comme pour les autres apps de l'équipe108MODEL_APP = "6839382600" # Lou-Ka v2 : son groupe interne donne le testeur à reprendre109110111def token():112 key = open(os.path.expanduser(f"~/.appstoreconnect/private_keys/AuthKey_{KEY_ID}.p8")).read()113 now = int(time.time())114 return jwt.encode({"iss": ISSUER, "iat": now, "exp": now + 900, "aud": "appstoreconnect-v1"}, key,115 algorithm="ES256", headers={"kid": KEY_ID})116117118def call(method, path, body=None):119 req = urllib.request.Request("https://api.appstoreconnect.apple.com" + path, method=method,120 data=json.dumps(body).encode() if body else None,121 headers={"Authorization": "Bearer " + token(), "Content-Type": "application/json"})122 try:123 with urllib.request.urlopen(req, timeout=40) as r:124 return r.status, json.loads(r.read() or b"{}")125 except urllib.error.HTTPError as e:126 return e.code, json.loads(e.read() or b"{}")127128129def app_id():130 s, j = call("GET", f"/v1/apps?filter[bundleId]={BUNDLE}&fields[apps]=name,bundleId,sku")131 for d in j.get("data", []):132 if d["attributes"]["bundleId"] == BUNDLE:133 return d["id"], d["attributes"]134 return None, None135136137def build(app, number=None):138 q = f"/v1/builds?filter[app]={app}&filter[preReleaseVersion.version]={VERSION}&sort=-uploadedDate&limit=5"139 if number:140 q += f"&filter[version]={number}"141 s, j = call("GET", q)142 data = j.get("data", [])143 return data[0] if data else None144145146def main():147 cmd = sys.argv[1] if len(sys.argv) > 1 else "app"148 if cmd == "raw":149 s, j = call(sys.argv[2], sys.argv[3], json.loads(sys.argv[4]) if len(sys.argv) > 4 else None)150 print(s, json.dumps(j, ensure_ascii=False)[:3000])151 return 0152 app, attrs = app_id()153 if cmd == "app":154 if not app:155 print("ABSENTE : aucune fiche App Store Connect pour", BUNDLE)156 return 1157 print(app, attrs["name"], attrs["sku"])158 return 0159 if not app:160 print("ABSENTE : aucune fiche App Store Connect pour", BUNDLE)161 return 1162 number = sys.argv[2] if len(sys.argv) > 2 else None163 if cmd == "build":164 b = build(app, number)165 if not b:166 print("aucun build", VERSION, number or "")167 return 1168 a = b["attributes"]169 print(b["id"], f"{VERSION} ({a['version']})", a["processingState"], "chiffrement:", a.get("usesNonExemptEncryption"),170 "iOS min:", a.get("minOsVersion"), "expire:", a.get("expirationDate"))171 return 0172 if cmd == "wait":173 # le build apparaît quelques minutes après l'envoi, puis passe de PROCESSING à VALID174 for _ in range(90):175 b = build(app, number)176 state = b["attributes"]["processingState"] if b else "pas encore visible"177 print(time.strftime("%H:%M:%S"), state, flush=True)178 if state in ("VALID", "INVALID", "FAILED"):179 return 0 if state == "VALID" else 1180 time.sleep(20)181 return 1182 if cmd == "group":183 # groupe interne (membres de l'équipe seulement) avec accès à tous les builds : rien n'est soumis à la184 # revue bêta, aucun testeur externe185 s, j = call("GET", f"/v1/apps/{app}/betaGroups?fields[betaGroups]=name,isInternalGroup,hasAccessToAllBuilds")186 group = next((g for g in j.get("data", []) if g["attributes"]["isInternalGroup"]), None)187 if not group:188 s, j = call("POST", "/v1/betaGroups", {"data": {"type": "betaGroups",189 "attributes": {"name": GROUP, "isInternalGroup": True, "hasAccessToAllBuilds": True},190 "relationships": {"app": {"data": {"type": "apps", "id": app}}}}})191 if s >= 300:192 print("création du groupe refusée :", s, json.dumps(j, ensure_ascii=False)[:600])193 return 1194 group = j["data"]195 gid = group["id"]196 s, j = call("GET", f"/v1/betaGroups/{gid}/betaTesters?limit=50")197 testers = j.get("data", [])198 if not testers:199 # même testeur interne que le groupe interne de l'app modèle (compte de l'équipe)200 s, j = call("GET", f"/v1/apps/{MODEL_APP}/betaGroups?fields[betaGroups]=isInternalGroup")201 model = next((g["id"] for g in j.get("data", []) if g["attributes"]["isInternalGroup"]), None)202 if model:203 s, j = call("GET", f"/v1/betaGroups/{model}/betaTesters?limit=50")204 for t in j.get("data", []):205 a = t["attributes"]206 s2, j2 = call("POST", "/v1/betaTesters", {"data": {"type": "betaTesters",207 "attributes": {"email": a["email"], "firstName": a.get("firstName"), "lastName": a.get("lastName")},208 "relationships": {"betaGroups": {"data": [{"type": "betaGroups", "id": gid}]}}}})209 if s2 >= 300:210 print("ajout du testeur refusé :", s2, json.dumps(j2, ensure_ascii=False)[:400])211 s, j = call("GET", f"/v1/betaGroups/{gid}/betaTesters?limit=50")212 testers = j.get("data", [])213 print(gid, group["attributes"]["name"], "interne, tous les builds ;", len(testers), "testeur(s)")214 return 0215 print("usage: asc.py app | build [numéro] | wait [numéro] | group | raw MÉTHODE CHEMIN [JSON]")216 return 2217218219if __name__ == "__main__":220 sys.exit(main())221