Unify Android and iOS config formats

This commit is contained in:
James Babcock committed 2026-10-31 15:43:55 -07:00
1 parent 35a4ae7064
commit 210b111e27
18 files changed
+1116 -427

No files matched your search

+118
View File
@@ -0,0 +1,118 @@
# Config transfer (Android and iOS)
Both platforms export and import the same JSON config document, so a config
pulled from one phone can be pushed to either platform.
```sh
scripts/pull_config.sh # Android -> faceclaw_settings.android.json
scripts/push_config.sh # faceclaw_settings.android.json -> Android
scripts/pull_config_ios.sh # iPhone -> faceclaw_settings.ios.json
scripts/push_config_ios.sh # faceclaw_settings.ios.json -> iPhone
scripts/pull_config.sh && scripts/push_config_ios.sh faceclaw_settings.android.json # Android -> iPhone
scripts/pull_config_ios.sh && scripts/push_config.sh faceclaw_settings.ios.json # iPhone -> Android
```
Push also accepts legacy Android shared-preferences XML (`faceclaw_settings.xml`
from older `pull_config.sh`). Pulls write files with mode 600; the default
filenames are gitignored. **Configs contain API keys and Terminal tokens: treat
them as secrets.**
## Format
```json
{
"schema": 2,
"platform": "android",
"appVersion": "0.8.3",
"settings": {
"display.timeFormat": "24h",
"terminal.autoReconnect": true,
"terminal.connections": [{ "id": "c1", "url": "g2mirror://token@host:8737", "enabled": true }]
},
"platformSettings": {
"deviceAddress.left": "EC:D7:82:69:3C:CB",
"notifications.sources": [{ "packageName": "com.tailscale.ipn", "appName": "Tailscale", "showOnGlasses": true }]
}
}
```
- `settings` are imported on any platform.
- `platformSettings` are imported only when `platform` matches the phone importing
them. They are the settings that would be wrong on another phone: the paired
glasses and ring, onboarding state, notification sources (Android package names
vs iOS bundle IDs), Android media apps, file paths (Files bookmarks, Teleprompter
recents), installed EvenHub packages, per-phone device IDs and `ios.*` internals.
The list is `SettingsTransfer.isPlatformLocal` in
`native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/settings/SettingsTransfer.kt`;
every other setting is portable, including ones only one platform uses today, so
they survive a round trip through the other platform. An enum value one platform
doesn't offer (e.g. the Android-only "external" assistant backend) is harmless:
each setting reads as its default when its stored value isn't one of its choices.
- Values are strings, booleans and numbers, as the app stores them. Settings stored
as JSON text (connections, folders, fonts, timers, EvenHub app storage, ...) are
written as real JSON objects/arrays when that round-trips exactly; on import any
object/array is stored back as its compact JSON text.
Schema 1 (a flat `settings` object, from older iOS pulls) is still accepted; its keys
are sorted into portable and platform-local at import time. When editing by hand,
move a key between the two sections to control whether it crosses platforms.
## Semantics
Push **merges**: settings the file doesn't mention are left alone, so a cross-platform
import keeps the target phone's pairing and other platform-local settings. To clear a
value, supply its empty/default value. Malformed files, null values and files over
2 MiB fail before the device is touched (`scripts/config_document.py`) or before
anything is written (the phone re-validates with the same Kotlin codec).
Each import first saves the previous settings: Android writes a config document to
the app's private `files/faceclaw-settings-previous.json`; iOS saves its preferences
to `Library/FaceclawConfigPort/previous.plist`. Both apps restart after an import.
Storage itself is unchanged and per-platform. Android keeps settings in
`shared_prefs/faceclaw_settings.xml`, except the pairing, onboarding and EvenHub
localStorage keys, which still live in NativeScript's `prefs.db.xml`; the export reads
and the import writes each key in the file the app reads it from
(`FaceclawSettingsPortReceiver.nativeScriptKey`). iOS keeps everything in its
NSUserDefaults app domain.
## Android
`pull_config.sh` / `push_config.sh` drive `FaceclawSettingsPortReceiver` with
`am broadcast`, which works on debug and release builds (release builds refuse
`run-as`). The receiver is guarded by `android.permission.DUMP`, so only the adb shell
can trigger it. The document is shuttled through the app's external files dir and
deleted as soon as it has been read. An import writes through the app's live
SharedPreferences, then exits the app so its next launch starts from the imported
settings. Pass `-s SERIAL` (or other adb options) to pick a device.
## iOS
Requires Xcode, Python 3, a development build with `FaceclawConfigPort`, and an
unlocked/trusted iPhone. Both commands restart Faceclaw, briefly interrupting its
Bluetooth and Terminal sessions.
```sh
scripts/pull_config_ios.sh -f /tmp/settings.json --device IPHONE_UDID
scripts/push_config_ios.sh faceclaw_settings.xml # legacy Android pull_config.sh output
```
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).
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
cfprefsd could restore from cache. Replies are checked against the request ID, so a
stale export cannot appear to confirm an import. Scripts do not print values and
remove their private temporary directory on exit. Device request/reply/backup files
stay in the private Library directory, outside Files/Finder Documents.
Terminal's configured `g2mirror://` scheme uses plain WebSockets; `g2mirrors://`
uses TLS. The iOS build declares local networking and an explicit ATS exception
for the current development server `100.68.94.67`. On iOS 17+, another literal IP
requires its own build-time `NSExceptionDomains` entry, or a TLS endpoint. The
exception does not disable TLS certificate verification. See Apple's
[IP exception rules](https://developer.apple.com/documentation/bundleresources/information-property-list/nsapptransportsecurity/nsexceptiondomains).
+132
View File
@@ -0,0 +1,132 @@
#!/usr/bin/env python3
"""Read a Faceclaw config file for push_config.sh / push_config_ios.sh.
The phone-side importer (Kotlin SettingsTransfer) does the authoritative validation and
platform filtering; this catches unusable files before the scripts touch a device, and
converts legacy Android shared-preferences XML (what pull_config.sh wrote before configs
were JSON) into a schema-1 document tagged as Android. See scripts/config-transfer.md.
config_document.py INPUT # prints the document to push
"""
import json
import math
from pathlib import Path
import sys
import xml.etree.ElementTree as ET
LIMIT = 2 * 1024 * 1024
def _check_value(key, value):
if not isinstance(key, str) or not key or len(key) > 512:
raise ValueError('Invalid setting name')
if value is None:
raise ValueError(f'Setting {key} is null; supply an empty value to clear it')
if isinstance(value, float) and not math.isfinite(value):
raise ValueError(f'Setting {key} is not a finite number')
if not isinstance(value, (str, bool, int, float, dict, list)):
raise ValueError(f'Unsupported value for setting {key}')
def _no_constants(name):
raise ValueError(f'{name} is not valid JSON')
def check_document(text):
"""Validate a JSON document's shape; returns (schema, platform, setting count)."""
try:
config = json.loads(text, parse_constant=_no_constants,
object_pairs_hook=_reject_duplicate_keys)
except json.JSONDecodeError as error:
raise ValueError(f'Config is not valid JSON: {error}') from None
if not isinstance(config, dict) or type(config.get('schema')) is not int or config['schema'] not in (1, 2):
raise ValueError('Expected a Faceclaw config with "schema": 1 or 2')
platform = config.get('platform')
if platform is not None and not isinstance(platform, str):
raise ValueError('"platform" must be a string')
count = 0
for section in ('settings', 'platformSettings'):
values = config.get(section, {} if section == 'platformSettings' else None)
if not isinstance(values, dict):
raise ValueError(f'"{section}" must be an object')
for key, value in values.items():
_check_value(key, value)
count += len(values)
if count > 4096:
raise ValueError('Too many settings')
return config['schema'], platform, count
def _reject_duplicate_keys(pairs):
result = {}
for key, value in pairs:
if key in result:
raise ValueError(f'Setting {key} appears more than once')
result[key] = value
return result
def convert_android_xml(data):
"""Android shared-preferences XML -> schema-1 document text (the phone classifies the keys)."""
if b'<!DOCTYPE' in data.upper() or b'<!ENTITY' in data.upper():
raise ValueError('XML declarations of document types/entities are not supported')
root = ET.fromstring(data)
if root.tag != 'map':
raise ValueError('Expected Android shared-preferences <map>')
settings = {}
for item in root:
key = item.get('name')
if key in settings:
raise ValueError('Duplicate setting name')
if item.tag == 'string':
value = item.text or ''
elif item.tag == 'boolean' and item.get('value') in ('true', 'false'):
value = item.get('value') == 'true'
elif item.tag in ('int', 'long', 'float'):
try:
value = float(item.get('value', '')) if item.tag == 'float' else int(item.get('value', ''))
except ValueError:
raise ValueError('Invalid numeric preference value') from None
else:
raise ValueError('Unsupported Android preference type')
if len(item):
raise ValueError('Nested preference content is not supported')
_check_value(key, value)
settings[key] = value
return json.dumps({'schema': 1, 'platform': 'android', 'settings': settings},
indent=2, ensure_ascii=False, allow_nan=False) + '\n'
def read_document(path):
"""The document to push for a JSON config or legacy Android XML file, validated."""
data = Path(path).read_bytes()
if len(data) > LIMIT:
raise ValueError('Config exceeds 2 MiB')
if data.lstrip().startswith(b'<'):
text = convert_android_xml(data)
else:
try:
text = data.decode('utf-8-sig')
except UnicodeDecodeError:
raise ValueError('Config is not UTF-8') from None
check_document(text)
if len(text.encode()) > LIMIT:
raise ValueError('Config exceeds 2 MiB')
return text
def main():
if len(sys.argv) != 2:
print(__doc__.strip(), file=sys.stderr)
return 2
try:
text = read_document(sys.argv[1])
except (OSError, ValueError, ET.ParseError) as error:
print(f'Error: {error}', file=sys.stderr)
return 1
sys.stdout.write(text)
return 0
if __name__ == '__main__':
sys.exit(main())
-53
View File
@@ -1,53 +0,0 @@
# iOS config transfer
Requires Xcode, Python 3, a development build with `FaceclawConfigPort`, and an
unlocked/trusted iPhone. Both commands restart Faceclaw, briefly interrupting its
Bluetooth and Terminal sessions.
```sh
scripts/pull_config_ios.sh # faceclaw_settings.ios.json
scripts/push_config_ios.sh # import the edited file
scripts/pull_config_ios.sh -f /tmp/settings.json --device IPHONE_UDID
scripts/push_config_ios.sh faceclaw_settings.xml # Android pull_config.sh output
```
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).
The JSON format preserves setting types:
```json
{
"schema": 1,
"settings": {
"terminal.connections": "[]",
"terminal.autoReconnect": true
}
}
```
Pull accepts an `.xml` output filename to write Android shared-preferences XML.
Push detects JSON or XML by content and supports strings, booleans and numbers.
Malformed input, unsupported values and files over 2 MiB fail before restarting
the app. Push **merges supplied keys**, preserving omitted settings (including
phone-specific pairing). To clear a value, supply its empty/default value.
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
cfprefsd could restore from cache. Each successful push first saves the previous
preferences to `Library/FaceclawConfigPort/previous.plist`. Replies are checked
against the request ID, so a stale export cannot appear to confirm an import.
Exports may contain API keys and Terminal tokens. Scripts do not print values,
write local exports with mode 600, and remove their private temporary directory
on exit. Default export filenames are gitignored. Device request/reply/backup
files stay in the private Library directory, outside Files/Finder Documents.
Terminal's configured `g2mirror://` scheme uses plain WebSockets; `g2mirrors://`
uses TLS. The iOS build declares local networking and an explicit ATS exception
for the current development server `100.68.94.67`. On iOS 17+, another literal IP
requires its own build-time `NSExceptionDomains` entry, or a TLS endpoint. The
exception does not disable TLS certificate verification. See Apple's
[IP exception rules](https://developer.apple.com/documentation/bundleresources/information-property-list/nsapptransportsecurity/nsexceptiondomains).
+25 -76
View File
@@ -2,7 +2,6 @@
"""Transfer Faceclaw preferences using Xcode's supported app-container APIs."""
import argparse
import json
import math
import os
from pathlib import Path
import subprocess
@@ -12,72 +11,13 @@ import time
import uuid
import xml.etree.ElementTree as ET
sys.path.insert(0, str(Path(__file__).resolve().parent))
from config_document import read_document # noqa: E402
BUNDLE = os.environ.get('IOS_BUNDLE_ID') or 'com.faceclaw.app'
REMOTE = 'Library/FaceclawConfigPort'
LIMIT = 2 * 1024 * 1024
def validate(settings):
if not isinstance(settings, dict) or len(settings) > 4096:
raise ValueError('Expected a settings object with at most 4096 entries')
for key, value in settings.items():
if not isinstance(key, str) or not key or len(key) > 512:
raise ValueError('Invalid setting name')
if type(value) not in (str, bool, int, float) or isinstance(value, float) and not math.isfinite(value):
raise ValueError('Settings must contain only strings, booleans and finite numbers')
return settings
def read_config(path):
data = Path(path).read_bytes()
if len(data) > LIMIT:
raise ValueError('Config exceeds 2 MiB')
if data.lstrip().startswith(b'<'):
if b'<!DOCTYPE' in data.upper() or b'<!ENTITY' in data.upper():
raise ValueError('XML declarations of document types/entities are not supported')
root = ET.fromstring(data)
if root.tag != 'map':
raise ValueError('Expected Android shared-preferences <map>')
settings = {}
for item in root:
key = item.get('name')
if key in settings:
raise ValueError('Duplicate setting name')
if item.tag == 'string':
value = item.text or ''
elif item.tag == 'boolean' and item.get('value') in ('true', 'false'):
value = item.get('value') == 'true'
elif item.tag in ('int', 'long', 'float'):
try:
value = float(item.get('value', '')) if item.tag == 'float' else int(item.get('value', ''))
except ValueError:
raise ValueError('Invalid numeric preference value') from None
else:
raise ValueError('Unsupported Android preference type')
if len(item):
raise ValueError('Nested preference content is not supported')
settings[key] = value
else:
config = json.loads(data)
if not isinstance(config, dict) or config.get('schema') != 1:
raise ValueError('Expected Faceclaw config with schema: 1 and a settings object')
settings = config.get('settings')
return validate(settings)
def encode_config(settings, xml=False):
validate(settings)
if not xml:
return (json.dumps({'schema': 1, 'settings': settings}, indent=2, ensure_ascii=False, allow_nan=False) + '\n').encode()
root = ET.Element('map')
for key, value in sorted(settings.items()):
if isinstance(value, str):
ET.SubElement(root, 'string', name=key).text = value
else:
kind = 'boolean' if isinstance(value, bool) else 'long' if isinstance(value, int) else 'float'
ET.SubElement(root, kind, name=key, value=str(value).lower())
ET.indent(root)
return ET.tostring(root, encoding='utf-8', xml_declaration=True) + b'\n'
# The app reads requests of up to 8 MiB: a 2 MiB document embedded as an escaped JSON string.
REQUEST_LIMIT = 8 * 1024 * 1024
def run(args, tolerate=False):
@@ -108,7 +48,7 @@ def atomic_write(path, data):
def transfer(args):
# Parse and validate before touching the device or restarting its app.
settings = read_config(args.file) if args.operation == 'push' else None
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')
@@ -126,11 +66,11 @@ def transfer(args):
device = available[0]['identifier']
identifier = str(uuid.uuid4())
payload = {'id': identifier, 'operation': args.operation}
if settings is not None:
payload['settings'] = settings
if document is not None:
payload['document'] = document
encoded = json.dumps(payload, ensure_ascii=False, allow_nan=False).encode()
if len(encoded) > LIMIT:
raise ValueError('Config request exceeds 2 MiB')
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)
@@ -164,18 +104,25 @@ def transfer(args):
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'):
raise RuntimeError(response.get('message', 'Config transfer failed'))
message = response.get('message', 'Config transfer failed')
if message == 'Invalid config request':
message += ' (does the installed build predate JSON config documents?)'
raise RuntimeError(message)
if args.operation == 'pull':
settings = response['config']['settings']
atomic_write(args.file, encode_config(settings, Path(args.file).suffix.lower() == '.xml'))
print(f'Pulled {len(settings)} settings to {args.file} (mode 600). App restarted.')
if not isinstance(response.get('document'), str):
raise RuntimeError('The installed build predates JSON config documents; update it and retry.')
atomic_write(args.file, response['document'].encode())
print(f'Pulled {response.get("count", "?")} settings to {args.file} (mode 600). App restarted.')
else:
print(f'Pushed {response["count"]} settings; app restarted. Unspecified settings preserved; previous preferences backed up in {REMOTE}/previous.plist.')
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 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 Android XML or Faceclaw JSON.')
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.add_argument('path', nargs='?')
parser.add_argument('-f', '--file')
@@ -185,6 +132,8 @@ def main():
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)
except (OSError, ValueError, RuntimeError, ET.ParseError) as error:
+52 -29
View File
@@ -1,11 +1,11 @@
#!/bin/bash
# Pull faceclaw's shared preferences off the attached device.
# Export faceclaw's settings from the attached Android device as a JSON config
# document (the same format as pull_config_ios.sh; see config-transfer.md).
# Usage: pull_config.sh [output-file] [-f output-file] [adb-options...]
#
# Uses run-as on debuggable (dev) builds. On release builds, where run-as is
# refused, falls back to the FaceclawSettingsPortReceiver broadcast, which
# copies the settings file into the app's external files dir for adb to pull
# (and which only the adb shell can trigger; see the receiver's javadoc).
# The app's FaceclawSettingsPortReceiver writes the document into its external
# files dir for adb to pull. Only the adb shell can trigger it (see the
# receiver's javadoc), and it works on release builds, where run-as is refused.
set -euo pipefail
source "$(cd "$(dirname "$0")" && pwd)/adbutil.sh"
@@ -14,10 +14,12 @@ usage() {
cat <<EOF
Usage: $(basename "$0") [output-file] [-f output-file] [adb-options...]
Pull faceclaw's shared preferences off the attached device into output-file
(default: faceclaw_settings.xml). The output file may be given as a bare
first argument or with -f anywhere. Any other arguments are passed through
to adb, e.g. -s SERIAL or -t ID to pick one of several attached devices.
Export faceclaw's settings from the attached device into output-file
(default: faceclaw_settings.android.json), readable only by you. The output
file may be given as a bare first argument or with -f anywhere. Any other
arguments are passed through to adb, e.g. -s SERIAL or -t ID to pick one of
several attached devices. Push the file to Android or iOS with push_config.sh
or push_config_ios.sh.
EOF
}
@@ -28,26 +30,47 @@ if [ "$ADBUTIL_HELP" = 1 ]; then
fi
PACKAGE=com.faceclaw.app
PREFS=shared_prefs/faceclaw_settings.xml
OUT="${ADBUTIL_FILE:-faceclaw_settings.xml}"
EXPORT_REMOTE=/sdcard/Android/data/$PACKAGE/files/faceclaw-settings-export.xml
OUT="${ADBUTIL_FILE:-faceclaw_settings.android.json}"
EXPORT_REMOTE=/sdcard/Android/data/$PACKAGE/files/faceclaw-settings-export.json
MODE="$(adb_preflight "$PACKAGE")"
if [ "$MODE" = debug ]; then
adb exec-out run-as "$PACKAGE" cat "$PREFS" > "$OUT"
echo "Pulled $PREFS to $OUT"
else
echo "Release build installed; using settings-port broadcast..."
RESULT="$(adb shell am broadcast -n "$PACKAGE/.FaceclawSettingsPortReceiver" \
-a com.faceclaw.app.SETTINGS_EXPORT)"
if ! printf '%s' "$RESULT" | grep -q 'data="exported:'; then
printf '%s\n' "$RESULT" >&2
echo "Error: export broadcast did not report success (old app version?)" >&2
case "$OUT" in
*.xml|*.XML)
echo "Error: configs are exported as JSON; choose a .json filename" >&2
exit 1
fi
adb pull "$EXPORT_REMOTE" "$OUT" >/dev/null
# The export contains API tokens; don't leave it sitting on shared storage.
adb shell rm "$EXPORT_REMOTE"
echo "Pulled $PREFS to $OUT (via settings-port export)"
;;
esac
adb_preflight "$PACKAGE" >/dev/null
export_broadcast() {
adb shell am broadcast --include-stopped-packages \
-n "$PACKAGE/.FaceclawSettingsPortReceiver" -a com.faceclaw.app.SETTINGS_EXPORT
}
RESULT="$(export_broadcast)"
if ! printf '%s' "$RESULT" | grep -q 'data='; then
# No reply at all: the broadcast reached a process that was exiting (the
# app exits just after an import). Try once more in a fresh one.
adb shell sleep 1
RESULT="$(export_broadcast)"
fi
if ! printf '%s' "$RESULT" | grep -q 'data="exported: .*\.json"'; then
printf '%s\n' "$RESULT" >&2
echo "Error: export broadcast did not report a JSON export (app predates JSON configs?)" >&2
exit 1
fi
# The export contains API tokens: keep it private locally, and don't leave it
# sitting on shared storage.
umask 077
TMP="$(mktemp "$OUT.XXXXXX")"
trap 'rm -f "$TMP"' EXIT
if ! OUTPUT="$(adb pull "$EXPORT_REMOTE" "$TMP" 2>&1)"; then
adb shell rm -f "$EXPORT_REMOTE"
printf '%s\n' "$OUTPUT" >&2
echo "Error: could not pull $EXPORT_REMOTE" >&2
exit 1
fi
adb shell rm -f "$EXPORT_REMOTE"
mv "$TMP" "$OUT"
trap - EXIT
echo "Pulled settings to $OUT (mode 600)"
+66 -49
View File
@@ -1,26 +1,29 @@
#!/bin/bash
# Push a shared-preferences file to faceclaw on the attached device.
# Import a JSON config document (from Android or iOS; see config-transfer.md)
# into faceclaw on the attached Android device.
# Usage: push_config.sh [input-file] [-f input-file] [adb-options...]
# Validates the XML, force-stops the app (so a running instance doesn't
# overwrite the pushed file from its in-memory prefs), then installs it.
#
# Uses run-as on debuggable (dev) builds. On release builds, where run-as is
# refused, falls back to the FaceclawSettingsPortReceiver broadcast: the file
# is staged in the app's external files dir and the receiver (adb-only; see
# its javadoc) validates and installs it, then exits so the next launch
# re-reads settings from disk.
# The import merges: settings the file doesn't mention are left alone, and
# settings that only make sense on the platform that exported them are left
# out when the file came from iOS. Legacy shared-preferences XML (what this
# script used to take) is converted first. The file is staged in the app's
# external files dir, and FaceclawSettingsPortReceiver (adb-only; see its
# javadoc) validates it, saves the previous settings, applies it, and exits
# the app so its next launch starts from the imported settings.
set -euo pipefail
source "$(cd "$(dirname "$0")" && pwd)/adbutil.sh"
SCRIPTS="$(cd "$(dirname "$0")" && pwd)"
source "$SCRIPTS/adbutil.sh"
usage() {
cat <<EOF
Usage: $(basename "$0") [input-file] [-f input-file] [adb-options...]
Push input-file (default: faceclaw_settings.xml) as faceclaw's shared
preferences on the attached device. The input file may be given as a bare
first argument or with -f anywhere. Any other arguments are passed through
to adb, e.g. -s SERIAL or -t ID to pick one of several attached devices.
Import input-file (default: faceclaw_settings.android.json) into faceclaw's
settings on the attached device. The file may be a config pulled from Android
or iOS, or legacy Android shared-preferences XML. It may be given as a bare
first argument or with -f anywhere. Any other arguments are passed through to
adb, e.g. -s SERIAL or -t ID to pick one of several attached devices.
EOF
}
@@ -31,44 +34,58 @@ if [ "$ADBUTIL_HELP" = 1 ]; then
fi
PACKAGE=com.faceclaw.app
PREFS=shared_prefs/faceclaw_settings.xml
IN="${ADBUTIL_FILE:-faceclaw_settings.xml}"
STAGE=/data/local/tmp/faceclaw_settings_push.xml
IMPORT_REMOTE=/sdcard/Android/data/$PACKAGE/files/faceclaw-settings-import.xml
IN="${ADBUTIL_FILE:-faceclaw_settings.android.json}"
IMPORT_REMOTE=/sdcard/Android/data/$PACKAGE/files/faceclaw-settings-import.json
if [ ! -f "$IN" ]; then
echo "Error: $IN not found" >&2
exit 1
fi
if command -v xmllint >/dev/null 2>&1; then
xmllint --noout "$IN"
elif command -v python3 >/dev/null 2>&1; then
python3 -c 'import sys, xml.etree.ElementTree as ET; ET.parse(sys.argv[1])' "$IN"
else
echo "Error: need xmllint or python3 to validate XML" >&2
exit 1
fi
MODE="$(adb_preflight "$PACKAGE")"
adb shell am force-stop "$PACKAGE"
if [ "$MODE" = debug ]; then
adb push "$IN" "$STAGE"
adb shell run-as "$PACKAGE" cp "$STAGE" "$PREFS"
adb shell rm "$STAGE"
echo "Pushed $IN to $PREFS (app was force-stopped; relaunch it to pick up the new settings)"
else
echo "Release build installed; using settings-port broadcast..."
adb push "$IN" "$IMPORT_REMOTE" >/dev/null
RESULT="$(adb shell am broadcast -n "$PACKAGE/.FaceclawSettingsPortReceiver" \
-a com.faceclaw.app.SETTINGS_IMPORT)"
if ! printf '%s' "$RESULT" | grep -q 'data="imported:'; then
printf '%s\n' "$RESULT" >&2
adb shell rm -f "$IMPORT_REMOTE"
echo "Error: import broadcast did not report success (old app version?)" >&2
exit 1
if [ -z "$ADBUTIL_FILE" ] && [ -f faceclaw_settings.xml ]; then
echo " (older pull_config.sh wrote faceclaw_settings.xml; pass it explicitly)" >&2
fi
echo "Pushed $IN to $PREFS via settings-port import (previous settings kept as $PREFS.bak)"
exit 1
fi
if ! command -v python3 >/dev/null 2>&1; then
echo "Error: python3 is needed to check the config before pushing it" >&2
exit 1
fi
umask 077
STAGE="$(mktemp "${TMPDIR:-/tmp}/faceclaw-config.XXXXXX")"
trap 'rm -f "$STAGE"' EXIT
# Validates (and converts legacy XML) before anything touches the device.
python3 "$SCRIPTS/config_document.py" "$IN" > "$STAGE"
adb_preflight "$PACKAGE" >/dev/null
if ! OUTPUT="$(adb push "$STAGE" "$IMPORT_REMOTE" 2>&1)"; then
printf '%s\n' "$OUTPUT" >&2
echo "Error: could not stage the config on the device" >&2
exit 1
fi
RESULT="$(adb shell am broadcast --include-stopped-packages \
-n "$PACKAGE/.FaceclawSettingsPortReceiver" -a com.faceclaw.app.SETTINGS_IMPORT)"
# The receiver deletes the staged file once read; this covers older builds.
adb shell rm -f "$IMPORT_REMOTE"
if ! printf '%s' "$RESULT" | grep -q 'data="imported:'; then
# An older build looks for a staged .xml file and reports "nothing staged".
if printf '%s' "$RESULT" | grep -q 'data="error:' && ! printf '%s' "$RESULT" | grep -q 'nothing staged'; then
printf '%s\n' "$RESULT" | sed -n 's/.*data="error: \(.*\)"$/Error: \1 (no settings were changed)/p' >&2
else
printf '%s\n' "$RESULT" >&2
echo "Error: import broadcast did not report success (app predates JSON configs?)" >&2
fi
exit 1
fi
printf '%s\n' "$RESULT" | sed -n 's/.*data="imported: \(.*\)"$/Imported \1/p'
# The app exits half a second after an import. Wait for that, so that a command
# run straight after this one (pull_config.sh, say) reaches a fresh process
# rather than the exiting one. A restarted process has a new pid. If the cached
# app freezer stops the process before it gets to exit, stop it from here.
PID="$(adb shell pidof "$PACKAGE" 2>/dev/null | tr -d '\r' | awk '{print $1}')"
if [ -n "$PID" ]; then
adb shell "i=0; while [ -d /proc/$PID ] && [ \$i -lt 50 ]; do sleep 0.1; i=\$((i+1)); done"
if adb shell "[ -d /proc/$PID ]" 2>/dev/null; then
adb shell am force-stop "$PACKAGE"
fi
fi
echo "The app restarts on its next launch with the imported settings."