Coverage for downtify/activity.py: 96%

138 statements  

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

1"""What users do on the server: the activity log and who's playing what. 

2 

3Admins see both in Settings > Activity (``GET /api/activity``, 

4``GET /api/activity/now``), much like a Jellyfin dashboard: 

5 

6* :class:`ActivityLog` - a history kept in ``<data>/downtify_activity.db``: 

7 sign-ins (and failed ones), sign-outs, songs started, downloads asked 

8 for, likes, deleted files, tracks whose audio was replaced, apps paired and unpaired, accounts created, 

9 changed and deleted, settings saved. Entries older than 

10 :data:`RETENTION_DAYS` are dropped. 

11* :class:`NowPlaying` - kept in memory: what each browser tab and app is 

12 playing right now, from the reports players send to 

13 ``POST /api/activity/playback`` while they play. A player that stops 

14 reporting drops off after :data:`NOW_PLAYING_TIMEOUT` seconds. 

15""" 

16 

17from __future__ import annotations 

18 

19import json 

20import re 

21import threading 

22import time 

23from contextlib import AbstractContextManager 

24from datetime import datetime, timedelta, timezone 

25from pathlib import Path 

26from typing import Any, Optional 

27 

28from .db.config import Dialect 

29from .db.core import Connection, Database, as_database 

30 

31#: How long entries are kept. 

32RETENTION_DAYS = 90 

33#: A player that hasn't reported for this long isn't playing any more. 

34NOW_PLAYING_TIMEOUT = 90 

35#: Longest page of entries one request gets. 

36MAX_PAGE = 200 

37 

38#: What entries record (``kind``). 

39KINDS = ( 

40 'login', 

41 'login_failed', 

42 'logout', 

43 'playback', 

44 'download', 

45 'like', 

46 'unlike', 

47 'delete', 

48 'audio_replaced', 

49 'album_compilation', 

50 'library_hidden', 

51 'library_shown', 

52 'device_paired', 

53 'device_unpaired', 

54 'user_created', 

55 'user_updated', 

56 'user_deleted', 

57 'password_changed', 

58 'settings_changed', 

59) 

60 

61_PRUNE_EVERY = 500 

62 

63 

64def _now() -> datetime: 

65 return datetime.now(timezone.utc) 

66 

67 

68def _clip(value: Any, length: int) -> str: 

69 return str(value or '')[:length] 

70 

71 

72def describe_user_agent(user_agent: str) -> str: 

73 """``Firefox on Linux``-style label for a browser, or ``''``.""" 

74 

75 ua = user_agent or '' 

76 browser = '' 

77 for name, pattern in ( 

78 ('Edge', r'Edg/'), 

79 ('Opera', r'OPR/'), 

80 ('Firefox', r'Firefox/'), 

81 ('Chrome', r'Chrome/'), 

82 ('Safari', r'Safari/'), 

83 ): 

84 if re.search(pattern, ua): 

85 browser = name 

86 break 

87 system = '' 

88 for name, pattern in ( 

89 ('Android', r'Android'), 

90 ('iOS', r'iPhone|iPad'), 

91 ('Windows', r'Windows'), 

92 ('macOS', r'Mac OS X'), 

93 ('Linux', r'Linux'), 

94 ): 

95 if re.search(pattern, ua): 

96 system = name 

97 break 

98 if browser and system: 

99 return f'{browser} on {system}' 

100 return browser or system 

101 

102 

103def track_label(track: dict[str, Any]) -> str: 

104 """``Artist - Title`` (or whichever of the two is known).""" 

105 

106 title = str(track.get('title') or '').strip() 

107 artist = str(track.get('artist') or '').strip() 

108 if title and artist: 

109 return f'{artist} - {title}' 

110 return title or artist or str(track.get('file') or '').strip() 

111 

112 

113class ActivityLog: 

114 """The history of what users did, newest first.""" 

115 

116 def __init__(self, db_path: str | Path | Database) -> None: 

117 self.db = as_database(db_path, 'activity') 

118 self._path = None if self.db.path is None else str(self.db.path) 

