phone-tools 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
phone_tools/VERSION ADDED
@@ -0,0 +1 @@
1
+ 0.1.0
@@ -0,0 +1,14 @@
1
+ """phone_tools: device state helpers for an adb-attached Android phone.
2
+
3
+ The package is stdlib only and shells out to `adb`; it never talks to a
4
+ device itself. `phone_tools/VERSION` is the single version source: setuptools
5
+ reads it for pyproject.toml, the flake reads it for the Nix package, and the
6
+ release workflow compares the tag with it. Do not write the version anywhere
7
+ else.
8
+ """
9
+
10
+ from importlib.resources import files
11
+
12
+ __version__ = (
13
+ files("phone_tools").joinpath("VERSION").read_text(encoding="utf-8").strip()
14
+ )
@@ -0,0 +1,6 @@
1
+ """Allow `python -m phone_tools` to behave like `phone-state`."""
2
+
3
+ from .state import main
4
+
5
+ if __name__ == "__main__":
6
+ raise SystemExit(main())
phone_tools/adb.py ADDED
@@ -0,0 +1,205 @@
1
+ """adb plumbing: run the binary, parse `adb devices -l`, pick one phone.
2
+
3
+ The selection rule is deliberately conservative. Two transports of the same
4
+ phone (USB plus wireless debugging) are normal and the USB one is preferred;
5
+ two different phones are ambiguous even when only one is on USB, because
6
+ picking the "convenient" one is still a guess.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import subprocess
12
+ from dataclasses import dataclass
13
+
14
+ DEFAULT_TIMEOUT = 60.0
15
+
16
+
17
+ class AdbError(RuntimeError):
18
+ """adb could not be executed, timed out, or exited non-zero."""
19
+
20
+
21
+ class SelectionError(RuntimeError):
22
+ """No single device can be chosen without guessing."""
23
+
24
+ def __init__(self, message: str, devices: list["Device"]) -> None:
25
+ super().__init__(message)
26
+ self.devices = devices
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class Device:
31
+ serial: str
32
+ state: str
33
+ transport: str
34
+ model: str
35
+ device: str
36
+
37
+ @property
38
+ def label(self) -> str:
39
+ return (
40
+ f"{self.serial} ({self.state}, {self.transport}, "
41
+ f"model={self.model or '?'}, device={self.device or '?'})"
42
+ )
43
+
44
+
45
+ def parse_devices(output: str) -> list[Device]:
46
+ """Parse the `adb devices -l` listing.
47
+
48
+ Lines before the header (the daemon's "starting now" notices) and comment
49
+ lines are ignored. The state is kept verbatim: only `device` is usable, but
50
+ `offline`/`unauthorized` entries still belong in an error listing.
51
+ """
52
+ devices: list[Device] = []
53
+ in_list = False
54
+ for raw in output.replace("\r\n", "\n").splitlines():
55
+ line = raw.strip()
56
+ if line == "List of devices attached":
57
+ in_list = True
58
+ continue
59
+ if not in_list or not line or line.startswith("*"):
60
+ continue
61
+ fields = line.split()
62
+ if len(fields) < 2:
63
+ continue
64
+ serial, state = fields[0], fields[1]
65
+ props: dict[str, str] = {}
66
+ for token in fields[2:]:
67
+ key, sep, value = token.partition(":")
68
+ if sep:
69
+ props[key] = value
70
+ if "usb" in props:
71
+ transport = "usb"
72
+ elif ":" in serial:
73
+ transport = "tcp"
74
+ else:
75
+ transport = "unknown"
76
+ devices.append(
77
+ Device(
78
+ serial=serial,
79
+ state=state,
80
+ transport=transport,
81
+ model=props.get("model", ""),
82
+ device=props.get("device", ""),
83
+ )
84
+ )
85
+ return devices
86
+
87
+
88
+ def identity(device: Device) -> tuple[str, ...]:
89
+ """A fingerprint that survives a USB/TCP transport change.
90
+
91
+ The serial does not: a USB phone is `R58M...` while its wireless debugging
92
+ entry is `192.0.2.5:5555`. The model/device pair does. Without it, the
93
+ serial is the identity.
94
+ """
95
+ if device.model and device.device:
96
+ return ("fingerprint", device.model.lower(), device.device.lower())
97
+ return ("serial", device.serial)
98
+
99
+
100
+ def _prefer_usb(candidates: list[Device], all_devices: list[Device]) -> Device:
101
+ usb = [device for device in candidates if device.transport == "usb"]
102
+ if len(usb) == 1:
103
+ return usb[0]
104
+ if len(usb) > 1:
105
+ raise SelectionError("more than one USB transport is attached", all_devices)
106
+ if len(candidates) == 1:
107
+ return candidates[0]
108
+ raise SelectionError(
109
+ "more than one transport is attached and none of them is USB", all_devices
110
+ )
111
+
112
+
113
+ def choose(devices: list[Device], requested: str | None = None) -> Device:
114
+ """Return the one usable device, or raise SelectionError.
115
+
116
+ `requested` comes from --serial or $ANDROID_SERIAL. It names a phone, not a
117
+ transport: if that phone is also attached over USB, the USB entry wins.
118
+ """
119
+ usable = [device for device in devices if device.state == "device"]
120
+ if requested:
121
+ match = next((device for device in usable if device.serial == requested), None)
122
+ if match is None:
123
+ raise SelectionError(
124
+ f"device {requested!r} is not attached and ready", devices
125
+ )
126
+ same_phone = [
127
+ device for device in usable if identity(device) == identity(match)
128
+ ]
129
+ return _prefer_usb(same_phone, devices)
130
+
131
+ if not usable:
132
+ raise SelectionError("no adb device is attached and ready", devices)
133
+
134
+ groups: dict[tuple[str, ...], list[Device]] = {}
135
+ for device in usable:
136
+ groups.setdefault(identity(device), []).append(device)
137
+ if len(groups) > 1:
138
+ raise SelectionError(
139
+ f"{len(groups)} different devices are attached; pass --serial", devices
140
+ )
141
+ return _prefer_usb(next(iter(groups.values())), devices)
142
+
143
+
144
+ def describe(devices: list[Device]) -> str:
145
+ if not devices:
146
+ return "adb devices -l reported no devices"
147
+ lines = "\n".join(f" {device.label}" for device in devices)
148
+ return f"adb devices -l reported:\n{lines}"
149
+
150
+
151
+ class Adb:
152
+ def __init__(self, executable: str = "adb", timeout: float = DEFAULT_TIMEOUT) -> None:
153
+ self.executable = executable
154
+ self.timeout = timeout
155
+
156
+ def run(self, argv: list[str], stdin: str | None = None) -> str:
157
+ try:
158
+ proc = subprocess.run(
159
+ [self.executable, *argv],
160
+ capture_output=True,
161
+ text=True,
162
+ input=stdin,
163
+ timeout=self.timeout,
164
+ )
165
+ except FileNotFoundError:
166
+ raise AdbError(f"cannot find the adb executable {self.executable!r}") from None
167
+ except PermissionError:
168
+ raise AdbError(
169
+ f"cannot execute the adb executable {self.executable!r}"
170
+ ) from None
171
+ except subprocess.TimeoutExpired:
172
+ raise AdbError(
173
+ f"{self.executable} {argv[0]} timed out after {self.timeout:g}s"
174
+ ) from None
175
+ if proc.returncode != 0:
176
+ detail = (proc.stderr or proc.stdout).strip().splitlines()
177
+ reason = detail[-1] if detail else f"exit {proc.returncode}"
178
+ raise AdbError(f"{self.executable} {' '.join(argv)} failed: {reason}")
179
+ return proc.stdout.replace("\r\n", "\n")
180
+
181
+ def devices(self) -> str:
182
+ return self.run(["devices", "-l"])
183
+
184
+ def shell(self, serial: str, *argv: str) -> str:
185
+ """Run one shell command, returning "" when adb fails.
186
+
187
+ State reads are allowed to come back empty: a missing line becomes
188
+ `unknown`, which is the honest answer, and one failed dumpsys must not
189
+ hide the fields the other dumps did provide.
190
+ """
191
+ try:
192
+ return self.run(["-s", serial, "shell", *argv])
193
+ except AdbError:
194
+ return ""
195
+
196
+ def shell_script(
197
+ self, serial: str, script: str, stdin: str | None = None
198
+ ) -> str:
199
+ """Run a shell script on the device, optionally feeding its stdin.
200
+
201
+ The script travels as one argument, so the remote shell owns the
202
+ quoting. `stdin` is for values that must not appear in any argv (the
203
+ PIN): the local adb call only ever sees the script text.
204
+ """
205
+ return self.run(["-s", serial, "shell", script], stdin=stdin)
phone_tools/prepare.py ADDED
@@ -0,0 +1,373 @@
1
+ """phone-prepare: the one preflight a device suite calls before it starts.
2
+
3
+ Order: choose the serial, wake the panel, apply `svc power stayon` (default
4
+ `usb`), then unlock. The stay-on setting is read and recorded *before* it is
5
+ changed, so the previous value can be put back either by the failure path here
6
+ or by a later `phone-prepare --restore`. Every non-zero exit leaves the setting
7
+ untouched or restored.
8
+
9
+ Serial selection, wake, unlock and the exit-code table are the same
10
+ implementations `phone-state`, `phone-wake` and `phone-unlock` use; this module
11
+ only orders them and owns the stay-on transaction.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import argparse
17
+ import json
18
+ import os
19
+ import sys
20
+ from pathlib import Path
21
+
22
+ from . import __version__
23
+ from .adb import (
24
+ Adb,
25
+ AdbError,
26
+ Device,
27
+ SelectionError,
28
+ choose,
29
+ describe,
30
+ parse_devices,
31
+ )
32
+ from .secrets import load_pin
33
+ from .state import collect, parse_stay_on
34
+ from .stayon import (
35
+ MODES,
36
+ StayOnError,
37
+ begin,
38
+ clear_record,
39
+ read_record,
40
+ record_path,
41
+ restore_stay_on,
42
+ undo,
43
+ )
44
+ from .unlock import DEFAULT_ATTEMPTS, Outcome, _attempts, unlock
45
+ from .wake import run_wake
46
+
47
+
48
+ def build_parser() -> argparse.ArgumentParser:
49
+ parser = argparse.ArgumentParser(
50
+ prog="phone-prepare",
51
+ description=(
52
+ "Choose one phone, wake it, set stay-on-while-plugged-in and "
53
+ "unlock it. Prints one JSON object with --json. --restore writes "
54
+ "the stay-on value recorded by the last run back."
55
+ ),
56
+ allow_abbrev=False,
57
+ )
58
+ parser.add_argument(
59
+ "--serial",
60
+ metavar="SERIAL",
61
+ help="adb serial to use (default: $ANDROID_SERIAL, else the only attached phone)",
62
+ )
63
+ parser.add_argument(
64
+ "--adb",
65
+ metavar="PATH",
66
+ default="adb",
67
+ help="adb executable to run (default: adb)",
68
+ )
69
+ parser.add_argument(
70
+ "--pin-file",
71
+ metavar="PATH",
72
+ help=(
73
+ "secrets file with a PHONE_PIN= line "
74
+ "(default: $PHONE_SECRETS, else /etc/nixos/phone-socks-secrets)"
75
+ ),
76
+ )
77
+ parser.add_argument(
78
+ "--attempts",
79
+ type=_attempts,
80
+ default=DEFAULT_ATTEMPTS,
81
+ metavar="N",
82
+ help=f"PIN entries to allow (default: {DEFAULT_ATTEMPTS})",
83
+ )
84
+ parser.add_argument(
85
+ "--stay-on",
86
+ nargs="?",
87
+ const="usb",
88
+ default="usb",
89
+ choices=MODES,
90
+ metavar="MODE",
91
+ help=(
92
+ "usb (default), ac, wireless, or none to leave the setting alone"
93
+ ),
94
+ )
95
+ parser.add_argument(
96
+ "--restore",
97
+ action="store_true",
98
+ help="write the stay-on value recorded by the last prepare back",
99
+ )
100
+ parser.add_argument(
101
+ "--json",
102
+ action="store_true",
103
+ help="print one JSON object instead of human text",
104
+ )
105
+ parser.add_argument(
106
+ "--verbose",
107
+ action="store_true",
108
+ help="log the states and decisions on stderr (never the PIN)",
109
+ )
110
+ parser.add_argument(
111
+ "--version", action="version", version=f"%(prog)s {__version__}"
112
+ )
113
+ return parser
114
+
115
+
116
+ def _log(verbose: bool, message: str) -> None:
117
+ if verbose:
118
+ print(f"phone-prepare: {message}", file=sys.stderr)
119
+
120
+
121
+ def _select(adb: Adb, requested: str | None) -> Device:
122
+ return choose(parse_devices(adb.devices()), requested)
123
+
124
+
125
+ def _payload(
126
+ device: Device, state: dict[str, object], pin_source: str | None
127
+ ) -> dict[str, object]:
128
+ """The phone-state fields the prepare contract promises, and no PIN."""
129
+ return {
130
+ "serial": device.serial,
131
+ "transport": device.transport,
132
+ "screen": state["screen"],
133
+ "keyguard": state["keyguard"],
134
+ "stay_on": state["stay_on"],
135
+ "pin_source": pin_source,
136
+ }
137
+
138
+
139
+ def _emit(
140
+ args: argparse.Namespace,
141
+ device: Device,
142
+ state: dict[str, object],
143
+ pin_source: str | None,
144
+ previous: str | None,
145
+ action: str,
146
+ ) -> None:
147
+ if args.json:
148
+ print(json.dumps(_payload(device, state, pin_source), separators=(",", ":")))
149
+ return
150
+ if action == "prepared":
151
+ detail = (
152
+ f"phone-prepare: {device.serial} {device.transport} "
153
+ f"screen={state['screen']} keyguard={state['keyguard']} "
154
+ f"stay_on={state['stay_on']}"
155
+ )
156
+ if previous is None:
157
+ detail = f"{detail}; previous stay_on_while_plugged_in not recorded"
158
+ else:
159
+ detail = (
160
+ f"{detail}; previous stay_on_while_plugged_in={previous} "
161
+ "(restore with phone-prepare --restore)"
162
+ )
163
+ print(detail)
164
+ else:
165
+ print(
166
+ f"phone-prepare: {device.serial} not prepared: "
167
+ f"screen={state['screen']} keyguard={state['keyguard']} "
168
+ f"lockout={state['lockout']}",
169
+ file=sys.stderr,
170
+ )
171
+
172
+
173
+ def _emit_restore(
174
+ args: argparse.Namespace,
175
+ device: Device,
176
+ previous: str,
177
+ restored: bool,
178
+ ) -> None:
179
+ if args.json:
180
+ print(
181
+ json.dumps(
182
+ {
183
+ "serial": device.serial,
184
+ "restored": restored,
185
+ "stay_on": parse_stay_on(previous),
186
+ },
187
+ separators=(",", ":"),
188
+ )
189
+ )
190
+ return
191
+ if restored:
192
+ print(
193
+ f"phone-prepare: {device.serial} stay_on_while_plugged_in "
194
+ f"restored to {previous}"
195
+ )
196
+ else:
197
+ print(
198
+ f"phone-prepare: {device.serial} nothing to restore; the last run "
199
+ "did not change stay_on_while_plugged_in"
200
+ )
201
+
202
+
203
+ def _undo(
204
+ adb: Adb,
205
+ serial: str,
206
+ previous: str,
207
+ path: Path,
208
+ verbose: bool,
209
+ ) -> None:
210
+ """Best-effort write-back after a failed prepare, then drop the record."""
211
+ error = undo(adb, serial, previous, path)
212
+ if error is None:
213
+ _log(verbose, f"restored stay_on_while_plugged_in={previous}")
214
+ else:
215
+ print(
216
+ f"phone-prepare: could not restore stay_on_while_plugged_in="
217
+ f"{previous}: {error}",
218
+ file=sys.stderr,
219
+ )
220
+
221
+
222
+ def _restore_mode(
223
+ args: argparse.Namespace, adb: Adb, requested: str | None
224
+ ) -> int:
225
+ try:
226
+ device = _select(adb, requested)
227
+ except AdbError as exc:
228
+ print(f"phone-prepare: {exc}", file=sys.stderr)
229
+ return 3
230
+ except SelectionError as exc:
231
+ print(f"phone-prepare: {exc}", file=sys.stderr)
232
+ print(describe(exc.devices), file=sys.stderr)
233
+ return 3
234
+
235
+ path = record_path()
236
+ record = read_record(path)
237
+ if record is None:
238
+ print(
239
+ "phone-prepare: no recorded stay_on_while_plugged_in to restore; "
240
+ "run phone-prepare without --restore first",
241
+ file=sys.stderr,
242
+ )
243
+ return 2
244
+ if record.serial != device.serial:
245
+ print(
246
+ f"phone-prepare: the recorded value belongs to {record.serial}, "
247
+ f"not {device.serial}; refusing to restore a different phone",
248
+ file=sys.stderr,
249
+ )
250
+ return 2
251
+ if not record.applied:
252
+ clear_record(path)
253
+ _emit_restore(args, device, record.previous, False)
254
+ return 0
255
+
256
+ try:
257
+ restore_stay_on(adb, device.serial, record.previous)
258
+ except AdbError as exc:
259
+ print(f"phone-prepare: {exc}", file=sys.stderr)
260
+ return 3
261
+ clear_record(path)
262
+ _emit_restore(args, device, record.previous, True)
263
+ return 0
264
+
265
+
266
+ def main(argv: list[str] | None = None) -> int:
267
+ args = build_parser().parse_args(argv)
268
+ adb = Adb(args.adb)
269
+ requested = args.serial or os.environ.get("ANDROID_SERIAL") or None
270
+ if args.restore:
271
+ return _restore_mode(args, adb, requested)
272
+
273
+ try:
274
+ device = _select(adb, requested)
275
+ except AdbError as exc:
276
+ print(f"phone-prepare: {exc}", file=sys.stderr)
277
+ return 3
278
+ except SelectionError as exc:
279
+ print(f"phone-prepare: {exc}", file=sys.stderr)
280
+ print(describe(exc.devices), file=sys.stderr)
281
+ return 3
282
+
283
+ pin, source, path = load_pin(pin_file=args.pin_file)
284
+ if pin is None or source is None:
285
+ print(
286
+ "phone-prepare: no usable PIN: set $PHONE_PIN or add a "
287
+ f"PHONE_PIN=<digits> line to {path} (or pass --pin-file PATH)",
288
+ file=sys.stderr,
289
+ )
290
+ return 5
291
+
292
+ serial = device.serial
293
+ # Set once step 2 has changed the setting, so any later failure (a raised
294
+ # AdbError, a failed unlock, Ctrl-C) still writes the previous value back.
295
+ # `_undo`/`clear_record` are the same calls the ordinary failure path uses.
296
+ undo_after: tuple[str, Path] | None = None
297
+ try:
298
+ state = collect(adb, device)
299
+ _log(
300
+ args.verbose,
301
+ f"{serial} screen={state['screen']} "
302
+ f"keyguard={state['keyguard']} lockout={state['lockout']} "
303
+ f"pin_source={source}",
304
+ )
305
+
306
+ # Step 1: wake. A panel that will not come on is exit 1 with the
307
+ # stay-on setting still untouched.
308
+ if state["screen"] != "on":
309
+ _log(args.verbose, "panel is not on; sending KEYCODE_WAKEUP")
310
+ woken = run_wake(adb, serial)
311
+ state = collect(adb, device)
312
+ _log(args.verbose, f"woke={woken} screen={state['screen']}")
313
+ if not woken:
314
+ _emit(args, device, state, source, None, "failed")
315
+ return 1
316
+
317
+ # Step 2: stay-on. Read and record before changing anything, so a
318
+ # failure below can put the exact previous value back.
319
+ record = record_path()
320
+ try:
321
+ previous, changed = begin(adb, serial, args.stay_on, record)
322
+ except StayOnError as exc:
323
+ print(f"phone-prepare: {exc}", file=sys.stderr)
324
+ return 3
325
+ except OSError as exc:
326
+ print(
327
+ f"phone-prepare: cannot write the stay-on record {record}: "
328
+ f"{exc}; refusing to change the setting",
329
+ file=sys.stderr,
330
+ )
331
+ return 2
332
+ except AdbError as exc:
333
+ print(f"phone-prepare: {exc}", file=sys.stderr)
334
+ return 3
335
+ _log(args.verbose, f"previous stay_on_while_plugged_in={previous}")
336
+ if changed and previous is not None:
337
+ undo_after = (previous, record)
338
+ else:
339
+ undo_after = None
340
+
341
+ # Step 3: unlock with the shared bounded loop.
342
+ outcome: Outcome = unlock(
343
+ adb, device, pin, source, args.attempts, args.verbose
344
+ )
345
+ if outcome.code != 0:
346
+ if changed and previous is not None:
347
+ _undo(adb, serial, previous, record, args.verbose)
348
+ else:
349
+ clear_record(record)
350
+ undo_after = None
351
+ try:
352
+ final = collect(adb, device)
353
+ except AdbError:
354
+ final = outcome.state
355
+ _emit(args, device, final, source, previous, "failed")
356
+ return outcome.code
357
+
358
+ final = collect(adb, device)
359
+ _emit(args, device, final, source, previous, "prepared")
360
+ return 0
361
+ except AdbError as exc:
362
+ if undo_after is not None:
363
+ _undo(adb, serial, undo_after[0], undo_after[1], args.verbose)
364
+ print(f"phone-prepare: {exc}", file=sys.stderr)
365
+ return 3
366
+ except KeyboardInterrupt:
367
+ if undo_after is not None:
368
+ _undo(adb, serial, undo_after[0], undo_after[1], args.verbose)
369
+ raise
370
+
371
+
372
+ if __name__ == "__main__":
373
+ raise SystemExit(main())