Coverage for downtify/cover_cache.py: 52%

107 statements  

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

1"""Optional on-disk cache for embedded cover art (``/cover`` endpoint).""" 

2 

3from __future__ import annotations 

4 

5import json 

6from pathlib import Path 

7from typing import Any, Optional 

8 

9from .cover_art import extract_cover_art 

10from .library_cache_keys import file_content_key 

11from .library_paths import locate_library_file 

12 

13 

14def _norm_filename(filename: str) -> str: 

15 return str(filename or '').strip().replace('\\', '/') 

16 

17 

18class CoverArtCache: 

19 """Stores cover bytes under *cache_dir* when enabled in settings.""" 

20 

21 def __init__(self, cache_dir: Path) -> None: 

22 self._dir = cache_dir 

23 self._dir.mkdir(parents=True, exist_ok=True) 

24 

25 def _paths(self, key: str) -> tuple[Path, Path]: 

26 return self._dir / f'{key}.meta', self._dir / f'{key}.bin' 

27 

28 def lookup( 

29 self, stored_path: str, full_path: Path 

30 ) -> Optional[tuple[bytes, str]]: 

31 name = _norm_filename(stored_path) 

32 if not name or not full_path.is_file(): 

33 return None 

34 try: 

35 mtime_ns, size = self._file_stat(full_path) 

36 except OSError: 

37 return None 

38 

39 ck = file_content_key(full_path) 

40 if not ck: 

41 return None 

42 meta_path, data_path = self._paths(ck) 

43 if not meta_path.is_file() or not data_path.is_file(): 

44 return None 

45 try: 

46 meta = json.loads(meta_path.read_text(encoding='utf-8')) 

47 except (OSError, json.JSONDecodeError): 

48 return None 

49 if ( 

50 int(meta.get('file_mtime_ns') or 0) != mtime_ns 

51 or int(meta.get('file_size') or 0) != size 

52 ): 

53 return None 

54 try: 

55 data = data_path.read_bytes() 

56 except OSError: 

57 return None 

58 if not data: 

59 return None 

60 mime = str(meta.get('mime') or 'image/jpeg') 

61 return data, mime 

62 

63 def store( 

64 self, 

65 stored_path: str, 

66 full_path: Path, 

67 data: bytes, 

68 mime: str, 

69 ) -> None: 

70 name = _norm_filename(stored_path) 

71 if not name or not data: 

72 return 

73 try: 

74 mtime_ns, size = self._file_stat(full_path) 

75 except OSError: 

76 return 

77 ck = file_content_key(full_path) 

78 if not ck: 

79 return 

80 meta_path, data_path = self._paths(ck) 

81 meta: dict[str, Any] = { 

82 'filename': name, 

83 'content_key': ck, 

84 'file_mtime_ns': mtime_ns, 

85 'file_size': size, 

86 'mime': mime or 'image/jpeg', 

87 } 

88 try: 

89 data_path.write_bytes(data) 

90 meta_path.write_text( 

91 json.dumps(meta, separators=(',', ':')), 

92 encoding='utf-8', 

93 ) 

94 except OSError: 

95 return 

96 

97 def refresh(self, stored_path: str, full_path: Path) -> None: 

98 data, mime = extract_cover_art(full_path) 

99 if data: 

100 self.store(stored_path, full_path, data, mime or 'image/jpeg') 

101 else: 

102 self.forget(stored_path, full_path=full_path) 

103 

104 def refresh_stored_path( 

105 self, 

106 stored_path: str, 

107 *, 

108 download_dir: Path, 

109 slskd_dir: Optional[Path] = None, 

110 ) -> None: 

111 full = locate_library_file(stored_path, download_dir, slskd_dir) 

112 if full is not None: 

113 self.refresh(stored_path, full) 

114 else: 

115 self.forget_by_stored_path(stored_path) 

116 

117 def forget_by_stored_path(self, stored_path: str) -> None: 

118 name = _norm_filename(stored_path) 

119 if not name: 

120 return 

121 for meta_file in self._dir.glob('*.meta'): 

122 try: 

123 meta = json.loads(meta_file.read_text(encoding='utf-8')) 

124 except (OSError, json.JSONDecodeError): 

125 continue 

126 if str(meta.get('filename') or '') != name: 

127 continue 

128 ck = str(meta.get('content_key') or '') 

129 if not ck: 

130 continue 

131 meta_path, data_path = self._paths(ck) 

132 for path in (meta_path, data_path): 

133 try: 

134 path.unlink(missing_ok=True) 

135 except OSError: 

136 pass 

137 

138 def forget( 

139 self, 

140 filename: str, 

141 *, 

142 full_path: Optional[Path] = None, 

143 ) -> None: 

144 if full_path is None: 

145 return 

146 ck = file_content_key(full_path) 

147 if not ck: 

148 return 

149 meta_path, data_path = self._paths(ck) 

150 for path in (meta_path, data_path): 

151 try: 

152 path.unlink(missing_ok=True) 

153 except OSError: 

154 pass 

155 

156 @staticmethod 

157 def _file_stat(full_path: Path) -> tuple[int, int]: 

158 st = full_path.stat() 

159 return int(st.st_mtime_ns), int(st.st_size)