119 self._lock = threading.Lock() 

120 self._since_prune = 0 

121 if self.db.dialect is Dialect.SQLITE: 

122 self._init_db() 

123 self.prune() 

124 

125 def _init_db(self) -> None: 

126 # SQLite only: on PostgreSQL the migration made this schema. 

127 with self._connect() as conn: 

128 conn.execute(""" 

129 CREATE TABLE IF NOT EXISTS activity ( 

130 id INTEGER PRIMARY KEY AUTOINCREMENT, 

131 at TEXT NOT NULL, 

132 user_id INTEGER NOT NULL DEFAULT 0, 

133 username TEXT NOT NULL DEFAULT '', 

134 kind TEXT NOT NULL, 

135 summary TEXT NOT NULL DEFAULT '', 

136 detail_json TEXT NOT NULL DEFAULT '{}', 

137 client TEXT NOT NULL DEFAULT '', 

138 ip TEXT NOT NULL DEFAULT '' 

139 ) 

140 """) 

141 conn.execute( 

142 'CREATE INDEX IF NOT EXISTS activity_user ' 

143 'ON activity (user_id, id)' 

144 ) 

145 

146 def _connect(self) -> AbstractContextManager[Connection]: 

147 return self.db.connect() 

148 

149 def record( 

150 self, 

151 kind: str, 

152 *, 

153 user_id: int = 0, 

154 username: str = '', 

155 summary: str = '', 

156 detail: Optional[dict[str, Any]] = None, 

157 client: str = '', 

158 ip: str = '', 

159 ) -> None: 

160 """Add an entry. *summary* is the one line shown for it (a song, 

161 a file, a username); *detail* anything else worth keeping.""" 

162 

163 with self._connect() as conn: 

164 conn.execute( 

165 'INSERT INTO activity (at, user_id, username, kind, ' 

166 'summary, detail_json, client, ip) ' 

167 'VALUES (?, ?, ?, ?, ?, ?, ?, ?)', 

168 ( 

169 _now().isoformat(), 

170 int(user_id or 0), 

171 _clip(username, 64), 

172 _clip(kind, 32), 

173 _clip(summary, 300), 

174 json.dumps(detail or {})[:4000], 

175 _clip(client, 100), 

176 _clip(ip, 64), 

177 ), 

178 ) 

179 with self._lock: 

180 self._since_prune += 1 

181 due = self._since_prune >= _PRUNE_EVERY 

182 if due: 

183 self._since_prune = 0 

184 if due: 

185 self.prune() 

186 

187 def entries( 

188 self, 

189 *, 

190 limit: int = 100, 

191 before: int = 0, 

192 user_id: int = 0, 

193 kinds: Optional[list[str]] = None, 

194 ) -> dict[str, Any]: 

195 """A page of entries, newest first: ``{entries, next}`` - pass 

196 ``next`` as *before* for the page after (``0`` at the end).""" 

197 

198 limit = max(1, min(int(limit), MAX_PAGE)) 

199 where = ['1 = 1'] 

200 args: list[Any] = [] 

201 if before: 

202 where.append('id < ?') 

203 args.append(int(before)) 

204 if user_id: 

205 where.append('user_id = ?') 

206 args.append(int(user_id)) 

207 if kinds: 

208 where.append(f'kind IN ({", ".join("?" for _ in kinds)})') 

209 args.extend(kinds) 

210 with self._connect() as conn: 

211 rows = conn.execute( 

212 f'SELECT * FROM activity WHERE {" AND ".join(where)} ' 

213 'ORDER BY id DESC LIMIT ?', 

214 (*args, limit + 1), 

215 ).fetchall() 

216 entries = [self._entry(row) for row in rows[:limit]] 

217 more = len(rows) > limit 

218 return { 

219 'entries': entries, 

220 'next': entries[-1]['id'] if more and entries else 0, 

221 } 

222 

223 @staticmethod 

224 def _entry(row: Any) -> dict[str, Any]: 

225 try: 

226 detail = json.loads(row['detail_json']) 

227 except ValueError: 

228 detail = {} 

