Files
lintunes/lintunes/cassette/syncthing_api.py
T
trav db9e5eab79 v0.26.0: Cassette footing — Syncthing client, host machine, Sync Settings
First step of friend library sharing (Cassette):

- cassette/syncthing_api.py: a typed wrapper over the *local* Syncthing's
  REST API. Key and address come from Syncthing's config.xml (config.json
  may override); every failure is a SyncthingError naming the step, what
  Syncthing said, and whether it's not running / a bad key / a refusal.
- cassette/state.py: friends, invites and share selections, kept in the
  machine-local ~/.local/share/lintunes/cassette, never the synced data dir.
- cassette/host.py: one machine runs Cassette. config.json flags it,
  preferences.json names it, and the other machine greys the menu group
  out and says where friend sharing lives.
- Connections ▸ Sync Settings…: VLC-style list + page, editing a copy
  that only OK writes. General shows Syncthing's status with a next step
  for every failure, the display name and an avatar picker.
2026-09-28 21:01:17 -07:00

293 lines
12 KiB
Python

"""The local Syncthing daemon's REST API — the only "network" Cassette uses.
LinTunes never talks to a friend's machine. It asks *this* machine's Syncthing
to add a device, share a folder, accept one, and to say what it can see;
Syncthing moves every byte. So this module is a thin, typed wrapper over
``http://127.0.0.1:8384/rest/...`` with one rule: **every failure says which
step failed and what Syncthing said** (``SyncthingError``), because the UI
promises never to fail silently.
Where the API lives and its key come from Syncthing's own ``config.xml`` (the
same file ``sync_identity`` reads for device names). ``config.json`` may
override either, for a Syncthing that isn't where we look.
"""
from __future__ import annotations
import logging
import xml.etree.ElementTree as ET
from dataclasses import dataclass
from pathlib import Path
import requests
from lintunes import sync_identity
log = logging.getLogger(__name__)
# config.json keys (per machine — which Syncthing this is is nobody else's
# business, same as ytdlp_cookies_browser).
API_KEY_KEY = "syncthing_api_key"
ADDRESS_KEY = "syncthing_address"
DEFAULT_ADDRESS = "127.0.0.1:8384"
TIMEOUT_S = 10
# SyncthingError.kind
NOT_RUNNING = "not_running" # nothing listening — Syncthing isn't started
BAD_KEY = "bad_key" # it answered 401/403: missing or wrong API key
NO_KEY = "no_key" # we couldn't find a key to send at all
OTHER = "other" # it answered, and said no
class SyncthingError(Exception):
"""A step that failed, and what Syncthing (or the socket) said."""
def __init__(self, step: str, detail: str, kind: str = OTHER,
status: int | None = None):
super().__init__(f"{step}: {detail}")
self.step = step
self.detail = detail
self.kind = kind
self.status = status # HTTP status, when Syncthing answered
@dataclass(frozen=True)
class Endpoint:
address: str # host:port
api_key: str
tls: bool = False
@property
def base_url(self) -> str:
return f"{'https' if self.tls else 'http'}://{self.address}"
def config_dir() -> Path | None:
"""Syncthing's home directory (holds config.xml), or None."""
return sync_identity._config_dir()
def read_gui_config(directory: Path | None = None) -> Endpoint | None:
"""The API endpoint as Syncthing's config.xml describes it, or None when
there is no config.xml or it names no key."""
directory = directory or config_dir()
if directory is None:
return None
try:
root = ET.parse(directory / "config.xml").getroot()
except (OSError, ET.ParseError):
return None
gui = root.find("gui")
if gui is None:
return None
key = (gui.findtext("apikey") or "").strip()
if not key:
return None
address = (gui.findtext("address") or DEFAULT_ADDRESS).strip()
# A GUI bound to 0.0.0.0 still answers on loopback, which is where we are.
if address.startswith("0.0.0.0:"):
address = "127.0.0.1:" + address.split(":", 1)[1]
tls = (gui.get("tls") or "").lower() == "true"
return Endpoint(address=address, api_key=key, tls=tls)
def resolve_endpoint(config: dict) -> Endpoint | None:
"""config.json overrides layered over config.xml. None means we have no
key to send — the "Can't reach Syncthing's API" state, not "not running"."""
found = read_gui_config()
key = (config.get(API_KEY_KEY) or "").strip() or (found.api_key if found else "")
if not key:
return None
address = ((config.get(ADDRESS_KEY) or "").strip()
or (found.address if found else DEFAULT_ADDRESS))
tls = found.tls if found else False
return Endpoint(address=address, api_key=key, tls=tls)
class SyncthingClient:
"""Typed calls over one Endpoint. Thread-safe enough for our use: each
call is one request on a shared Session (requests' Session is safe for
concurrent simple requests); the event long-poll gets its own client."""
def __init__(self, endpoint: Endpoint, session=None):
self.endpoint = endpoint
self._session = session or requests.Session()
self._session.headers["X-API-Key"] = endpoint.api_key
# ---- plumbing ----
def _request(self, method: str, path: str, step: str, *, params=None,
json=None, timeout: float = TIMEOUT_S):
url = self.endpoint.base_url + path
try:
response = self._session.request(
method, url, params=params, json=json, timeout=timeout,
verify=False) # Syncthing's GUI cert is self-signed
except requests.ConnectionError as exc:
raise SyncthingError(step, f"nothing answered at {self.endpoint.address}"
f" ({exc.__class__.__name__})", NOT_RUNNING) from exc
except requests.Timeout as exc:
raise SyncthingError(step, "Syncthing didn't answer in time",
NOT_RUNNING) from exc
except requests.RequestException as exc:
raise SyncthingError(step, str(exc)) from exc
if response.status_code in (401, 403):
raise SyncthingError(step, "Syncthing refused the API key", BAD_KEY)
if response.status_code >= 400:
text = (response.text or "").strip() or f"HTTP {response.status_code}"
raise SyncthingError(step, text, status=response.status_code)
if not response.content:
return None
try:
return response.json()
except ValueError:
return response.text
# ---- system ----
def version(self) -> str:
return self._request("GET", "/rest/system/version",
"Checking Syncthing's version")["version"]
def my_id(self) -> str:
return self._request("GET", "/rest/system/status",
"Reading this computer's device ID")["myID"]
def connections(self) -> dict:
"""{device id: {"connected": bool, ...}}"""
data = self._request("GET", "/rest/system/connections",
"Checking connections")
return (data or {}).get("connections", {})
def device_stats(self) -> dict:
"""{device id: {"lastSeen": iso, ...}}"""
return self._request("GET", "/rest/stats/device",
"Reading when devices were last seen") or {}
def folder_stats(self) -> dict:
"""{folder id: {"lastFile": {"at": iso, ...}, "lastScan": iso}}"""
return self._request("GET", "/rest/stats/folder",
"Reading folder activity") or {}
# ---- devices ----
def device(self, device_id: str) -> dict | None:
try:
return self._request("GET", f"/rest/config/devices/{device_id}",
"Looking up a device")
except SyncthingError as exc:
if exc.status == 404:
return None
raise
def add_device(self, device_id: str, name: str):
"""Add (or rename) a device. Idempotent."""
self._request("PUT", f"/rest/config/devices/{device_id}",
f"Adding {name}'s computer to Syncthing",
json={"deviceID": device_id, "name": name,
"addresses": ["dynamic"]})
def remove_device(self, device_id: str, name: str = "the device"):
self._request("DELETE", f"/rest/config/devices/{device_id}",
f"Removing {name}'s computer from Syncthing")
# ---- folders ----
def folder(self, folder_id: str) -> dict | None:
try:
return self._request("GET", f"/rest/config/folders/{folder_id}",
"Looking up a folder")
except SyncthingError as exc:
if exc.status == 404:
return None
raise
def add_folder(self, folder_id: str, label: str, path: Path, kind: str,
device_ids=(), step: str = "Creating a shared folder"):
"""Create or replace a folder. ``kind`` is sendonly/receiveonly/…"""
self._request("PUT", f"/rest/config/folders/{folder_id}", step, json={
"id": folder_id, "label": label, "path": str(path), "type": kind,
"devices": [{"deviceID": d} for d in device_ids],
"fsWatcherEnabled": True,
})
def share_folder(self, folder_id: str, device_id: str,
step: str = "Sharing a folder"):
"""Add ``device_id`` to a folder's device list. Idempotent."""
folder = self.folder(folder_id)
if folder is None:
raise SyncthingError(step, f"folder {folder_id} doesn't exist")
devices = folder.get("devices") or []
if any(d.get("deviceID") == device_id for d in devices):
return
devices.append({"deviceID": device_id})
self._request("PATCH", f"/rest/config/folders/{folder_id}", step,
json={"devices": devices})
def remove_folder(self, folder_id: str, step: str = "Removing a folder"):
self._request("DELETE", f"/rest/config/folders/{folder_id}", step)
def min_disk_free(self, folder_id: str | None = None) -> tuple[float, str]:
"""(value, unit) of a folder's free-space floor — below it Syncthing
stops syncing. Falls back to the defaults for new folders."""
data = None
if folder_id:
data = self.folder(folder_id)
if data is None:
data = self._request("GET", "/rest/config/defaults/folder",
"Reading Syncthing's folder defaults")
floor = (data or {}).get("minDiskFree") or {}
return float(floor.get("value", 1)), floor.get("unit", "%")
# ---- pending (someone knocking) ----
def pending_devices(self) -> dict:
"""{device id: {"name": str, "time": iso, "address": str}}"""
return self._request("GET", "/rest/cluster/pending/devices",
"Checking for computers asking to connect") or {}
def pending_folders(self, device_id: str | None = None) -> dict:
"""{folder id: {"offeredBy": {device id: {...}}}}"""
params = {"device": device_id} if device_id else None
return self._request("GET", "/rest/cluster/pending/folders",
"Checking for folders offered to us",
params=params) or {}
# ---- database ----
def completion(self, folder_id: str, device_id: str | None = None) -> dict:
params = {"folder": folder_id}
if device_id:
params["device"] = device_id
return self._request("GET", "/rest/db/completion",
"Checking sync progress", params=params) or {}
def file_info(self, folder_id: str, name: str) -> dict | None:
try:
return self._request("GET", "/rest/db/file", "Checking a file",
params={"folder": folder_id, "file": name})
except SyncthingError as exc:
if exc.status == 404:
return None
raise
# ---- events ----
def events(self, since: int, types=(), timeout_s: int = 60) -> list:
"""Long-poll /rest/events. Returns [] on the server's own timeout."""
params = {"since": since, "timeout": timeout_s}
if types:
params["events"] = ",".join(types)
return self._request("GET", "/rest/events", "Waiting for Syncthing events",
params=params, timeout=timeout_s + 10) or []
def disk_floor_bytes(value: float, unit: str, total_bytes: int) -> int:
"""A minDiskFree setting in bytes, for a disk of ``total_bytes``."""
if unit == "%":
return int(total_bytes * value / 100)
scale = {"": 1, "B": 1, "kB": 10**3, "MB": 10**6, "GB": 10**9,
"TB": 10**12, "KiB": 2**10, "MiB": 2**20, "GiB": 2**30,
"TiB": 2**40}
return int(value * scale.get(unit, 1))