Coverage for downtify/mobile_routes.py: 39%

462 statements  

« prev     ^ index     » next       coverage.py v7.17.4, created at 2026-11-21 22:18 +0000

1"""The API the Downtify apps use: ``/api/v1``. 

2 

3Separate from the web app's routes (whose shapes the web app depends on 

4and which don't change) so this surface can be versioned on its own - 

5``api_version`` in ``GET /api/server/info`` says which one a server 

6speaks. Everything is addressed by **track id** (see 

7:mod:`downtify.library_sync`), never by file path. The full contract, 

8from discovery to reporting plays, is ``docs/mobile-client-contract.md``. 

9""" 

10 

11from __future__ import annotations 

12 

13import asyncio 

14import mimetypes 

15import time 

16from pathlib import Path 

17from typing import Any, Optional 

18from urllib.parse import quote 

19 

20from fastapi import APIRouter, HTTPException, Query, Request, Response 

21from fastapi.responses import FileResponse 

22from loguru import logger 

23 

24from . import api 

25from .auth import SIGNED_URL_DEFAULT_TTL, SIGNED_URL_MAX_TTL, Principal 

26from .cover_thumbs import normalize_size 

27from .library_catalog import list_library_entries, resolve_library_file 

28from .library_paths_cache import invalidate_library_paths_cache 

29from .likes import content_key_for 

30from .lyrics import read_track_lyrics 

31from .manual_playlists import MAX_TRACKS_PER_EDIT, ManualPlaylistError 

32from .metadata_edit import edit_file, validate_changes 

33from .mobile_track_ids import resolve_mobile_track_ids 

34from .transcode import ( 

35 FORMATS, 

36 TranscodeError, 

37 normalize_bitrate, 

38 serve_original, 

39) 

40 

41router = APIRouter(prefix='/api/v1') 

42 

43#: How long a phone may keep an audio file or cover without asking again. 

44_PRIVATE_CACHE = 'private, max-age=604800' 

45 

46 

47def _sync(): 

48 if api.state.library_sync is None: 

49 raise HTTPException(status_code=503, detail='Starting up') 

50 return api.state.library_sync 

51 

52 

53def _refresh() -> int: 

54 """Bring the track ids in line with what's on disk; the new cursor.""" 

55 

56 return _sync().refresh(list_library_entries(api.library_context())) 

57 

58 

59def _track_path( 

60 track_id: str, request: Request 

61) -> tuple[dict[str, Any], Path]: 

62 """A track's row and file, or 404.""" 

63 

64 sync = _sync() 

65 row = sync.row_for(track_id) 

66 if row is None: 

67 _refresh() 

68 row = sync.row_for(track_id) 

69 if row is None: 

70 raise HTTPException(status_code=404, detail='Track not found') 

71 principal = api.principal_of(request) 

72 visibility_request = request 

73 if principal is not None and principal.kind == 'signed' and api.state.auth: 

74 device = api.state.auth.get_device(principal.device_id) 

75 if device is None or device.get('revoked_at'): 

76 raise HTTPException(status_code=404, detail='Track not found') 

77 user_id = int(device.get('user_id') or 0) 

78 user = api.state.auth.users.get(user_id) 

79 if user is None: 

80 raise HTTPException(status_code=404, detail='Track not found') 

81 state = dict(request.scope.get('state') or {}) 

82 state['principal'] = Principal( 

83 'signed', 

84 principal.scope, 

85 principal.device_id, 

86 user_id, 

87 device.get('username') or user.get('username') or '', 

88 user.get('role') or '', 

89 ) 

90 visibility_request = Request({**request.scope, 'state': state}) 

91 if not api.filter_paths_for_request([row['file']], visibility_request): 

92 raise HTTPException(status_code=404, detail='Track not found') 

93 full = resolve_library_file(row['file'], api.library_context()) 

94 if full is None: 

95 raise HTTPException(status_code=404, detail='File not found') 

96 return row, full 

97 

98 

99# ── The library ───────────────────────────────────────────────────────── 

100 

101 

102@router.get('/library') 

103async def library( 

104 request: Request, 

105 response: Response, 

106 since: int = Query(0, ge=0), 

107 refresh: bool = Query(False), 

108) -> Any: 

109 """Tracks added or changed since *since*, and ids of tracks removed. 

110 

111 ``{cursor, full, tracks, deleted}``; keep ``cursor`` for next time. 

112 ``full: true`` means ``tracks`` is the whole library (a first sync, or 

113 a cursor too old to answer): replace everything you have with it. 

114 The folder scan behind it is cached for a minute or so; 

115 ``refresh=true`` (pull to refresh) rescans now - for files added to 

116 the folder by something other than Downtify. 

117 """ 

118 

