Files
lintunes/lintunes/storage/json_storage.py
T
trav 5831175584 v0.14.0: a removal you make sticks
Round 43 made the merge report honest, and in doing so made its one real
limitation impossible to miss: every merge was a union, so a song removed from a
playlist on one machine was handed straight back by the other on the next sync,
and a track deleted from the library came back with it. A deletion you cannot
make stick is not a deletion.

The union was there for a real reason — two copies with no common ancestor
cannot tell "A added this" from "B removed it" — so the missing evidence is
written down instead of inferred. New lintunes/tombstones.py: a playlist keeps
track_events {track id: [when, add|remove]}, the library keeps deleted_tracks
{track id: when} in library_metadata.json, and a merge applies the newest event
per track across both copies. A removal beats a copy that merely still had the
song; a deliberate re-add afterwards beats the removal; a track nobody touched
still merges as a union, which stays the safe behavior where there is no
evidence either way.

Deliberately not "the newer copy wins wholesale": that one-liner silently drops
a song the other machine added while you were removing one, which
test_an_unrelated_addition_is_not_lost pins.

Events are recorded in the funnels that already exist — _set_track_ids diffs
before/after so a reorder records nothing, _remove_tracks stamps the library,
_restore_tracks clears it so Ctrl+Z takes the tombstone back — and pruned after
30 days at the save boundary.

Three edges worth naming:

* Track ids are never reused. The next id came from max(library.tracks), so
  deleting the highest-numbered track freed its id, and the next import would be
  dropped on sight by the dead id's own tombstone on every machine.
* library_metadata.json is merged before library.json, since it carries the
  record the library merge is filtered against and rglob order is not a plan.
* A merge applying a deletion never touches a music file — it drops the library
  entry only, and test_a_merge_never_touches_a_music_file fails the run if
  send_to_trash is so much as called. Applied removals grade WARNING and name
  the song.

Claude-Session: https://claude.ai/code/session_01Y9ZEFi4qNJ39FMiBtiAxy2
2026-08-27 18:31:33 -04:00

182 lines
7.5 KiB
Python

