forked from Blendman974/faceclaw
Unify Android and iOS config formats
This commit is contained in:
1 parent
35a4ae7064
commit
210b111e27
18 files changed
+1116
-427
No files matched your search
+25
-76
@@ -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:
|
||||
|
||||
Reference in new issue
Block a user