Coverage for downtify/library_cleanup.py: 94%

52 statements  

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

1"""Leftovers to clean up after a library track is deleted. 

2 

3Shared by ``DELETE /delete`` / ``/delete/batch`` (``main.py``) and the 

4library catalog deletes (``downtify/library_delete.py``: playlist delete, 

5tag-mismatch cleanup), so every way of removing a track leaves the same 

6state behind. 

7""" 

8 

9from __future__ import annotations 

10 

11from pathlib import Path 

12 

13from loguru import logger 

14 

15from . import lyrics as lyrics_mod 

16 

17_AUDIO_EXTENSIONS = {'.mp3', '.m4a', '.flac', '.ogg', '.wav', '.aac', '.opus'} 

18 

19#: Filename written by Downloader._save_album_cover next to every track 

20#: of an album folder (organize-by-album layout only). 

21ALBUM_COVER_FILENAME = 'cover.jpg' 

22 

23 

24def delete_lrc_sidecar(audio_path: Path) -> None: 

25 """Best-effort removal of the .lrc sidecar for a deleted track. 

26 

27 Removes both a sidecar next to the audio file and one in a dedicated 

28 lyrics folder (see ``lyrics.lrc_path_for``). A missing or unremovable 

29 sidecar must not fail the audio file's own deletion. 

30 """ 

31 

32 seen: set[Path] = set() 

33 for lrc in lyrics_mod.lrc_candidates(audio_path): 

34 key = str(lrc) 

35 if key in seen: 

36 continue 

37 seen.add(key) 

38 try: 

39 lrc.unlink(missing_ok=True) 

40 except OSError: 

41 logger.opt(exception=True).warning( 

42 'Could not remove LRC sidecar {}', lrc 

43 ) 

44 root = lyrics_mod.lrc_tree_root() 

45 if root is not None: 

46 prune_empty_parent_dirs(lrc.parent, root) 

47 

48 

49def delete_album_cover_if_orphaned(audio_path: Path) -> None: 

50 """Best-effort removal of a now-unused ``cover.jpg``. 

51 

52 ``cover.jpg`` (written by ``Downloader._save_album_cover`` under the 

53 *Organize by album* layout) sits once per album folder, shared by 

54 every track in it — so it's only safe to delete once no other track 

55 in that same folder still needs it. Checked *after* the audio file 

56 itself is gone, so the deleted track doesn't count as a remaining 

57 dependent. 

58 """ 

59 folder = audio_path.parent 

60 cover = folder / ALBUM_COVER_FILENAME 

61 if not cover.is_file(): 

62 return 

63 still_used = any( 

64 p.is_file() and p.suffix.lower() in _AUDIO_EXTENSIONS 

65 for p in folder.iterdir() 

66 ) 

67 if still_used: 

68 return 

69 try: 

70 cover.unlink(missing_ok=True) 

71 except OSError: 

72 logger.opt(exception=True).warning( 

73 'Could not remove orphaned album cover {}', cover 

74 ) 

75 

76 

77def prune_empty_parent_dirs(start_dir: Path, root: Path) -> None: 

78 """Remove ``start_dir`` and its empty ancestors, stopping at ``root``. 

79 

80 Run after a track and its sidecars are deleted, so a per-playlist or 

81 per-artist/album folder left with nothing in it doesn't linger 

82 forever. Climbs one directory at a time and stops at the first one 

83 that still has something in it — ``root`` (the downloads directory) 

84 is never removed itself, even if it ends up empty. 

85 """ 

86 try: 

87 root = root.resolve() 

88 current = start_dir.resolve() 

89 except OSError: 

90 return 

91 # Safety: only ever climb within root's own tree, never above it. 

92 if current != root and root not in current.parents: 

93 return 

94 while current != root: 

95 try: 

96 if any(current.iterdir()): 

97 return 

98 current.rmdir() 

99 except OSError: 

100 return 

101 current = current.parent 

102 

103 

104def remove_track_leftovers(audio_path: Path, root: Path) -> None: 

105 """Run every cleanup step for an already-deleted track under ``root``.""" 

106 

107 delete_lrc_sidecar(audio_path) 

108 delete_album_cover_if_orphaned(audio_path) 

109 prune_empty_parent_dirs(audio_path.parent, root)