Coverage for downtify/navidrome_ratings_routes.py: 92%

153 statements  

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

1"""Navidrome star ratings API (admins): run now, preview, stop, and the 

2repeat schedule. The logic is in :mod:`downtify.navidrome_ratings`. 

3 

4One job runs at a time, in a thread; the Settings page polls 

5``GET /api/navidrome/ratings`` for its progress. Every outcome is saved 

6to ``navidrome_ratings.json`` in the data directory, so the last result 

7and the time of the last real run survive a restart. 

8""" 

9 

10from __future__ import annotations 

11 

12import asyncio 

13import contextlib 

14import json 

15import os 

16import secrets 

17import threading 

18from datetime import datetime, timezone 

19from pathlib import Path 

20from typing import Any, Optional 

21 

22import httpx 

23from fastapi import APIRouter, Depends, HTTPException 

24from loguru import logger 

25from pydantic import BaseModel 

26 

27from . import api, library_only 

28from .admin_access import admin_user 

29from .navidrome import ( 

30 NavidromeClient, 

31 SubsonicError, 

32 _effective_navidrome_settings, 

33) 

34from .navidrome_ratings import ( 

35 DeezerUnavailable, 

36 RatingRun, 

37 effective_settings, 

38 next_run_at, 

39) 

40 

41router = APIRouter( 

42 prefix='/api/navidrome/ratings', dependencies=[Depends(admin_user)] 

43) 

44 

45STATE_FILE = 'navidrome_ratings.json' 

46 

47UNREADABLE_NAVIDROME = 'Navidrome sent an answer Downtify could not read' 

48 

49_lock = threading.Lock() 

50_job: dict[str, Any] = {} 

51 

52 

53class RunRequest(BaseModel): 

54 preview: bool = False 

55 skip_rated: Optional[bool] = None 

56 skip_starred: Optional[bool] = None 

57 grading: Optional[str] = None 

58 

59 

60def _now() -> str: 

61 return datetime.now(timezone.utc).isoformat() 

62 

63 

64def _data_dir() -> Path: 

65 path = api.state.settings_path 

66 return Path(path).parent if path else Path('/data') 

67 

68 

69def _read_state() -> dict[str, Any]: 

70 try: 

71 data = json.loads( 

72 (_data_dir() / STATE_FILE).read_text(encoding='utf-8') 

73 ) 

74 except (OSError, ValueError): 

75 return {} 

76 return data if isinstance(data, dict) else {} 

77 

78 

79def _write_state(data: dict[str, Any]) -> None: 

80 path = _data_dir() / STATE_FILE 

81 tmp = path.with_name(path.name + '.tmp') 

82 try: 

83 tmp.write_text(json.dumps(data), encoding='utf-8') 

84 os.replace(tmp, path) 

85 except OSError: 

86 logger.exception('ratings: could not save {}', path) 

87 with contextlib.suppress(OSError): 

88 tmp.unlink() 

89 

90 

91def _public_job() -> dict[str, Any]: 

92 return {k: v for k, v in _job.items() if k != 'cancel'} 

93 

94 

95def _navidrome_ready() -> Optional[dict[str, Any]]: 

96 cfg = _effective_navidrome_settings(api.state.settings) 

97 if cfg['enabled'] and NavidromeClient(cfg).configured(): 

98 return cfg 

99 return None 

100 

101 

102def _saved_options() -> dict[str, Any]: 

103 return effective_settings(api.state.settings.get('navidrome_ratings')) 

104 

105 

106def _finish(job: dict[str, Any]) -> None: 

107 job['finished_at'] = _now() 

108 result = job.get('result') or {} 

109 logger.info( 

110 'ratings: run {} (preview={}): rated {}, skipped {}, not found {}', 

111 job['state'], 

112 job['preview'], 

113 result.get('rated', 0), 

114 result.get('skipped', 0), 

115 result.get('not_found', 0), 

116 ) 

117 state = _read_state() 

118 state['last_run'] = {k: v for k, v in job.items() if k != 'cancel'} 

119 if not job['preview']: 

120 state['last_rating_run'] = { 

121 'started_at': job['started_at'], 

122 'finished_at': job['finished_at'], 

123 'state': job['state'], 

124 } 

125 _write_state(state) 

126 

127 

128def start_run( 

129 *, preview: bool, options: dict[str, Any], trigger: str 

130) -> dict[str, Any]: 

131 """Start the one ratings job; raises 400/409 when it cannot.""" 

132 

133 global _job 

134 with _lock: 

135 if _job.get('state') == 'running': 

136 raise HTTPException(409, detail={'code': 'ratings_busy'}) 

137 cfg = _navidrome_ready() 

138 if cfg is None: 

139 raise HTTPException( 

140 400, detail={'code': 'navidrome_not_configured'} 

141 ) 

