Coverage for downtify/account_routes.py: 88%

256 statements  

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

1"""HTTP routes for accounts: your own, everyone's (admins), and activity. 

2 

3* ``/api/me...`` - the signed-in user: who they are, their username, 

4 password, preferences (Settings > General) and signing out everywhere. 

5* ``/api/users...`` - admins manage every account. 

6* ``/api/activity...`` - admins read the activity log and see what is 

7 playing; every player reports what it plays to 

8 ``POST /api/activity/playback``. 

9 

10Who may call what is in :data:`downtify.auth.RULES`; the routes here 

11only check *whose* data it is. Stores: :mod:`downtify.users`, 

12:mod:`downtify.activity`. 

13""" 

14 

15from __future__ import annotations 

16 

17import asyncio 

18from typing import Any 

19 

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

21from loguru import logger 

22 

23from . import api 

24from .activity import KINDS, clean_track, track_label 

25from .auth import SESSION_COOKIE, AuthStore, Principal, session_cookie 

26from .library_catalog import entry_content_key, listing_for_request 

27from .monitor import delete_user_watches 

28from .users import ROLE_USER, UserError, UserStore 

29 

30router = APIRouter() 

31 

32 

33def _store() -> AuthStore: 

34 if api.state.auth is None: 

35 raise HTTPException(status_code=500, detail='Sign-in is not ready') 

36 return api.state.auth 

37 

38 

39def _users() -> UserStore: 

40 return _store().users 

41 

42 

43def _accounts_on() -> None: 

44 """409 when accounts are turned off (``DOWNTIFY_DISABLE_AUTH``): 

45 there is one user and no password to manage.""" 

46 

47 if _store().auth_disabled: 

48 raise HTTPException( 

49 status_code=409, 

50 detail='Accounts are turned off (DOWNTIFY_DISABLE_AUTH)', 

51 ) 

52 

53 

54def _me(request: Request) -> Principal: 

55 principal = api.principal_of(request) 

56 if principal is None or not principal.user_id: 

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

58 return principal 

59 

60 

61async def _json(request: Request) -> dict[str, Any]: 

62 try: 

63 payload = await request.json() 

64 except Exception: 

65 return {} 

66 return payload if isinstance(payload, dict) else {} 

67 

68 

69def _bad(exc: UserError) -> HTTPException: 

70 return HTTPException(status_code=400, detail=str(exc)) 

71 

72 

73async def _sign_out_user(user_id: int, keep_session: str = '') -> None: 

74 """Unpair *user_id*'s devices and end their sessions but 

75 *keep_session*, closing their sockets.""" 

76 

77 devices = await asyncio.to_thread( 

78 _store().revoke_user, user_id, keep_session 

79 ) 

80 for device_id in devices: 

81 await api.state.connections.close_device(device_id) 

82 if not keep_session: 

83 await api.state.connections.close_user(user_id) 

84 

85 

86# ── You ───────────────────────────────────────────────────────────────── 

87 

88 

89@router.get('/api/me') 

90def get_me(request: Request) -> dict[str, Any]: 

91 """``{user, preferences, playlist_sharing}`` for whoever is signed 

92 in (a browser or a paired app); ``playlist_sharing`` is whether the 

93 admin lets users share playlists.""" 

94 

95 me = _me(request) 

96 user = _users().get(me.user_id) 

97 if user is None: 

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

99 return { 

100 'user': user, 

101 'preferences': _users().preferences(me.user_id), 

102 'playlist_sharing': api.sharing_enabled(), 

103 } 

104 

105 

106@router.patch('/api/me') 

107async def update_me(request: Request) -> dict[str, Any]: 

108 """Change your own username: ``{username}``.""" 

109 

110 _accounts_on() 

111 me = _me(request) 

112 payload = await _json(request) 

113 try: 

114 user = await asyncio.to_thread( 

115 _users().update, me.user_id, username=payload.get('username') 

116 ) 

117 except UserError as exc: 

118 raise _bad(exc) from exc 

119 if user['username'] != me.username: 

120 await api.log_activity( 

121 request, 

122 'user_updated', 

123 user['username'], 

124 {'from': me.username, 'to': user['username']}, 

125 ) 

126 return {'user': user} 

127 

128 

129@router.put('/api/me/password') 

130async def change_my_password(request: Request) -> dict[str, Any]: 

131 """Change your password: ``{current_password, new_password}``. Every 

132 other browser and app of yours stays signed in; use 

133 ``POST /api/me/sign-out-everywhere`` for that.""" 

134 

135 _accounts_on() 

136 me = _me(request) 

