Coverage for downtify/likes.py: 97%
146 statements
« prev ^ index » next coverage.py v7.17.4, created at 2026-11-21 22:18 +0000
« prev ^ index » next coverage.py v7.17.4, created at 2026-11-21 22:18 +0000
1"""Songs the user has liked, and the playlist that lists them.
3Liking is a heart on a track in the library. The likes live in
4``downtify_library.db`` — on the server, so a heart tapped on a phone is
5there on the desktop too — and, as long as there is at least one, they
6are also written out as a regular M3U playlist, so the same songs show up
7in Downtify's Library and in any media server pointed at the folder.
9Two things are easy to get wrong here, and both are handled on purpose:
11* The playlist is a plain file next to the ones downloaded playlists
12 write, so its name can't be one a downloaded playlist could also have
13 (a Spotify playlist called "Liked songs" is common): it would write the
14 same file. It gets a reserved name, ``LIKED_PLAYLIST_NAME``.
15* Deleting a playlist in Downtify deletes its tracks from disk. Deleting
16 *this* one only ever means "unlike everything" — see the guard on
17 ``DELETE /api/library/playlist``.
18"""
20from __future__ import annotations
22import threading
23from collections.abc import Collection, Sequence
24from datetime import datetime, timezone
25from pathlib import Path
26from typing import Any, Optional
28from loguru import logger
30from . import m3u
31from .db.config import Dialect
32from .db.core import Database, as_database
33from .db.dialect import column_names, insertion_order_col
34from .library_cache_keys import file_content_key
35from .library_catalog import LibraryContext
36from .library_paths import locate_library_file
37from .library_reconcile import build_disk_content_index
39#: The M3U's name: reserved, so no downloaded playlist can write over it.
40LIKED_PLAYLIST_NAME = 'Downtify Liked Songs'
42_SYNC_LOCK = threading.Lock()
45def _now_iso() -> str:
46 return datetime.now(timezone.utc).isoformat()
49def _norm(path: str) -> str:
50 return str(path or '').strip().replace('\\', '/')
53def is_liked_playlist(name: Any) -> bool:
54 """True for the reserved name, however the caller cased or spaced it."""
56 return str(name or '').strip().casefold() == LIKED_PLAYLIST_NAME.casefold()
59class LikedTracks:
60 """The liked library files, newest like first, per user.
62 Each row keeps the file's library path (what the player, the Library
63 and M3U files use), a content key so a like can follow the file when
64 it is moved (see :func:`remap_moved`), and a snapshot of its title,
65 artist and length for the playlist's ``#EXTINF`` lines, so rewriting
66 the playlist never has to read every liked file's tags again.
68 ``user_id`` ``0`` rows predate per-user likes and belong to the
69 admin, like every other ownerless thing. The on-disk liked playlist
70 (``LIKED_PLAYLIST_NAME``) is that admin set too - other users' likes
71 live in the database (web UI and apps) only, so one user's hearts
72 never show up in another user's library folder.
73 """
75 def __init__(self, path_or_db: str | Path | Database) -> None:
76 self.db = as_database(path_or_db, 'library')
77 if isinstance(path_or_db, Database):
78 self._path = str(self.db.path) if self.db.path else None
79 else:
80 self._path = str(path_or_db)
81 self._init_db()
83 def _connect(self):
84 return self.db.connect()
86 def _init_db(self) -> None:
87 # On PostgreSQL the library_b migration already created the final
88 # table (with its ``id`` column) and there is nothing to rebuild.
89 if self.db.dialect is not Dialect.SQLITE:
90 return
91 with self.db.transaction(lock=True) as conn:
92 conn.execute("""
93 CREATE TABLE IF NOT EXISTS liked_tracks (
94 stored_path TEXT PRIMARY KEY,
95 content_key TEXT NOT NULL DEFAULT '',
96 title TEXT NOT NULL DEFAULT '',
97 artist TEXT NOT NULL DEFAULT '',
98 duration REAL NOT NULL DEFAULT 0,
99 liked_at TEXT NOT NULL
100 )
101 """)
102 if 'user_id' not in column_names(conn, 'liked_tracks'):
103 # Rebuild to the per-user primary key. The transaction
104 # (BEGIN IMMEDIATE, COMMIT or ROLLBACK) is the session's.
105 order = insertion_order_col(conn.dialect)
106 conn.execute("""
107 CREATE TABLE liked_tracks_new (
108 stored_path TEXT NOT NULL,
109 user_id INTEGER NOT NULL DEFAULT 0,
110 content_key TEXT NOT NULL DEFAULT '',
111 title TEXT NOT NULL DEFAULT '',
112 artist TEXT NOT NULL DEFAULT '',
113 duration REAL NOT NULL DEFAULT 0,
114 liked_at TEXT NOT NULL,
115 PRIMARY KEY (user_id, stored_path)
116 )
117 """)
118 conn.execute(f"""
119 INSERT INTO liked_tracks_new
120 (stored_path, user_id, content_key, title, artist,
121 duration, liked_at)
122 SELECT stored_path, 0, content_key, title, artist,
123 duration, liked_at
124 FROM liked_tracks ORDER BY {order}
125 """)
126 conn.execute('DROP TABLE liked_tracks')
127 conn.execute(
128 'ALTER TABLE liked_tracks_new RENAME TO liked_tracks'
129 )
131 def like(
132 self,
133 stored_path: str,
134 *,
135 content_key: str = '',
136 title: str = '',
137 artist: str = '',
138 duration: float = 0.0,
139 user_id: int = 0,
140 ) -> bool:
141 """Like a file. ``True`` when it wasn't liked yet.
143 Liking it again is a no-op that keeps its place in the order, so
144 a double tap never moves a song to the top.
145 """
147 path = _norm(stored_path)
148 if not path:
149 return False
150 with self._connect() as conn:
151 cur = conn.execute(
152 """INSERT INTO liked_tracks
153 (stored_path, user_id, content_key, title, artist,
154 duration, liked_at)
155 VALUES (?, ?, ?, ?, ?, ?, ?)
156 ON CONFLICT(user_id, stored_path) DO NOTHING""",
157 (
158 path,
159 int(user_id or 0),
160 content_key or '',
161 title or '',
162 artist or '',
163 float(duration or 0.0),
164 _now_iso(),
165 ),
166 )
167 return cur.rowcount > 0
169 def unlike(self, stored_path: str, user_id: Optional[int] = None) -> bool:
170 """Remove a like. ``True`` when there was one.
172 With *user_id* only that user's heart goes (a user unliking);
173 without it every row for the path goes (the file itself is gone).
174 """
176 path = _norm(stored_path)
177 if not path:
178 return False
179 with self._connect() as conn:
180 if user_id is None:
181 cur = conn.execute(
182 'DELETE FROM liked_tracks WHERE stored_path = ?',
183 (path,),
184 )
185 else:
186 cur = conn.execute(
187 'DELETE FROM liked_tracks WHERE stored_path = ? '
188 'AND user_id = ?',
189 (path, int(user_id)),
190 )
191 return cur.rowcount > 0
193 def clear(self, user_id: Optional[int] = None) -> int:
194 """Unlike everything (*user_id*'s, or all when ``None``)."""
196 with self._connect() as conn:
197 if user_id is None:
198 return conn.execute('DELETE FROM liked_tracks').rowcount
199 cur = conn.execute(
200 'DELETE FROM liked_tracks WHERE user_id = ?',
201 (int(user_id),),
202 )
203 return cur.rowcount
205 def count(self, user_id: Optional[int] = None) -> int:
206 with self._connect() as conn:
207 if user_id is None:
208 row = conn.execute(
209 'SELECT COUNT(*) AS n FROM liked_tracks'
210 ).fetchone()
211 else:
212 row = conn.execute(
213 'SELECT COUNT(*) AS n FROM liked_tracks WHERE user_id = ?',
214 (int(user_id),),
215 ).fetchone()
216 return int(row['n'])
218 def count_by_user(self) -> dict[int, int]:
219 """Likes per account (Settings → Users summary)."""
221 with self._connect() as conn:
222 rows = conn.execute(
223 'SELECT user_id, COUNT(*) AS n FROM liked_tracks '
224 'GROUP BY user_id'
225 ).fetchall()
226 return {int(row['user_id']): int(row['n']) for row in rows}
228 def rows(self, user_id: Optional[int] = None) -> list[dict[str, Any]]:
229 # ``rowid`` on SQLite, the ``id`` identity column on PostgreSQL.
230 order = insertion_order_col(self.db.dialect)
231 with self._connect() as conn:
232 if user_id is None:
233 found = conn.execute(
234 f"""SELECT stored_path, user_id, content_key, title,
235 artist, duration, liked_at
236 FROM liked_tracks
237 ORDER BY liked_at DESC, {order} DESC"""
238 ).fetchall()
239 else:
240 found = conn.execute(
241 f"""SELECT stored_path, user_id, content_key, title,
242 artist, duration, liked_at
243 FROM liked_tracks
244 WHERE user_id = ?
245 ORDER BY liked_at DESC, {order} DESC""",
246 (int(user_id),),
247 ).fetchall()
248 return [
249 {
250 'stored_path': str(row['stored_path']),
251 'user_id': int(row['user_id']),
252 'content_key': str(row['content_key'] or ''),
253 'title': str(row['title'] or ''),
254 'artist': str(row['artist'] or ''),
255 'duration': float(row['duration'] or 0.0),
256 'liked_at': str(row['liked_at']),
257 }
258 for row in found
259 ]
261 def paths(self, user_id: Optional[int] = None) -> list[str]:
262 return [row['stored_path'] for row in self.rows(user_id)]
264 def remove_user(self, user_id: int) -> int:
265 """Drop a deleted account's likes; how many went."""
267 return self.clear(user_id)
269 def reassign_legacy(self, user_id: int) -> int:
270 """Give pre-feature rows (``user_id`` ``0``) to *user_id*.
272 Runs once on the first start with ownership; later system rows
273 keep ``0`` (admins-only), so this must not run again.
274 """
276 if not user_id:
277 return 0
278 with self._connect() as conn:
279 cur = conn.execute(
280 'UPDATE liked_tracks SET user_id = ? WHERE user_id = 0',
281 (int(user_id),),
282 )
283 return cur.rowcount
285 def update_path(
286 self, old: str, new: str, user_id: Optional[int] = None
287 ) -> bool:
288 """Point a like at the file's new path, after it moved."""
290 old_path, new_path = _norm(old), _norm(new)
291 if not old_path or not new_path or old_path == new_path:
292 return False
293 scope = '' if user_id is None else 'AND user_id = ?'
294 args: tuple[Any, ...] = (
295 (new_path,) if user_id is None else (new_path, int(user_id))
296 )
297 old_args: tuple[Any, ...] = (
298 (old_path,) if user_id is None else (old_path, int(user_id))
299 )
300 # Check-then-write: one write transaction (BEGIN IMMEDIATE on
301 # SQLite). On PostgreSQL the old rows are locked first so a
302 # concurrent unlike or repoint of the same like waits its turn.
303 lock = ' FOR UPDATE' if self.db.dialect is Dialect.POSTGRES else ''
304 with self.db.transaction(lock=True) as conn:
305 conn.execute(
306 'SELECT 1 FROM liked_tracks WHERE stored_path = ? '
307 + scope
308 + lock,
309 old_args,
310 ).fetchone()
311 if conn.execute(
312 'SELECT 1 FROM liked_tracks WHERE stored_path = ? ' + scope,
313 args,
314 ).fetchone():
315 # Already liked there: the old row is just a duplicate.
316 conn.execute(
317 'DELETE FROM liked_tracks WHERE stored_path = ? ' + scope,
318 old_args,
319 )
320 return True
321 cur = conn.execute(
322 'UPDATE liked_tracks SET stored_path = ? '
323 'WHERE stored_path = ? ' + scope,
324 (new_path,) + old_args,
325 )
326 return cur.rowcount > 0
329def sync_liked_playlist(
330 likes: LikedTracks,
331 download_dir: Path,
332 slskd_dir: Optional[Path] = None,
333 extra_dirs: Optional[Sequence[Path]] = None,
334 user_ids: Optional[Collection[int]] = None,
335) -> Optional[Path]:
336 """Write the liked playlist, or take it away when there is nothing to list.
338 The playlist exists exactly while at least one liked file is still on
339 disk: with none, the M3U is removed rather than left stale (the
340 writer refuses to write an empty one, and would leave the old file
341 behind). Returns the M3U's path, or ``None`` when there isn't one.
343 A liked file that has gone missing is skipped, not unliked — an
344 unmounted drive shouldn't cost anyone their hearts. It comes back the
345 next time the playlist is written after the file returns.
347 Only *user_ids*' likes are written (``None``: everyone's). The
348 on-disk playlist is the shared one, so callers pass the admin set -
349 other users' likes never land in the library folder.
350 """
352 with _SYNC_LOCK:
353 rows = likes.rows()
354 if user_ids is not None:
355 wanted = {int(uid) for uid in user_ids}
356 rows = [row for row in rows if row['user_id'] in wanted]
357 entries = [
358 {
359 'filename': row['stored_path'],
360 'title': row['title'],
361 'artist': row['artist'],
362 'duration': row['duration'],
363 }
364 for row in rows
365 ]
366 if entries:
367 path, _kept = m3u.write_m3u(
368 download_dir,
369 LIKED_PLAYLIST_NAME,
370 entries,
371 slskd_dir=slskd_dir,
372 extra_dirs=extra_dirs,
373 )
374 if path is not None:
375 return path
376 stale = m3u.m3u_path_for(download_dir, LIKED_PLAYLIST_NAME)
377 try:
378 stale.unlink(missing_ok=True)
379 except OSError:
380 logger.opt(exception=True).warning(
381 'Could not remove the liked songs playlist {}', stale
382 )
383 return None
386def remap_moved(likes: LikedTracks, ctx: LibraryContext) -> int:
387 """Follow liked files that were moved on disk.
389 The same idea as "Fix library paths" for the track index and the
390 playlist catalog: a like keeps the file's content key, and a file
391 that is gone from its path but turns up elsewhere with the same key
392 is the same file. Returns how many likes were repointed.
393 """
395 rows = [row for row in likes.rows() if row['content_key']]
396 if not rows:
397 return 0
398 disk = build_disk_content_index(ctx)
399 if not disk:
400 return 0
401 moved = 0
402 for row in rows:
403 old = row['stored_path']
404 new = disk.get(row['content_key'])
405 if not new or new == old:
406 continue
407 if locate_library_file(
408 old, ctx.download_dir, ctx.slskd_dir, ctx.extra_dirs
409 ):
410 continue # Still where it was: the key just matches a twin.
411 if likes.update_path(old, new):
412 moved += 1
413 if moved:
414 logger.info('liked songs: followed {} moved file(s)', moved)
415 return moved
418def content_key_for(full_path: Path) -> str:
419 return file_content_key(full_path) or ''