"""What goes into my outgoing folder for a friend — the files they read. ``out/`` is a Syncthing send-only folder, so everything written here reaches the friend. Writes are atomic (temp name, then rename) and **skipped when the bytes wouldn't change**: an unchanged rewrite still moves the mtime, and Syncthing would dutifully re-announce the file. This round writes only the introduction — ``cassette.json`` (display name, format version, avatar name) and ``avatar.png``. The trimmed library and requests file join it later. """ from __future__ import annotations import json from pathlib import Path FORMAT_VERSION = 1 INFO_FILE = "cassette.json" AVATAR_FILE = "avatar.png" STIGNORE = ".stignore" # Our own temp files never need to reach the friend. (Syncthing ignores its # own .syncthing.*.tmp already.) STIGNORE_TEXT = "// written by LinTunes\n*.tmp\n*.part\n" def write_bytes_if_changed(path: Path, data: bytes) -> bool: """Atomically write ``data`` unless ``path`` already holds exactly it. Returns True when something was written.""" try: if path.read_bytes() == data: return False except OSError: pass path.parent.mkdir(parents=True, exist_ok=True) tmp = path.with_name(path.name + ".tmp") tmp.write_bytes(data) tmp.replace(path) return True def write_json_if_changed(path: Path, data) -> bool: text = json.dumps(data, indent=1, ensure_ascii=False, sort_keys=True) return write_bytes_if_changed(path, text.encode("utf-8")) def read_json(path: Path, default=None): """A friend's file, tolerating absence and a half-synced/garbled copy.""" try: return json.loads(path.read_text(encoding="utf-8")) except (OSError, ValueError): return default def prepare_out_dir(out: Path): out.mkdir(parents=True, exist_ok=True) write_bytes_if_changed(out / STIGNORE, STIGNORE_TEXT.encode()) def publish_intro(out: Path, display_name: str, avatar_source: Path | None): """cassette.json + avatar.png. ``avatar_source`` None removes the avatar.""" prepare_out_dir(out) has_avatar = avatar_source is not None and avatar_source.exists() if has_avatar: write_bytes_if_changed(out / AVATAR_FILE, avatar_source.read_bytes()) else: (out / AVATAR_FILE).unlink(missing_ok=True) write_json_if_changed(out / INFO_FILE, { "format": FORMAT_VERSION, "name": display_name, "avatar": AVATAR_FILE if has_avatar else "", }) def read_intro(in_dir: Path) -> dict: """A friend's cassette.json, or {}.""" data = read_json(in_dir / INFO_FILE, {}) return data if isinstance(data, dict) else {}