229 return { 

230 'id': int(row['id']), 

231 'at': row['at'], 

232 'user_id': int(row['user_id']), 

233 'username': row['username'], 

234 'kind': row['kind'], 

235 'summary': row['summary'], 

236 'detail': detail, 

237 'client': row['client'], 

238 'ip': row['ip'], 

239 } 

240 

241 def prune(self, days: int = RETENTION_DAYS) -> int: 

242 cutoff = (_now() - timedelta(days=days)).isoformat() 

243 with self._connect() as conn: 

244 return conn.execute( 

245 'DELETE FROM activity WHERE at < ?', (cutoff,) 

246 ).rowcount 

247 

248 

249class NowPlaying: 

250 """What each player is playing, from its reports. In memory only.""" 

251 

252 def __init__(self, timeout: float = NOW_PLAYING_TIMEOUT) -> None: 

253 self._timeout = timeout 

254 self._lock = threading.Lock() 

255 # (user_id, player key) -> entry 

256 self._players: dict[tuple[int, str], dict[str, Any]] = {} 

257 

258 def report( 

259 self, 

260 *, 

261 user_id: int, 

262 username: str, 

263 player: str, 

264 client: str, 

265 state: str, 

266 track: dict[str, Any], 

267 position: float = 0.0, 

268 ip: str = '', 

269 ) -> bool: 

270 """Note a player's report; whether it started a new song (the 

271 caller logs that). *state* ``stopped`` removes the player.""" 

272 

273 key = (int(user_id), player) 

274 now = time.monotonic() 

275 with self._lock: 

276 self._drop_stale(now) 

277 if state == 'stopped': 

278 self._players.pop(key, None) 

279 return False 

280 previous = self._players.get(key) 

281 song = str(track.get('track_id') or track.get('file') or '') 

282 started = previous is None or previous['song'] != song 

283 self._players[key] = { 

284 'user_id': int(user_id), 

285 'username': username, 

286 'client': client, 

287 'ip': ip, 

288 'song': song, 

289 'track': track, 

290 'paused': state == 'paused', 

291 'position': max(0.0, float(position or 0)), 

292 'seen': now, 

293 'started_at': ( 

294 _now().isoformat() if started else previous['started_at'] 

295 ), 

296 } 

297 return started and state == 'playing' 

298 

299 def _drop_stale(self, now: float) -> None: 

300 for key, entry in list(self._players.items()): 

301 if now - entry['seen'] > self._timeout: 

302 del self._players[key] 

303 

304 def forget_user(self, user_id: int) -> None: 

305 with self._lock: 

306 for key in [k for k in self._players if k[0] == user_id]: 

307 del self._players[key] 

308 

309 def active(self) -> list[dict[str, Any]]: 

310 """Players heard from lately, playing ones first.""" 

311 

312 now = time.monotonic() 

313 with self._lock: 

314 self._drop_stale(now) 

315 entries = [ 

316 { 

317 'user_id': e['user_id'], 

318 'username': e['username'], 

319 'client': e['client'], 

320 'ip': e['ip'], 

321 'track': e['track'], 

322 'paused': e['paused'], 

323 'position': e['position'], 

324 'started_at': e['started_at'], 

325 'seconds_ago': int(now - e['seen']), 

326 } 

327 for e in self._players.values() 

328 ] 

329 return sorted( 

330 entries, key=lambda e: (e['paused'], e['username'].lower()) 

331 ) 

332 

333 

334def clean_track(value: Any) -> dict[str, Any]: 

335 """The track a player reports, reduced to what's shown.""" 

336 

337 if not isinstance(value, dict): 

338 return {} 

339 track: dict[str, Any] = { 

340 key: _clip(value.get(key), 300) 

341 for key in ('title', 'artist', 'album', 'file', 'track_id', 'cover') 

342 if value.get(key) 

343 } 

344 try: 

345 duration = float(value.get('duration') or 0) 

346 except (TypeError, ValueError): 

347 duration = 0.0 

348 if duration > 0: 

349 track['duration'] = round(duration, 1) 

350 return track