137 ip = api.request_ip(request) 

138 limiter = api.state.login_limiter 

139 wait = limiter.retry_after(ip) 

140 if wait: 

141 raise HTTPException( 

142 status_code=429, 

143 detail='Too many attempts. Try again later.', 

144 headers={'Retry-After': str(wait)}, 

145 ) 

146 payload = await _json(request) 

147 current = str(payload.get('current_password') or '') 

148 if not await asyncio.to_thread( 

149 _users().check_password, me.user_id, current 

150 ): 

151 limiter.fail(ip) 

152 raise HTTPException( 

153 status_code=403, detail='The current password is wrong' 

154 ) 

155 try: 

156 await asyncio.to_thread( 

157 _users().set_password, 

158 me.user_id, 

159 payload.get('new_password'), 

160 ) 

161 except UserError as exc: 

162 raise _bad(exc) from exc 

163 await api.log_activity(request, 'password_changed', me.username) 

164 user = await asyncio.to_thread(_users().get, me.user_id) 

165 return {'user': user} 

166 

167 

168@router.get('/api/me/preferences') 

169def get_my_preferences(request: Request) -> dict[str, Any]: 

170 return _users().preferences(_me(request).user_id) 

171 

172 

173@router.put('/api/me/preferences') 

174async def set_my_preferences(request: Request) -> dict[str, Any]: 

175 """Merge ``{theme, locale, show_lyrics, search_albums, 

176 show_public_playlists}`` (any of them) 

177 into your preferences; the result. Yours only - nobody else's 

178 Downtify changes.""" 

179 

180 me = _me(request) 

181 payload = await _json(request) 

182 return await asyncio.to_thread( 

183 _users().set_preferences, me.user_id, payload 

184 ) 

185 

186 

187@router.post('/api/me/sign-out-everywhere') 

188async def sign_out_everywhere( 

189 request: Request, response: Response 

190) -> dict[str, Any]: 

191 """Unpair every app of yours and sign out every browser of yours, 

192 this one included.""" 

193 

194 _accounts_on() 

195 me = _me(request) 

196 await _sign_out_user(me.user_id) 

197 api.state.now_playing.forget_user(me.user_id) 

198 response.delete_cookie(SESSION_COOKIE, path='/') 

199 logger.info('User {} signed out everywhere', me.username) 

200 return {'revoked': True} 

201 

202 

203# ── Everyone (admins) ─────────────────────────────────────────────────── 

204 

205 

206def _with_devices(users: list[dict[str, Any]]) -> list[dict[str, Any]]: 

207 counts: dict[int, int] = {} 

208 for device in _store().list_devices(): 

209 uid = int(device['user_id']) 

210 counts[uid] = counts.get(uid, 0) + 1 

211 return [{**u, 'devices': counts.get(u['id'], 0)} for u in users] 

212 

213 

214@router.get('/api/users') 

215def list_users() -> list[dict[str, Any]]: 

216 """Every account, with how many apps each has paired.""" 

217 

218 _accounts_on() 

219 return _with_devices(_users().list()) 

220 

221 

222@router.post('/api/users') 

223async def create_user(request: Request) -> dict[str, Any]: 

224 """Add an account: ``{username, password, role}`` (``admin`` or 

225 ``user``, default ``user``).""" 

226 

227 _accounts_on() 

228 payload = await _json(request) 

229 try: 

230 user = await asyncio.to_thread( 

231 _users().create, 

232 payload.get('username'), 

233 payload.get('password'), 

234 str(payload.get('role') or ROLE_USER), 

235 ) 

236 except UserError as exc: 

237 raise _bad(exc) from exc 

238 await api.log_activity( 

239 request, 'user_created', user['username'], {'role': user['role']} 

240 ) 

241 logger.info('Created user {} ({})', user['username'], user['role']) 

242 return user 

243 

244 

245@router.patch('/api/users/{user_id}') 

246async def update_user(user_id: int, request: Request) -> dict[str, Any]: 

247 """Change an account: any of ``{username, role, password}``. A new 

248 password signs that user out of every browser (but this one, when 

249 it's your own) - their paired apps stay paired.""" 

250 

251 _accounts_on() 

252 me = _me(request) 

253 payload = await _json(request) 

254 before = await asyncio.to_thread(_users().get, user_id) 

255 if before is None: 

256 raise HTTPException(status_code=404, detail='User not found') 

257 try: 

258 user = await asyncio.to_thread( 

259 _users().update, 

260 user_id, 

261 username=payload.get('username'), 

262 role=payload.get('role'), 

263 ) 

264 if payload.get('password'): 