119 if refresh: 

120 invalidate_library_paths_cache(notify=False, drop_entries=True) 

121 before = await asyncio.to_thread(_sync().cursor) 

122 cursor = await asyncio.to_thread(_refresh) 

123 if cursor != before: 

124 # Found something new on disk: other apps should sync too. 

125 api.announce_library_changed() 

126 allowed = api.allowed_entry_keys(request) 

127 scope = 'a' if allowed is None else api.request_user_id(request) 

128 etag = f'"lib-{cursor}-{since}-{scope}"' 

129 if request.headers.get('if-none-match') == etag: 

130 return Response(status_code=304, headers={'ETag': etag}) 

131 response.headers['ETag'] = etag 

132 response.headers['Cache-Control'] = 'private, no-cache' 

133 return await asyncio.to_thread( 

134 _sync().changes, since, allowed_keys=allowed 

135 ) 

136 

137 

138@router.get('/tracks/{track_id}') 

139def track(track_id: str, request: Request) -> dict[str, Any]: 

140 row, _full = _track_path(track_id, request) 

141 return row 

142 

143 

144@router.get('/tracks/{track_id}/lyrics') 

145def track_lyrics(track_id: str, request: Request) -> dict[str, Any]: 

146 """``{synced, plain}``: the ``.lrc`` sidecar and the embedded lyrics.""" 

147 

148 _row, full = _track_path(track_id, request) 

149 return read_track_lyrics(full) 

150 

151 

152@router.get('/playlists') 

153async def playlists(request: Request) -> list[dict[str, Any]]: 

154 """Downloaded playlists as ``{name, liked, manual, count, track_ids, 

155 cover, owner, visibility, mine, followed, can_edit_tracks, 

156 shared_with_me, new, hidden_count}`` - ``cover`` is a path for 

157 ``GET /playlist-cover?file=`` or ``''``; ``hidden_count`` is how many 

158 songs the owner hid from an imported playlist (``0`` for everything 

159 else). 

160 

161 A user sees their own playlists (and their own liked songs as the 

162 liked one), those shared with them (``shared_with_me``; ``new`` until 

163 opened) and public ones: the ones they follow, and - unless they 

164 switched *Show public playlists* off - the rest. ``mine`` says whether 

165 it is theirs to change, ``can_edit_tracks`` whether they may add and 

166 remove its songs (a Library playlist of theirs, or one shared with 

167 them as an editor), ``owner`` is the owner's username and 

168 ``visibility`` is ``private``, ``shared`` or ``public``. Own playlists 

169 also list ``shared_with`` and ``editors`` (usernames). 

170 """ 

171 

172 await asyncio.to_thread(_refresh) 

173 found = await asyncio.to_thread(api.playlists_for_request, request) 

174 paths = [f for p in found for f in p['files']] 

175 visible = set( 

176 await asyncio.to_thread(api.filter_paths_for_request, paths, request) 

177 ) 

178 ids = await asyncio.to_thread(_sync().ids_for_paths, visible) 

179 return [ 

180 { 

181 'name': p['name'], 

182 'display_name': p.get('display_name', p['name']), 

183 'liked': p['liked'], 

184 'manual': bool(p.get('manual')), 

185 'count': sum(f in visible for f in p['files']), 

186 'cover': p['cover'], 

187 'track_ids': [ 

188 ids[f] for f in p['files'] if f in visible and f in ids 

189 ], 

190 'owner': p.get('owner', ''), 

191 'visibility': p.get('visibility', 'private'), 

192 'mine': bool(p.get('mine', True)), 

193 'followed': bool(p.get('followed')), 

194 'can_edit_tracks': bool(p.get('can_edit_tracks')), 

195 'favorite': bool(p.get('favorite')), 

196 'shared_with_me': bool(p.get('shared_with_me')), 

197 'new': bool(p.get('new')), 

198 'hidden_count': int(p.get('hidden_count') or 0), 

199 **( 

200 {'shared_with': p['shared_with']} 

201 if p.get('shared_with') 

202 else {} 

203 ), 

204 **({'editors': p['editors']} if p.get('editors') else {}), 

205 } 

206 for p in found 

207 ] 

208 

209 

210def _require_playlist_writer(request: Request) -> None: 

211 if not api.request_user_id(request) and not api.request_is_admin(request): 

212 raise HTTPException(status_code=401, detail='Sign in required') 

213 

214 

215async def _mobile_playlist_result( 

216 result: dict[str, Any], request: Request 

217) -> dict[str, Any]: 

218 files = list(result.get('files') or []) 

219 files = await asyncio.to_thread( 

220 api.filter_paths_for_request, files, request 

221 ) 

222 ids = await asyncio.to_thread(_sync().ids_for_paths, files) 

