Coverage for downtify/slskd_misses.py: 100%

36 statements  

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

1"""Why slskd wasn't used: the reasons downloads fell through to another 

2source. 

3 

4With slskd first in the source order, every song it can't serve is 

5fetched by the next source (YouTube Music, YouTube...) or fails. The 

6downloader carries the reason slskd gave up (``song['slskd_miss']``, see 

7``slskd_provider.take_miss``) to ``Downloader.on_outcome``, and 

8``api.record_download_outcome`` keeps one row here per such download: 

9when, why, what was used instead (``fallback``, ``''`` when nothing was 

10found anywhere) and the song. ``GET /api/slskd/misses`` counts them by 

11reason; ``DELETE /api/slskd/misses`` starts the count over, so the effect 

12of a settings change shows on its own. 

13""" 

14 

15from __future__ import annotations 

16 

17from collections import Counter 

18from datetime import datetime, timedelta, timezone 

19from pathlib import Path 

20from typing import Any 

21 

22from .db.config import Dialect 

23from .db.core import Database, as_database 

24 

25#: Like the download log: long enough for a year's view. 

26RETENTION_DAYS = 400 

27#: How many recent songs the summary lists. 

28RECENT = 50 

29 

30 

31def _now() -> datetime: 

32 return datetime.now(timezone.utc) 

33 

34 

35class SlskdMisses: 

36 """The ``slskd_misses`` table of ``downtify_library.db``.""" 

37 

38 def __init__(self, path_or_db: str | Path | Database) -> None: 

39 self.db = as_database(path_or_db, 'library') 

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

41 self._init_db() 

42 

43 def _init_db(self) -> None: 

44 # On PostgreSQL migration 0004 created it. 

45 with self.db.connect() as conn: 

46 conn.execute(""" 

47 CREATE TABLE IF NOT EXISTS slskd_misses ( 

48 id INTEGER PRIMARY KEY AUTOINCREMENT, 

49 at TEXT NOT NULL, 

50 reason TEXT NOT NULL, 

51 detail TEXT NOT NULL DEFAULT '', 

52 fallback TEXT NOT NULL DEFAULT '', 

53 title TEXT NOT NULL DEFAULT '', 

54 artist TEXT NOT NULL DEFAULT '' 

55 ) 

56 """) 

57 conn.execute( 

58 'CREATE INDEX IF NOT EXISTS idx_slskd_misses_at ' 

59 'ON slskd_misses (at)' 

60 ) 

61 

62 def record( 

63 self, 

64 reason: str, 

65 *, 

66 detail: str = '', 

67 fallback: str = '', 

68 title: str = '', 

69 artist: str = '', 

70 ) -> None: 

71 with self.db.connect() as conn: 

72 conn.execute( 

73 'INSERT INTO slskd_misses ' 

74 '(at, reason, detail, fallback, title, artist) ' 

75 'VALUES (?, ?, ?, ?, ?, ?)', 

76 ( 

77 _now().isoformat(), 

78 str(reason or 'unknown')[:40], 

79 str(detail or '')[:200], 

80 str(fallback or '')[:40], 

81 str(title or '')[:200], 

82 str(artist or '')[:200], 

83 ), 

84 ) 

85 

86 def summary(self) -> dict[str, Any]: 

87 """``{total, since, reasons: [{reason, count}], fallbacks: 

88 {source: count}, recent: [...]}``, most frequent reason first.""" 

89 

90 with self.db.connect() as conn: 

91 rows = [ 

92 dict(r) 

93 for r in conn.execute( 

94 'SELECT at, reason, detail, fallback, title, artist ' 

95 'FROM slskd_misses ORDER BY id DESC' 

96 ) 

97 ] 

98 reasons = Counter(row['reason'] for row in rows) 

99 fallbacks = Counter(row['fallback'] or 'none' for row in rows) 

100 return { 

101 'total': len(rows), 

102 'since': rows[-1]['at'] if rows else None, 

103 'reasons': [ 

104 {'reason': reason, 'count': count} 

105 for reason, count in reasons.most_common() 

106 ], 

107 'fallbacks': dict(fallbacks.most_common()), 

108 'recent': rows[:RECENT], 

109 } 

110 

111 def reset(self) -> int: 

112 """Start over: forget every recorded reason.""" 

113 

114 with self.db.connect() as conn: 

115 return conn.execute('DELETE FROM slskd_misses').rowcount 

116 

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

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

119 with self.db.connect() as conn: 

120 return conn.execute( 

121 'DELETE FROM slskd_misses WHERE at < ?', (cutoff,) 

122 ).rowcount