265 await asyncio.to_thread( 

266 _users().set_password, user_id, payload.get('password') 

267 ) 

268 keep = ( 

269 session_cookie(request.scope) if user_id == me.user_id else '' 

270 ) 

271 await asyncio.to_thread(_store().end_user_sessions, user_id, keep) 

272 await api.log_activity( 

273 request, 'password_changed', user['username'] 

274 ) 

275 except UserError as exc: 

276 raise _bad(exc) from exc 

277 changes = { 

278 key: {'from': before[key], 'to': user[key]} 

279 for key in ('username', 'role') 

280 if before[key] != user[key] 

281 } 

282 if changes: 

283 await api.log_activity( 

284 request, 'user_updated', user['username'], changes 

285 ) 

286 found = await asyncio.to_thread(_users().get, user_id) 

287 return found or user 

288 

289 

290@router.delete('/api/users/{user_id}') 

291async def delete_user(user_id: int, request: Request) -> dict[str, Any]: 

292 """Delete an account: its apps are unpaired and its browsers signed 

293 out. Not your own, and not the last admin.""" 

294 

295 _accounts_on() 

296 me = _me(request) 

297 if user_id == me.user_id: 

298 raise HTTPException( 

299 status_code=400, detail='You cannot delete your own account' 

300 ) 

301 try: 

302 user = await asyncio.to_thread(_users().delete, user_id) 

303 except UserError as exc: 

304 status = 404 if 'not found' in str(exc) else 400 

305 raise HTTPException(status_code=status, detail=str(exc)) from exc 

306 await _sign_out_user(user_id) 

307 api.state.now_playing.forget_user(user_id) 

308 await asyncio.to_thread(_forget_user_library, user_id) 

309 await api.log_activity(request, 'user_deleted', user['username']) 

310 logger.info('Deleted user {}', user['username']) 

311 return {'id': user_id, 'deleted': True} 

312 

313 

314@router.get('/api/users/stats') 

315async def user_library_stats(request: Request) -> dict[str, Any]: 

316 """Per-account usage for Settings → Users (admins): tracks and bytes 

317 owned, likes, playlists, downloads ordered and traffic both ways, 

318 plus the totals across everyone.""" 

319 

320 _me(request) 

321 return await asyncio.to_thread(_build_user_stats) 

322 

323 

324def _build_user_stats() -> dict[str, Any]: 

325 users = _users().list() 

326 try: 

327 entries = listing_for_request(api.library_context()) 

328 except Exception: 

329 entries = [] 

330 live: dict[str, int] = {} 

331 for entry in entries: 

332 try: 

333 live[entry_content_key(entry)] = int(entry.get('size') or 0) 

334 except (TypeError, ValueError): 

335 continue 

336 live.pop('', None) 

337 owners = api.state.track_owners 

338 owned: dict[int, set[str]] = {} 

339 if owners is not None: 

340 for user in users: 

341 try: 

342 owned[user['id']] = owners.owned_keys(user['id']) 

343 except Exception: 

344 owned[user['id']] = set() 

345 likes = ( 

346 api.state.likes.count_by_user() if api.state.likes is not None else {} 

347 ) 

348 playlists: dict[int, int] = {} 

349 catalog = api.state.playlist_catalog 

350 if catalog is not None: 

351 try: 

352 for uid in catalog.playlist_owner_map().values(): 

353 playlists[int(uid)] = playlists.get(int(uid), 0) + 1 

354 except Exception: 

355 logger.opt(exception=True).debug( 

356 'Could not count catalog playlists per user' 

357 ) 

358 manual = api.state.manual_playlist_owners 

359 if manual is not None: 

360 try: 

361 for uid in manual.owner_map().values(): 

362 playlists[int(uid)] = playlists.get(int(uid), 0) + 1 

363 except Exception: 

364 logger.opt(exception=True).debug( 

365 'Could not count manual playlists per user' 

366 ) 

367 traffic = ( 

368 api.state.traffic.totals() if api.state.traffic is not None else {} 

369 ) 

370 rows = [] 

371 for user in users: 

372 uid = user['id'] 

373 keys = owned.get(uid, set()) & live.keys() 

374 flow = traffic.get(uid, {}) 

375 rows.append({ 

376 'id': uid, 

377 'username': user['username'], 

378 'role': user['role'], 

379 'tracks': len(keys), 

380 'bytes': sum(live[key] for key in keys), 

381 'likes': likes.get(uid, 0), 

382 'playlists': playlists.get(uid, 0), 

383 'downloads': len(owned.get(uid, set())), 

384 'traffic_in': flow.get('in', 0), 

385 'traffic_out': flow.get('out', 0), 

386 }) 