223 response = { 

224 'name': str(result.get('name') or ''), 

225 'manual': bool(result.get('manual')), 

226 'count': len(files), 

227 'track_ids': [ids[file] for file in files if file in ids], 

228 } 

229 for key in ('added', 'removed', 'already'): 

230 if key in result: 

231 value = result[key] 

232 if key == 'already': 

233 visible = await asyncio.to_thread( 

234 api.filter_paths_for_request, value, request 

235 ) 

236 response[key] = [ids[file] for file in visible if file in ids] 

237 else: 

238 response[key] = value 

239 return response 

240 

241 

242@router.post('/playlists') 

243async def create_mobile_playlist(request: Request) -> dict[str, Any]: 

244 _require_playlist_writer(request) 

245 _sync() 

246 payload = await api._json_object(request) 

247 name = payload.get('name') 

248 if not isinstance(name, str) or not name.strip(): 

249 raise HTTPException(status_code=400, detail='name is required') 

250 result = await api.create_library_playlist_endpoint(request) 

251 await api.announce_playlists_changed() 

252 return await _mobile_playlist_result(result, request) 

253 

254 

255@router.post('/playlists/rename') 

256async def rename_mobile_playlist(request: Request) -> dict[str, Any]: 

257 _require_playlist_writer(request) 

258 _sync() 

259 payload = await api._json_object(request) 

260 name, new_name = payload.get('name'), payload.get('new_name') 

261 if ( 

262 not isinstance(name, str) 

263 or not name.strip() 

264 or not isinstance(new_name, str) 

265 or not new_name.strip() 

266 ): 

267 raise HTTPException( 

268 status_code=400, detail='name and new_name are required' 

269 ) 

270 entry = api.require_playlist_visible(name.strip(), request, manage=True) 

271 if not entry.get('manual'): 

272 raise HTTPException( 

273 status_code=403, detail='Only a Library playlist can be renamed' 

274 ) 

275 result = await api.rename_library_playlist_endpoint(request) 

276 out = await _mobile_playlist_result(result, request) 

277 out['previous'] = entry['name'] 

278 return out 

279 

280 

281@router.post('/playlists/tracks') 

282async def edit_mobile_playlist_tracks(request: Request) -> dict[str, Any]: 

283 _require_playlist_writer(request) 

284 _sync() 

285 payload = await api._json_object(request) 

286 name = payload.get('name') 

287 if not isinstance(name, str) or not name.strip(): 

288 raise HTTPException(status_code=400, detail='name is required') 

289 groups: dict[str, list[Any]] = {} 

290 for key in ('add', 'remove'): 

291 if key in payload and not isinstance(payload[key], list): 

292 raise HTTPException( 

293 status_code=400, detail=f'{key} must be a list' 

294 ) 

295 groups[key] = payload.get(key, []) 

296 raw_refs = payload.get('remove_entries', []) 

297 if not isinstance(raw_refs, list): 

298 raise HTTPException( 

299 status_code=400, detail='remove_entries must be a list' 

300 ) 

301 ref_occurrences = [] 

302 for ref in raw_refs: 

303 if ( 

304 not isinstance(ref, dict) 

305 or type(ref.get('occurrence', 0)) is not int 

306 or ref.get('occurrence', 0) < 0 

307 ): 

308 raise HTTPException( 

309 status_code=400, detail='Invalid remove_entries item' 

310 ) 

311 ref_occurrences.append(ref.get('occurrence', 0)) 

312 if 'allow_duplicates' in payload and not isinstance( 

313 payload['allow_duplicates'], bool 

314 ): 

315 raise HTTPException( 

316 status_code=400, detail='allow_duplicates must be a boolean' 

317 ) 

318 total = sum(map(len, groups.values())) + len(raw_refs) 

319 if total > MAX_TRACKS_PER_EDIT: 

320 raise HTTPException( 

321 status_code=400, detail='Too many track references' 

322 ) 

323 # Validate every id before any lookup, including ids in a later group. 

324 raw_ids = ( 

325 groups['add'] 

326 + groups['remove'] 

327 + [ref.get('track_id') for ref in raw_refs] 

328 ) 

329 for track_id in raw_ids: 

330 if not isinstance(track_id, str) or not track_id.strip(): 

331 raise HTTPException( 

332 status_code=400, detail='track_ids must be strings' 

333 ) 

334 

335 entry = await asyncio.to_thread( 

336 api.require_playlist_visible, name.strip(), request 

337 ) 

338 if not entry.get('manual'): 

339 raise HTTPException( 

340 status_code=403, detail='Only a Library playlist can be edited' 

341 ) 

342 if not entry.get('mine', True) and not entry.get('can_edit_tracks'): 