142 job: dict[str, Any] = { 

143 'id': secrets.token_urlsafe(8), 

144 'state': 'running', 

145 'trigger': trigger, 

146 'preview': preview, 

147 'started_at': _now(), 

148 'finished_at': None, 

149 'progress': {'done': 0, 'total': 0, 'step': ''}, 

150 'result': None, 

151 'error': None, 

152 'cancel': False, 

153 } 

154 

155 logger.info( 

156 'ratings: run started (trigger={}, preview={}, options={})', 

157 trigger, 

158 preview, 

159 options, 

160 ) 

161 

162 def progress(done: int, total: int, step: str) -> None: 

163 job['progress'] = {'done': done, 'total': total, 'step': step} 

164 

165 async def work() -> None: 

166 try: 

167 run = RatingRun( 

168 NavidromeClient(cfg), 

169 options, 

170 preview=preview, 

171 cancelled=lambda: bool(job['cancel']), 

172 progress=progress, 

173 ) 

174 result = await asyncio.to_thread(run.run) 

175 job['state'] = result['state'] 

176 job['result'] = result 

177 except asyncio.CancelledError: 

178 # Shutdown mid-run: record it, then let the cancel go on. 

179 job['state'] = 'stopped' 

180 _finish(job) 

181 raise 

182 except DeezerUnavailable as exc: 

183 _fail(job, 'deezer_unreachable', str(exc)) 

184 except (SubsonicError, httpx.HTTPError) as exc: 

185 _fail(job, 'navidrome_failed', _navidrome_message(exc)) 

186 except ValueError: 

187 # Navidrome's "Invalid Subsonic response", or a proxy's 

188 # login page that is not JSON. 

189 _fail(job, 'navidrome_failed', UNREADABLE_NAVIDROME) 

190 except Exception as exc: 

191 logger.exception('ratings: run failed') 

192 _fail(job, 'ratings_failed', str(exc)) 

193 _finish(job) 

194 

195 # Raises the library-only 409 itself (and closes the coroutine). 

196 api.spawn_task(work(), name='navidrome-ratings') 

197 _job = job 

198 return _public_job() 

199 

200 

201def _navidrome_message(exc: Exception) -> str: 

202 """A message for a Navidrome failure that never holds a URL (the 

203 request URL carries the Subsonic token and salt).""" 

204 

205 if isinstance(exc, SubsonicError): 

206 return str(exc)[:160] 

207 if isinstance(exc, httpx.HTTPStatusError): 

208 return f'HTTP {exc.response.status_code}' 

209 return f'Could not reach Navidrome ({type(exc).__name__})' 

210 

211 

212def _fail(job: dict[str, Any], code: str, message: str) -> None: 

213 job['state'] = 'failed' 

214 job['error'] = {'code': code, 'message': message} 

215 logger.warning('ratings: run failed ({}): {}', code, message) 

216 

217 

218def maybe_start_scheduled(now: datetime) -> bool: 

219 """Start a scheduled run when one is due; whether it did.""" 

220 

221 options = _saved_options() 

222 if options['repeat'] == 'off': 

223 return False 

224 if _navidrome_ready() is None: 

225 return False 

226 if library_only.enabled(api.state.settings) or _job.get('state') == ( 

227 'running' 

228 ): 

229 return False 

230 due = next_run_at(options, _read_state().get('last_rating_run')) 

231 if due is None or due > now: 

232 return False 

233 try: 

234 start_run(preview=False, options=options, trigger='schedule') 

235 except HTTPException as exc: 

236 logger.info('ratings: scheduled run not started: {}', exc.detail) 

237 return False 

238 return True 

239 

240 

241async def schedule_loop( 

242 *, first_delay: float = 600, interval: float = 3600 

243) -> None: 

244 """Check hourly whether a scheduled run is due.""" 

245 

246 await asyncio.sleep(first_delay) 

247 while True: 

248 try: 

249 maybe_start_scheduled(datetime.now(timezone.utc)) 

250 except Exception: 

251 logger.exception('ratings: schedule check failed') 

252 await asyncio.sleep(interval) 

253 

254 

255@router.get('') 

256async def ratings_status() -> dict[str, Any]: 

257 """The running or last job, the saved last result and the next run.""" 

258 

259 state = _read_state() 

260 due = None 

261 if _navidrome_ready() is not None and not library_only.enabled( 

262 api.state.settings 

263 ): 

264 due = next_run_at(_saved_options(), state.get('last_rating_run')) 

265 return { 

266 'job': _public_job() or None, 

267 'last': state.get('last_run'), 

268 'next_run_at': due.isoformat() if due else None, 

269 } 

270 

271 

272@router.post('/run') 

273async def ratings_run(body: RunRequest) -> dict[str, Any]: 

274 given = { 

275 k: v 

276 for k, v in body.model_dump().items() 

277 if v is not None and k != 'preview' 

278 } 

279 options = effective_settings({**_saved_options(), **given}) 

280 return start_run(preview=body.preview, options=options, trigger='manual') 

281 

282 

283@router.post('/cancel') 

284async def ratings_cancel() -> dict[str, Any]: 

285 if _job: 

286 _job['cancel'] = True 

287 return _public_job()