Coverage for downtify/library_visibility.py: 100%
161 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"""What an admin hides from the other users' view of the library.
3The library is shared: every account sees every song anyone downloaded.
4An admin can take songs, albums or artists *out of the view of users who
5aren't admins* - and put them back. Nothing is deleted, and admins keep
6seeing everything (with a mark on what's hidden). With nothing hidden,
7which is how it starts, there is nothing to evaluate.
9Three kinds of rule, each matching the way the Library groups things:
11* **track** - one file. Remembered by its content key (name + size, which
12 survives a folder move) *and* its library path (which survives the file
13 being rewritten in place, e.g. by an upgrade), so neither a move nor a
14 rewrite quietly shows a hidden song again. Flows that rewrite a file
15 re-point the rule (:meth:`LibraryVisibility.rekey_track`).
16* **album** - every track of an album, by album artist + title (the
17 album-artist tag as it is, so a ``Various Artists`` compilation is one
18 album - rules made before that, keyed by its tracks' own artist, still
19 match).
20* **artist** - every track filed under an artist (their album artist, as
21 the Library's Artists tab groups them).
23Hiding controls what is *listed* to a user - the Library, search's "in
24library" marks, the apps' sync - not who can fetch a file whose address
25they know; it is not an access-control boundary.
26"""
28from __future__ import annotations
30import threading
31from dataclasses import dataclass
32from datetime import datetime, timezone
33from pathlib import Path
34from typing import Any
36from .db.config import Dialect
37from .db.core import Database, as_database
38from .db.dialect import insertion_order_col
39from .library_catalog import (
40 album_artist_of,
41 album_owner_of,
42 entry_content_key,
43)
45KIND_TRACK = 'track'
46KIND_ALBUM = 'album'
47KIND_ARTIST = 'artist'
48KINDS = (KIND_TRACK, KIND_ALBUM, KIND_ARTIST)
50# Joins an album's artist and title in one stored key.
51_SEP = '\x1f'
54def _now_iso() -> str:
55 return datetime.now(timezone.utc).isoformat()
58def _fold(value: Any) -> str:
59 return str(value or '').strip().casefold()
62def _norm_path(path: Any) -> str:
63 return str(path or '').strip().replace('\\', '/')
66def artist_key(name: Any) -> str:
67 """The stored key of an artist: their name, case-insensitively."""
69 return _fold(name)
72def album_key(artist: Any, title: Any) -> str:
73 """The stored key of an album: its artist and title, case-insensitively."""
75 return f'{_fold(artist)}{_SEP}{_fold(title)}'
78@dataclass(frozen=True)
79class HiddenRules:
80 """Everything currently hidden, ready to test library rows against."""
82 track_keys: frozenset[str] = frozenset()
83 track_paths: frozenset[str] = frozenset()
84 albums: frozenset[str] = frozenset()
85 artists: frozenset[str] = frozenset()
87 def __bool__(self) -> bool:
88 return bool(
89 self.track_keys or self.track_paths or self.albums or self.artists
90 )
92 def reason(self, entry: dict[str, Any]) -> str:
93 """Why *entry* is hidden - ``artist``, ``album`` or ``track`` (the
94 widest rule first) - or ``''`` when it is shown."""
96 if not self:
97 return ''
98 artist = album_artist_of(entry)
99 if artist and artist_key(artist) in self.artists:
100 return KIND_ARTIST
101 album = str(entry.get('album') or '').strip()
102 if album and (
103 album_key(album_owner_of(entry), album) in self.albums
104 or album_key(artist, album) in self.albums
105 ):
106 return KIND_ALBUM
107 if (
108 _norm_path(entry.get('file')) in self.track_paths
109 or entry_content_key(entry) in self.track_keys
110 ):
111 return KIND_TRACK
112 return ''
114 def hides(self, entry: dict[str, Any]) -> bool:
115 return bool(self.reason(entry))
117 def album_reason(self, artist: Any, title: Any) -> str:
118 """``artist`` or ``album`` when that whole album is hidden by a
119 rule on it (or its artist), else ``''``."""
121 if artist_key(artist) in self.artists:
122 return KIND_ARTIST
123 if album_key(artist, title) in self.albums:
124 return KIND_ALBUM
125 return ''
127 def artist_hidden(self, name: Any) -> bool:
128 return artist_key(name) in self.artists
131class LibraryVisibility:
132 """The hidden items, in ``downtify_library.db``."""
134 def __init__(self, db_path: str | Path | Database) -> None:
135 self.db = as_database(db_path, 'library')
136 if isinstance(db_path, Database):
137 self._path = str(self.db.path) if self.db.path else None
138 else:
139 self._path = str(db_path)
140 self._lock = threading.Lock()
141 self._rules: HiddenRules | None = None
142 self._init_db()
144 def _connect(self):
145 return self.db.connect()
147 def _init_db(self) -> None:
148 # PostgreSQL gets its schema from the migrations.
149 if self.db.dialect is not Dialect.SQLITE:
150 return
151 with self._connect() as conn:
152 conn.execute("""
153 CREATE TABLE IF NOT EXISTS hidden_library_items (
154 kind TEXT NOT NULL,
155 item_key TEXT NOT NULL,
156 item_path TEXT NOT NULL DEFAULT '',
157 label TEXT NOT NULL DEFAULT '',
158 detail TEXT NOT NULL DEFAULT '',
159 hidden_at TEXT NOT NULL,
160 PRIMARY KEY (kind, item_key)
161 )
162 """)
163 conn.execute("""
164 CREATE INDEX IF NOT EXISTS idx_hidden_library_path
165 ON hidden_library_items (item_path)
166 """)
168 def rules(self) -> HiddenRules:
169 """The current rules (kept in memory until something changes)."""
171 with self._lock:
172 if self._rules is None:
173 self._rules = self._load()
174 return self._rules
176 def _load(self) -> HiddenRules:
177 keys: set[str] = set()
178 paths: set[str] = set()
179 albums: set[str] = set()
180 artists: set[str] = set()
181 with self._connect() as conn:
182 rows = conn.execute(
183 'SELECT kind, item_key, item_path FROM hidden_library_items'
184 ).fetchall()
185 for row in rows:
186 kind = row['kind']
187 if kind == KIND_TRACK:
188 keys.add(row['item_key'])
189 if row['item_path']:
190 paths.add(row['item_path'])
191 elif kind == KIND_ALBUM:
192 albums.add(row['item_key'])
193 elif kind == KIND_ARTIST:
194 artists.add(row['item_key'])
195 return HiddenRules(
196 frozenset(keys),
197 frozenset(paths),
198 frozenset(albums),
199 frozenset(artists),
200 )
202 def _changed(self) -> None:
203 self._rules = None
205 def invalidate(self) -> None:
206 """Reload rules after an atomic audio-reference transaction."""
207 with self._lock:
208 self._changed()
210 def hide(
211 self,
212 kind: str,
213 key: str,
214 *,
215 label: str = '',
216 detail: str = '',
217 path: str = '',
218 ) -> bool:
219 """Hide one item. ``True`` when it wasn't hidden already."""
221 if kind not in KINDS or not key:
222 return False
223 with self._lock, self._connect() as conn:
224 cur = conn.execute(
225 """INSERT INTO hidden_library_items
226 (kind, item_key, item_path, label, detail, hidden_at)
227 VALUES (?, ?, ?, ?, ?, ?)
228 ON CONFLICT(kind, item_key) DO NOTHING""",
229 (kind, key, _norm_path(path), label, detail, _now_iso()),
230 )
231 added = cur.rowcount > 0
232 if added:
233 self._changed()
234 return added
236 def show(self, kind: str, key: str) -> bool:
237 """Show one item again. ``True`` when it was hidden."""
239 with self._lock, self._connect() as conn:
240 cur = conn.execute(
241 'DELETE FROM hidden_library_items '
242 'WHERE kind = ? AND item_key = ?',
243 (kind, key),
244 )
245 removed = cur.rowcount > 0
246 if removed:
247 self._changed()
248 return removed
250 def show_track_by_path(self, path: str) -> int:
251 """Show the hidden track(s) stored at *path* (a file whose
252 content key changed since it was hidden). How many."""
254 normal = _norm_path(path)
255 if not normal:
256 return 0
257 with self._lock, self._connect() as conn:
258 cur = conn.execute(
259 'DELETE FROM hidden_library_items '
260 'WHERE kind = ? AND item_path = ?',
261 (KIND_TRACK, normal),
262 )
263 if cur.rowcount:
264 self._changed()
265 return cur.rowcount
267 def rekey_track(
268 self, old_key: str, new_key: str, stored_path: str = ''
269 ) -> int:
270 """Point a hidden track at its rewritten file (upgrade, replace)."""
272 old = str(old_key or '').strip()
273 new = str(new_key or '').strip()
274 if not old or not new or old == new:
275 return 0
276 path = _norm_path(stored_path)
277 with self._lock, self._connect() as conn:
278 # Skip the move when the new key is already hidden (what SQLite's
279 # UPDATE OR IGNORE did); the old row is dropped below.
280 cur = conn.execute(
281 'UPDATE hidden_library_items SET item_key = ?, '
282 "item_path = COALESCE(NULLIF(?, ''), item_path) "
283 'WHERE kind = ? AND item_key = ? AND NOT EXISTS ('
284 ' SELECT 1 FROM hidden_library_items AS other '
285 ' WHERE other.kind = ? AND other.item_key = ?)',
286 (new, path, KIND_TRACK, old, KIND_TRACK, new),
287 )
288 moved = cur.rowcount
289 conn.execute(
290 'DELETE FROM hidden_library_items '
291 'WHERE kind = ? AND item_key = ?',
292 (KIND_TRACK, old),
293 )
294 if moved:
295 self._changed()
296 return moved
298 def drop_track(self, content_key: str) -> None:
299 """Forget a hidden track whose file is gone."""
301 key = str(content_key or '').strip()
302 if not key:
303 return
304 with self._lock, self._connect() as conn:
305 cur = conn.execute(
306 'DELETE FROM hidden_library_items '
307 'WHERE kind = ? AND item_key = ?',
308 (KIND_TRACK, key),
309 )
310 if cur.rowcount:
311 self._changed()
313 def items(self) -> dict[str, list[dict[str, Any]]]:
314 """Every hidden item for the admin's list, newest first:
315 ``{tracks, albums, artists}``."""
317 order = insertion_order_col(self.db.dialect)
318 with self._connect() as conn:
319 rows = conn.execute(
320 'SELECT kind, item_key, item_path, label, detail, hidden_at '
321 'FROM hidden_library_items '
322 f'ORDER BY hidden_at DESC, {order} DESC'
323 ).fetchall()
324 out: dict[str, list[dict[str, Any]]] = {
325 'tracks': [],
326 'albums': [],
327 'artists': [],
328 }
329 for row in rows:
330 item = {
331 'label': row['label'],
332 'detail': row['detail'],
333 'hidden_at': row['hidden_at'],
334 }
335 if row['kind'] == KIND_TRACK:
336 out['tracks'].append({
337 **item,
338 'file': row['item_path'],
339 'key': row['item_key'],
340 })
341 elif row['kind'] == KIND_ALBUM:
342 artist, _, title = row['item_key'].partition(_SEP)
343 out['albums'].append({
344 **item,
345 'title': row['label'],
346 'artist': row['detail'],
347 'key': row['item_key'],
348 'folded': [artist, title],
349 })
350 elif row['kind'] == KIND_ARTIST:
351 out['artists'].append({
352 **item,
353 'name': row['label'],
354 'key': row['item_key'],
355 })
356 return out