Coverage for downtify/deemix_upgrade_playlists.py: 97%

64 statements  

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

1"""Publish replacement M3U paths before any old audio can be removed.""" 

2 

3from __future__ import annotations 

4 

5import hashlib 

6import os 

7import tempfile 

8from pathlib import Path 

9from typing import Callable 

10 

11 

12def digest(path: Path) -> str: 

13 checksum = hashlib.sha256() 

14 with path.open('rb') as source: 

15 for block in iter(lambda: source.read(1024 * 1024), b''): 

16 checksum.update(block) 

17 return checksum.hexdigest() 

18 

19 

20def playlist_files(roots: list[Path]) -> list[Path]: 

21 """One walk per batch, never follow directory symlinks.""" 

22 found: set[Path] = set() 

23 for root in roots: 

24 for directory, _, names in os.walk(root, followlinks=False): 

25 for name in names: 

26 if Path(name).suffix.lower() in {'.m3u', '.m3u8'}: 

27 found.add(Path(directory, name)) 

28 return sorted(found) 

29 

30 

31def rewrite_playlists( 

32 roots: list[Path], 

33 writable_root: Path, 

34 mapping: dict[Path, tuple[Path, float]], 

35 *, 

36 stopped: Callable[[], bool], 

37) -> None: 

38 """Keep comments, ordering and manual-playlist markers; fail closed. 

39 

40 A partly published batch is safe to repeat: original audio still 

41 exists, and an already rewritten line no longer matches the map. 

42 Read-only playlists referring to originals block the entire batch. 

43 """ 

44 root = writable_root.resolve() 

45 changes: list[tuple[Path, bytes, str]] = [] 

46 for playlist in playlist_files(roots): 

47 if stopped(): 

48 raise InterruptedError('Replacement paused before publication') 

49 original = playlist.read_bytes() 

50 lines = original.decode('utf-8-sig').splitlines(keepends=True) 

51 changed = False 

52 for index, line in enumerate(lines): 

53 value = line.strip() 

54 if not value or value.startswith('#'): 

55 continue 

56 target = mapping.get((playlist.parent / value).resolve()) 

57 if target is None: 

58 continue 

59 if not playlist.resolve().is_relative_to(root): 

60 raise ValueError( 

61 'An external playlist still uses the original' 

62 ) 

63 new_path, duration = target 

64 ending = '\r\n' if line.endswith('\r\n') else '\n' 

65 lines[index] = ( 

66 os.path.relpath(new_path, playlist.parent).replace('\\', '/') 

67 + ending 

68 ) 

69 if index and lines[index - 1].startswith('#EXTINF:'): 

70 _, comma, label = lines[index - 1].partition(',') 

71 if comma: 

72 lines[index - 1] = f'#EXTINF:{round(duration)},{label}' 

73 changed = True 

74 if changed: 

75 changes.append(( 

76 playlist, 

77 ''.join(lines).encode('utf-8'), 

78 hashlib.sha256(original).hexdigest(), 

79 )) 

80 for playlist, content, expected in changes: 

81 if stopped(): 

82 raise InterruptedError('Replacement paused before publication') 

83 temporary: Path | None = None 

84 try: 

85 with tempfile.NamedTemporaryFile( 

86 dir=playlist.parent, prefix='.audio-relink-', delete=False 

87 ) as output: 

88 temporary = Path(output.name) 

89 output.write(content) 

90 output.flush() 

91 os.fsync(output.fileno()) 

92 os.chmod(temporary, playlist.stat().st_mode & 0o777) 

93 if digest(playlist) != expected: 

94 raise ValueError( 

95 'Playlist changed during replacement; original audio retained' 

96 ) 

97 os.replace(temporary, playlist) 

98 finally: 

99 if temporary is not None: 

100 temporary.unlink(missing_ok=True)