Files
lintunes/lintunes/andtunes/sync.py
T
trav d6140f5ac4 v0.35.0: a play history for the yearly Wrapped
The play journals keep running totals per track, which is enough for "most
played ever" and nothing a Wrapped asks: top songs of this year, minutes
listened, which month, what time of day, what got skipped. Those all come
from one timestamped line per listen, so LinTunes now keeps that, while
Preferences -> General -> "Keep a play history for my yearly Wrapped" is on.

history/<machine>/<YYYY-MM>.jsonl, one writer per folder like the journals:
local start time with its offset, ms actually heard (Player adds position
steps under 1.5 s, so seeks and pauses don't count), how it ended, where it
played and from what, and a name/artist/album snapshot that outlives a
delete. Under 5 s is noise and never written.

andTunes 0.3.0 writes the same lines on the Rabbit when sync says the
desktop wants them, and sync copies each month home when the device's copy
is longer. "Share this year's play history with friends" puts a trimmed
copy (no ids, playlists or devices) in each friend's cassette folder, daily
in November and December and monthly otherwise.
2026-10-02 16:47:40 -07:00

717 lines
29 KiB
Python

"""Sync the whole opted-in library into ``Music/andTunes/`` on the device.
A sibling of `device_sync.plan_sync` / `DeviceSyncWorker` and of
`export/exporter.py`: same shape (a pure planning function, then a worker on a
daemon thread reporting through Qt signals), same MTP caveats (never copystat,
never trust mtimes — diff by name + size), same "write the index last" rule
that keeps an interrupted run from leaving a manifest naming files that aren't
there.
What differs, and why it's a separate worker rather than a flag on the old one:
* One tree for the whole library instead of one folder per playlist, so paths
are nested and directories have to be created and pruned.
* An album-art pass, which reads local files the planner never touches.
* Several trailing files (every m3u, then `library.json`) instead of one m3u.
The old per-playlist sync is untouched and still on the menu — it is what
feeds Auxio, and it stays until andTunes can actually play a song.
"""
import json
import os
import shutil
import threading
from dataclasses import dataclass, field
from importlib import resources
from pathlib import Path
from PyQt6.QtCore import QObject, pyqtSignal
from .. import __version__
from ..device_sync import CHUNK, build_m3u, track_display
from ..export import web_support
from . import art as art_mod
from . import layout
from . import plays as plays_mod
from .layout import (
ART_DIR, BUTTONS_DIR, MANIFEST_NAME, PRESERVED_DIRS, album_key,
art_relpath, assert_inside, media_relpath, playlist_relpath,
)
from .manifest import build_manifest
@dataclass
class MediaItem:
track_id: int
src: Path
rel: str # "Media/Artist/Album/04 Song.mp3", posix, under the root
size: int
track: object = None
# "flac" when the worker must transcode first (no fresh cached FLAC yet);
# then `size` is only the source's, and `device_size` is what's already
# on the device, so an unchanged conversion isn't copied again.
convert_to: str | None = None
device_size: int | None = None
@dataclass
class PlaylistEntry:
name: str
persistent_id: str
rel: str # "Playlists/Name.m3u"
entries: list = field(default_factory=list) # (media_rel, secs, display)
track_ids: list = field(default_factory=list) # playing order, with repeats
@dataclass
class AndTunesPlan:
device: object
root: Path
items: list = field(default_factory=list) # every track that should be there
copies: list = field(default_factory=list) # the subset needing transfer
kept: int = 0
stale: list = field(default_factory=list) # rel paths to delete
skipped: int = 0
playlists: list = field(default_factory=list) # PlaylistEntry
albums: dict = field(default_factory=dict) # album key -> representative MediaItem
# album key -> size of its cover already on the device, from the scan
# planning does anyway. The art pass compares against this instead of a
# stat per album, which over gvfs-MTP is a round trip each.
art_sizes: dict = field(default_factory=dict)
copy_art: bool = True
bytes_to_copy: int = 0
bytes_freed: int = 0
refused: list = field(default_factory=list) # (display, reason)
data_dir: Path | None = None # where the device's play counts come back to
history: bool = False # ask the app to keep a listen history
@property
def conversions(self) -> list:
return [item for item in self.copies if item.convert_to]
@property
def needs_ffmpeg(self) -> bool:
return bool(self.conversions)
def drop_conversions(self, reason: str):
"""Leave out every track that still needs transcoding (no ffmpeg).
They simply aren't present this run: the index is written from what
landed, so the app never lists them. Anything already on the device
from an earlier sync is left alone rather than counted stale.
"""
dropped = {item.track_id for item in self.conversions}
for item in self.conversions:
self.refused.append((track_display(item.track), reason))
self.bytes_to_copy -= item.size
self.copies = [i for i in self.copies if i.track_id not in dropped]
self.items = [i for i in self.items if i.track_id not in dropped]
def default_buttons() -> list:
"""The bundled button PNGs (rendered by andtunes/tools/make_buttons.py).
Their names are a contract with the app, which draws
``Buttons/<name>.png`` in preference to its own copy.
"""
folder = resources.files("lintunes.andtunes") / "buttons"
try:
return sorted((p for p in folder.iterdir() if p.name.endswith(".png")),
key=lambda p: p.name)
except (FileNotFoundError, NotADirectoryError):
return []
def flac_cache(track) -> Path:
"""Where a track's FLAC conversion is kept between syncs.
Keyed by track id, so a rename doesn't orphan it; stale once the source
is newer (a re-tag rewrites the file), exactly like the art cache.
"""
base = os.environ.get("XDG_CACHE_HOME", str(Path.home() / ".cache"))
return Path(base) / "lintunes" / "andtunes-flac" / f"{track.track_id}.flac"
def _fresh(cache: Path, src: Path) -> bool:
try:
return cache.stat().st_mtime >= src.stat().st_mtime
except OSError:
return False
def _relative_to_playlists(media_rel: str) -> str:
"""A media path as seen from inside the Playlists/ folder."""
return "../" + media_rel
def plan_andtunes_sync(playlists, tracks_by_id, root: Path, device=None,
copy_art: bool = True,
data_dir: Path | None = None) -> AndTunesPlan:
"""Diff the selected playlists against the andTunes tree already there.
Pure planning — nothing is created, copied, or deleted. Album art is
deliberately *not* rendered here: it means a mutagen open per album, and
planning runs on the GUI thread. The worker does it, which costs the
progress bar an accurate byte total for a few hundred KB of JPEG and buys
a window that doesn't freeze.
"""
plan = AndTunesPlan(device=device, root=Path(root), copy_art=copy_art,
data_dir=Path(data_dir) if data_dir else None)
# Resolve every unique track across every selected playlist to a real
# file, through the same format gate the web-mix export uses: Android's
# MediaPlayer decodes the browser set (MP3, AAC, FLAC, Vorbis, Opus, WAV),
# so ALAC, AIFF and oddities become FLAC — lossless, never a lossy
# re-encode — and FairPlay is refused, never attempted.
items: dict[int, MediaItem] = {}
skipped: set[int] = set()
refused: set[int] = set()
for playlist in playlists:
for tid in playlist.track_ids:
if tid in items or tid in skipped or tid in refused:
continue
track = tracks_by_id.get(tid)
src = Path(track.location) if track and track.location else None
if src is None or not src.is_file():
skipped.add(tid)
continue
convert_to, reason = web_support.conversion_for(track.location, track.kind)
if reason:
refused.add(tid)
plan.refused.append((track_display(track), reason))
continue
rel, size, item_src = media_relpath(track), src.stat().st_size, src
if convert_to:
# media_relpath ends in the source's own suffix (maybe none).
ext = Path(track.location).suffix
rel = rel[: len(rel) - len(ext)] + ".flac"
cached = flac_cache(track)
if _fresh(cached, src):
# Converted on an earlier sync: a plain byte copy now,
# diffed by the FLAC's own size like any other file.
item_src, size, convert_to = cached, cached.stat().st_size, None
items[tid] = MediaItem(tid, item_src, rel, size, track,
convert_to=convert_to)
plan.skipped = len(skipped)
# Same collision rule as the per-playlist sync: every member of a
# colliding group gets the [track_id] suffix, so a name never depends on
# which playlist happened to be walked first.
# Folded, because the device's filesystem is case-insensitive: two songs
# whose paths differ only in case are one file there, not two.
by_rel: dict[str, list[MediaItem]] = {}
for item in items.values():
by_rel.setdefault(item.rel.lower(), []).append(item)
for group in by_rel.values():
if len(group) > 1:
for item in group:
stem, ext = os.path.splitext(item.rel)
item.rel = f"{stem} [{item.track_id}]{ext}"
plan.items = sorted(items.values(), key=lambda i: i.track_id)
# One representative track per album for the art pass. Lowest track id
# wins so the choice doesn't depend on playlist order either.
for item in plan.items:
plan.albums.setdefault(album_key(item.track), item)
for playlist in playlists:
entry = PlaylistEntry(name=playlist.name,
persistent_id=playlist.persistent_id,
rel=playlist_relpath(playlist.name))
for tid in playlist.track_ids:
item = items.get(tid)
if item is None:
continue # no local file; left out of both m3u and manifest
entry.entries.append((
_relative_to_playlists(item.rel),
round(item.track.total_time / 1000),
track_display(item.track)))
entry.track_ids.append(tid)
plan.playlists.append(entry)
# Diff against the device by name + size (mtimes lie over MTP).
on_device = _scan_device(plan.root)
expected = {item.rel for item in plan.items}
expected |= {entry.rel for entry in plan.playlists}
if plan.copy_art:
expected |= {art_relpath(key) for key in plan.albums}
expected.add(MANIFEST_NAME)
# Compared case-folded: the device filesystem is case-insensitive, so a
# song filed under "Toro y Moi" here and "Toro Y Moi" there is the same
# file. Exact-string matching saw it as stale *and* missing and re-copied
# it over MTP every single sync.
on_device_folded = {rel.lower(): size for rel, size in on_device.items()}
expected_folded = {rel.lower() for rel in expected}
if plan.copy_art:
for key in plan.albums:
size = on_device_folded.get(art_relpath(key).lower())
if size is not None:
plan.art_sizes[key] = size
for item in plan.items:
if item.convert_to:
# Its FLAC size is unknown until the worker converts it.
item.device_size = on_device_folded.get(item.rel.lower())
plan.copies.append(item)
plan.bytes_to_copy += item.size
elif on_device_folded.get(item.rel.lower()) == item.size:
plan.kept += 1
else:
plan.copies.append(item)
plan.bytes_to_copy += item.size
# plan.stale keeps the device's own spelling — _delete_stale unlinks by it.
for rel, size in sorted(on_device.items()):
if rel.lower() not in expected_folded:
plan.stale.append(rel)
plan.bytes_freed += size
return plan
def _scan_device(root: Path) -> dict[str, int]:
"""Every file under the andTunes root, by root-relative posix path.
`Buttons/` (the user's own menu artwork) and `plays/` (written by the app)
are skipped entirely — sync reads those, it doesn't own them.
"""
found: dict[str, int] = {}
root = Path(root)
for dirpath, dirnames, filenames in os.walk(root):
rel_dir = Path(dirpath).relative_to(root)
if rel_dir == Path("."):
dirnames[:] = [d for d in dirnames if d not in PRESERVED_DIRS]
for name in filenames:
rel = (rel_dir / name).as_posix()
try:
found[rel] = (Path(dirpath) / name).stat().st_size
except OSError:
continue
return found
class _Cancelled(Exception):
"""Internal: unwinds _run when cancel() was requested."""
class AndTunesPlanWorker(QObject):
"""`plan_andtunes_sync` on a daemon thread, because planning reads MTP.
The planner is pure and writes nothing, but it walks every file on the
device, and over gvfs-MTP that is thousands of round trips — several
seconds on trav's 2,400-song library. On the GUI thread that is a frozen
window, and GNOME offers to kill the app: "lintunes is not responding" is
how a sync got force-quit halfway through. `disk_usage` rides along
because it is one more MTP call the caller needed before deciding.
"""
planned = pyqtSignal(object, object) # AndTunesPlan, free bytes
failed = pyqtSignal(str)
def __init__(self, playlists, tracks, root, device, *,
copy_art=True, data_dir=None, parent=None):
super().__init__(parent)
self._args = (playlists, tracks, root, device)
self._copy_art = copy_art
self._data_dir = data_dir
self._busy = False
def busy(self) -> bool:
return self._busy
def start(self):
if self._busy:
return
self._busy = True
threading.Thread(target=self._run_guarded, daemon=True).start()
def _run_guarded(self):
try:
self._run()
finally:
self._busy = False
def _run(self):
playlists, tracks, root, device = self._args
try:
plan = plan_andtunes_sync(playlists, tracks, root, device,
copy_art=self._copy_art,
data_dir=self._data_dir)
free = shutil.disk_usage(device.root).free if device else 0
except OSError as e:
name = device.name if device else "device"
self.failed.emit(f"Couldn't read the {name}: {e}")
return
self.planned.emit(plan, free)
class AndTunesSyncWorker(QObject):
"""Runs an AndTunesPlan on a daemon thread, reporting through signals.
Progress is emitted in KiB (a pyqtSignal(int) is a C int — byte counts
overflow past 2 GiB) and the label names the phase, because the art and
index phases move no audio bytes.
Cancelling stops at the next chunk boundary and still writes the index:
the manifest and m3us are rewritten to list only what is actually on the
device, so a cancelled sync leaves andTunes a smaller working library
rather than a broken one. Re-syncing picks up the rest.
"""
progress = pyqtSignal(int, int, str) # done_kib, total_kib, phase label
finished = pyqtSignal(dict)
cancelled = pyqtSignal(dict)
failed = pyqtSignal(str)
def __init__(self, plan: AndTunesPlan, parent=None):
super().__init__(parent)
self._plan = plan
self._busy = False
self._cancel = threading.Event()
def busy(self) -> bool:
return self._busy
def cancel(self):
self._cancel.set()
def _check_cancel(self):
if self._cancel.is_set():
raise _Cancelled
def start(self):
if self._busy:
return
self._busy = True
threading.Thread(target=self._run_guarded, daemon=True).start()
def _run_guarded(self):
try:
self._run()
finally:
self._busy = False
# ---- the run ----
def _run(self):
plan = self._plan
device_name = plan.device.name if plan.device else "device"
self._dest = None # in-flight partial, removed on abort
self._removed = 0
self._present: set[int] = set() # track ids really on the device
self._art: dict[str, str] = {} # album key -> art rel path
self._art_written = 0 # covers actually (re)written
self._total_kib = max(plan.bytes_to_copy // 1024, 1)
self._done = 0
self._plays = 0 # tracks whose play counts came back
self._unconverted = 0 # conversions ffmpeg couldn't do
self._unwritable: list[tuple[str, str]] = [] # (song, why) per refusal
try:
self._check_cancel()
plan.root.mkdir(parents=True, exist_ok=True)
to_copy = {item.track_id for item in plan.copies}
self._present = {item.track_id for item in plan.items
if item.track_id not in to_copy}
self._bring_back_plays()
self._delete_stale()
self._copy_media()
self._sync_art()
self._write_index()
self._ship_buttons()
self._prune_empty_dirs()
self.finished.emit({
"device": device_name,
"playlists": len(plan.playlists),
"copied": len(self._present) - plan.kept,
"kept": plan.kept,
"removed": self._removed,
"skipped": plan.skipped,
"albums": len(self._art),
"covers_copied": self._art_written,
"tracks": len(self._present),
"plays": self._plays,
"refused": len(plan.refused),
"unconverted": self._unconverted,
"unwritable": list(self._unwritable),
})
except _Cancelled:
self._drop_partial()
# Leave a library that matches the device: the index lists only
# tracks whose files are really there. Art isn't re-rendered here
# — _write_index reads what is already on the device.
try:
self._write_index()
except OSError:
pass # device going away; the size diff self-heals next time
self.cancelled.emit({
"device": device_name,
"copied": len(self._present) - plan.kept,
"total": len(plan.copies),
"removed": self._removed,
"plays": self._plays,
})
except OSError as e:
self._drop_partial()
self.failed.emit(
f"Sync failed: {e}. Is the {device_name} still connected?")
def _drop_partial(self):
if self._dest is None:
return
try:
self._dest.unlink()
except OSError:
pass
self._dest = None
def _emit(self, label: str):
self.progress.emit(self._done // 1024, self._total_kib, label)
def _bring_back_plays(self):
"""First, before anything is copied: even a cancelled sync should
bring the Rabbit's play counts home. A journal we can't read now is
read next time — counts only grow."""
if self._plan.data_dir is None:
return
try:
self._plays = plays_mod.bring_back(self._plan.root, self._plan.data_dir)
except OSError:
self._plays = 0
try:
plays_mod.bring_back_history(self._plan.root, self._plan.data_dir)
except OSError:
pass # next sync: the files only grow
def _convert(self, item) -> Path | None:
"""Transcode into the FLAC cache; None when ffmpeg can't.
One file ffmpeg chokes on costs that song, not the sync — the same
way a vanished source does. A cancel mid-conversion leaves no cache
entry behind.
"""
cache = flac_cache(item.track)
tmp = cache.with_suffix(".tmp.flac")
try:
cache.parent.mkdir(parents=True, exist_ok=True)
web_support.convert_to_flac(item.src, tmp, self._cancel)
self._check_cancel()
tmp.replace(cache)
except OSError:
tmp.unlink(missing_ok=True)
self._unconverted += 1
return None
return cache
def _delete_stale(self):
plan = self._plan
for rel in plan.stale:
self._check_cancel()
try:
target = assert_inside(plan.root, plan.root / rel)
target.unlink()
self._removed += 1
except layout.DeviceLayoutError:
continue # never reachable by construction; refuse anyway
except OSError:
pass # one stubborn file shouldn't kill the sync
def _copy_media(self):
plan = self._plan
for i, item in enumerate(plan.copies, start=1):
self._check_cancel()
label = f"{i}/{len(plan.copies)} {Path(item.rel).stem}"
src = item.src
if item.convert_to:
# ffmpeg reports no byte progress; the bar holds, then jumps.
self._emit(f"{label} (converting to FLAC)")
if not item.src.is_file():
self._done += item.size
continue
src = self._convert(item)
if src is None:
self._done += item.size
continue
size = src.stat().st_size
# Swap the source's size for the FLAC's in the running total.
self._total_kib = max(self._total_kib + (size - item.size) // 1024, 1)
if item.device_size == size:
# Already on the device from an earlier sync, identical.
self._done += size
self._present.add(item.track_id)
continue
# A source gone since planning means Syncthing moved it under us
# (a metadata edit on the other machine relocates files) — skip
# it, don't abort. Once open, the fd pins the inode.
try:
fsrc = open(src, "rb")
except FileNotFoundError:
self._done += item.size
self._emit(label)
continue
dest = plan.root / item.rel
# One song the device won't take is one song, not the sync. A
# gvfs-MTP mount can hold a *phantom* directory — one it lists but
# the device doesn't have — and every write into it fails EIO
# forever, since mkdir(exist_ok=True) sees the phantom and does
# nothing. Aborting here cost trav 2,400 songs for one folder; and
# counting the track present anyway (the older sin) put a song in
# library.json that isn't on the device, which the app then skips
# mid-playlist. So: report it, and leave it out of the manifest.
try:
dest.parent.mkdir(parents=True, exist_ok=True)
self._dest = dest
# Manual chunked copy: byte-accurate progress, and no copystat
# (gvfs-MTP rejects it).
with fsrc, open(dest, "wb") as fdst:
while True:
chunk = fsrc.read(CHUNK)
if not chunk:
break
fdst.write(chunk)
self._done += len(chunk)
self._emit(label)
self._check_cancel()
except OSError as e:
fsrc.close()
self._drop_partial()
self._unwritable.append((track_display(item.track),
e.strerror or str(e)))
self._done += item.size
self._emit(label)
continue
self._dest = None
self._present.add(item.track_id)
def _sync_art(self):
"""One cover per album, written only when it differs by size.
The device side of the comparison comes from the planner's scan, and
an album without art is remembered by the cache, so an unchanged
library costs no device I/O here at all — it used to be an MTP stat
per album, plus a mutagen open and an unlink attempt for every
artless one, every sync.
"""
plan = self._plan
if not plan.copy_art:
return
total = len(plan.albums)
for i, (key, item) in enumerate(sorted(plan.albums.items()), start=1):
self._check_cancel()
if item.track_id not in self._present:
continue
rel = art_relpath(key)
dest = plan.root / rel
on_device = plan.art_sizes.get(key)
jpeg = art_mod.album_art_jpeg(item.track)
if not jpeg:
# The album lost its art (or never had any): don't leave a
# cover behind that the manifest no longer points at.
if on_device is not None:
try:
assert_inside(plan.root, dest).unlink()
except (layout.DeviceLayoutError, OSError):
pass
continue
if on_device != len(jpeg):
self._emit(f"Copying album art {i}/{total}")
dest.parent.mkdir(parents=True, exist_ok=True)
dest.write_bytes(jpeg)
self._art_written += 1
elif i % 25 == 0 or i == total:
self._emit(f"Checking album art {i}/{total}")
self._art[key] = rel
def _write_index(self):
"""The m3us and then library.json — always last, always consistent.
Everything here describes what is on the device *now*, so an
interrupted sync leaves the app a shorter library rather than one
with holes in it.
"""
plan = self._plan
total = len(plan.playlists)
for i, entry in enumerate(plan.playlists, start=1):
self._emit(f"Writing playlist {i}/{total}")
rows = [row for row, tid in zip(entry.entries, entry.track_ids)
if tid in self._present]
dest = plan.root / entry.rel
dest.parent.mkdir(parents=True, exist_ok=True)
dest.write_text(build_m3u(rows), encoding="utf-8")
# Which covers are on the device right now, rather than which ones
# this run wrote — so a cancelled sync still points at art an earlier
# sync left behind. One listing of Art/, not a stat per album: over
# MTP that was 500-odd round trips with the progress line frozen on
# the last album, which reads exactly like a hang.
self._emit("Writing the library")
try:
on_device = {p.name for p in (plan.root / ART_DIR).iterdir()}
except OSError:
on_device = set()
have_art = {key for key in plan.albums
if Path(art_relpath(key)).name in on_device}
entries = [(item.track, item.rel,
art_relpath(k) if (k := album_key(item.track)) in have_art
else None)
for item in plan.items if item.track_id in self._present]
playlists = [(e.name, e.persistent_id, e.track_ids)
for e in plan.playlists]
payload = build_manifest(entries, playlists,
generator=f"lintunes {__version__}",
history=plan.history)
(plan.root / MANIFEST_NAME).write_text(
json.dumps(payload, ensure_ascii=False, separators=(",", ":")),
encoding="utf-8")
def _ship_buttons(self):
"""Default button artwork, only where the file is missing.
`Buttons/` is the user's folder: a file already there — ours from an
earlier sync, or their own art — is never overwritten, and nothing in
it is ever deleted (the device scan skips it entirely). One stubborn
file costs a default image, not the sync.
"""
plan = self._plan
self._emit("Tidying up")
folder = assert_inside(plan.root, plan.root / BUTTONS_DIR)
for src in default_buttons():
dest = folder / src.name
try:
if dest.exists():
continue
folder.mkdir(parents=True, exist_ok=True)
dest.write_bytes(src.read_bytes())
except OSError:
continue
def _prune_empty_dirs(self):
"""Drop folders an artist or album left behind when it went away.
Bottom-up so a whole emptied branch goes in one pass, guarded like
every other delete, and never inside Buttons/ or plays/ — those are
the device's, and an empty one still belongs to it.
"""
plan = self._plan
for dirpath, _dirnames, _filenames in os.walk(plan.root, topdown=False):
current = Path(dirpath)
if current == plan.root:
continue
rel = current.relative_to(plan.root)
if rel.parts[0] in PRESERVED_DIRS:
continue
# Ask the filesystem, not os.walk: walking bottom-up means a
# parent's listing was taken before its children were removed, so
# an emptied branch would only lose its deepest folder per sync.
try:
if any(current.iterdir()):
continue
except OSError:
continue
try:
assert_inside(plan.root, current).rmdir()
except (layout.DeviceLayoutError, OSError):
pass