import json
from pathlib import Path
from lintunes import tombstones
from lintunes.models import Track, Playlist, PlaylistSettings, Library
from lintunes.paths import to_relative, to_absolute
def save_library(library: Library, data_dir: Path):
data_dir.mkdir(parents=True, exist_ok=True)
save_tracks(library, data_dir)
save_metadata(library, data_dir)
playlists_dir = data_dir / "playlists"
playlists_dir.mkdir(exist_ok=True)
keep = set()
for persistent_id, playlist in library.playlists.items():
save_playlist(playlist, data_dir)
keep.add(f"{persistent_id}.json")
# Remove files for playlists that no longer exist
for playlist_file in playlists_dir.glob("*.json"):
if playlist_file.name not in keep:
playlist_file.unlink()
def save_tracks(library: Library, data_dir: Path, journal=None):
data_dir.mkdir(parents=True, exist_ok=True)
tracks_dict = {}
for tid, track in library.tracks.items():
data = track.to_dict()
if "location" in data:
# Store paths relative to the data dir so the library is portable
# across machines that sync the folder to different mount points.
data["location"] = to_relative(data["location"], data_dir)
if journal is not None:
# A Track carries the *effective* play count (base plus every
# machine's journal). library.json must get the base back — writing
# the effective value here would fold this machine's plays into the
# base and count them twice on the next load. See play_journal.
_write_base_play_fields(data, journal.base_fields(tid))
tracks_dict[str(tid)] = data
write_json(data_dir / "library.json", tracks_dict)
def _write_base_play_fields(data: dict, base: dict):
"""Put the base play fields back into a to_dict() result, keeping to_dict's
rule that a default-valued field is omitted rather than stored."""
for field, value in base.items():
if value in (0, None, ""):
data.pop(field, None)
else:
data[field] = value
def save_metadata(library: Library, data_dir: Path):
data_dir.mkdir(parents=True, exist_ok=True)
metadata = {
# Both spellings, always. Old code reads the absolute key and behaves
# exactly as it did; new code prefers the relative one. Old code that
# *writes* this file simply drops the new keys, and the reader below
# falls back to the absolute one — so no version combination hard-fails.
"music_folder": library.music_folder,
"music_folder_rel": to_relative(library.music_folder, data_dir)
if library.music_folder else "",
"music_folder_set_at": library.music_folder_set_at,
"import_date": library.import_date,
"track_count": len(library.tracks),
"playlist_count": len(library.playlists),
"library_settings": library.library_settings.to_dict(),
# Pruned at the boundary, like the derived-membership gate below: the
# in-memory dict stays honest, the file doesn't grow forever.
"deleted_tracks": {str(tid): when for tid, when
in tombstones.prune(library.deleted_tracks).items()},
}
write_json(data_dir / "library_metadata.json", metadata)
def save_playlist(playlist: Playlist, data_dir: Path):
playlists_dir = data_dir / "playlists"
playlists_dir.mkdir(parents=True, exist_ok=True)
data = playlist.to_dict()
if data.get("track_events"):
data["track_events"] = tombstones.prune(data["track_events"])
if not data["track_events"]:
del data["track_events"]
if playlist.has_derived_membership:
# Membership is a pure function of the criteria and the library, and
# every machine recomputes it on load — storing it only bought a
# Syncthing conflict per song. Same shape as the base-play-count rule in
# save_tracks: to_dict() stays honest, the gate lives at the boundary.
data["track_ids"] = []
data["derived_membership"] = True
write_json(playlists_dir / f"{playlist.persistent_id}.json", data)
def delete_playlist_file(persistent_id: str, data_dir: Path):
path = data_dir / "playlists" / f"{persistent_id}.json"
if path.exists():
path.unlink()
def load_library(data_dir: Path) -> Library:
if not data_dir.exists():
return Library()
# Load tracks
tracks = {}
library_path = data_dir / "library.json"
if library_path.exists():
tracks_dict = read_json(library_path)
for tid_str, track_data in tracks_dict.items():
track = Track.from_dict(track_data)
# Stored relative to the data dir; resolve back to an absolute path.
track.location = to_absolute(track.location, data_dir)
tracks[track.track_id] = track
# Load metadata. The three music_folder fields are read raw and left
# unresolved on purpose — deciding *which* one applies on this machine
# needs the config file too, so it lives in lintunes.music_folder and this
# module stays a dumb (de)serializer.
music_folder = ""
music_folder_rel = ""
music_folder_set_at = None
import_date = None
deleted_tracks = {}
library_settings = PlaylistSettings()
metadata_path = data_dir / "library_metadata.json"
if metadata_path.exists():
metadata = read_json(metadata_path)
music_folder = metadata.get("music_folder", "")
music_folder_rel = metadata.get("music_folder_rel", "")
music_folder_set_at = metadata.get("music_folder_set_at")
import_date = metadata.get("import_date")
deleted_tracks = {int(tid): when for tid, when
in (metadata.get("deleted_tracks") or {}).items()}
if "library_settings" in metadata:
library_settings = PlaylistSettings.from_dict(metadata["library_settings"])
# Load playlists
playlists = {}
playlists_dir = data_dir / "playlists"
if playlists_dir.exists():
for playlist_file in playlists_dir.glob("*.json"):
playlist_data = read_json(playlist_file)
playlist = Playlist.from_dict(playlist_data)
playlists[playlist.persistent_id] = playlist
# A deleted track can still be sitting in a library.json that synced in
# from a machine which hasn't heard about the deletion yet, and in the
# track_ids of any playlist that held it. Applying the record here covers
# every load path at once — startup and the reload_from_disk reconcile.
for tid in deleted_tracks:
tracks.pop(tid, None)
if deleted_tracks:
for playlist in playlists.values():
if any(tid in deleted_tracks for tid in playlist.track_ids):
playlist.track_ids = [tid for tid in playlist.track_ids
if tid not in deleted_tracks]
return Library(
tracks=tracks,
playlists=playlists,
deleted_tracks=deleted_tracks,
music_folder=music_folder,
music_folder_rel=music_folder_rel,
music_folder_set_at=music_folder_set_at,
import_date=import_date,
library_settings=library_settings,
)
def write_json(path: Path, data: dict):
tmp = path.with_suffix(path.suffix + ".tmp")
with open(tmp, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
tmp.replace(path)
def read_json(path: Path) -> dict:
with open(path, "r", encoding="utf-8") as f:
return json.load(f)