Coverage for downtify/library_fingerprint.py: 84%
80 statements
« prev ^ index » next coverage.py v7.17.4, created at 2026-11-21 22:18 +0000
« prev ^ index » next coverage.py v7.17.4, created at 2026-11-21 22:18 +0000
1"""Hash of audio filenames in each library folder so ``GET /tracks``
2can skip a full scan. Playlist M3U writes are ignored.
3"""
5from __future__ import annotations
7import hashlib
8import os
9from collections.abc import Sequence
10from pathlib import Path
11from typing import Any, Optional
13#: Folders ``library_catalog`` excludes from the audio listing.
14_SKIP_DIRNAMES = frozenset({'Podcasts', 'Playlists'})
15_AUDIO_SUFFIXES = frozenset({
16 '.mp3',
17 '.m4a',
18 '.flac',
19 '.ogg',
20 '.wav',
21 '.aac',
22 '.opus',
23})
24_STAGING = '.downtify-upgrade'
27def library_tree_fingerprint(
28 download_dir: Path,
29 slskd_dir: Optional[Path] = None,
30 extra_dirs: Sequence[Path] = (),
31) -> str:
32 """Hash of each library folder's path + mtime (not per-file stats)."""
34 digest = hashlib.sha256()
35 seen: set[str] = set()
36 for root, prune_sidecars in _roots(download_dir, slskd_dir, extra_dirs):
37 _hash_tree(digest, root, seen, prune_sidecars=prune_sidecars)
38 return digest.hexdigest()
41def _roots(
42 download_dir: Path,
43 slskd_dir: Optional[Path],
44 extra_dirs: Sequence[Path],
45) -> list[tuple[Path, bool]]:
46 items: list[tuple[Path, bool]] = [(Path(download_dir), True)]
47 if slskd_dir is not None:
48 items.append((Path(slskd_dir), False))
49 for extra in extra_dirs or ():
50 items.append((Path(extra), False))
51 return items
54def _hash_tree(
55 digest: Any,
56 root: Path,
57 seen: set[str],
58 *,
59 prune_sidecars: bool,
60) -> None:
61 try:
62 resolved = root.resolve()
63 except OSError:
64 digest.update(b'?:')
65 digest.update(str(root).encode('utf-8', 'replace'))
66 digest.update(b'\n')
67 return
68 key = str(resolved)
69 if key in seen:
70 return
71 seen.add(key)
72 try:
73 is_dir = resolved.is_dir()
74 except OSError:
75 is_dir = False
76 if not is_dir:
77 digest.update(b'missing:')
78 digest.update(key.encode('utf-8', 'replace'))
79 digest.update(b'\n')
80 return
81 for dirpath, dirnames, filenames in os.walk(resolved, followlinks=False):
82 current = Path(dirpath)
83 if prune_sidecars and current == resolved:
84 dirnames[:] = [
85 name for name in dirnames if name not in _SKIP_DIRNAMES
86 ]
87 dirnames.sort()
88 audio_names = [
89 name
90 for name in filenames
91 if _STAGING not in name
92 and Path(name).suffix.lower() in _AUDIO_SUFFIXES
93 ]
94 audio_names.sort()
95 digest.update(dirpath.encode('utf-8', 'replace'))
96 digest.update(b'\0')
97 digest.update('\n'.join(audio_names).encode('utf-8', 'replace'))
98 digest.update(b'\n')
101def playlist_listing_fingerprint(download_dir: Path) -> str:
102 """Hash of every ``.m3u`` / ``.m3u8`` (name + mtime)."""
104 digest = hashlib.sha256()
105 base = Path(download_dir)
106 try:
107 if not base.is_dir():
108 return digest.hexdigest()
109 except OSError:
110 return digest.hexdigest()
111 found: list[tuple[str, int]] = []
112 for dirpath, _dirnames, filenames in os.walk(base, followlinks=False):
113 for name in filenames:
114 if not name.lower().endswith(('.m3u', '.m3u8')):
115 continue
116 path = os.path.join(dirpath, name)
117 try:
118 mtime_ns = os.stat(path, follow_symlinks=True).st_mtime_ns
119 except OSError:
120 mtime_ns = 0
121 found.append((path, int(mtime_ns)))
122 found.sort()
123 for path, mtime_ns in found:
124 digest.update(path.encode('utf-8', 'replace'))
125 digest.update(b'\0')
126 digest.update(str(mtime_ns).encode())
127 digest.update(b'\n')
128 return digest.hexdigest()