343 raise HTTPException( 

344 status_code=403, detail='Only an editor can change this playlist' 

345 ) 

346 resolved = await resolve_mobile_track_ids( 

347 _sync(), 

348 raw_ids, 

349 request, 

350 refresh=_refresh, 

351 filter_paths=api.filter_paths_for_request, 

352 ) 

353 add_end = len(groups['add']) 

354 remove_end = add_end + len(groups['remove']) 

355 add_files = resolved[:add_end] 

356 remove_files = resolved[add_end:remove_end] 

357 refs = [ 

358 {'file': path, 'occurrence': occurrence} 

359 for path, occurrence in zip(resolved[remove_end:], ref_occurrences) 

360 ] 

361 try: 

362 result = await asyncio.to_thread( 

363 api.edit_manual_playlist, 

364 api.library_context(), 

365 entry['name'], 

366 add=add_files, 

367 remove=remove_files, 

368 remove_entries=[ 

369 (item['file'], item['occurrence']) for item in refs 

370 ], 

371 allow_duplicates=payload.get('allow_duplicates', False), 

372 ) 

373 except ManualPlaylistError as exc: 

374 raise HTTPException( 

375 status_code=exc.status_code, detail=str(exc) 

376 ) from exc 

377 invalidate_library_paths_cache() 

378 if entry.get('visibility', 'private') != 'private': 

379 await api.announce_playlists_changed() 

380 return await _mobile_playlist_result(result, request) 

381 

382 

383@router.put('/playlists/order') 

384async def reorder_mobile_playlist(request: Request) -> dict[str, Any]: 

385 _require_playlist_writer(request) 

386 _sync() 

387 payload = await api._json_object(request) 

388 name, ids = payload.get('name'), payload.get('track_ids') 

389 if ( 

390 not isinstance(name, str) 

391 or not name.strip() 

392 or not isinstance(ids, list) 

393 ): 

394 raise HTTPException( 

395 status_code=400, detail='name and track_ids are required' 

396 ) 

397 if len(ids) > MAX_TRACKS_PER_EDIT: 

398 raise HTTPException( 

399 status_code=400, detail='Too many track references' 

400 ) 

401 if any(not isinstance(item, str) or not item.strip() for item in ids): 

402 raise HTTPException( 

403 status_code=400, detail='track_ids must be strings' 

404 ) 

405 entry = await asyncio.to_thread( 

406 api.require_playlist_visible, name.strip(), request 

407 ) 

408 if not entry.get('manual'): 

409 raise HTTPException( 

410 status_code=403, detail='Only a Library playlist can be edited' 

411 ) 

412 if not entry.get('mine', True) and not entry.get('can_edit_tracks'): 

413 raise HTTPException( 

414 status_code=403, detail='Only an editor can change this playlist' 

415 ) 

416 paths = await resolve_mobile_track_ids( 

417 _sync(), 

418 ids, 

419 request, 

420 refresh=_refresh, 

421 filter_paths=api.filter_paths_for_request, 

422 ) 

423 visible = await asyncio.to_thread( 

424 api.filter_paths_for_request, list(entry.get('files') or []), request 

425 ) 

426 try: 

427 result = await asyncio.to_thread( 

428 api.reorder_manual_playlist, 

429 api.library_context(), 

430 entry['name'], 

431 paths, 

432 visible=set(visible), 

433 ) 

434 except ManualPlaylistError as exc: 

435 raise HTTPException( 

436 status_code=exc.status_code, detail=str(exc) 

437 ) from exc 

438 invalidate_library_paths_cache() 

439 if entry.get('visibility', 'private') != 'private': 

440 await api.announce_playlists_changed() 

441 return await _mobile_playlist_result(result, request) 

442 

443 

444@router.get('/usernames') 

445async def usernames(request: Request) -> dict[str, Any]: 

446 """``{enabled, usernames}``: who a playlist can be shared with 

447 (everyone but you) - names only, since users can't list accounts. 

448 ``enabled`` is the admin's *Allow users to share playlists*.""" 

449 

450 me = api.request_user_id(request) 

451 enabled = api.sharing_enabled() 

452 names = sorted( 

453 (name for uid, name in api._usernames().items() if uid != me), 

454 key=str.casefold, 

455 ) 

456 return {'enabled': enabled, 'usernames': names if enabled else []} 

457 

458 

459@router.get('/tracks/{track_id}/loudness') 

460async def track_loudness(track_id: str, request: Request) -> dict[str, Any]: 

461 """The track's playback loudness profile (see downtify/loudness.py).""" 

462 

463 row, _ = await asyncio.to_thread(_track_path, track_id, request) 

464 return await api.track_loudness(request, str(row['file'])) 

465 

466 

467@router.put('/playlists/favorite') 

