mirror of
https://git.undefined-dev.fr/Blendman974/faceclaw.git
synced 2026-11-19 21:03:09 +00:00
G1 support: Preserve connections after flashing, debug
This commit is contained in:
1 parent
595b462b2e
commit
b353483ac2
38 files changed
+1291
-178
No files matched your search
@@ -102,6 +102,12 @@ Use `--device` / `-d` or set `IOS_DEVICE` when more than one device is connected
|
||||
Without either, the script selects the only device with an active Xcode tunnel.
|
||||
For the simulator, add `--simulator` (defaults to `booted`; `--device` selects one).
|
||||
|
||||
`scripts/resetOnboardingIos.sh` is the iOS counterpart of `scripts/resetOnboarding.sh`.
|
||||
It pulls the config, then pushes every `onboarding.*` key that is set back to its empty
|
||||
value, which the app reads the same as a missing key. Pushes can't remove keys, and the
|
||||
plist can't be edited directly (see below). Its `--all` uninstalls the app, since iOS has
|
||||
no equivalent of `pm clear`.
|
||||
|
||||
Transfers use `devicectl` app-container access. The app consumes a uniquely
|
||||
identified request at bootstrap, before loading settings getters and workers;
|
||||
it applies imports through NSUserDefaults rather than overwriting a plist that
|
||||
|
||||
+127
-62
@@ -18,6 +18,7 @@ BUNDLE = os.environ.get('IOS_BUNDLE_ID') or 'com.faceclaw.app'
|
||||
REMOTE = 'Library/FaceclawConfigPort'
|
||||
# The app reads requests of up to 8 MiB: a 2 MiB document embedded as an escaped JSON string.
|
||||
REQUEST_LIMIT = 8 * 1024 * 1024
|
||||
ONBOARDING_PREFIX = 'onboarding.'
|
||||
|
||||
|
||||
def run(args, tolerate=False):
|
||||
@@ -46,96 +47,160 @@ def atomic_write(path, data):
|
||||
temporary.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def resolve_device(args, work):
|
||||
device = args.device or os.environ.get('IOS_DEVICE')
|
||||
if args.simulator:
|
||||
return device or 'booted'
|
||||
if device:
|
||||
return device
|
||||
listing = work / 'devices.json'
|
||||
run(['devicectl', 'list', 'devices', '--json-output', str(listing)])
|
||||
devices = json.loads(listing.read_text())['result']['devices']
|
||||
available = [d for d in devices if d.get('connectionProperties', {}).get('tunnelState') == 'connected']
|
||||
if len(available) != 1:
|
||||
raise ValueError('Specify the iPhone with --device UDID (or IOS_DEVICE)')
|
||||
return available[0]['identifier']
|
||||
|
||||
|
||||
def exchange(args, work, device, operation, document=None):
|
||||
"""Restart the app with one request for it to consume at launch; returns its successful reply."""
|
||||
if args.simulator:
|
||||
container = Path(run(['simctl', 'get_app_container', device, BUNDLE, 'data']).stdout.strip())
|
||||
identifier = str(uuid.uuid4())
|
||||
payload = {'id': identifier, 'operation': operation}
|
||||
if document is not None:
|
||||
payload['document'] = document
|
||||
encoded = json.dumps(payload, ensure_ascii=False, allow_nan=False).encode()
|
||||
if len(encoded) > REQUEST_LIMIT:
|
||||
raise ValueError('Config request exceeds 8 MiB')
|
||||
stage = work / 'FaceclawConfigPort'
|
||||
stage.mkdir(mode=0o700, exist_ok=True)
|
||||
atomic_write(stage / 'request.json', encoded)
|
||||
if args.simulator:
|
||||
remote = container / REMOTE
|
||||
remote.mkdir(parents=True, exist_ok=True)
|
||||
atomic_write(remote / 'request.json', encoded)
|
||||
run(['simctl', 'terminate', device, BUNDLE], tolerate=True)
|
||||
run(['simctl', 'launch', device, BUNDLE])
|
||||
else:
|
||||
run(['devicectl', 'device', 'copy', 'to', '--device', device, '--domain-type', 'appDataContainer',
|
||||
'--domain-identifier', BUNDLE, '--source', str(stage), '--destination', REMOTE])
|
||||
run(['devicectl', 'device', 'process', 'launch', '--device', device, '--terminate-existing', BUNDLE])
|
||||
deadline = time.monotonic() + 25
|
||||
response = None
|
||||
while time.monotonic() < deadline:
|
||||
if args.simulator:
|
||||
response_path = remote / 'response.json'
|
||||
else:
|
||||
response_path = work / 'response.json'
|
||||
run(['devicectl', 'device', 'copy', 'from', '--device', device, '--domain-type', 'appDataContainer',
|
||||
'--domain-identifier', BUNDLE, '--source', REMOTE + '/response.json', '--destination', str(response_path)], tolerate=True)
|
||||
try:
|
||||
candidate = json.loads(response_path.read_text())
|
||||
if candidate.get('id') == identifier:
|
||||
response = candidate
|
||||
break
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
if response is None:
|
||||
raise RuntimeError('No matching config response. Unlock the phone and install a build with config-port support, then retry.')
|
||||
if not response.get('ok'):
|
||||
message = response.get('message', 'Config transfer failed')
|
||||
if message == 'Invalid config request':
|
||||
message += ' (does the installed build predate JSON config documents?)'
|
||||
raise RuntimeError(message)
|
||||
return response
|
||||
|
||||
|
||||
def pull_document(args, work, device):
|
||||
response = exchange(args, work, device, 'pull')
|
||||
if not isinstance(response.get('document'), str):
|
||||
raise RuntimeError('The installed build predates JSON config documents; update it and retry.')
|
||||
return response
|
||||
|
||||
|
||||
def transfer(args):
|
||||
# Parse and validate before touching the device or restarting its app.
|
||||
document = read_document(args.file) if args.operation == 'push' else None
|
||||
with tempfile.TemporaryDirectory(prefix='faceclaw-config-') as work:
|
||||
work = Path(work)
|
||||
device = args.device or os.environ.get('IOS_DEVICE')
|
||||
if args.simulator:
|
||||
device = device or 'booted'
|
||||
container = Path(run(['simctl', 'get_app_container', device, BUNDLE, 'data']).stdout.strip())
|
||||
else:
|
||||
if not device:
|
||||
listing = work / 'devices.json'
|
||||
run(['devicectl', 'list', 'devices', '--json-output', str(listing)])
|
||||
devices = json.loads(listing.read_text())['result']['devices']
|
||||
available = [d for d in devices if d.get('connectionProperties', {}).get('tunnelState') == 'connected']
|
||||
if len(available) != 1:
|
||||
raise ValueError('Specify the iPhone with --device UDID (or IOS_DEVICE)')
|
||||
device = available[0]['identifier']
|
||||
identifier = str(uuid.uuid4())
|
||||
payload = {'id': identifier, 'operation': args.operation}
|
||||
if document is not None:
|
||||
payload['document'] = document
|
||||
encoded = json.dumps(payload, ensure_ascii=False, allow_nan=False).encode()
|
||||
if len(encoded) > REQUEST_LIMIT:
|
||||
raise ValueError('Config request exceeds 8 MiB')
|
||||
stage = work / 'FaceclawConfigPort'
|
||||
stage.mkdir(mode=0o700)
|
||||
atomic_write(stage / 'request.json', encoded)
|
||||
if args.simulator:
|
||||
remote = container / REMOTE
|
||||
remote.mkdir(parents=True, exist_ok=True)
|
||||
atomic_write(remote / 'request.json', encoded)
|
||||
run(['simctl', 'terminate', device, BUNDLE], tolerate=True)
|
||||
run(['simctl', 'launch', device, BUNDLE])
|
||||
else:
|
||||
run(['devicectl', 'device', 'copy', 'to', '--device', device, '--domain-type', 'appDataContainer',
|
||||
'--domain-identifier', BUNDLE, '--source', str(stage), '--destination', REMOTE])
|
||||
run(['devicectl', 'device', 'process', 'launch', '--device', device, '--terminate-existing', BUNDLE])
|
||||
deadline = time.monotonic() + 25
|
||||
response = None
|
||||
while time.monotonic() < deadline:
|
||||
if args.simulator:
|
||||
response_path = remote / 'response.json'
|
||||
else:
|
||||
response_path = work / 'response.json'
|
||||
run(['devicectl', 'device', 'copy', 'from', '--device', device, '--domain-type', 'appDataContainer',
|
||||
'--domain-identifier', BUNDLE, '--source', REMOTE + '/response.json', '--destination', str(response_path)], tolerate=True)
|
||||
try:
|
||||
candidate = json.loads(response_path.read_text())
|
||||
if candidate.get('id') == identifier:
|
||||
response = candidate
|
||||
break
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
if response is None:
|
||||
raise RuntimeError('No matching config response. Unlock the phone and install a build with config-port support, then retry.')
|
||||
if not response.get('ok'):
|
||||
message = response.get('message', 'Config transfer failed')
|
||||
if message == 'Invalid config request':
|
||||
message += ' (does the installed build predate JSON config documents?)'
|
||||
raise RuntimeError(message)
|
||||
device = resolve_device(args, work)
|
||||
if args.operation == 'pull':
|
||||
if not isinstance(response.get('document'), str):
|
||||
raise RuntimeError('The installed build predates JSON config documents; update it and retry.')
|
||||
response = pull_document(args, work, device)
|
||||
atomic_write(args.file, response['document'].encode())
|
||||
print(f'Pulled {response.get("count", "?")} settings to {args.file} (mode 600). App restarted.')
|
||||
else:
|
||||
response = exchange(args, work, device, 'push', document)
|
||||
skipped = response.get('skipped') or []
|
||||
note = f' Left out {len(skipped)} {response.get("sourcePlatform") or "other-platform"}-only settings.' if skipped else ''
|
||||
print(f'Pushed {response["count"]} settings; app restarted.{note} Unspecified settings preserved; '
|
||||
f'previous preferences backed up in {REMOTE}/previous.plist.')
|
||||
|
||||
|
||||
def onboarding_reset_document(pulled):
|
||||
"""A document clearing the onboarding keys set in a pulled config, or None if none are.
|
||||
|
||||
Pushes merge, so a key can be overwritten but not removed. Every onboarding key reads the
|
||||
value written here the same as a missing key: false for flags, "" for the finished version.
|
||||
"""
|
||||
cleared = {}
|
||||
for key, value in json.loads(pulled).get('platformSettings', {}).items():
|
||||
if not key.startswith(ONBOARDING_PREFIX):
|
||||
continue
|
||||
blank = False if isinstance(value, bool) else 0 if isinstance(value, (int, float)) else ''
|
||||
if value != blank:
|
||||
cleared[key] = blank
|
||||
if not cleared:
|
||||
return None
|
||||
return json.dumps({'schema': 2, 'platform': 'ios', 'settings': {}, 'platformSettings': cleared})
|
||||
|
||||
|
||||
def reset_onboarding(args):
|
||||
with tempfile.TemporaryDirectory(prefix='faceclaw-config-') as work:
|
||||
work = Path(work)
|
||||
device = resolve_device(args, work)
|
||||
if args.all:
|
||||
print(f'Uninstalling {BUNDLE}, which removes ALL of its data...')
|
||||
if args.simulator:
|
||||
run(['simctl', 'uninstall', device, BUNDLE])
|
||||
else:
|
||||
run(['devicectl', 'device', 'uninstall', 'app', '--device', device, BUNDLE])
|
||||
print('Done. Reinstall (npm run run:ios) to start from a clean onboarding.')
|
||||
return
|
||||
print(f'Clearing onboarding preference keys ({ONBOARDING_PREFIX}*) for {BUNDLE}...')
|
||||
document = onboarding_reset_document(pull_document(args, work, device)['document'])
|
||||
if document is None:
|
||||
print('No onboarding keys were set. App is already in pre-onboarding state.')
|
||||
return
|
||||
keys = json.loads(document)['platformSettings']
|
||||
exchange(args, work, device, 'push', document)
|
||||
for key in keys:
|
||||
print(f' cleared {key}')
|
||||
print(f'Done. Faceclaw has restarted into onboarding; previous preferences backed up in {REMOTE}/previous.plist.')
|
||||
|
||||
|
||||
def main():
|
||||
os.umask(0o077)
|
||||
parser = argparse.ArgumentParser(description='Pull/push iOS Faceclaw config; restarts the app. Requires Xcode and an unlocked development device. Push merges supplied keys; accepts Faceclaw JSON from either platform, or legacy Android XML.')
|
||||
parser.add_argument('operation', choices=['pull', 'push'])
|
||||
parser = argparse.ArgumentParser(description='Pull/push iOS Faceclaw config, or reset its onboarding state; restarts the app. Requires Xcode and an unlocked development device. Push merges supplied keys; accepts Faceclaw JSON from either platform, or legacy Android XML.')
|
||||
parser.add_argument('operation', choices=['pull', 'push', 'reset-onboarding'])
|
||||
parser.add_argument('path', nargs='?')
|
||||
parser.add_argument('-f', '--file')
|
||||
parser.add_argument('-d', '--device', help='iPhone UDID/name, or simulator ID with --simulator; defaults to IOS_DEVICE or the only connected device')
|
||||
parser.add_argument('--simulator', action='store_true', help='Use simctl (default device: booted)')
|
||||
parser.add_argument('--all', action='store_true', help='With reset-onboarding: uninstall the app, wiping ALL of its data')
|
||||
args = parser.parse_args()
|
||||
if args.operation == 'reset-onboarding' and (args.path or args.file):
|
||||
parser.error('reset-onboarding does not take a file')
|
||||
if args.all and args.operation != 'reset-onboarding':
|
||||
parser.error('--all only applies to reset-onboarding')
|
||||
if args.path and args.file:
|
||||
parser.error('Specify one file, either positional or with -f')
|
||||
args.file = args.file or args.path or 'faceclaw_settings.ios.json'
|
||||
if args.operation == 'pull' and Path(args.file).suffix.lower() == '.xml':
|
||||
parser.error('Configs are pulled as JSON; choose a .json filename')
|
||||
try:
|
||||
transfer(args)
|
||||
(reset_onboarding if args.operation == 'reset-onboarding' else transfer)(args)
|
||||
except (OSError, ValueError, RuntimeError, ET.ParseError) as error:
|
||||
print(f'Error: {error}', file=sys.stderr)
|
||||
return 1
|
||||
|
||||
@@ -15,20 +15,21 @@
|
||||
# scripts/resetOnboarding.sh --all # full `pm clear` (wipes everything)
|
||||
# scripts/resetOnboarding.sh -s <device-id> # target a specific adb device
|
||||
#
|
||||
# The device id defaults to $FACECLAW_DEVICE_ID, then to the id used by
|
||||
# build_and_run.sh. adb is located the same way build.sh finds its tools.
|
||||
# The device id defaults to DEVICE_ID from build_paths.sh, the same device
|
||||
# build_and_run.sh targets. adb must be on PATH, or added to it in build_paths.sh.
|
||||
|
||||
# Sourced ahead of strict mode, since the build scripts source it without one.
|
||||
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
if [ -f "$ROOT/build_paths.sh" ]; then
|
||||
source "$ROOT/build_paths.sh"
|
||||
fi
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
PACKAGE="com.faceclaw.app"
|
||||
PREF_KEY_PREFIX="onboarding."
|
||||
DEVICE_ID="${FACECLAW_DEVICE_ID:-3A101JEHN12330}"
|
||||
WIPE_ALL=0
|
||||
|
||||
# Match build.sh's tool locations so adb is on PATH even from a bare shell.
|
||||
export ANDROID_HOME="${ANDROID_HOME:-/Users/jbabcock/Library/Android/sdk}"
|
||||
export PATH="$ANDROID_HOME/platform-tools:$PATH"
|
||||
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--all) WIPE_ALL=1; shift ;;
|
||||
@@ -44,8 +45,19 @@ done
|
||||
|
||||
command -v adb >/dev/null 2>&1 || { echo "error: adb not found on PATH" >&2; exit 1; }
|
||||
|
||||
if [ -z "${DEVICE_ID:-}" ]; then
|
||||
echo "error: no adb device; set DEVICE_ID in build_paths.sh or pass -s <device-id>." >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
ADB="adb -s $DEVICE_ID"
|
||||
|
||||
# Network devices (host:port) need an explicit connect first. A failure here is
|
||||
# reported by the connected-device check below.
|
||||
case "$DEVICE_ID" in
|
||||
*:*) adb connect "$DEVICE_ID" >/dev/null 2>&1 || true ;;
|
||||
esac
|
||||
|
||||
# Confirm the device is actually there before doing anything.
|
||||
if ! $ADB get-state >/dev/null 2>&1; then
|
||||
echo "error: adb device '$DEVICE_ID' not connected." >&2
|
||||
|
||||
Executable
+35
@@ -0,0 +1,35 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# resetOnboardingIos.sh — reset Faceclaw on an iPhone back to its pre-onboarding
|
||||
# state, for testing the onboarding flow repeatedly. The iOS counterpart of
|
||||
# resetOnboarding.sh.
|
||||
#
|
||||
# By default this only clears the onboarding-related preference keys
|
||||
# (onboarding.complete, onboarding.previewOnly, the on-glasses onboarding's
|
||||
# onboarding.glassesFinishedVersion, ...) and leaves everything else, notably
|
||||
# the saved glasses/ring identities, intact. It restarts Faceclaw twice, and
|
||||
# leaves it running in onboarding. Pass --all to uninstall the app instead,
|
||||
# which wipes ALL of its data and permissions; you then have to reinstall it.
|
||||
#
|
||||
# Usage:
|
||||
# scripts/resetOnboardingIos.sh # reset onboarding flags only
|
||||
# scripts/resetOnboardingIos.sh --all # uninstall (wipes everything)
|
||||
# scripts/resetOnboardingIos.sh -d <device-id> # target a specific iPhone
|
||||
# scripts/resetOnboardingIos.sh --simulator # target the booted simulator
|
||||
#
|
||||
# The device defaults to IOS_DEVICE from build_paths.sh, then to the only iPhone
|
||||
# connected. Needs Xcode and an unlocked phone with a development build installed;
|
||||
# see config-transfer.md.
|
||||
|
||||
# Sourced ahead of strict mode, since the build scripts source it without one.
|
||||
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
if [ -f "$ROOT/build_paths.sh" ]; then
|
||||
source "$ROOT/build_paths.sh"
|
||||
fi
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
# ios_config.py reads these from its environment.
|
||||
export IOS_DEVICE IOS_BUNDLE_ID
|
||||
|
||||
exec python3 "$ROOT/scripts/ios_config.py" reset-onboarding "$@"
|
||||
Reference in new issue
Block a user