android-device-control 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.
- android_device_control/__init__.py +1 -0
- android_device_control/android_mcp.py +107 -0
- android_device_control/device_info.py +182 -0
- android_device_control/messages.py +164 -0
- android_device_control/phone.py +568 -0
- android_device_control/receipts.py +224 -0
- android_device_control-0.1.0.dist-info/METADATA +151 -0
- android_device_control-0.1.0.dist-info/RECORD +12 -0
- android_device_control-0.1.0.dist-info/WHEEL +5 -0
- android_device_control-0.1.0.dist-info/entry_points.txt +6 -0
- android_device_control-0.1.0.dist-info/licenses/LICENSE +21 -0
- android_device_control-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Android device controls and diagnostics for authorized ADB devices."""
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Serve guarded Android Control tools over local MCP stdio."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import re
|
|
7
|
+
from typing import TYPE_CHECKING
|
|
8
|
+
|
|
9
|
+
if __package__:
|
|
10
|
+
from . import phone
|
|
11
|
+
else:
|
|
12
|
+
import phone
|
|
13
|
+
|
|
14
|
+
if TYPE_CHECKING:
|
|
15
|
+
from mcp.server.fastmcp import FastMCP
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
SERIAL = re.compile(r"[A-Za-z0-9._:-]+")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def authorized_devices(device: str | None = None) -> list[dict[str, str]]:
|
|
22
|
+
devices = []
|
|
23
|
+
for line in phone.devices().splitlines():
|
|
24
|
+
fields = line.split(maxsplit=2)
|
|
25
|
+
if len(fields) < 2:
|
|
26
|
+
continue
|
|
27
|
+
serial, state = fields[:2]
|
|
28
|
+
if state == "device" and SERIAL.fullmatch(serial) and (device is None or serial == device):
|
|
29
|
+
devices.append({"serial": serial, "state": state})
|
|
30
|
+
return devices
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def require_device(requested: str | None, configured: str | None) -> str:
|
|
34
|
+
if configured is not None and requested not in (None, configured):
|
|
35
|
+
raise phone.PhoneError("device is outside the server's configured scope")
|
|
36
|
+
serial = configured if configured is not None else requested
|
|
37
|
+
if not serial or not SERIAL.fullmatch(serial):
|
|
38
|
+
raise phone.PhoneError("provide an explicit valid device serial")
|
|
39
|
+
if not authorized_devices(serial):
|
|
40
|
+
raise phone.PhoneError("device is not connected and authorized in ADB")
|
|
41
|
+
return serial
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def create_server(device: str | None = None, *, allow_input: bool = False) -> FastMCP:
|
|
45
|
+
if device is not None and not SERIAL.fullmatch(device):
|
|
46
|
+
raise phone.PhoneError("--device requires an explicit valid device serial")
|
|
47
|
+
if allow_input and device is None:
|
|
48
|
+
raise phone.PhoneError("--allow-input requires --device")
|
|
49
|
+
|
|
50
|
+
try:
|
|
51
|
+
from mcp.server.fastmcp import FastMCP
|
|
52
|
+
from mcp.types import ToolAnnotations
|
|
53
|
+
except ModuleNotFoundError as exc:
|
|
54
|
+
if exc.name not in ("mcp", "mcp.server.fastmcp"):
|
|
55
|
+
raise
|
|
56
|
+
install_command = (
|
|
57
|
+
"python -m pip install 'android-device-control[mcp]'"
|
|
58
|
+
if __package__
|
|
59
|
+
else "python -m pip install -r requirements-mcp.txt"
|
|
60
|
+
)
|
|
61
|
+
raise phone.PhoneError(f"install the optional MCP SDK with {install_command}") from exc
|
|
62
|
+
|
|
63
|
+
server = FastMCP("Android Control")
|
|
64
|
+
read_only = ToolAnnotations(readOnlyHint=True)
|
|
65
|
+
|
|
66
|
+
@server.tool(annotations=read_only)
|
|
67
|
+
def list_devices() -> list[dict[str, str]]:
|
|
68
|
+
"""List connected, ADB-authorized devices by serial and state within the server scope."""
|
|
69
|
+
return authorized_devices(device)
|
|
70
|
+
|
|
71
|
+
@server.tool(annotations=read_only)
|
|
72
|
+
def foreground(serial: str | None = None) -> str:
|
|
73
|
+
"""Read the focused Android package and activity. Supply a serial on an unscoped server."""
|
|
74
|
+
return phone.foreground(require_device(serial, device))
|
|
75
|
+
|
|
76
|
+
@server.tool(annotations=read_only)
|
|
77
|
+
def snapshot(serial: str | None = None) -> str:
|
|
78
|
+
"""Read the guarded UI summary. Supply a serial on an unscoped server."""
|
|
79
|
+
target = require_device(serial, device)
|
|
80
|
+
root, _ = phone.stable_tree(target)
|
|
81
|
+
lines, _ = phone.build_refs(root)
|
|
82
|
+
return "\n".join(lines)
|
|
83
|
+
|
|
84
|
+
if allow_input:
|
|
85
|
+
@server.tool(annotations=ToolAnnotations(readOnlyHint=False, destructiveHint=True))
|
|
86
|
+
def tap_label(label: str) -> str:
|
|
87
|
+
"""Tap one exact accessibility label on the configured device. Inspect the result separately."""
|
|
88
|
+
return phone.tap_label(require_device(None, device), label)
|
|
89
|
+
|
|
90
|
+
return server
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def main(argv: list[str] | None = None) -> int:
|
|
94
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
95
|
+
parser.add_argument("--device", help="scope the server to one explicit ADB serial")
|
|
96
|
+
parser.add_argument("--allow-input", action="store_true", help="enable exact-label taps on --device")
|
|
97
|
+
args = parser.parse_args(argv)
|
|
98
|
+
try:
|
|
99
|
+
server = create_server(args.device, allow_input=args.allow_input)
|
|
100
|
+
except phone.PhoneError as exc:
|
|
101
|
+
parser.error(str(exc))
|
|
102
|
+
server.run(transport="stdio")
|
|
103
|
+
return 0
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
if __name__ == "__main__":
|
|
107
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Read a small, privacy-conscious set of facts from one Android device.
|
|
3
|
+
|
|
4
|
+
Only fixed, read-only ADB queries are issued. The report intentionally never
|
|
5
|
+
queries subscriber identifiers, phone numbers, network addresses or accounts.
|
|
6
|
+
Battery dump output is parsed transiently and only selected fields are printed;
|
|
7
|
+
raw diagnostic output is not saved or included in the report.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import argparse
|
|
12
|
+
import re
|
|
13
|
+
import subprocess
|
|
14
|
+
import sys
|
|
15
|
+
import unicodedata
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
|
|
18
|
+
TIMEOUT_SECONDS = 12
|
|
19
|
+
SERIAL_RE = re.compile(r"[A-Za-z0-9._:-]{1,128}\Z")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class DeviceInfoError(RuntimeError):
|
|
23
|
+
"""A safe, user-facing error that contains no device output."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True)
|
|
27
|
+
class Result:
|
|
28
|
+
value: str
|
|
29
|
+
state: str = "available"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def adb(device: str, *args: str) -> str:
|
|
33
|
+
"""Run one fixed ADB argument vector; never invoke a local shell."""
|
|
34
|
+
try:
|
|
35
|
+
result = subprocess.run(
|
|
36
|
+
["adb", "-s", device, *args],
|
|
37
|
+
capture_output=True,
|
|
38
|
+
timeout=TIMEOUT_SECONDS,
|
|
39
|
+
check=False,
|
|
40
|
+
)
|
|
41
|
+
except subprocess.TimeoutExpired as exc:
|
|
42
|
+
raise DeviceInfoError("ADB query timed out") from exc
|
|
43
|
+
except OSError as exc:
|
|
44
|
+
raise DeviceInfoError("ADB could not be started") from exc
|
|
45
|
+
if result.returncode:
|
|
46
|
+
raise DeviceInfoError(f"ADB query failed (exit {result.returncode})")
|
|
47
|
+
return result.stdout.decode("utf-8", "replace").strip()
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def query_property(device: str, key: str) -> Result:
|
|
51
|
+
value = adb(device, "shell", "getprop", key).strip()
|
|
52
|
+
# Device properties are untrusted terminal input. Keep values bounded and
|
|
53
|
+
# single-line so control sequences cannot alter the report presentation.
|
|
54
|
+
if (not value or len(value) > 128
|
|
55
|
+
or any(unicodedata.category(char).startswith("C")
|
|
56
|
+
or unicodedata.category(char) in ("Zl", "Zp") for char in value)
|
|
57
|
+
or value == "[ro.boot.unknown]"):
|
|
58
|
+
return Result("unavailable", "unavailable")
|
|
59
|
+
return Result(value)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def battery(device: str) -> dict[str, Result]:
|
|
63
|
+
text = adb(device, "shell", "dumpsys", "battery")
|
|
64
|
+
values = dict(re.findall(r"^\s*(level|status):\s*(\d+)\s*$", text, re.MULTILINE))
|
|
65
|
+
level = values.get("level", "")
|
|
66
|
+
status = values.get("status", "")
|
|
67
|
+
if level and not 0 <= int(level) <= 100:
|
|
68
|
+
level = ""
|
|
69
|
+
status_names = {"1": "unknown", "2": "charging", "3": "discharging",
|
|
70
|
+
"4": "not charging", "5": "full"}
|
|
71
|
+
return {
|
|
72
|
+
"Battery level": Result(f"{level}%") if level else Result("unavailable", "unavailable"),
|
|
73
|
+
"Battery status": Result(status_names[status]) if status in status_names
|
|
74
|
+
else Result("unavailable", "unavailable"),
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def data_storage(device: str) -> Result:
|
|
79
|
+
text = adb(device, "shell", "df", "-k", "/data")
|
|
80
|
+
lines = [line.split() for line in text.splitlines() if line.strip()]
|
|
81
|
+
# Android may report a storage alias (for example an emulated-storage
|
|
82
|
+
# mount) for the explicitly requested /data path. Accept one numeric row;
|
|
83
|
+
# don't require its displayed mount label to literally be /data.
|
|
84
|
+
rows = []
|
|
85
|
+
for fields in lines[1:]:
|
|
86
|
+
if len(fields) >= 6 and all(re.fullmatch(r"\d+", field) for field in fields[1:4]):
|
|
87
|
+
rows.append(fields)
|
|
88
|
+
if len(rows) != 1:
|
|
89
|
+
return Result("unavailable", "unavailable")
|
|
90
|
+
total, used, free = (int(rows[0][i]) for i in (1, 2, 3))
|
|
91
|
+
if total <= 0 or used > total or free > total:
|
|
92
|
+
return Result("unavailable", "unavailable")
|
|
93
|
+
return Result(
|
|
94
|
+
f"{used / 1024:.0f} MiB used / {free / 1024:.0f} MiB free / "
|
|
95
|
+
f"{total / 1024:.0f} MiB total"
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def hardware_features(device: str) -> Result:
|
|
100
|
+
text = adb(device, "shell", "pm", "list", "features")
|
|
101
|
+
features = set(re.findall(r"^feature:([A-Za-z0-9_.-]+)\s*$", text, re.MULTILINE))
|
|
102
|
+
prefixes = ("android.hardware.telephony", "android.hardware.telephony.euicc")
|
|
103
|
+
selected = sorted(feature for feature in features if feature.startswith(prefixes))
|
|
104
|
+
if not text:
|
|
105
|
+
return Result("unavailable", "unavailable")
|
|
106
|
+
return Result(", ".join(selected) if selected else "none reported")
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def sim_info(device: str) -> dict[str, Result]:
|
|
110
|
+
# This property carries SIM state tokens only, never phone numbers or IDs.
|
|
111
|
+
value = adb(device, "shell", "getprop", "gsm.sim.state").strip()
|
|
112
|
+
states = [token.strip().upper() for token in value.split(",") if token.strip()]
|
|
113
|
+
if not states or any(not re.fullmatch(r"[A-Z_ -]{1,32}", state) for state in states):
|
|
114
|
+
return {"SIM state entries": Result("unavailable", "unavailable"),
|
|
115
|
+
"SIM states": Result("unavailable", "unavailable")}
|
|
116
|
+
return {"SIM state entries": Result(str(len(states))),
|
|
117
|
+
"SIM states": Result(", ".join(states))}
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def error_result(error: DeviceInfoError) -> Result:
|
|
121
|
+
"""Preserve failure versus absence without exposing command output."""
|
|
122
|
+
return Result(str(error), "error")
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def collect(device: str) -> list[tuple[str, Result]]:
|
|
126
|
+
fields: list[tuple[str, Result]] = []
|
|
127
|
+
for label, key in (
|
|
128
|
+
("Manufacturer", "ro.product.manufacturer"),
|
|
129
|
+
("Model", "ro.product.model"),
|
|
130
|
+
("Android version", "ro.build.version.release"),
|
|
131
|
+
("Android SDK", "ro.build.version.sdk"),
|
|
132
|
+
):
|
|
133
|
+
try:
|
|
134
|
+
fields.append((label, query_property(device, key)))
|
|
135
|
+
except DeviceInfoError as exc:
|
|
136
|
+
fields.append((label, error_result(exc)))
|
|
137
|
+
try:
|
|
138
|
+
fields.extend(battery(device).items())
|
|
139
|
+
except DeviceInfoError as exc:
|
|
140
|
+
fields.extend((label, error_result(exc)) for label in ("Battery level", "Battery status"))
|
|
141
|
+
for label, query in (("/data storage", data_storage),
|
|
142
|
+
("Telephony/eSIM hardware features", hardware_features)):
|
|
143
|
+
try:
|
|
144
|
+
fields.append((label, query(device)))
|
|
145
|
+
except DeviceInfoError as exc:
|
|
146
|
+
fields.append((label, error_result(exc)))
|
|
147
|
+
try:
|
|
148
|
+
fields.extend(sim_info(device).items())
|
|
149
|
+
except DeviceInfoError as exc:
|
|
150
|
+
fields.extend((label, error_result(exc))
|
|
151
|
+
for label in ("SIM state entries", "SIM states"))
|
|
152
|
+
# Sensitive values are never queried or displayed. In particular, don't
|
|
153
|
+
# add getprop ro.serialno, dumpsys iphonesubinfo/account, or ip/mac commands.
|
|
154
|
+
for label in ("Hardware serial", "IMEI", "ICCID", "MAC/IP addresses",
|
|
155
|
+
"Account details", "Raw device dumps"):
|
|
156
|
+
fields.append((label, Result("withheld for privacy", "withheld")))
|
|
157
|
+
return fields
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def main(argv: list[str] | None = None) -> int:
|
|
161
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
162
|
+
parser.add_argument("--device", required=True, help="explicit ADB device serial")
|
|
163
|
+
args = parser.parse_args(argv)
|
|
164
|
+
if not SERIAL_RE.fullmatch(args.device):
|
|
165
|
+
parser.error("--device must be an explicit ADB serial using letters, digits, '.', '_', ':', or '-'")
|
|
166
|
+
try:
|
|
167
|
+
fields = collect(args.device)
|
|
168
|
+
except DeviceInfoError as exc:
|
|
169
|
+
print(f"Error: {exc}", file=sys.stderr)
|
|
170
|
+
return 1
|
|
171
|
+
print("Android device information (read-only; sensitive identifiers withheld)")
|
|
172
|
+
# The selected ADB serial can itself identify a device, so expose only that
|
|
173
|
+
# one was explicitly selected; don't echo the serial into terminal logs.
|
|
174
|
+
print("ADB device: explicitly selected")
|
|
175
|
+
for label, result in fields:
|
|
176
|
+
suffix = f" [{result.state}]" if result.state != "available" else ""
|
|
177
|
+
print(f"{label}: {result.value}{suffix}")
|
|
178
|
+
return 0
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
if __name__ == "__main__":
|
|
182
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Read SMS inbox messages from one explicitly selected Android device.
|
|
3
|
+
|
|
4
|
+
This command is read-only: it runs a fixed ``content query`` against the SMS
|
|
5
|
+
inbox and never stores results. Message bodies are private content and are
|
|
6
|
+
printed to the terminal, so use an exact ``--sender`` filter when possible.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import argparse
|
|
11
|
+
from collections import Counter
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
import json
|
|
14
|
+
import re
|
|
15
|
+
import shlex
|
|
16
|
+
import subprocess
|
|
17
|
+
import sys
|
|
18
|
+
|
|
19
|
+
TIMEOUT_SECONDS = 20
|
|
20
|
+
SERIAL_RE = re.compile(r"[A-Za-z0-9._:-]{1,128}\Z")
|
|
21
|
+
SENDER_RE = re.compile(r"[^\x00-\x1f\x7f]{1,128}\Z")
|
|
22
|
+
ROW_RE = re.compile(
|
|
23
|
+
r"^Row: \d+ _id=(\d+), address=([^,]*), body=(.*), date=(\d+), sub_id=([^,]*)$"
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class MessagesError(RuntimeError):
|
|
28
|
+
"""A safe user-facing error without raw device output."""
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True)
|
|
32
|
+
class Message:
|
|
33
|
+
message_id: int
|
|
34
|
+
sender: str
|
|
35
|
+
body: str
|
|
36
|
+
date_ms: int
|
|
37
|
+
subscription_id: str
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def sql_string(value: str) -> str:
|
|
41
|
+
"""Quote one SQL string literal for the content provider's --where value."""
|
|
42
|
+
return "'" + value.replace("'", "''") + "'"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def build_command(device: str, sender: str | None) -> list[str]:
|
|
46
|
+
if not SERIAL_RE.fullmatch(device):
|
|
47
|
+
raise MessagesError("provide an explicit valid ADB device serial")
|
|
48
|
+
command = [
|
|
49
|
+
"adb", "-s", device, "shell", "content", "query",
|
|
50
|
+
"--uri", "content://sms/inbox",
|
|
51
|
+
"--projection", "_id:address:body:date:sub_id",
|
|
52
|
+
]
|
|
53
|
+
if sender is not None:
|
|
54
|
+
if not SENDER_RE.fullmatch(sender):
|
|
55
|
+
raise MessagesError("sender must be 1–128 printable characters")
|
|
56
|
+
where = f"address={sql_string(sender)}"
|
|
57
|
+
# adb shell forwards a command through Android's shell; quote this
|
|
58
|
+
# complete SQL expression for that second parsing layer as well.
|
|
59
|
+
command.extend(("--where", shlex.quote(where)))
|
|
60
|
+
return command
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def query(device: str, sender: str | None = None) -> list[Message]:
|
|
64
|
+
command = build_command(device, sender)
|
|
65
|
+
try:
|
|
66
|
+
result = subprocess.run(
|
|
67
|
+
command, capture_output=True, timeout=TIMEOUT_SECONDS, check=False
|
|
68
|
+
)
|
|
69
|
+
except subprocess.TimeoutExpired as exc:
|
|
70
|
+
raise MessagesError("SMS inbox query timed out") from exc
|
|
71
|
+
except OSError as exc:
|
|
72
|
+
raise MessagesError("ADB could not be started") from exc
|
|
73
|
+
if result.returncode:
|
|
74
|
+
# Android/provider errors can echo query data; do not relay stdout/stderr.
|
|
75
|
+
raise MessagesError(
|
|
76
|
+
"SMS inbox query failed; check device connection and SMS permission"
|
|
77
|
+
)
|
|
78
|
+
output = result.stdout.decode("utf-8", "replace")
|
|
79
|
+
if output.strip() == "No result found.":
|
|
80
|
+
return []
|
|
81
|
+
messages: list[Message] = []
|
|
82
|
+
rows = re.split(r"(?m)(?=^Row: \d+ _id=\d+, address=)", output)
|
|
83
|
+
for row in rows:
|
|
84
|
+
row = row.rstrip("\r\n")
|
|
85
|
+
if not row.strip():
|
|
86
|
+
continue
|
|
87
|
+
match = re.fullmatch(ROW_RE.pattern, row, re.DOTALL)
|
|
88
|
+
if not match:
|
|
89
|
+
raise MessagesError("SMS provider returned an unsupported row format")
|
|
90
|
+
message_id, address, body, date_ms, sub_id = match.groups()
|
|
91
|
+
if sender is not None and address != sender:
|
|
92
|
+
# Defense in depth: never print rows outside the requested sender.
|
|
93
|
+
continue
|
|
94
|
+
messages.append(Message(int(message_id), address, body, int(date_ms), sub_id))
|
|
95
|
+
return messages
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def senders(device: str) -> Counter[str]:
|
|
99
|
+
if not SERIAL_RE.fullmatch(device):
|
|
100
|
+
raise MessagesError("provide an explicit valid ADB device serial")
|
|
101
|
+
try:
|
|
102
|
+
result = subprocess.run(
|
|
103
|
+
["adb", "-s", device, "shell", "content", "query", "--uri",
|
|
104
|
+
"content://sms/inbox", "--projection", "address"],
|
|
105
|
+
capture_output=True, timeout=TIMEOUT_SECONDS, check=False,
|
|
106
|
+
)
|
|
107
|
+
except (OSError, subprocess.TimeoutExpired) as exc:
|
|
108
|
+
raise MessagesError("SMS sender query failed; check device connection") from exc
|
|
109
|
+
if result.returncode:
|
|
110
|
+
raise MessagesError("SMS sender query failed; check device connection and SMS permission")
|
|
111
|
+
output = result.stdout.decode("utf-8", "replace").strip()
|
|
112
|
+
if output == "No result found.":
|
|
113
|
+
return Counter()
|
|
114
|
+
counts: Counter[str] = Counter()
|
|
115
|
+
for line in output.splitlines():
|
|
116
|
+
match = re.fullmatch(r"Row: \d+ address=(.*)", line)
|
|
117
|
+
if not match:
|
|
118
|
+
raise MessagesError("SMS provider returned an unsupported sender format")
|
|
119
|
+
counts[match.group(1)] += 1
|
|
120
|
+
return counts
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def main(argv: list[str] | None = None) -> int:
|
|
124
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
125
|
+
parser.add_argument("--device", required=True, help="explicit ADB device serial")
|
|
126
|
+
parser.add_argument(
|
|
127
|
+
"--sender", help="exact sender/address filter (recommended for privacy)"
|
|
128
|
+
)
|
|
129
|
+
parser.add_argument("--senders", action="store_true", help="list sender names and counts without message bodies")
|
|
130
|
+
parser.add_argument("--contains", help="show messages containing this text (case-insensitive)")
|
|
131
|
+
parser.add_argument("--subscription", help="show messages for this subscription ID")
|
|
132
|
+
parser.add_argument(
|
|
133
|
+
"--limit", type=int, default=20,
|
|
134
|
+
help="maximum number of returned messages (default: 20; maximum: 100)",
|
|
135
|
+
)
|
|
136
|
+
args = parser.parse_args(argv)
|
|
137
|
+
if not 1 <= args.limit <= 100:
|
|
138
|
+
parser.error("--limit must be between 1 and 100")
|
|
139
|
+
if args.senders and (args.sender or args.contains or args.subscription):
|
|
140
|
+
parser.error("--senders cannot be combined with message filters")
|
|
141
|
+
try:
|
|
142
|
+
if args.senders:
|
|
143
|
+
for name, count in sorted(senders(args.device).items()):
|
|
144
|
+
print(f"{json.dumps(name, ensure_ascii=False)}: {count}")
|
|
145
|
+
return 0
|
|
146
|
+
messages = query(args.device, args.sender)
|
|
147
|
+
except MessagesError as exc:
|
|
148
|
+
print(f"Error: {exc}", file=sys.stderr)
|
|
149
|
+
return 1
|
|
150
|
+
selected = [item for item in messages
|
|
151
|
+
if (not args.contains or args.contains.casefold() in item.body.casefold())
|
|
152
|
+
and (not args.subscription or args.subscription == item.subscription_id)]
|
|
153
|
+
selected = sorted(selected, key=lambda item: (item.date_ms, item.message_id))[-args.limit:]
|
|
154
|
+
print(f"SMS inbox messages: {len(selected)} shown")
|
|
155
|
+
for message in selected:
|
|
156
|
+
print(f"\nFrom: {json.dumps(message.sender, ensure_ascii=False)}")
|
|
157
|
+
print(f"Date (Unix milliseconds): {message.date_ms}")
|
|
158
|
+
print(f"Subscription ID: {message.subscription_id}")
|
|
159
|
+
print(f"Message: {json.dumps(message.body, ensure_ascii=False)}")
|
|
160
|
+
return 0
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
if __name__ == "__main__":
|
|
164
|
+
raise SystemExit(main())
|