468async def favorite_playlist(request: Request) -> dict[str, Any]: 

469 """Set the same account preference as the web player.""" 

470 return await api.set_playlist_favorite_endpoint(request) 

471 

472 

473async def _playlist_name(request: Request) -> str: 

474 name = request.query_params.get('name', '') 

475 if not name: 

476 try: 

477 payload = await request.json() 

478 except Exception: 

479 payload = {} 

480 name = str((payload or {}).get('name') or '') 

481 name = name.strip() 

482 if not name: 

483 raise HTTPException(status_code=400, detail='name is required') 

484 return name 

485 

486 

487def _shares(): 

488 if api.state.playlist_shares is None: 

489 raise HTTPException(status_code=503, detail='Starting up') 

490 return api.state.playlist_shares 

491 

492 

493@router.post('/playlists/follow') 

494async def follow_playlist(request: Request) -> dict[str, Any]: 

495 """Follow a public playlist (``{name}``): it stays in your list and 

496 follows its owner's changes, until they make it private.""" 

497 

498 name = await _playlist_name(request) 

499 user_id = api.request_user_id(request) 

500 if not user_id: 

501 raise HTTPException(status_code=401, detail='Sign in required') 

502 entry = api.require_playlist_visible(name, request) 

503 if entry.get('mine') or entry.get('visibility') != 'public': 

504 raise HTTPException( 

505 status_code=400, detail='Only public playlists can be followed' 

506 ) 

507 await asyncio.to_thread(_shares().follow, user_id, entry['name'], True) 

508 await api.announce_playlists_changed() 

509 return {'name': entry['name'], 'followed': True} 

510 

511 

512@router.delete('/playlists/follow') 

513async def unfollow_playlist(request: Request) -> dict[str, Any]: 

514 """Stop following a playlist (``?name=``). Idempotent.""" 

515 

516 name = await _playlist_name(request) 

517 user_id = api.request_user_id(request) 

518 if not user_id: 

519 raise HTTPException(status_code=401, detail='Sign in required') 

520 await asyncio.to_thread(_shares().follow, user_id, name, False) 

521 await api.announce_playlists_changed() 

522 return {'name': name, 'followed': False} 

523 

524 

525@router.post('/playlists/seen') 

526async def playlist_seen(request: Request) -> dict[str, Any]: 

527 """Clear the *new* marker of a playlist shared with you (``{name}``).""" 

528 

529 name = await _playlist_name(request) 

530 user_id = api.request_user_id(request) 

531 if not user_id: 

532 raise HTTPException(status_code=401, detail='Sign in required') 

533 await asyncio.to_thread(_shares().mark_seen, name, user_id) 

534 return {'name': name, 'new': False} 

535 

536 

537@router.get('/playlists/hidden') 

538async def hidden_songs(request: Request) -> dict[str, Any]: 

539 """The songs hidden from an imported playlist of yours (``?name=``), 

540 most recently hidden first: ``{name, songs: [{key, label, track_id, 

541 hidden_at}]}``. ``track_id`` is ``''`` once the song's file is no 

542 longer in the library; ``key`` is what ``show`` takes.""" 

543 

544 name = await _playlist_name(request) 

545 found = await asyncio.to_thread(api.hidden_playlist_songs, name, request) 

546 files = [song['file'] for song in found['songs'] if song['present']] 

547 ids = await asyncio.to_thread(_sync().ids_for_paths, files) 

548 return { 

549 'name': found['name'], 

550 'songs': [ 

551 { 

552 'key': song['key'], 

553 'label': song['label'], 

554 'track_id': ids.get(song['file'], '') 

555 if song['present'] 

556 else '', 

557 'hidden_at': song['hidden_at'], 

558 } 

559 for song in found['songs'] 

560 ], 

561 } 

562 

563 

564@router.post('/playlists/hidden') 

565async def change_hidden_songs(request: Request) -> dict[str, Any]: 

566 """Hide tracks from an imported playlist of yours, or show hidden 

567 songs again: ``{name, hide: [track_ids], show: [keys]}``. A hidden 

568 song leaves the playlist and stays out when its watch or link brings 

569 it back; the track itself stays in the library. Answers ``{name, 

570 hidden, keys, shown, restored, count, track_ids}``: ``keys`` undo the 

571 hide (pass them as ``show``), ``track_ids`` are the playlist's tracks 

572 after the change.""" 

573 

574 try: 

575 payload = await request.json() 

576 except Exception: 

577 payload = {} 

578 payload = payload if isinstance(payload, dict) else {} 

579 name = str(payload.get('name') or '').strip() 

580 if not name: 

581 raise HTTPException(status_code=400, detail='name is required') 

