Coverage for downtify/library_only.py: 98%
110 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"""Library-only policy and deterministic recommendations, without providers."""
3from __future__ import annotations
5import threading
6import unicodedata
7from collections.abc import Iterator
8from contextlib import contextmanager
9from typing import Any
10from urllib.parse import quote
12from fastapi import HTTPException
14from .library_sync import grouping_keys, split_artists
16DETAIL = 'Library-only mode is enabled. Only library music is available.'
18# These endpoints have local answers in api.py when the policy is enabled.
19LOCAL_ROUTES = {
20 '/api/songs/search',
21 '/api/albums/search',
22 '/api/artists/search',
23 '/api/finder/search',
24 '/api/similar/tracks',
25 '/api/discover/chart',
26 '/api/discover',
27 '/api/discover/collections',
28 '/api/discover/collections/deezer',
29 '/api/discover/collections/spotify',
30}
31REMOTE_PREFIXES = (
32 '/api/download/',
33 '/api/stream',
34 '/api/preview',
35 '/api/url',
36 '/api/song/url',
37 '/api/finder/',
38 '/api/artists/top_',
39 '/api/artists/info',
40 '/api/artists/similar',
41 '/api/artists/photo-proxy',
42 '/api/artists/art/search',
43 '/api/artists/art/spotify_candidate',
44 '/api/artists/art/from_url',
45 '/api/artists/profile/ensure',
46 '/api/artists/profile/bio/preview',
47 # Searching for and fetching a version; uploading a file of your own
48 # (/api/library/replace/upload) stays local.
49 '/api/library/replace/candidates',
50 '/api/playlists/incomplete',
51 '/api/playlists/batches/',
52)
53REMOTE_ACTIONS = {
54 '/api/artists/profile/bio',
55 '/api/podcasts/search',
56 '/api/podcasts/resolve',
57 '/api/podcasts/subscribe',
58 '/api/library/upgrade/scan',
59 '/api/library/upgrade/start',
60 '/api/library/upgrade/resume',
61 '/api/library/replace',
62 '/api/deemix/test',
63 '/api/slskd/test',
64 '/api/navidrome/ratings/run',
65}
68def enabled(settings: dict[str, Any]) -> bool:
69 """Only a saved JSON boolean enables the policy."""
70 return settings.get('library_only') is True
73def remote_route(path: str, method: str) -> bool:
74 """Whether a web route can resolve, fetch or suggest external music."""
75 return (
76 path in LOCAL_ROUTES
77 or path.startswith(REMOTE_PREFIXES)
78 or (path in REMOTE_ACTIONS and method not in {'DELETE', 'PUT'})
79 or (path.startswith('/api/monitor') and method in {'POST', 'PATCH'})
80 or (path.startswith('/api/podcasts/') and path.endswith('/download'))
81 )
84class Policy:
85 """Serialize activation with admission of external work, never cancel it."""
87 def __init__(self) -> None:
88 self._lock = threading.RLock()
89 self._active = 0
91 @contextmanager
92 def external(self, settings: dict[str, Any]) -> Iterator[None]:
93 with self._lock:
94 if enabled(settings):
95 raise HTTPException(status_code=409, detail=DETAIL)
96 self._active += 1
97 try:
98 yield
99 finally:
100 with self._lock:
101 self._active -= 1
103 def set_enabled(self, settings: dict[str, Any], value: Any) -> None:
104 """Reject invalid or busy transitions before modifying any setting."""
105 if not isinstance(value, bool):
106 raise HTTPException(
107 status_code=400, detail='library_only must be a boolean'
108 )
109 with self._lock:
110 if value and not enabled(settings) and self._active:
111 raise HTTPException(
112 status_code=409,
113 detail='External music operations are active. Wait for them to finish before enabling library-only mode.',
114 )
115 settings['library_only'] = value
118policy = Policy()
121def text(value: Any) -> str:
122 """Accent-insensitive text shared by local search and similarity."""
123 return ''.join(
124 c
125 for c in unicodedata.normalize('NFKD', str(value or '').casefold())
126 if not unicodedata.combining(c)
127 ).strip()
130def song(entry: dict[str, Any]) -> dict[str, Any]:
131 """A search row with a local identity; no provider URL or preview."""
132 file = str(entry.get('file') or '')
133 return {
134 'song_id': 'library:' + file,
135 'name': str(entry.get('title') or ''),
136 'artists': [
137 a.strip()
138 for a in str(entry.get('artist') or '').split(';')
139 if a.strip()
140 ],
141 'artist': str(entry.get('artist') or ''),
142 'album_name': str(entry.get('album') or ''),
143 'duration': entry.get('duration') or 0,
144 'explicit': bool(entry.get('explicit')),
145 'has_cover': bool(entry.get('has_cover')),
146 'file': file,
147 'url': '',
148 'cover_url': '/cover?file=' + quote(file, safe=''),
149 'source': 'library',
150 }
153def search(
154 entries: list[dict[str, Any]], query: str, limit: int = 20
155) -> list[dict[str, Any]]:
156 """All query words must occur in the local tags; stable ordering."""
157 words = text(query).split()
158 if not words:
159 return []
160 matches = [
161 e
162 for e in entries
163 if all(
164 w
165 in text(
166 ' '.join(
167 str(e.get(k) or '') for k in ('title', 'artist', 'album')
168 )
169 )
170 for w in words
171 )
172 ]
173 matches.sort(key=lambda e: (text(e.get('title')), str(e.get('file'))))
174 return [song(e) for e in matches[:limit]]
177def artist_keys(entry: dict[str, Any]) -> set[str]:
178 return {
179 text(a)
180 for a in split_artists(str(entry.get('artist') or ''))
181 if text(a)
182 }
185def similarity_score(entry: dict[str, Any], seed: dict[str, Any]) -> int:
186 shared_artist = bool(artist_keys(entry) & artist_keys(seed))
187 same_album_artist = bool(
188 text(entry.get('album_artist'))
189 and text(entry.get('album_artist')) == text(seed.get('album_artist'))
190 )
191 same_album = bool(
192 text(entry.get('album'))
193 and text(entry.get('album')) == text(seed.get('album'))
194 and (shared_artist or same_album_artist)
195 )
196 shared_genre = bool(
197 text(entry.get('genre'))
198 and text(entry.get('genre')) == text(seed.get('genre'))
199 )
200 return 4 * shared_artist + 2 * same_album + shared_genre
203def similar(
204 entries: list[dict[str, Any]], artist: str, track: str, limit: int
205) -> dict[str, Any]:
206 """Rank saved tags, never fetch radio; unknown seeds have no suggestions."""
207 a, t = text(artist), text(track)
208 seeds = (
209 [
210 e
211 for e in entries
212 if (not a or a == text(e.get('artist')) or a in artist_keys(e))
213 and (not t or t == text(e.get('title')))
214 ]
215 if a or t
216 else []
217 )
218 ranked = []
219 for entry in entries:
220 if entry in seeds:
221 continue
222 score = max(
223 (similarity_score(entry, seed) for seed in seeds), default=0
224 )
225 if score:
226 ranked.append((score, entry))
227 ranked.sort(
228 key=lambda pair: (
229 -pair[0],
230 text(pair[1].get('title')),
231 str(pair[1].get('file')),
232 )
233 )
234 seen = set()
235 tracks = []
236 for score, entry in ranked:
237 identity = (text(entry.get('artist')), text(entry.get('title')))
238 if identity not in seen:
239 tracks.append({**song(entry), 'match': score})
240 seen.add(identity)
241 if len(tracks) >= limit:
242 break
243 return {
244 'artist': artist,
245 'track': track,
246 'source': 'library',
247 'tracks': tracks,
248 }
251def catalog(
252 entries: list[dict[str, Any]], query: str = '', limit: int = 25
253) -> dict[str, Any]:
254 """The existing search/card shapes, populated only from visible files."""
255 album_groups: dict[str, list[dict[str, Any]]] = {}
256 artist_groups: dict[str, list[dict[str, Any]]] = {}
257 for entry in entries:
258 keys = grouping_keys(entry)
259 if keys['album_artist']:
260 artist_groups.setdefault(keys['artist_id'], []).append(entry)
261 if entry.get('album'):
262 album_groups.setdefault(keys['album_id'], []).append(entry)
264 def matches(label: str) -> bool:
265 return all(word in text(label) for word in text(query).split())
267 artists = []
268 for identity, group in artist_groups.items():
269 name = grouping_keys(group[0])['album_artist']
270 if matches(name):
271 artists.append({
272 'artist_id': 'library:' + identity,
273 'name': name,
274 'artist': name,
275 'cover_url': song(group[0])['cover_url'],
276 'picture_url': song(group[0])['cover_url'],
277 'source': 'library',
278 'kind': 'artist',
279 'url': name,
280 'track_count': len(group),
281 'because': [],
282 })
283 albums = []
284 for identity, group in album_groups.items():
285 first = group[0]
286 artist = grouping_keys(first)['album_artist']
287 name = str(first.get('album') or '')
288 if matches(artist + ' ' + name):
289 albums.append({
290 'album_id': 'library:' + identity,
291 'name': name,
292 'artist': artist,
293 'cover_url': song(first)['cover_url'],
294 'year': str(first.get('year') or ''),
295 'source': 'library',
296 'kind': 'album',
297 'url': artist + ' ' + name,
298 'track_count': len(group),
299 'release_type': 'Album',
300 'reason': 'more_from',
301 'because': [],
302 })
303 artists.sort(key=lambda row: text(row['name']))
304 albums.sort(key=lambda row: (text(row['artist']), text(row['name'])))
305 return {
306 'source': 'library',
307 'tracks': search(entries, query, limit)
308 if query.strip()
309 else [song(e) for e in entries[:limit]],
310 'artists': artists[:limit],
311 'albums': albums[:limit],
312 'playlists': [],
313 }
316def playlist_rows(
317 playlists: list[dict[str, Any]], limit: int = 25
318) -> list[dict[str, Any]]:
319 """Keep each accessible playlist's real identity and display name."""
320 result = [
321 {
322 'playlist_id': 'library:' + p['name'],
323 'playlist_name': p['name'],
324 'name': p.get('display_name') or p['name'],
325 'owner': p.get('owner', ''),
326 'source': 'library',
327 'kind': 'playlist',
328 'url': p.get('display_name') or p['name'],
329 'cover_url': '/playlist-cover?file='
330 + quote(str(p['cover']), safe='')
331 if p.get('cover')
332 else '',
333 'track_count': p.get('count', 0),
334 'favorite': bool(p.get('favorite')),
335 'artist': '',
336 'because': [],
337 }
338 for p in playlists
339 ]
340 result.sort(key=lambda row: (not row['favorite'], text(row['name'])))
341 return result[:limit]