macOS / Tests (AppleSilicon) (push) Canceled after 0s
macOS / Tests (Intel) (push) Canceled after 0s
macOS / Build (AppleSilicon) (push) Canceled after 0s
macOS / Build (Intel) (push) Canceled after 0s
macOS / Publish the GitHub Release (push) Canceled after 0s
251 lines
9.4 KiB
Python
251 lines
9.4 KiB
Python
"""Cassette's own state: who my friends are, what I share with each, what I've
|
|
asked each of them for.
|
|
|
|
It lives in the machine-local cassette root (``paths.data_dir()/cassette/
|
|
state.json``; ``~/.local/share/lintunes/…`` on Linux), **not** in the synced
|
|
data dir: only the host machine runs Cassette, the friend folders it
|
|
describes exist only here, and a second copy riding Syncthing would just be a conflict waiting to happen.
|
|
|
|
Plain dataclasses with ``to_dict``/``from_dict``, like ``lintunes/models``;
|
|
``save`` is atomic (``json_storage.write_json``).
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import copy
|
|
import getpass
|
|
from dataclasses import dataclass, field
|
|
from datetime import datetime, timezone
|
|
from pathlib import Path
|
|
|
|
from lintunes import paths
|
|
from lintunes.config import load_config
|
|
from lintunes.storage.json_storage import read_json, write_json
|
|
|
|
ROOT_KEY = "cassette_root" # config.json override
|
|
STATE_FILE = "state.json"
|
|
FORMAT_VERSION = 1
|
|
|
|
# Invite.status
|
|
OPEN = "open"
|
|
USED = "used"
|
|
CANCELLED = "cancelled"
|
|
|
|
# Friend.layout — how their followed playlists appear in my sidebar
|
|
LAYOUT_MIXED = "mixed"
|
|
LAYOUT_FOLDER = "folder"
|
|
|
|
# Friend.followed_mode — what happens to a followed playlist's songs
|
|
FOLLOW_SEPARATE = "separate"
|
|
FOLLOW_LIBRARY = "library"
|
|
|
|
# Friend.role — which side of the invite this machine was on
|
|
INVITER = "inviter"
|
|
INVITEE = "invitee"
|
|
|
|
|
|
def now_iso() -> str:
|
|
return datetime.now(timezone.utc).replace(tzinfo=None).isoformat(
|
|
timespec="seconds")
|
|
|
|
|
|
def cassette_root() -> Path:
|
|
override = (load_config().get(ROOT_KEY) or "").strip()
|
|
if override:
|
|
return Path(override).expanduser()
|
|
return paths.data_dir() / "cassette"
|
|
|
|
|
|
def default_display_name() -> str:
|
|
try:
|
|
return getpass.getuser()
|
|
except Exception:
|
|
return "LinTunes"
|
|
|
|
|
|
@dataclass
|
|
class Selection:
|
|
"""What one friend (or everyone, in share-same mode) may cassette.
|
|
|
|
Artists and albums are stored as the track ids they covered when checked
|
|
(a snapshot: a new album shows up unchecked). ``all_library`` and shared
|
|
playlists are live — they're evaluated each time the copy is built."""
|
|
all_library: bool = False
|
|
track_ids: set = field(default_factory=set)
|
|
all_playlists: bool = False
|
|
playlist_ids: set = field(default_factory=set)
|
|
|
|
def to_dict(self) -> dict:
|
|
return {"all_library": self.all_library,
|
|
"track_ids": sorted(self.track_ids),
|
|
"all_playlists": self.all_playlists,
|
|
"playlist_ids": sorted(self.playlist_ids)}
|
|
|
|
@classmethod
|
|
def from_dict(cls, d: dict | None) -> "Selection":
|
|
d = d or {}
|
|
return cls(all_library=bool(d.get("all_library", False)),
|
|
track_ids={int(t) for t in d.get("track_ids", [])},
|
|
all_playlists=bool(d.get("all_playlists", False)),
|
|
playlist_ids=set(d.get("playlist_ids", [])))
|
|
|
|
def is_empty(self) -> bool:
|
|
return not (self.all_library or self.track_ids
|
|
or self.all_playlists or self.playlist_ids)
|
|
|
|
|
|
@dataclass
|
|
class Invite:
|
|
token: str
|
|
created: str = ""
|
|
status: str = OPEN
|
|
folder_id: str = "" # my outgoing folder, created with the invite
|
|
|
|
def to_dict(self) -> dict:
|
|
return {"token": self.token, "created": self.created,
|
|
"status": self.status, "folder_id": self.folder_id}
|
|
|
|
@classmethod
|
|
def from_dict(cls, d: dict) -> "Invite":
|
|
return cls(token=d["token"], created=d.get("created", ""),
|
|
status=d.get("status", OPEN),
|
|
folder_id=d.get("folder_id", ""))
|
|
|
|
|
|
@dataclass
|
|
class Friend:
|
|
token: str
|
|
device_id: str
|
|
name: str
|
|
role: str = INVITEE
|
|
out_folder: str = "" # Syncthing folder id I write (send-only)
|
|
in_folder: str = "" # Syncthing folder id they write (receive-only here)
|
|
added: str = ""
|
|
connected_at: str = "" # first time the handshake completed
|
|
last_synced: str = "" # last time both folders were seen up to date
|
|
selection: Selection = field(default_factory=Selection)
|
|
layout: str = LAYOUT_FOLDER
|
|
followed_mode: str = FOLLOW_SEPARATE
|
|
followed: list = field(default_factory=list) # their playlist pids
|
|
cassetted: list = field(default_factory=list) # their track ids I want
|
|
|
|
def to_dict(self) -> dict:
|
|
return {"token": self.token, "device_id": self.device_id,
|
|
"name": self.name, "role": self.role,
|
|
"out_folder": self.out_folder, "in_folder": self.in_folder,
|
|
"added": self.added, "connected_at": self.connected_at,
|
|
"last_synced": self.last_synced,
|
|
"selection": self.selection.to_dict(), "layout": self.layout,
|
|
"followed_mode": self.followed_mode,
|
|
"followed": list(self.followed),
|
|
"cassetted": list(self.cassetted)}
|
|
|
|
@classmethod
|
|
def from_dict(cls, d: dict) -> "Friend":
|
|
return cls(token=d["token"], device_id=d.get("device_id", ""),
|
|
name=d.get("name", ""), role=d.get("role", INVITEE),
|
|
out_folder=d.get("out_folder", ""),
|
|
in_folder=d.get("in_folder", ""),
|
|
added=d.get("added", ""),
|
|
connected_at=d.get("connected_at", ""),
|
|
last_synced=d.get("last_synced", ""),
|
|
selection=Selection.from_dict(d.get("selection")),
|
|
layout=d.get("layout", LAYOUT_FOLDER),
|
|
followed_mode=d.get("followed_mode", FOLLOW_SEPARATE),
|
|
followed=list(d.get("followed", [])),
|
|
cassetted=[int(t) for t in d.get("cassetted", [])])
|
|
|
|
|
|
@dataclass
|
|
class CassetteState:
|
|
display_name: str = field(default_factory=default_display_name)
|
|
avatar: str = "" # filename inside the cassette root, "" = none
|
|
# On by default (Round 105): one selection for everyone is what a first
|
|
# friend expects; per-friend pages are the exception.
|
|
share_same_for_all: bool = True
|
|
general: Selection = field(default_factory=Selection)
|
|
invites: dict = field(default_factory=dict) # token -> Invite
|
|
friends: dict = field(default_factory=dict) # token -> Friend
|
|
# Unknown devices knocking while an invite is open are added with nothing
|
|
# shared, just long enough to see which folder they offer (Syncthing
|
|
# hides an unknown device's folders): device id -> when we started.
|
|
probing: dict = field(default_factory=dict)
|
|
# Devices that turned out not to hold an open invite: device id -> when.
|
|
# They stay pending in Syncthing, untouched, and aren't probed again.
|
|
rejected: dict = field(default_factory=dict)
|
|
# When this year's play history last went to friends (cassette/wrapped.py).
|
|
wrapped_published_at: str = ""
|
|
|
|
def to_dict(self) -> dict:
|
|
return {"version": FORMAT_VERSION,
|
|
"display_name": self.display_name, "avatar": self.avatar,
|
|
"share_same_for_all": self.share_same_for_all,
|
|
"general": self.general.to_dict(),
|
|
"invites": [i.to_dict() for i in self.invites.values()],
|
|
"friends": [f.to_dict() for f in self.friends.values()],
|
|
"probing": dict(self.probing), "rejected": dict(self.rejected),
|
|
"wrapped_published_at": self.wrapped_published_at}
|
|
|
|
@classmethod
|
|
def from_dict(cls, d: dict | None) -> "CassetteState":
|
|
d = d or {}
|
|
state = cls(display_name=d.get("display_name") or default_display_name(),
|
|
avatar=d.get("avatar", ""),
|
|
share_same_for_all=bool(d.get("share_same_for_all", True)),
|
|
general=Selection.from_dict(d.get("general")),
|
|
probing=dict(d.get("probing", {})),
|
|
rejected=dict(d.get("rejected", {})),
|
|
wrapped_published_at=d.get("wrapped_published_at", ""))
|
|
for raw in d.get("invites", []):
|
|
invite = Invite.from_dict(raw)
|
|
state.invites[invite.token] = invite
|
|
for raw in d.get("friends", []):
|
|
friend = Friend.from_dict(raw)
|
|
state.friends[friend.token] = friend
|
|
return state
|
|
|
|
def copy(self) -> "CassetteState":
|
|
return copy.deepcopy(self)
|
|
|
|
def open_invites(self) -> list[Invite]:
|
|
return [i for i in self.invites.values() if i.status == OPEN]
|
|
|
|
def selection_for(self, friend: Friend) -> Selection:
|
|
"""The selection that actually applies to ``friend``."""
|
|
return self.general if self.share_same_for_all else friend.selection
|
|
|
|
def friend_by_device(self, device_id: str) -> Friend | None:
|
|
return next((f for f in self.friends.values()
|
|
if f.device_id == device_id), None)
|
|
|
|
|
|
def load_state(root: Path | None = None) -> CassetteState:
|
|
path = (root or cassette_root()) / STATE_FILE
|
|
if not path.exists():
|
|
return CassetteState()
|
|
try:
|
|
return CassetteState.from_dict(read_json(path))
|
|
except (ValueError, OSError, KeyError):
|
|
return CassetteState()
|
|
|
|
|
|
def save_state(state: CassetteState, root: Path | None = None):
|
|
root = root or cassette_root()
|
|
root.mkdir(parents=True, exist_ok=True)
|
|
write_json(root / STATE_FILE, state.to_dict())
|
|
|
|
|
|
def friend_dir(root: Path, token: str) -> Path:
|
|
return root / "friends" / token
|
|
|
|
|
|
def out_dir(root: Path, token: str) -> Path:
|
|
return friend_dir(root, token) / "out"
|
|
|
|
|
|
def in_dir(root: Path, token: str) -> Path:
|
|
return friend_dir(root, token) / "in"
|
|
|
|
|
|
def cache_dir(root: Path, token: str) -> Path:
|
|
return friend_dir(root, token) / "cache"
|