geesawra.industries/hydraulophone
An unofficial YouTube Music app for iPhone, iPad, and Mac.
0
0
#!/usr/bin/env python3
"""Choose a paired physical iPhone and establish its CoreDevice connection."""
from __future__ import annotations
import json
import os
import subprocess
import sys
def fail(message: str) -> None:
print(message, file=sys.stderr)
raise SystemExit(1)
def nested_value(device: dict, *paths: tuple[str, ...]) -> str | None:
for path in paths:
value: object = device
for key in path:
if not isinstance(value, dict):
value = None
break
value = value.get(key)
if isinstance(value, str) and value:
return value
return None
def print_connected_udid(device: dict[str, str]) -> None:
# A paired Wi-Fi iPhone can appear as "available" until a CoreDevice
# request opens its tunnel. The install command needs that live tunnel.
command = ["xcrun", "devicectl", "device", "info", "details", "--device", device["udid"]]
try:
result = subprocess.run(command, capture_output=True, text=True, timeout=30)
except (OSError, subprocess.TimeoutExpired):
fail(f"Could not connect to {device['name']}. Unlock it and check its Wi-Fi connection.")
if result.returncode != 0:
fail(f"Could not connect to {device['name']}. Unlock it and check its Wi-Fi connection.")
print(device["udid"])
def main() -> None:
command = [
"xcrun",
"devicectl",
"list",
"devices",
"--filter",
"Reality = 'physical' AND Platform BEGINSWITH 'iOS' AND Model CONTAINS 'iPhone'",
"--json-output",
"-",
]
try:
result = subprocess.run(command, capture_output=True, text=True, timeout=90)
except (OSError, subprocess.TimeoutExpired) as error:
fail(f"Could not read connected iPhones from devicectl: {error}")
if result.returncode != 0:
detail = result.stderr.strip() or result.stdout.strip()
fail(f"devicectl could not list connected iPhones.\n{detail}")
try:
payload = json.loads(result.stdout)
devices = payload["result"]["devices"]
except (json.JSONDecodeError, KeyError, TypeError) as error:
fail(f"Could not parse the devicectl device list: {error}")
candidates = []
for device in devices:
if not isinstance(device, dict):
continue
name = nested_value(
device,
("deviceProperties", "name"),
("properties", "state", "name"),
("properties", "device", "name"),
("properties", "name"),
("name",),
) or "Unnamed iPhone"
udid = nested_value(
device,
("hardwareProperties", "udid"),
("properties", "hardware", "udid"),
("properties", "udid"),
("udid",),
)
identifier = nested_value(device, ("identifier",))
if udid:
candidates.append({"name": name, "udid": udid, "identifier": identifier})
if not candidates:
fail(
"No available physical iPhones were found. Connect and unlock an iPhone, "
"then trust this Mac and enable Developer Mode if prompted."
)
requested = os.environ.get("HYDRAULOPHONE_DEVICE", "").strip()
if requested:
matches = [
device
for device in candidates
if requested in (device["udid"], device["identifier"], device["name"])
]
if len(matches) == 1:
print_connected_udid(matches[0])
return
if len(matches) > 1:
fail(f"HYDRAULOPHONE_DEVICE={requested!r} matches more than one device; use a UDID.")
available = ", ".join(f"{d['name']} ({d['udid']})" for d in candidates)
fail(f"No available iPhone matches HYDRAULOPHONE_DEVICE={requested!r}. Found: {available}")
if len(candidates) == 1:
print_connected_udid(candidates[0])
return
print("Select a connected iPhone:", file=sys.stderr)
for index, device in enumerate(candidates, start=1):
print(f" {index}. {device['name']} ({device['udid']})", file=sys.stderr)
if not sys.stdin.isatty():
fail("Set HYDRAULOPHONE_DEVICE to an iPhone UDID or exact name in non-interactive use.")
try:
selection = input("Device number: ").strip()
selected_index = int(selection) - 1
selected = candidates[selected_index]
except (ValueError, IndexError, EOFError):
fail("Choose one of the listed device numbers.")
print_connected_udid(selected)
if __name__ == "__main__":
main()