582 paths = [ 

583 (await asyncio.to_thread(_track_path, str(track_id), request))[0][ 

584 'file' 

585 ] 

586 for track_id in _strings(payload.get('hide')) 

587 ] 

588 result = await api.change_hidden_playlist_songs( 

589 request, name, paths, _strings(payload.get('show')) 

590 ) 

591 files = list(result.get('files') or []) 

592 ids = await asyncio.to_thread(_sync().ids_for_paths, files) 

593 return { 

594 'name': result['name'], 

595 'hidden': result['hidden'], 

596 'keys': result['keys'], 

597 'shown': result['shown'], 

598 'restored': result['restored'], 

599 'count': len(files), 

600 'track_ids': [ids[f] for f in files if f in ids], 

601 } 

602 

603 

604def _strings(value: Any) -> list[str]: 

605 if not isinstance(value, list): 

606 return [] 

607 return [str(item) for item in value if str(item or '').strip()] 

608 

609 

610@router.get('/likes') 

611async def likes(request: Request) -> dict[str, Any]: 

612 """The liked tracks, most recently liked first: ``{track_ids}``.""" 

613 

614 store = api.state.likes 

615 if store is None: 

616 raise HTTPException(status_code=503, detail='Starting up') 

617 paths = await asyncio.to_thread(store.paths, api.likes_scope(request)) 

618 ids = await asyncio.to_thread(_sync().ids_for_paths, paths) 

619 return {'track_ids': [ids[p] for p in paths if p in ids]} 

620 

621 

622@router.put('/likes') 

623async def set_like(request: Request) -> dict[str, Any]: 

624 """Like or unlike a track: ``{track_id, liked}``. Idempotent.""" 

625 

626 try: 

627 payload = await request.json() 

628 except Exception: 

629 payload = {} 

630 track_id = str((payload or {}).get('track_id') or '') 

631 if not track_id: 

632 raise HTTPException(status_code=400, detail='track_id is required') 

633 row = await asyncio.to_thread(_sync().row_for, track_id) 

634 if row is None: 

635 raise HTTPException(status_code=404, detail='Track not found') 

636 liked = bool(payload.get('liked', True)) 

637 result = await api.apply_like( 

638 row['file'], liked, user_id=api.request_user_id(request) 

639 ) 

640 await api.log_activity(request, 'like' if liked else 'unlike', row['file']) 

641 return {'track_id': track_id, 'liked': result['liked']} 

642 

643 

644# ── Streaming ─────────────────────────────────────────────────────────── 

645 

646# Players (Android's included) want the registered types, not the 

647# ``audio/x-flac`` some systems' mime tables give. 

648_AUDIO_TYPES = { 

649 '.mp3': 'audio/mpeg', 

650 '.flac': 'audio/flac', 

651 '.m4a': 'audio/mp4', 

652 '.mp4': 'audio/mp4', 

653 '.ogg': 'audio/ogg', 

654 '.opus': 'audio/ogg', 

655 '.wav': 'audio/wav', 

656} 

657 

658 

659def audio_media_type(path: Path) -> str: 

660 return ( 

661 _AUDIO_TYPES.get(path.suffix.lower()) 

662 or mimetypes.guess_type(path.name)[0] 

663 or 'application/octet-stream' 

664 ) 

665 

666 

667def _download_name(row: dict[str, Any], extension: str) -> str: 

668 base = Path(row['file']).stem 

669 return f"attachment; filename*=UTF-8''{quote(base + extension)}" 

670 

671 

672async def _wait_or_disconnect( 

673 request: Request, job: asyncio.Future[Path] 

674) -> Optional[Path]: 

675 """The job's result, or ``None`` when the client went away first (the 

676 job is then cancelled, which stops ffmpeg if nobody else waits).""" 

677 

678 while True: 

679 done, _pending = await asyncio.wait({job}, timeout=0.5) 

680 if done: 

681 return job.result() 

682 if await request.is_disconnected(): 

683 job.cancel() 

684 return None 

685 

686 

687@router.api_route('/tracks/{track_id}/stream', methods=['GET', 'HEAD']) 

688async def stream( 

689 track_id: str, 

690 request: Request, 

691 fmt: str = Query('original', alias='format'), 

692 bitrate: int = Query(0), 

693 download: bool = Query(False), 

694) -> Response: 

695 """The track's audio, with HTTP Range support. 

696 

697 ``format=original`` (default) is the file as it is. ``opus``, ``aac`` 

698 or ``mp3`` with a ``bitrate`` (kbps) is a transcoded copy - unless the 

699 original is already lossy and no bigger than that, in which case the 

700 original comes back (``X-Downtify-Transcoded: no``). ``download=true`` 

701 adds a ``Content-Disposition`` for saving the file. 

702 """ 

