知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.
Swift androidlinuxlive-captionsmacosmeeting-notesmenubar-appsimultaneous-interpretationspeech-recognitionsubtitlesswiftswiftuitranslationwindows
build(ios): device builds, signed with a profile, plus the icon, privacy manifest and scripts for provisioning and TestFlight
wquguru187524f1ba4b
diff --git a/Sources/CicadaIcon/main.swift b/Sources/CicadaIcon/main.swiftindex 6ef246c..6e2053a 100644--- a/Sources/CicadaIcon/main.swift+++ b/Sources/CicadaIcon/main.swift@@ -82,7 +82,9 @@ enum CicadaLogo {}}-func render(_ px: Int, dev: Bool) -> Data {+/// `ios`: the iPhone and iPad icon, a full-bleed opaque square (the system draws the corners and+/// App Store Connect refuses an alpha channel); otherwise the macOS grid with its margin and shadow.+func render(_ px: Int, dev: Bool, ios: Bool = false) -> Data {let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: px, pixelsHigh: px, bitsPerSample: 8,samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB,bytesPerRow: 0, bitsPerPixel: 0)!@@ -90,13 +92,18 @@ func render(_ px: Int, dev: Bool) -> Data {NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: rep)let s = CGFloat(px) / 1024// macOS icon grid: an 824 pt body inset 100 pt, corner ≈ 185 pt.- let body = NSRect(x: 100 * s, y: 100 * s, width: 824 * s, height: 824 * s)- let squircle = NSBezierPath(roundedRect: body, xRadius: 185 * s, yRadius: 185 * s)- let shadow = NSShadow()- shadow.shadowBlurRadius = 20 * s- shadow.shadowOffset = NSSize(width: 0, height: -8 * s)- shadow.shadowColor = NSColor.black.withAlphaComponent(0.25)- shadow.set()+ // iOS: the body overflows the canvas by 80 pt a side, so the logo's own rounded tile reaches+ // past every corner and the system's mask is the only rounding.+ let body = ios ? NSRect(x: -80 * s, y: -80 * s, width: 1184 * s, height: 1184 * s) : NSRect(x: 100 * s, y: 100 * s, width: 824 * s, height: 824 * s)+ let squircle = ios ? NSBezierPath(rect: NSRect(x: 0, y: 0, width: 1024 * s, height: 1024 * s))+ : NSBezierPath(roundedRect: body, xRadius: 185 * s, yRadius: 185 * s)+ if !ios {+ let shadow = NSShadow()+ shadow.shadowBlurRadius = 20 * s+ shadow.shadowOffset = NSSize(width: 0, height: -8 * s)+ shadow.shadowColor = NSColor.black.withAlphaComponent(0.25)+ shadow.set()+ }orange.setFill()squircle.fill()NSShadow().set()@@ -115,21 +122,34 @@ func render(_ px: Int, dev: Bool) -> Data {NSGraphicsContext.saveGraphicsState()squircle.addClip()ink.setFill()- NSRect(x: body.minX, y: body.minY, width: body.width, height: 170 * s).fill()+ let band = ios ? NSRect(x: 0, y: 0, width: 1024 * s, height: 190 * s) : NSRect(x: body.minX, y: body.minY, width: body.width, height: 170 * s)+ band.fill()let font = NSFont.systemFont(ofSize: 110 * s, weight: .heavy)let text = NSAttributedString(string: "DEV", attributes: [.font: font, .foregroundColor: NSColor.white, .kern: 14 * s,])let size = text.size()- text.draw(at: NSPoint(x: body.midX - size.width / 2 + 7 * s, y: body.minY + (170 * s - size.height) / 2 + 6 * s))+ text.draw(at: NSPoint(x: band.midX - size.width / 2 + 7 * s, y: band.minY + (band.height - size.height) / 2 + 6 * s))NSGraphicsContext.restoreGraphicsState()}NSGraphicsContext.restoreGraphicsState()+ if ios, let image = rep.cgImage,+ let opaque = CGContext(data: nil, width: px, height: px, bitsPerComponent: 8, bytesPerRow: 0,+ space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue) {+ // Drawn again without an alpha channel: a fully opaque RGBA PNG is still refused.+ opaque.draw(image, in: CGRect(x: 0, y: 0, width: px, height: px))+ if let flat = opaque.makeImage() { return NSBitmapImageRep(cgImage: flat).representation(using: .png, properties: [:])! }+ }return rep.representation(using: .png, properties: [:])!}let args = Array(CommandLine.arguments.dropFirst())let dev = args.contains("--dev")+// --ios <file.png>: the 1024 px iOS icon only (ios/scripts/build.sh).+if let i = args.firstIndex(of: "--ios"), i + 1 < args.count {+ try render(1024, dev: dev, ios: true).write(to: URL(fileURLWithPath: args[i + 1]))+ exit(0)+}let out = URL(fileURLWithPath: args.first { $0 != "--dev" } ?? "AppIcon.iconset")try FileManager.default.createDirectory(at: out, withIntermediateDirectories: true)for size in [16, 32, 128, 256, 512] {diff --git a/ios/Resources/Info.plist b/ios/Resources/Info.plistindex bf66478..eec9e02 100644--- a/ios/Resources/Info.plist+++ b/ios/Resources/Info.plist@@ -32,6 +32,8 @@<array><string>iPhoneSimulator</string></array>+ <key>ITSAppUsesNonExemptEncryption</key>+ <false/><key>LSRequiresIPhoneOS</key><true/><key>MinimumOSVersion</key>diff --git a/ios/Resources/PrivacyInfo.xcprivacy b/ios/Resources/PrivacyInfo.xcprivacynew file mode 100644index 0000000..51d95c8--- /dev/null+++ b/ios/Resources/PrivacyInfo.xcprivacy@@ -0,0 +1,34 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<!-- The app's privacy manifest (App Store Connect refuses builds without one that use these APIs).+ UserDefaults: the app's own settings (CA92.1). File timestamps: of files in the app's container,+ an imported copy's date and the voice clip's age (C617.1). No tracking. -->+<plist version="1.0">+<dict>+ <key>NSPrivacyTracking</key>+ <false/>+ <key>NSPrivacyTrackingDomains</key>+ <array/>+ <key>NSPrivacyCollectedDataTypes</key>+ <array/>+ <key>NSPrivacyAccessedAPITypes</key>+ <array>+ <dict>+ <key>NSPrivacyAccessedAPIType</key>+ <string>NSPrivacyAccessedAPICategoryUserDefaults</string>+ <key>NSPrivacyAccessedAPITypeReasons</key>+ <array>+ <string>CA92.1</string>+ </array>+ </dict>+ <dict>+ <key>NSPrivacyAccessedAPIType</key>+ <string>NSPrivacyAccessedAPICategoryFileTimestamp</string>+ <key>NSPrivacyAccessedAPITypeReasons</key>+ <array>+ <string>C617.1</string>+ </array>+ </dict>+ </array>+</dict>+</plist>diff --git a/ios/scripts/build.sh b/ios/scripts/build.shindex 23cca17..1853963 100755--- a/ios/scripts/build.sh+++ b/ios/scripts/build.sh@@ -1,13 +1,26 @@#!/usr/bin/env bash-# Builds ios/build/Cicada.app for the iOS simulator: the shared Mac sources (ios/shared-sources.txt)-# and ios/Sources in one module, bundled by hand like the Mac's scripts/build.sh (no .xcodeproj).+# Builds Cicada.app: the shared Mac sources (ios/shared-sources.txt) and ios/Sources in one module,+# bundled by hand like the Mac's scripts/build.sh (no .xcodeproj).# Without RELEASE=1 it is a dev build: "Cicada Dev", bundle id com.wquguru.cicada.dev, cicada-dev:// commands.+# ios/scripts/build.sh the simulator: ios/build/Cicada.app, signed ad hoc+# DEVICE=1 ios/scripts/build.sh an iPhone or iPad: ios/build/device/Cicada.app, signed with+# SIGN_IDENTITY and the profiles PROFILE (app) and PROFILE_LIVE+# (the extension); ios/scripts/provision.sh makes them+# BUILD_NUMBER sets CFBundleVersion (TestFlight wants it to grow); default: the commit count.set -euo pipefailcd "$(dirname "$0")/../.."-SDK=iphonesimulator-TARGET=arm64-apple-ios26.0-simulator-APP=ios/build/Cicada.app+if [[ "${DEVICE:-}" == 1 ]]; then+ SDK=iphoneos+ TARGET=arm64-apple-ios26.0+ APP=ios/build/device/Cicada.app+ PLATFORM=iPhoneOS+else+ SDK=iphonesimulator+ TARGET=arm64-apple-ios26.0-simulator+ APP=ios/build/Cicada.app+ PLATFORM=iPhoneSimulator+firm -rf "$APP"mkdir -p "$APP"@@ -45,6 +58,20 @@ xcrun --sdk "$SDK" swiftc -O -swift-version 5 -parse-as-library -module-name Cicintents_metadata Cicada "$APP" "$APP/Cicada" "${files[@]}"cp ios/Resources/Info.plist "$APP/Info.plist"+cp ios/Resources/PrivacyInfo.xcprivacy "$APP/"+# The home screen icon: the Mac's renderer draws the full-bleed iOS square (no alpha), actool+# compiles it into Assets.car and says which Info.plist keys point at it.+ICON_TOOL=.build/release/CicadaIcon+[[ -x $ICON_TOOL ]] || swift build -c release --product CicadaIcon >/dev/null+mkdir -p "$WORK/Assets.xcassets/AppIcon.appiconset"+"$ICON_TOOL" --ios "$WORK/Assets.xcassets/AppIcon.appiconset/icon.png" $([[ "${RELEASE:-}" == 1 ]] || echo --dev)+printf '%s' '{"images":[{"filename":"icon.png","idiom":"universal","platform":"ios","size":"1024x1024"}],"info":{"author":"xcode","version":1}}' \+ > "$WORK/Assets.xcassets/AppIcon.appiconset/Contents.json"+printf '%s' '{"info":{"author":"xcode","version":1}}' > "$WORK/Assets.xcassets/Contents.json"+xcrun actool "$WORK/Assets.xcassets" --compile "$APP" --platform "$SDK" --minimum-deployment-target 26.0 \+ --app-icon AppIcon --target-device iphone --target-device ipad \+ --output-partial-info-plist "$WORK/assets.plist" --output-format human-readable-text >/dev/null+/usr/libexec/PlistBuddy -c "Merge $WORK/assets.plist" "$APP/Info.plist" >/dev/null# UI text is the Mac's: the Chinese source is the key, the other languages translate it.for d in Resources/*.lproj; domkdir -p "$APP/$(basename "$d")"@@ -56,8 +83,6 @@ cp Resources/sample/sample.m4a "$APP/"cp -R Resources/models/SpeakerEmbedding.mlpackage "$APP/"# The logo on the 听会议室 card: the Mac's own icon renderer (Sources/CicadaIcon), not a fourth# copy of the geometry. It is a host tool, built once.-ICON_TOOL=.build/release/CicadaIcon-[[ -x $ICON_TOOL ]] || swift build -c release --product CicadaIcon >/dev/nullICONS=$(mktemp -d)"$ICON_TOOL" "$ICONS/logo.iconset" >/dev/nullcp "$ICONS/logo.iconset/[email protected]" "$APP/logo.png"@@ -80,7 +105,22 @@ cp "$APP/logo.png" "$APPEX/"for d in "$APP"/*.lproj; do cp -R "$d" "$APPEX/"; donePLIST="$APP/Info.plist"-/usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString $(tr -d '[:space:]' < VERSION)" "$PLIST"+BUILD=${BUILD_NUMBER:-$(git rev-list --count HEAD 2>/dev/null || echo 1)}+for p in "$PLIST" "$APPEX/Info.plist"; do+ /usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString $(tr -d '[:space:]' < VERSION)" \+ -c "Set :CFBundleVersion $BUILD" -c "Set :CFBundleSupportedPlatforms:0 $PLATFORM" "$p"+done+# What Xcode writes into every bundle it builds; App Store Connect checks them.+SDKVER=$(xcrun --sdk "$SDK" --show-sdk-version)+SDKBUILD=$(xcrun --sdk "$SDK" --show-sdk-build-version)+XCBUILD=$(xcodebuild -version | awk '/Build version/{print $3}')+XCVER=$(xcodebuild -version | awk '/^Xcode/{split($2,v,"."); printf "%d%d%d0", v[1], v[2], v[3]}')+for p in "$PLIST" "$APPEX/Info.plist"; do+ /usr/libexec/PlistBuddy -c "Add :DTPlatformName string $SDK" -c "Add :DTPlatformVersion string $SDKVER" \+ -c "Add :DTPlatformBuild string $SDKBUILD" -c "Add :DTSDKName string $SDK$SDKVER" -c "Add :DTSDKBuild string $SDKBUILD" \+ -c "Add :DTXcode string $XCVER" -c "Add :DTXcodeBuild string $XCBUILD" \+ -c "Add :DTCompiler string com.apple.compilers.llvm.clang.1_0" -c "Add :BuildMachineOSBuild string $(sw_vers -buildVersion)" "$p"+doneif [[ "${RELEASE:-}" != 1 ]]; thenSTAMP="$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo local) @ $(git rev-parse --short HEAD 2>/dev/null || echo none)"/usr/libexec/PlistBuddy -c "Set :CFBundleIdentifier com.wquguru.cicada.dev" \@@ -92,7 +132,21 @@ if [[ "${RELEASE:-}" != 1 ]]; then"$PLIST"/usr/libexec/PlistBuddy -c "Set :CFBundleIdentifier com.wquguru.cicada.dev.live" "$APPEX/Info.plist"fi-/usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString $(tr -d '[:space:]' < VERSION)" "$APPEX/Info.plist"-codesign --force --sign - "$APPEX" 2>/dev/null-codesign --force --sign - "$APP" 2>/dev/null-echo "Built $APP ($(/usr/libexec/PlistBuddy -c 'Print :CFBundleIdentifier' "$PLIST"))"+if [[ "${DEVICE:-}" != 1 ]]; then+ codesign --force --sign - "$APPEX" 2>/dev/null+ codesign --force --sign - "$APP" 2>/dev/null+else+ # A device needs a real signature: each bundle carries its profile, and is signed with the+ # entitlements that profile grants (the extension first, then the app around it).+ : "${SIGN_IDENTITY:?DEVICE=1 needs SIGN_IDENTITY (and PROFILE, PROFILE_LIVE): see ios/scripts/provision.sh}"+ sign() { # <bundle> <profile>+ cp "$2" "$1/embedded.mobileprovision"+ security cms -D -i "$2" > "$WORK/profile.plist"+ /usr/libexec/PlistBuddy -x -c "Print :Entitlements" "$WORK/profile.plist" > "$WORK/entitlements.plist"+ codesign --force --sign "$SIGN_IDENTITY" --entitlements "$WORK/entitlements.plist" --generate-entitlement-der "$1"+ }+ sign "$APPEX" "${PROFILE_LIVE:?}"+ sign "$APP" "${PROFILE:?}"+ codesign --verify --deep --strict "$APP"+fi+echo "Built $APP ($(/usr/libexec/PlistBuddy -c 'Print :CFBundleIdentifier' "$PLIST") $(tr -d '[:space:]' < VERSION) ($BUILD))"diff --git a/ios/scripts/device.sh b/ios/scripts/device.shnew file mode 100755index 0000000..63d9f40--- /dev/null+++ b/ios/scripts/device.sh@@ -0,0 +1,16 @@+#!/usr/bin/env bash+# Builds the dev app for a connected iPhone or iPad, installs and opens it.+# ios/scripts/device.sh [<device name or UDID>]+# Signing: the variables ios/tools/provision.py development prints, read from+# ~/.cicada-signing/ios-development.env (run provision.py once and save its output there).+set -euo pipefail+cd "$(dirname "$0")/../.."+ENV=~/.cicada-signing/ios-development.env+[[ -f $ENV ]] || { echo "no $ENV: ios/tools/provision.py development > $ENV"; exit 1; }+# shellcheck disable=SC1090+source "$ENV"+DEVICE=1 ios/scripts/build.sh+TARGET=${1:-$(xcrun devicectl list devices | grep -E 'available \(paired\)|connected' | grep -v simulated | grep -oE '[0-9A-F]{8}-[0-9A-F]{16}' | head -1)}+[[ -n $TARGET ]] || { echo "no iPhone or iPad connected"; exit 1; }+xcrun devicectl device install app --device "$TARGET" ios/build/device/Cicada.app+xcrun devicectl device process launch --device "$TARGET" com.wquguru.cicada.devdiff --git a/ios/scripts/testflight.sh b/ios/scripts/testflight.shnew file mode 100755index 0000000..bde3930--- /dev/null+++ b/ios/scripts/testflight.sh@@ -0,0 +1,26 @@+#!/usr/bin/env bash+# Builds the release app for the App Store, packs it as an .ipa and uploads it to App Store Connect,+# where it shows up in TestFlight after processing (10–30 min).+# ios/scripts/testflight.sh build, pack and upload+# ios/scripts/testflight.sh --no-upload+# Signing: ~/.cicada-signing/ios-appstore.env (ios/tools/provision.py appstore > that file).+# Upload: ASC_KEY_ID and ASC_ISSUER_ID, with the key's .p8 in ~/.cicada-signing (altool looks there+# through API_PRIVATE_KEYS_DIR). The app's record must exist in App Store Connect first.+set -euo pipefail+cd "$(dirname "$0")/../.."+ENV=~/.cicada-signing/ios-appstore.env+[[ -f $ENV ]] || { echo "no $ENV: ios/tools/provision.py appstore > $ENV"; exit 1; }+# shellcheck disable=SC1090+source "$ENV"+RELEASE=1 DEVICE=1 ios/scripts/build.sh+OUT=ios/build/testflight+rm -rf "$OUT" && mkdir -p "$OUT/Payload"+cp -R ios/build/device/Cicada.app "$OUT/Payload/"+(cd "$OUT" && zip -qry Cicada.ipa Payload)+echo "Packed $OUT/Cicada.ipa"+[[ "${1:-}" == --no-upload ]] && exit 0+: "${ASC_KEY_ID:?}" "${ASC_ISSUER_ID:?}"+API_PRIVATE_KEYS_DIR=~/.cicada-signing xcrun altool --validate-app -f "$OUT/Cicada.ipa" -t ios \+ --apiKey "$ASC_KEY_ID" --apiIssuer "$ASC_ISSUER_ID"+API_PRIVATE_KEYS_DIR=~/.cicada-signing xcrun altool --upload-app -f "$OUT/Cicada.ipa" -t ios \+ --apiKey "$ASC_KEY_ID" --apiIssuer "$ASC_ISSUER_ID"diff --git a/ios/tools/asc.py b/ios/tools/asc.pynew file mode 100755index 0000000..7653995--- /dev/null+++ b/ios/tools/asc.py@@ -0,0 +1,69 @@+#!/usr/bin/env python3+"""App Store Connect API for iOS signing, without Xcode's account sign-in and without third-party+packages: the JWT is signed with openssl (ES256), requests go through urllib.++Credentials come from the environment (never from the repo):+ ASC_KEY_ID, ASC_ISSUER_ID, ASC_KEY_PATH (the .p8, e.g. ~/.cicada-signing/AuthKey_<id>.p8)++ ios/tools/asc.py get <path> e.g. /v1/bundleIds?filter[identifier]=com.wquguru.cicada+ ios/tools/asc.py post <path> <json>+ ios/tools/asc.py delete <path>+Prints the JSON reply. ios/scripts/provision.sh builds on it.+"""+import base64, json, os, subprocess, sys, tempfile, time, urllib.error, urllib.request++BASE = "https://api.appstoreconnect.apple.com"+++def b64url(b: bytes) -> str:+ return base64.urlsafe_b64encode(b).rstrip(b"=").decode()+++def der_to_raw(der: bytes) -> bytes:+ """openssl's ECDSA signature is DER (SEQUENCE of two INTEGERs); a JWT wants r || s, 32 bytes each."""+ def read_int(buf, i):+ assert buf[i] == 0x02+ n = buf[i + 1]+ v = buf[i + 2:i + 2 + n]+ return v.lstrip(b"\x00").rjust(32, b"\x00"), i + 2 + n+ assert der[0] == 0x30+ i = 2 if der[1] < 0x80 else 2 + (der[1] & 0x7F)+ r, i = read_int(der, i)+ s, _ = read_int(der, i)+ return r + s+++def token() -> str:+ key_id, issuer, path = os.environ["ASC_KEY_ID"], os.environ["ASC_ISSUER_ID"], os.path.expanduser(os.environ["ASC_KEY_PATH"])+ now = int(time.time())+ head = b64url(json.dumps({"alg": "ES256", "kid": key_id, "typ": "JWT"}).encode())+ body = b64url(json.dumps({"iss": issuer, "iat": now, "exp": now + 1100, "aud": "appstoreconnect-v1"}).encode())+ signing = f"{head}.{body}".encode()+ der = subprocess.run(["openssl", "dgst", "-sha256", "-sign", path], input=signing, capture_output=True, check=True).stdout+ return f"{head}.{body}.{b64url(der_to_raw(der))}"+++def call(method: str, path: str, data=None):+ req = urllib.request.Request(BASE + path, method=method,+ data=json.dumps(data).encode() if data is not None else None,+ headers={"Authorization": f"Bearer {token()}", "Content-Type": "application/json"})+ try:+ with urllib.request.urlopen(req, timeout=60) as r:+ raw = r.read()+ return r.status, json.loads(raw) if raw else {}+ except urllib.error.HTTPError as e:+ raw = e.read()+ try:+ return e.code, json.loads(raw)+ except ValueError:+ return e.code, {"raw": raw.decode(errors="replace")}+++if __name__ == "__main__":+ if len(sys.argv) < 3:+ sys.exit(__doc__)+ method, path = sys.argv[1].upper(), sys.argv[2]+ data = json.loads(sys.argv[3]) if len(sys.argv) > 3 else None+ status, reply = call(method, path, data)+ print(json.dumps({"status": status, **reply} if isinstance(reply, dict) else {"status": status, "data": reply}, ensure_ascii=False, indent=1))+ sys.exit(0 if status < 400 else 1)diff --git a/ios/tools/provision.py b/ios/tools/provision.pynew file mode 100755index 0000000..bf127eb--- /dev/null+++ b/ios/tools/provision.py@@ -0,0 +1,120 @@+#!/usr/bin/env python3+"""Makes what a signed iOS build needs, through the App Store Connect API (ios/tools/asc.py):+the App IDs, the connected devices, a certificate whose private key is on this Mac, and the two+provisioning profiles (the app and the CicadaLive extension). Prints the variables+ios/scripts/build.sh signs with. Safe to run again: it reuses what is there.++ ios/tools/provision.py development Apple Development, the dev bundle ids, this Mac's devices+ ios/tools/provision.py appstore Apple Distribution, the release bundle ids (TestFlight)++Needs ASC_KEY_ID, ASC_ISSUER_ID, ASC_KEY_PATH for a key that may manage Certificates,+Identifiers & Profiles (Admin, or App Manager with that access). Keys and certificates live in+~/.cicada-signing (0700); the certificate goes into the login keychain, usable by codesign only.+"""+import base64, json, os, re, subprocess, sys+sys.path.insert(0, os.path.dirname(__file__))+from asc import call++HOME = os.path.expanduser("~/.cicada-signing")+KIND = sys.argv[1] if len(sys.argv) > 1 else "development"+DEV = KIND == "development"+APP_ID = "com.wquguru.cicada.dev" if DEV else "com.wquguru.cicada"+IDS = {APP_ID: "Cicada Dev" if DEV else "Cicada", APP_ID + ".live": "Cicada Dev Live" if DEV else "Cicada Live"}+CERT_TYPE = "DEVELOPMENT" if DEV else "DISTRIBUTION"+PROFILE_TYPE = "IOS_APP_DEVELOPMENT" if DEV else "IOS_APP_STORE"+++def ok(status, reply, what):+ if status >= 400:+ sys.exit(f"{what} failed ({status}): {json.dumps(reply.get('errors', reply), ensure_ascii=False)}")+ return reply+++def run(*cmd, **kw):+ return subprocess.run(cmd, check=True, capture_output=True, text=True, **kw).stdout+++def bundle_id(identifier, name):+ _, r = call("GET", f"/v1/bundleIds?filter[identifier]={identifier}&fields[bundleIds]=identifier,platform")+ found = [b for b in r.get("data", []) if b["attributes"]["identifier"] == identifier]+ if found:+ return found[0]["id"]+ r = ok(*call("POST", "/v1/bundleIds", {"data": {"type": "bundleIds", "attributes": {+ "identifier": identifier, "name": name, "platform": "IOS"}}}), f"register {identifier}")+ print(f"registered App ID {identifier}", file=sys.stderr)+ return r["data"]["id"]+++def devices():+ """Physical devices this Mac is paired with, registered if they aren't yet."""+ out = run("xcrun", "devicectl", "list", "devices")+ udids = {m.group(2): m.group(1).strip() for m in re.finditer(r"^(\S.*?)\s{2,}.*?([0-9A-F]{8}-[0-9A-F]{16}) \(UDID\)", out, re.M)}+ _, r = call("GET", "/v1/devices?limit=200&fields[devices]=udid,name,status")+ known = {d["attributes"]["udid"]: d["id"] for d in r.get("data", [])}+ ids = []+ for udid, name in udids.items():+ if udid not in known:+ r2 = ok(*call("POST", "/v1/devices", {"data": {"type": "devices", "attributes": {+ "name": name, "udid": udid, "platform": "IOS"}}}), f"register device {name}")+ known[udid] = r2["data"]["id"]+ print(f"registered device {name} {udid}", file=sys.stderr)+ ids.append(known[udid])+ if not ids:+ sys.exit("no iPhone or iPad connected (xcrun devicectl list devices)")+ return ids+++def certificate():+ """A certificate of this kind whose private key is in ~/.cicada-signing; made if there is none."""+ key, cer = f"{HOME}/ios-{KIND}.key", f"{HOME}/ios-{KIND}.cer"+ _, r = call("GET", f"/v1/certificates?filter[certificateType]={CERT_TYPE}&fields[certificates]=certificateContent,serialNumber,expirationDate")+ if os.path.exists(key) and os.path.exists(cer):+ mine = run("openssl", "x509", "-inform", "der", "-in", cer, "-noout", "-serial").split("=")[1].strip().upper()+ for c in r.get("data", []):+ if c["attributes"]["serialNumber"].upper().lstrip("0") == mine.lstrip("0"):+ return c["id"], cer+ os.makedirs(HOME, mode=0o700, exist_ok=True)+ run("openssl", "genrsa", "-out", key, "2048")+ os.chmod(key, 0o600)+ csr = run("openssl", "req", "-new", "-key", key, "-subj", f"/CN=Cicada iOS {KIND}/O=Indaloop LLC")+ r = ok(*call("POST", "/v1/certificates", {"data": {"type": "certificates", "attributes": {+ "certificateType": CERT_TYPE, "csrContent": csr}}}), f"create {CERT_TYPE} certificate")+ with open(cer, "wb") as f:+ f.write(base64.b64decode(r["data"]["attributes"]["certificateContent"]))+ # Into the login keychain, the key usable by codesign without a prompt.+ p12, password = f"{HOME}/ios-{KIND}.p12", base64.b64encode(os.urandom(18)).decode()+ pem = run("openssl", "x509", "-inform", "der", "-in", cer)+ run("openssl", "pkcs12", "-export", "-legacy", "-inkey", key, "-out", p12, "-passout", f"pass:{password}", input=pem)+ run("security", "import", p12, "-k", os.path.expanduser("~/Library/Keychains/login.keychain-db"),+ "-P", password, "-T", "/usr/bin/codesign")+ os.remove(p12)+ print(f"created {CERT_TYPE} certificate {r['data']['id']} and added it to the login keychain", file=sys.stderr)+ return r["data"]["id"], cer+++def profile(identifier, bundle, cert, device_ids):+ name = f"Cicada {KIND} {identifier}"+ _, r = call("GET", f"/v1/profiles?filter[name]={name}&fields[profiles]=name,profileState")+ for p in r.get("data", []): # remade each time, so it always holds today's devices and certificate+ call("DELETE", f"/v1/profiles/{p['id']}")+ rel = {"bundleId": {"data": {"type": "bundleIds", "id": bundle}},+ "certificates": {"data": [{"type": "certificates", "id": cert}]}}+ if DEV:+ rel["devices"] = {"data": [{"type": "devices", "id": d} for d in device_ids]}+ r = ok(*call("POST", "/v1/profiles", {"data": {"type": "profiles", "attributes": {+ "name": name, "profileType": PROFILE_TYPE}, "relationships": rel}}), f"profile {name}")+ os.makedirs(f"{HOME}/profiles", mode=0o700, exist_ok=True)+ path = f"{HOME}/profiles/{identifier}.{KIND}.mobileprovision"+ with open(path, "wb") as f:+ f.write(base64.b64decode(r["data"]["attributes"]["profileContent"]))+ return path+++bundles = {i: bundle_id(i, n) for i, n in IDS.items()}+device_ids = devices() if DEV else []+cert, cer = certificate()+sha1 = run("openssl", "x509", "-inform", "der", "-in", cer, "-noout", "-fingerprint", "-sha1").split("=")[1].replace(":", "").strip()+paths = {i: profile(i, b, cert, device_ids) for i, b in bundles.items()}+print(f"export SIGN_IDENTITY={sha1}")+print(f"export PROFILE='{paths[APP_ID]}'")+print(f"export PROFILE_LIVE='{paths[APP_ID + '.live']}'")