387 return { 

388 'users': rows, 

389 'totals': { 

390 'users': len(rows), 

391 'tracks': len(live), 

392 'bytes': sum(live.values()), 

393 'likes': sum(likes.values()), 

394 'playlists': sum(playlists.values()), 

395 'downloads': sum(len(keys) for keys in owned.values()), 

396 'traffic_in': sum(flow.get('in', 0) for flow in traffic.values()), 

397 'traffic_out': sum( 

398 flow.get('out', 0) for flow in traffic.values() 

399 ), 

400 }, 

401 } 

402 

403 

404def _forget_user_library(user_id: int) -> None: 

405 """Release a deleted account's library: track ownership, likes, 

406 manual playlists, podcast shows, watches, listens and traffic. 

407 Files stay on disk (now admin-visible).""" 

408 

409 try: 

410 if api.state.track_owners is not None: 

411 api.state.track_owners.remove_user(user_id) 

412 if api.state.likes is not None: 

413 api.state.likes.remove_user(user_id) 

414 if api.state.manual_playlist_owners is not None: 

415 api.state.manual_playlist_owners.remove_user(user_id) 

416 if api.state.playlist_shares is not None: 

417 api.state.playlist_shares.remove_user(user_id) 

418 if api.state.podcasts is not None: 

419 api.state.podcasts.remove_user(user_id) 

420 if api.state.discover is not None: 

421 api.state.discover.remove_user(user_id) 

422 if api.state.traffic is not None: 

423 api.state.traffic.remove_user(user_id) 

424 if api.state.monitor_db is not None: 

425 delete_user_watches(api.state.monitor_db, user_id) 

426 except Exception: 

427 logger.opt(exception=True).warning( 

428 'Could not release the library of deleted user {}', user_id 

429 ) 

430 

431 

432# ── Activity ──────────────────────────────────────────────────────────── 

433 

434 

435@router.get('/api/activity') 

436def get_activity( 

437 limit: int = Query(100, ge=1, le=200), 

438 before: int = Query(0, ge=0), 

439 user_id: int = Query(0, ge=0), 

440 kind: str = Query(''), 

441) -> dict[str, Any]: 

442 """The activity log, newest first: ``{entries, next}``. ``kind`` is 

443 one kind or several, comma-separated; ``next`` goes in ``before`` 

444 for the next page (``0``: there is none).""" 

445 

446 log = api.state.activity 

447 if log is None: 

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

449 kinds = [k for k in kind.split(',') if k in KINDS] if kind else None 

450 return log.entries( 

451 limit=limit, before=before, user_id=user_id, kinds=kinds 

452 ) 

453 

454 

455@router.get('/api/activity/now') 

456def now_playing() -> list[dict[str, Any]]: 

457 """What every browser and app is playing now (heard from in the last 

458 90 seconds), playing ones first.""" 

459 

460 return api.state.now_playing.active() 

461 

462 

463@router.post('/api/activity/playback') 

464async def report_playback(request: Request) -> dict[str, Any]: 

465 """A player says what it's playing: ``{player, state, track, 

466 position}`` - ``player`` any id stable for this player (a browser 

467 tab, an app install), ``state`` ``playing``, ``paused`` or 

468 ``stopped``, ``track`` ``{title, artist, album, file | track_id, 

469 duration, cover}``. Send it when a song starts, on pause/resume and 

470 stop, and about every 30 s while playing.""" 

471 

472 me = _me(request) 

473 payload = await _json(request) 

474 state = str(payload.get('state') or 'playing') 

475 if state not in {'playing', 'paused', 'stopped'}: 

476 raise HTTPException(status_code=400, detail='Unknown state') 

477 track = clean_track(payload.get('track')) 

478 if state != 'stopped' and not (track.get('file') or track.get('track_id')): 

479 raise HTTPException(status_code=400, detail='track is required') 

480 try: 

481 position = float(payload.get('position') or 0) 

482 except (TypeError, ValueError): 

483 position = 0.0 

484 client = await asyncio.to_thread(api.client_label, request, me) 

485 player = str(payload.get('player') or me.device_id or 'web')[:64] 

486 started = api.state.now_playing.report( 

487 user_id=me.user_id, 

488 username=me.username, 

489 player=f'{me.device_id}:{player}', 

490 client=client, 

491 state=state, 

492 track=track, 

493 position=position, 

494 ip=api.request_ip(request), 

495 ) 

496 if started: 

497 await api.log_activity( 

498 request, 'playback', track_label(track), {'track': track} 

499 ) 

500 return {'ok': True}