703 

704 row, full = await asyncio.to_thread(_track_path, track_id, request) 

705 fmt = fmt.lower() 

706 headers = {'Cache-Control': _PRIVATE_CACHE} 

707 if fmt != 'original': 

708 transcoder = api.state.transcoder 

709 kbps = normalize_bitrate(bitrate) or 160 

710 if fmt not in FORMATS: 

711 raise HTTPException(status_code=400, detail='Unknown format') 

712 if transcoder is None or not transcoder.available: 

713 raise HTTPException( 

714 status_code=501, detail='Transcoding is not available' 

715 ) 

716 if not serve_original(row['codec'], int(row['bitrate']), kbps): 

717 job = asyncio.ensure_future(transcoder.get(full, fmt, kbps)) 

718 try: 

719 target = await _wait_or_disconnect(request, job) 

720 except TranscodeError as exc: 

721 raise HTTPException(status_code=500, detail=str(exc)) from exc 

722 if target is None: 

723 logger.debug( 

724 'Stream {}: client left during transcode', track_id 

725 ) 

726 return Response(status_code=499) 

727 headers['X-Downtify-Transcoded'] = f'{fmt}/{kbps}' 

728 if download: 

729 headers['Content-Disposition'] = _download_name( 

730 row, FORMATS[fmt].extension 

731 ) 

732 return FileResponse( 

733 target, media_type=FORMATS[fmt].media_type, headers=headers 

734 ) 

735 headers['X-Downtify-Transcoded'] = 'no' 

736 if download: 

737 headers['Content-Disposition'] = _download_name(row, full.suffix) 

738 return FileResponse( 

739 full, media_type=audio_media_type(full), headers=headers 

740 ) 

741 

742 

743@router.api_route('/tracks/{track_id}/cover', methods=['GET', 'HEAD']) 

744async def cover( 

745 track_id: str, request: Request, size: str = Query('') 

746) -> Response: 

747 """The track's cover: ``size=150|300|600`` (longest side, px) or full 

748 size when omitted. Cached on the server, ETag for conditional GETs.""" 

749 

750 _row, full = await asyncio.to_thread(_track_path, track_id, request) 

751 thumbs = api.state.cover_thumbs 

752 if thumbs is None: 

753 raise HTTPException(status_code=503, detail='Starting up') 

754 found = await asyncio.to_thread(thumbs.get, full, normalize_size(size)) 

755 if found is None: 

756 raise HTTPException(status_code=404, detail='No cover') 

757 data, mime, etag = found 

758 headers = {'ETag': etag, 'Cache-Control': _PRIVATE_CACHE} 

759 if request.headers.get('if-none-match') == etag: 

760 return Response(status_code=304, headers=headers) 

761 return Response(content=data, media_type=mime, headers=headers) 

762 

763 

764# ── Signed URLs ───────────────────────────────────────────────────────── 

765 

766_SIGNABLE = ( 

767 '/api/v1/tracks/', 

768 '/downloads/', 

769 '/media/', 

770 '/cover', 

771 '/playlist-cover', 

772) 

773 

774 

775@router.post('/sign') 

776async def sign(request: Request) -> dict[str, Any]: 

777 """Signed URLs for players that can't send the device token (a Cast 

778 receiver): ``{items: [{path, params}], ttl}`` -> 

779 ``{urls: [...], expires_at}``. Only for a paired app, and only for 

780 audio and cover paths; ``ttl`` is seconds (default 1 h, at most 24 h). 

781 """ 

782 

783 principal: Optional[Principal] = (request.scope.get('state') or {}).get( 

784 'principal' 

785 ) 

786 if principal is None or not principal.device_id: 

787 raise HTTPException( 

788 status_code=400, detail='Only a paired app can sign URLs' 

789 ) 

790 try: 

791 payload = await request.json() 

792 except Exception: 

793 payload = {} 

794 items = (payload or {}).get('items') 

795 if not isinstance(items, list) or not items or len(items) > 500: 

796 raise HTTPException(status_code=400, detail='items is required') 

797 try: 

798 ttl = int(payload.get('ttl') or SIGNED_URL_DEFAULT_TTL) 

799 except (TypeError, ValueError): 

800 ttl = SIGNED_URL_DEFAULT_TTL 

801 ttl = max(60, min(ttl, SIGNED_URL_MAX_TTL)) 

802 signer = api.state.auth.signer if api.state.auth else None 

803 if signer is None: 

804 raise HTTPException(status_code=503, detail='Starting up') 

805 urls = [] 

806 for item in items: 

807 path = str((item or {}).get('path') or '') 

808 params = (item or {}).get('params') or {} 

809 if not path.startswith(_SIGNABLE) or '..' in path: 

