Skip to content

CLI for SidePulse

Python

Support Android pairing and FCM delivery in the CLI

Peter Kuharfbb35414fd84
diff --git a/README.md b/README.md
index 95f90f3..03549e3 100644
--- a/README.md
+++ b/README.md
@@ -39,7 +39,7 @@ Homebrew or administrator access. On Linux, install Python 3.10 or newer first.
`~/.local/share/sidepulse/venv`, installs SidePulse from GitHub, links the CLI
at `~/.local/bin/sidepulse`, and runs `sidepulse setup`. On macOS, setup also
installs the menu-bar app and hardware helpers. On Linux, it automatically
-uses CLI-only mode for mounted SidePulse devices and iPhone linking/push. Run
+uses CLI-only mode for mounted SidePulse devices and iPhone/Android linking and push. Run
`sidepulse update` to upgrade to the newest version from GitHub.
Setup also installs a headless SidePulse service. It runs through a LaunchAgent
@@ -226,7 +226,24 @@ must be FAT12 starting at sector zero, with one FAT and 512-byte sectors. Progra
are limited to 512 bytes and 20 lines. It writes the existing file's first data
sector and updates its directory size, preserving its FAT allocation.
-### Link an iPhone
+### Link an iPhone or Android phone
+
+Both apps can scan the QR code from `sidepulse link`, or you can paste the
+complete push token shown by the app. Android tokens use
+`fcm_<registration-token>_<32-character-sender-key>`. Keep the entire token,
+including its case and underscores. Android delivery uses the production
+bridge's FCM route and data messages; the phone applies the program to its
+connected Dot through USB. Its app must have USB access.
+
+Existing iPhone links are preserved. Android links are stored alongside them
+with private file permissions. Re-pairing the same registration replaces its
+sender key; Android link IDs stay stable when the sender key changes.
+`sidepulse push`, `sidepulse write`, `--to`, and `--all` support both platforms.
+For example:
+
+```sh
+sidepulse push "off\n#00ff00 pulse" --to "Pixel 10 Pro XL" --title "Build complete"
+```
Run one command and either scan the terminal QR code with the SidePulse iOS app
or paste the push token shown by the app. Production tokens have 64 hexadecimal
@@ -260,7 +277,7 @@ older unkeyed senders must obtain a new token.
sidepulse link
```
-List saved iPhones and remove a stale link by its displayed ID:
+List saved phones and remove a stale link by its displayed ID:
```sh
sidepulse unlink
diff --git a/docs/ANDROID_CLI_VALIDATION.json b/docs/ANDROID_CLI_VALIDATION.json
new file mode 100644
index 0000000..26f5460
--- /dev/null
+++ b/docs/ANDROID_CLI_VALIDATION.json
@@ -0,0 +1,28 @@
+{
+ "client": "locally installed sidepulse CLI",
+ "phone": "Pixel 10 Pro XL",
+ "bridge": "https://bridge.sidepulse.io",
+ "cli_exit": 0,
+ "instrumentation": "OK (1 test)",
+ "title": "Production delivery test",
+ "activity_before": 34,
+ "inbox_before": 34,
+ "usb_command_before": 120,
+ "ready_at": 1790837074497,
+ "production_push_received": true,
+ "status": "wrote",
+ "activity_after": 35,
+ "inbox_after": 35,
+ "usb_command_after_delivery": 121,
+ "usb_command_after_recovery": 121,
+ "usb_applied": 121,
+ "recovery_id_matches": true,
+ "empty_recovery": true,
+ "standard_tls_trust": true,
+ "received_at": 1790837075395,
+ "receipt_uses_sender_event_id": true,
+ "validation_date": "2026-09-30",
+ "led_program": "#00ff00 450ms cosine\noff 160ms none\n",
+ "wireless_adb": true,
+ "python_verification": "114 targeted compatibility, packaging, linking, and delivery tests passed; other tests passed in the broader run."
+}
diff --git a/src/sidepulse/cli.py b/src/sidepulse/cli.py
index 04413da..96fc9f1 100644
--- a/src/sidepulse/cli.py
+++ b/src/sidepulse/cli.py
@@ -53,7 +53,7 @@ from .links import (
listen_for_ios_registration,
load_ios_links,
new_pairing_channel,
- normalize_apns_token,
+ normalize_phone_token,
pairing_url,
remove_ios_link,
render_terminal_qr,
@@ -191,16 +191,16 @@ def build_sidepulse_parser() -> argparse.ArgumentParser:
link = subparsers.add_parser(
"link",
- help="Link an iPhone or connect this computer to a remote SidePulse receiver.",
+ help="Link an iPhone or Android phone, or connect this computer to a remote SidePulse receiver.",
)
link.add_argument("relay_code", nargs="?", help="Relay code printed by the receiving Mac.")
link.set_defaults(func=cmd_sidepulse_link)
unlink = subparsers.add_parser(
"unlink",
- help="List linked iPhones or remove one by its displayed ID.",
+ help="List linked phones or remove one by its displayed ID.",
)
- unlink.add_argument("link_id", nargs="?", help="Exact linked iPhone ID to remove.")
+ unlink.add_argument("link_id", nargs="?", help="Exact linked phone ID to remove.")
unlink.set_defaults(func=cmd_sidepulse_unlink)
service = subparsers.add_parser(
@@ -718,7 +718,7 @@ def cmd_sidepulse_link(args: argparse.Namespace) -> int:
+ ", ".join(f"{link.name} ({link.link_id})" for link in existing)
)
print()
- print("Link your iPhone")
+ print("Link your iPhone or Android phone")
print()
print("Scan this QR code with your phone:")
print()
@@ -755,13 +755,13 @@ def cmd_sidepulse_link(args: argparse.Namespace) -> int:
input_enabled = False
continue
try:
- token = normalize_apns_token(value)
+ token = normalize_phone_token(value)
except LinkError as exc:
print(f"Invalid token: {exc}")
prompt_visible = False
continue
link = IOSLink(
- name="iPhone",
+ name="Android phone" if token.startswith("fcm_") else "iPhone",
token=token,
server=server,
linked_at=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
@@ -795,9 +795,9 @@ def cmd_sidepulse_unlink(args: argparse.Namespace) -> int:
links = load_ios_links()
if args.link_id is None:
if not links:
- print("No linked iPhones.")
+ print("No linked phones.")
return 0
- print("Linked iPhones:")
+ print("Linked phones:")
for link in links:
print(f" {link.name} ({link.link_id})")
print("Remove one with `sidepulse unlink ID_FROM_LIST`.")
@@ -805,7 +805,7 @@ def cmd_sidepulse_unlink(args: argparse.Namespace) -> int:
matches = [link for link in links if link.link_id.casefold() == args.link_id.casefold()]
if not matches:
- print(f"sidepulse unlink: No linked iPhone has ID {args.link_id!r}.", file=sys.stderr)
+ print(f"sidepulse unlink: No linked phone has ID {args.link_id!r}.", file=sys.stderr)
return 1
if len(matches) != 1:
print(
@@ -821,7 +821,7 @@ def cmd_sidepulse_unlink(args: argparse.Namespace) -> int:
print(f"sidepulse unlink: Could not save the linked phones: {exc}", file=sys.stderr)
return 1
if removed is None:
- print("sidepulse unlink: The linked iPhone has already been removed.", file=sys.stderr)
+ print("sidepulse unlink: The linked phone has already been removed.", file=sys.stderr)
return 1
print(f"Unlinked {removed.name} ({removed.link_id}).")
return 0
diff --git a/src/sidepulse/links.py b/src/sidepulse/links.py
index fe2c6a9..20839e0 100644
--- a/src/sidepulse/links.py
+++ b/src/sidepulse/links.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import hashlib
import json
import os
import queue
@@ -23,6 +24,7 @@ from .settings import default_config_dir
DEFAULT_BRIDGE_SERVER = "https://bridge.sidepulse.io"
PAIRING_TIMEOUT_SECONDS = 5 * 60
IOS_BUNDLE_ID = "io.sidepulse.ios"
+ANDROID_PACKAGE_ID = "io.sidepulse.android"
APNS_TOKEN_PATTERN = re.compile(r"(?:dev_)?[0-9a-f]{64}(?:_[A-Za-z0-9_-]{1,128})?")
PAIRING_CHANNEL_PATTERN = re.compile(r"^[A-Za-z0-9_-]{11}$")
@@ -32,14 +34,26 @@ class LinkError(RuntimeError):
@dataclass(frozen=True)
-class IOSLink:
+class PhoneLink:
name: str
token: str
server: str = DEFAULT_BRIDGE_SERVER
linked_at: str = ""
+ @property
+ def platform(self) -> str:
+ return "android" if self.token.startswith("fcm_") else "ios"
+
+ @property
+ def device_token(self) -> str:
+ if self.platform == "android":
+ return self.token[:-33]
+ return self.token[:68] if self.token.startswith("dev_") else self.token[:64]
+
@property
def link_id(self) -> str:
+ if self.platform == "android":
+ return hashlib.sha256(self.device_token.encode("ascii")).hexdigest()[:12]
return self.token[:12]
def to_dict(self) -> dict[str, str]:
@@ -52,6 +66,10 @@ class IOSLink:
}
+# Preserve the existing public API and integrations while supporting both phones.
+IOSLink = PhoneLink
+
+
def default_links_path() -> Path:
return default_config_dir() / "links.json"
@@ -87,7 +105,25 @@ def normalize_apns_token(value: str) -> str:
return token
+def normalize_fcm_token(value: str) -> str:
+ """Keep the opaque registration unchanged; only the final suffix is a key."""
+ token = value.strip()
+ if not token.startswith("fcm_") or not re.fullmatch(r"_[0-9a-f]{32}", token[-33:]):
+ raise LinkError("Android push token must start with 'fcm_' and end with a 32-character sender key.")
+ registration = token[4:-33]
+ if not 1 <= len(registration) <= 4096 or any(
+ not 33 <= ord(char) <= 126 or char in "/\\?#%" for char in registration
+ ):
+ raise LinkError("Android push token contains an invalid registration token.")
+ return token
+
+
+def normalize_phone_token(value: str) -> str:
+ return normalize_fcm_token(value) if value.strip().startswith("fcm_") else normalize_apns_token(value)
+
+
def load_ios_links(path: Path | None = None) -> tuple[IOSLink, ...]:
+ """Load all phones, including legacy version-1 iOS entries."""
target = (path or default_links_path()).expanduser()
try:
data = json.loads(target.read_text(encoding="utf-8"))
@@ -97,24 +133,28 @@ def load_ios_links(path: Path | None = None) -> tuple[IOSLink, ...]:
return ()
if not isinstance(data, dict) or data.get("version") != 1:
return ()
- items = data.get("ios")
- if not isinstance(items, list):
- return ()
links: list[IOSLink] = []
- for item in items:
- if not isinstance(item, dict):
+ for platform, normalizer, default_name in (
+ ("ios", normalize_apns_token, "iPhone"),
+ ("android", normalize_fcm_token, "Android phone"),
+ ):
+ items = data.get(platform, [])
+ if not isinstance(items, list):
continue
- try:
- links.append(
- IOSLink(
- name=str(item.get("name") or "iPhone"),
- token=normalize_apns_token(str(item["token"])),
- server=normalize_server(str(item.get("server") or DEFAULT_BRIDGE_SERVER)),
- linked_at=str(item.get("linked_at") or ""),
+ for item in items:
+ if not isinstance(item, dict):
+ continue
+ try:
+ links.append(
+ PhoneLink(
+ name=str(item.get("name") or default_name),
+ token=normalizer(str(item["token"])),
+ server=normalize_server(str(item.get("server") or DEFAULT_BRIDGE_SERVER)),
+ linked_at=str(item.get("linked_at") or ""),
+ )
)
- )
- except (KeyError, LinkError):
- continue
+ except (KeyError, LinkError):
+ continue
return tuple(links)
@@ -125,13 +165,18 @@ def save_ios_links(links: Iterable[IOSLink], path: Path | None = None) -> Path:
target.parent.chmod(0o700)
except OSError:
pass
+ phones = tuple(links)
payload = {
"version": 1,
- "ios": [link.to_dict() for link in links],
+ "ios": [link.to_dict() for link in phones if link.platform == "ios"],
+ "android": [link.to_dict() for link in phones if link.platform == "android"],
}
temporary = target.with_suffix(target.suffix + ".tmp")
- temporary.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
- temporary.chmod(0o600)
+ # Create privately before writing credentials, including under a permissive umask.
+ descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
+ with os.fdopen(descriptor, "w", encoding="utf-8") as output:
+ os.fchmod(output.fileno(), 0o600)
+ output.write(json.dumps(payload, indent=2, sort_keys=True) + "\n")
temporary.replace(target)
target.chmod(0o600)
return target
@@ -142,9 +187,7 @@ def store_ios_link(link: IOSLink, path: Path | None = None) -> tuple[IOSLink, ..
updated: list[IOSLink] = []
replaced = False
for existing in current:
- existing_device = existing.token[:68] if existing.token.startswith("dev_") else existing.token[:64]
- new_device = link.token[:68] if link.token.startswith("dev_") else link.token[:64]
- if existing_device == new_device:
+ if (existing.platform, existing.device_token) == (link.platform, link.device_token):
updated.append(link)
replaced = True
else:
@@ -263,6 +306,26 @@ def iter_sse_messages(response) -> Iterable[str]:
yield "\n".join(data_lines)
+def parse_phone_registration(value: str, *, server: str) -> PhoneLink:
+ try:
+ payload = json.loads(value)
+ except json.JSONDecodeError as exc:
+ raise LinkError("Pairing response was not valid JSON.") from exc
+ if isinstance(payload, dict) and payload.get("type") == "ios_registration":
+ return parse_ios_registration(value, server=server)
+ if not isinstance(payload, dict) or payload.get("v") != 1 or payload.get("type") != "android_registration":
+ raise LinkError("Pairing response has an unsupported format.")
+ device = payload.get("device")
+ if not isinstance(device, dict) or device.get("platform") != "android" or device.get("package_id") != ANDROID_PACKAGE_ID:
+ raise LinkError("Pairing response did not include a supported SidePulse Android device.")
+ return PhoneLink(
+ name=str(device.get("name") or "Android phone").strip()[:80] or "Android phone",
+ token=normalize_fcm_token(str(device.get("push_token") or "")),
+ server=normalize_server(server),
+ linked_at=datetime.now(timezone.utc).isoformat(),
+ )
+
+
def listen_for_ios_registration(
server: str,
channel: str,
@@ -281,7 +344,7 @@ def listen_for_ios_registration(
if stop.is_set():
return
try:
- link = parse_ios_registration(message, server=server)
+ link = parse_phone_registration(message, server=server)
except LinkError:
continue
results.put(link)
@@ -316,10 +379,13 @@ def send_ios_program(
alert["body"] = clean_message
aps["alert"] = alert
- payload: dict[str, object] = {
- "aps": aps,
- "data": custom_data,
- }
+ payload: dict[str, object] = {"data": custom_data}
+ if link.platform == "android":
+ payload["sidepulse_event_id"] = custom_data["sidepulse_event_id"]
+ channel = normalize_fcm_token(link.token)
+ else:
+ payload["aps"] = aps
+ channel = "apns_" + normalize_apns_token(link.token)
if program is not None:
payload["leds"] = program
if clean_title:
@@ -327,7 +393,7 @@ def send_ios_program(
if clean_message:
payload["body"] = clean_message
body = json.dumps(payload, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
- url = f"{normalize_server(link.server)}/api/leds/apns_{link.token}"
+ url = f"{normalize_server(link.server)}/api/leds/{urllib.parse.quote(channel, safe='')}"
request = urllib.request.Request(
url,
data=body,
@@ -339,6 +405,18 @@ def send_ios_program(
return response.read().decode("utf-8", errors="replace").strip()
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", errors="replace").strip()
+ for secret in (url, urllib.parse.quote(channel, safe=""), channel, link.token,
+ link.device_token, link.token.rsplit("_", 1)[-1]):
+ detail = detail.replace(secret, "[redacted]")
raise LinkError(detail or f"Bridge returned HTTP {exc.code}.") from exc
except (OSError, urllib.error.URLError) as exc:
- raise LinkError(f"Could not reach the bridge: {exc}") from exc
+ raise LinkError("Could not reach the bridge. Check the connection and bridge server.") from exc
+
+
+# Platform-neutral names for new callers; old names remain compatible.
+load_phone_links = load_ios_links
+save_phone_links = save_ios_links
+store_phone_link = store_ios_link
+remove_phone_link = remove_ios_link
+listen_for_phone_registration = listen_for_ios_registration
+send_phone_program = send_ios_program
diff --git a/src/sidepulse/status_bar.py b/src/sidepulse/status_bar.py
index f804066..093bb1f 100644
--- a/src/sidepulse/status_bar.py
+++ b/src/sidepulse/status_bar.py
@@ -2112,7 +2112,7 @@ class StatusBarController(NSObject):
None,
)
if link is None:
- self.set_settings_message("That iPhone is no longer linked.")
+ self.set_settings_message("That phone is no longer linked.")
self.refresh_(None)
return
if not confirm_linked_phone_removal(link.name):
@@ -2122,7 +2122,7 @@ class StatusBarController(NSObject):
try:
removed = remove_ios_link(link.token)
if removed is None:
- self.set_settings_message("That iPhone is no longer linked.")
+ self.set_settings_message("That phone is no longer linked.")
else:
self.settings = self.settings.without_device(device_id)
save_settings(self.settings)
@@ -3743,11 +3743,11 @@ def build_device_menu_item(device: StatusBarDevice, target: StatusBarController)
if device.remote_link is not None:
submenu.addItem_(NSMenuItem.separatorItem())
- submenu.addItem_(disabled_menu_item("Linked iPhone"))
+ submenu.addItem_(disabled_menu_item("Linked phone"))
submenu.addItem_(disabled_menu_item(f"ID {device.remote_link.link_id}"))
submenu.addItem_(disabled_menu_item(device.remote_link.server))
remove_phone = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
- "Remove iPhone...",
+ "Remove phone...",
"removeLinkedPhone:",
"",
)
@@ -3886,7 +3886,7 @@ def confirm_linked_phone_removal(name: str) -> bool:
alert = NSAlert.alloc().init()
alert.setMessageText_(f"Remove {name}?")
alert.setInformativeText_(
- "This Mac will stop sending SidePulse updates to this iPhone. "
+ "This Mac will stop sending SidePulse updates to this phone. "
"You can link it again later."
)
alert.addButtonWithTitle_("Remove")
diff --git a/tests/test_android_links.py b/tests/test_android_links.py
new file mode 100644
index 0000000..e92929b
--- /dev/null
+++ b/tests/test_android_links.py
@@ -0,0 +1,144 @@
+from __future__ import annotations
+
+import io
+import json
+import queue
+import sys
+import tempfile
+import threading
+import time
+import unittest
+import urllib.error
+import urllib.parse
+from pathlib import Path
+from unittest.mock import MagicMock, patch
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
+
+from sidepulse.cli import sidepulse_main
+from sidepulse.links import (
+ LinkError, PhoneLink, listen_for_phone_registration, load_phone_links,
+ normalize_fcm_token, parse_phone_registration, remove_phone_link,
+ send_phone_program, store_phone_link,
+)
+
+TOKEN = "fcm_Case_sensitive:opaque_registration_with_underscores_" + "a" * 32
+
+
+def registration(**overrides):
+ device = {"name": "Pixel 10 Pro XL", "platform": "android",
+ "package_id": "io.sidepulse.android", "push_token": TOKEN}
+ device.update(overrides)
+ return json.dumps({"v": 1, "type": "android_registration", "device": device})
+
+
+class AndroidLinkTests(unittest.TestCase):
+ def test_registration_and_opaque_token_preserve_case_and_underscores(self):
+ link = parse_phone_registration(registration(), server="https://bridge.sidepulse.io")
+ self.assertEqual(link.token, TOKEN)
+ self.assertEqual(link.platform, "android")
+ self.assertEqual(link.name, "Pixel 10 Pro XL")
+ for change in ({"platform": "ios"}, {"package_id": "other.app"}, {"push_token": "a" * 64}):
+ with self.subTest(change=change), self.assertRaises(LinkError):
+ parse_phone_registration(registration(**change), server="https://bridge.sidepulse.io")
+
+ def test_invalid_sender_tokens_are_rejected_without_exposing_secrets(self):
+ for token in ("fcm__" + "a" * 32, TOKEN[:-1], TOKEN[:-32] + "A" * 32,
+ "fcm_" + "x" * 4097 + "_" + "a" * 32,
+ *["fcm_x" + char + "y_" + "a" * 32 for char in "/\\?#%\n é"]):
+ with self.subTest(token_length=len(token)), self.assertRaises(LinkError) as error:
+ normalize_fcm_token(token)
+ self.assertNotIn(token, str(error.exception))
+
+ def test_rekey_preserves_id_and_existing_ios_links(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / "links.json"
+ path.write_text(json.dumps({"version": 1, "ios": [{"name": "iPhone", "token": "b" * 64}]}))
+ iphone = load_phone_links(path)[0]
+ pixel = PhoneLink("Pixel", TOKEN)
+ updated = PhoneLink("Pixel", TOKEN[:-32] + "c" * 32)
+ other = PhoneLink("Other Pixel", TOKEN.replace("underscores", "different"))
+ self.assertEqual(pixel.link_id, updated.link_id)
+ self.assertNotEqual(pixel.link_id, other.link_id)
+ store_phone_link(pixel, path)
+ store_phone_link(other, path)
+ self.assertEqual(store_phone_link(updated, path), (iphone, updated, other))
+ self.assertEqual(path.stat().st_mode & 0o777, 0o600)
+ self.assertEqual(remove_phone_link(updated.token, path), updated)
+ self.assertEqual(load_phone_links(path), (iphone, other))
+
+ def test_sse_pairing_ignores_invalid_events_then_links_android(self):
+ response = MagicMock()
+ response.__enter__.return_value = iter([
+ b'data: {"v":1,"type":"unsupported"}\n', b'\n',
+ b'data: ' + registration().encode() + b'\n', b'\n',
+ ])
+ results = queue.Queue()
+ with patch("sidepulse.links.urllib.request.urlopen", return_value=response):
+ listen_for_phone_registration("https://bridge.sidepulse.io", "7kP2_xQ9mLs",
+ results, threading.Event(), deadline=time.monotonic() + 1)
+ self.assertEqual(results.get_nowait().token, TOKEN)
+
+ def test_fcm_data_payload_has_single_prefix_and_root_event_id(self):
+ response = MagicMock()
+ response.__enter__.return_value.read.return_value = b"OK"
+ with patch("sidepulse.links.urllib.request.urlopen", return_value=response) as request:
+ send_phone_program(PhoneLink("Pixel", TOKEN), "off", event_id="event-1",
+ title="Build complete", message="Tests passed",
+ data={"source": {"name": "Mac"}, "sidepulse_event_id": "wrong"})
+ sent = request.call_args.args[0]
+ self.assertEqual(urllib.parse.unquote(sent.full_url), "https://bridge.sidepulse.io/api/leds/" + TOKEN)
+ payload = json.loads(sent.data)
+ self.assertNotIn("aps", payload)
+ self.assertEqual(payload["sidepulse_event_id"], "event-1")
+ self.assertEqual(payload["data"]["sidepulse_event_id"], "event-1")
+ self.assertEqual(payload["leds"], "off")
+ self.assertEqual(payload["body"], "Tests passed")
+ self.assertEqual(payload["data"]["source"], {"name": "Mac"})
+
+ def test_http_and_connection_errors_do_not_print_sender_credentials(self):
+ url = "https://bridge.sidepulse.io/api/leds/" + TOKEN
+ errors = [urllib.error.URLError(url),
+ urllib.error.HTTPError(url, 400, "bad", {}, io.BytesIO(("Rejected " + TOKEN).encode()))]
+ for error in errors:
+ with patch("sidepulse.links.urllib.request.urlopen", side_effect=error):
+ with self.assertRaises(LinkError) as result:
+ send_phone_program(PhoneLink("Pixel", TOKEN), "off")
+ self.assertNotIn(TOKEN, str(result.exception))
+ self.assertNotIn("a" * 32, str(result.exception))
+
+ def test_installed_cli_routes_by_name_and_unlinks_by_id(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / "links.json"
+ phone = PhoneLink("Pixel 10 Pro XL", TOKEN)
+ store_phone_link(phone, path)
+ response = MagicMock()
+ response.__enter__.return_value.read.return_value = b"OK"
+ with (patch("sidepulse.links.default_links_path", return_value=path),
+ patch("sidepulse.cli.discover_devices", return_value=[]),
+ patch("sidepulse.cli._remote_event_data", return_value={}),
+ patch("sidepulse.links.urllib.request.urlopen", return_value=response) as request,
+ patch("sys.stdout", io.StringIO())):
+ self.assertEqual(sidepulse_main(["push", "off", "--to", phone.name]), 0)
+ self.assertEqual(json.loads(request.call_args.args[0].data)["title"], "Update")
+ self.assertEqual(sidepulse_main(["unlink", phone.link_id]), 0)
+ self.assertEqual(load_phone_links(path), ())
+
+ def test_cli_accepts_a_pasted_android_token(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / "links.json"
+ with (patch("sidepulse.links.default_links_path", return_value=path),
+ patch("sidepulse.cli.ensure_receiver_config"),
+ patch("sidepulse.cli.relay_link_command", return_value="sidepulse link receiver"),
+ patch("sidepulse.cli.render_terminal_qr", return_value="QR"),
+ patch("sidepulse.cli.threading.Thread"),
+ patch("sidepulse.cli.select.select", return_value=([sys.stdin], [], [])),
+ patch("sys.stdin", io.StringIO(TOKEN + "\n")),
+ patch("sys.stdout", io.StringIO())):
+ self.assertEqual(sidepulse_main(["link"]), 0)
+ self.assertEqual(load_phone_links(path)[0].token, TOKEN)
+ self.assertEqual(load_phone_links(path)[0].name, "Android phone")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_status_bar_ui.py b/tests/test_status_bar_ui.py
index b61bc46..710eeee 100644
--- a/tests/test_status_bar_ui.py
+++ b/tests/test_status_bar_ui.py
@@ -472,9 +472,9 @@ class MenuBuildTests(StatusBarTestCase):
self.assertIn("Agent Status", submenu_titles)
self.assertIn("Manual", submenu_titles)
self.assertNotIn("Battery Level", submenu_titles)
- self.assertIn("Linked iPhone", submenu_titles)
+ self.assertIn("Linked phone", submenu_titles)
self.assertIn("ID aaaaaaaaaaaa", submenu_titles)
- self.assertIn("Remove iPhone...", submenu_titles)
+ self.assertIn("Remove phone...", submenu_titles)
self.assertNotIn("Brightness 100%", submenu_titles)
def test_remove_linked_iphone_requires_confirmation_and_deletes_link(self):