810 raise HTTPException( 

811 status_code=400, detail=f'Cannot sign {path!r}' 

812 ) 

813 if not isinstance(params, dict): 

814 raise HTTPException(status_code=400, detail='Bad params') 

815 urls.append( 

816 signer.sign_url( 

817 path, 

818 [(str(k), str(v)) for k, v in params.items()], 

819 device_id=principal.device_id, 

820 ttl=ttl, 

821 ) 

822 ) 

823 return {'urls': urls, 'expires_at': int(time.time()) + ttl} 

824 

825 

826@router.patch('/tracks/{track_id}/metadata') 

827async def edit_track_metadata( 

828 track_id: str, request: Request 

829) -> dict[str, Any]: 

830 """Edit tags on one visible track; see the batch endpoint for details.""" 

831 payload = await request.json() 

832 if not isinstance(payload, dict): 

833 raise HTTPException(status_code=422, detail='Expected an object') 

834 results = await _edit_metadata( 

835 request, 

836 [track_id], 

837 payload.get('changes'), 

838 {track_id: payload.get('revision')}, 

839 ) 

840 result = results[0] 

841 if result.get('error'): 

842 raise HTTPException( 

843 status_code=result['status'], detail=result['error'] 

844 ) 

845 return result 

846 

847 

848@router.patch('/tracks/metadata/batch') 

849async def edit_tracks_metadata(request: Request) -> dict[str, Any]: 

850 """Apply common changes to track IDs, reporting success or failure per track.""" 

851 payload = await request.json() 

852 if not isinstance(payload, dict) or not isinstance( 

853 payload.get('track_ids'), list 

854 ): 

855 raise HTTPException(status_code=422, detail='track_ids must be a list') 

856 ids = payload['track_ids'] 

857 if ( 

858 not ids 

859 or len(ids) > 500 

860 or any(not isinstance(i, str) or not i for i in ids) 

861 or len(set(ids)) != len(ids) 

862 ): 

863 raise HTTPException( 

864 status_code=422, detail='Provide 1 to 500 unique track IDs' 

865 ) 

866 revisions = payload.get('revisions', {}) 

867 if not isinstance(revisions, dict): 

868 raise HTTPException( 

869 status_code=422, detail='revisions must be an object' 

870 ) 

871 return { 

872 'results': await _edit_metadata( 

873 request, ids, payload.get('changes'), revisions 

874 ) 

875 } 

876 

877 

878async def _edit_metadata( 

879 request: Request, ids: list[str], changes: Any, revisions: dict[str, Any] 

880) -> list[dict[str, Any]]: 

881 principal = api.principal_of(request) 

882 if ( 

883 principal is None 

884 or principal.kind not in {'session', 'device', 'open'} 

885 or not api.request_user_id(request) 

886 ): 

887 raise HTTPException(status_code=401, detail='Sign in required') 

888 try: 

889 changes = validate_changes(changes) 

890 except ValueError as exc: 

891 raise HTTPException(status_code=422, detail=str(exc)) from exc 

892 await asyncio.to_thread(_refresh) 

893 results = [] 

894 changed = False 

895 for track_id in ids: 

896 try: 

897 row, full = await asyncio.to_thread(_track_path, track_id, request) 

898 file = row['file'] 

899 revision = revisions.get(track_id) 

900 if revision is not None and revision != row.get('revision'): 

901 raise HTTPException( 

902 status_code=409, 

903 detail='Track changed; reload and try again', 

904 ) 

905 old_key = content_key_for(full) or '' 

906 await asyncio.to_thread(edit_file, full, changes) 

907 changed = True 

908 new_key = content_key_for(full) or '' 

909 if old_key and new_key and old_key != new_key: 

910 await asyncio.to_thread( 

911 api.rekey_file_owners, old_key, new_key, file 

912 ) 

913 await asyncio.to_thread(api._after_replacement, file, full) 

914 changed = True 

915 results.append({'id': track_id, 'ok': True}) 

916 except HTTPException as exc: 

917 results.append({ 

918 'id': track_id, 

919 'ok': False, 

920 'status': exc.status_code, 

921 'error': exc.detail, 

922 }) 

923 except (OSError, ValueError, TypeError, KeyError) as exc: 

924 results.append({ 

925 'id': track_id, 

926 'ok': False, 

927 'status': 422, 

928 'error': str(exc), 

929 }) 

930 except Exception: 

931 logger.exception('Could not edit metadata for track {}', track_id) 

932 results.append({ 

933 'id': track_id, 

934 'ok': False, 

935 'status': 500, 

936 'error': 'Could not edit metadata', 

937 }) 

938 if changed: 

939 await asyncio.to_thread(_refresh) 

940 api.announce_library_changed() 

941 return results