Coverage for downtify/metadata_edit.py: 34%
103 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"""Validated, staged edits of embedded library metadata."""
3from __future__ import annotations
5import os
6import shutil
7import tempfile
8import threading
9from pathlib import Path
10from typing import Any
12from mutagen import File as MutagenFile
13from mutagen.id3 import ID3, TCMP, TXXX
14from mutagen.mp4 import MP4
16from .lyrics import can_mutate_audio
18_FIELDS = {
19 'title': 'title',
20 'artist': 'artist',
21 'album': 'album',
22 'album_artist': 'albumartist',
23 'track_number': 'tracknumber',
24 'release_date': 'date',
25 'genre': 'genre',
26}
27_lock = threading.RLock()
30def validate_changes(changes: Any) -> dict[str, Any]:
31 if not isinstance(changes, dict) or not changes:
32 raise ValueError('Provide at least one metadata field')
33 unknown = set(changes) - set(_FIELDS) - {'explicit', 'compilation'}
34 if unknown:
35 raise ValueError(
36 'Unknown metadata fields: ' + ', '.join(sorted(unknown))
37 )
38 result = {}
39 for field, raw_value in changes.items():
40 value = raw_value
41 if field in {'explicit', 'compilation'}:
42 if value is not None and not isinstance(value, bool):
43 raise ValueError(f'{field} must be a boolean or null')
44 elif field == 'track_number':
45 if value is not None and (
46 isinstance(value, bool)
47 or not isinstance(value, int)
48 or not 1 <= value <= 9999
49 ):
50 raise ValueError(
51 'track_number must be an integer between 1 and 9999, or null'
52 )
53 elif value is not None:
54 if (
55 not isinstance(value, str)
56 or len(value) > 1000
57 or '\x00' in value
58 ):
59 raise ValueError(f'Invalid {field}')
60 value = value.strip() or None
61 result[field] = value
62 return result
65def edit_file(path: Path, changes: dict[str, Any]) -> None:
66 """Copy and retag a file before atomically replacing it, preserving other tags."""
67 with _lock:
68 if not can_mutate_audio(path):
69 raise PermissionError('Audio file is read-only')
70 before = path.stat()
71 fd, temp = tempfile.mkstemp(
72 prefix='.downtify-tags-', suffix=path.suffix, dir=path.parent
73 )
74 os.close(fd)
75 staged = Path(temp)
76 try:
77 shutil.copy2(path, staged)
78 audio = MutagenFile(str(staged), easy=True)
79 if audio is None:
80 raise ValueError('Unsupported audio format')
81 if audio.tags is None:
82 audio.add_tags()
83 for field, value in changes.items():
84 if field in {'explicit', 'compilation'}:
85 continue
86 key = _FIELDS[field]
87 if value is None:
88 if key in audio:
89 del audio[key]
90 else:
91 audio[key] = str(value)
92 audio.save()
93 # The multi-artist tag takes precedence over the artist tag when
94 # read. Remove it when editing artist so the two cannot disagree.
95 if (
96 'artist' in changes
97 or 'explicit' in changes
98 or 'compilation' in changes
99 ):
100 _write_special(staged, changes)
101 current = path.stat()
102 if (current.st_ino, current.st_size, current.st_mtime_ns) != (
103 before.st_ino,
104 before.st_size,
105 before.st_mtime_ns,
106 ):
107 raise ValueError(
108 'File changed while editing; reload and try again'
109 )
110 os.replace(staged, path)
111 finally:
112 staged.unlink(missing_ok=True)
115def _write_special(path: Path, changes: dict[str, Any]) -> None:
116 if path.suffix.lower() == '.mp3':
117 tags = ID3(str(path))
118 if 'artist' in changes:
119 tags.delall('TXXX:ARTISTS')
120 if 'explicit' in changes:
121 tags.delall('TXXX:ITUNESADVISORY')
122 if changes['explicit'] is not None:
123 tags.add(
124 TXXX(
125 encoding=3,
126 desc='ITUNESADVISORY',
127 text=['1' if changes['explicit'] else '2'],
128 )
129 )
130 if 'compilation' in changes:
131 tags.delall('TCMP')
132 if changes['compilation'] is not None:
133 tags.add(
134 TCMP(
135 encoding=3,
136 text=['1' if changes['compilation'] else '0'],
137 )
138 )
139 tags.save(v2_version=4)
140 elif path.suffix.lower() in {'.m4a', '.mp4'}:
141 audio = MP4(str(path))
142 if 'artist' in changes:
143 audio.pop('----:com.apple.iTunes:ARTISTS', None)
144 if 'explicit' in changes:
145 audio.pop('rtng', None)
146 if changes['explicit'] is not None:
147 audio['rtng'] = [1 if changes['explicit'] else 2]
148 if 'compilation' in changes:
149 audio.pop('cpil', None)
150 if changes['compilation'] is not None:
151 audio['cpil'] = changes['compilation']
152 audio.save()
153 else:
154 audio = MutagenFile(str(path))
155 if audio is None or audio.tags is None:
156 raise ValueError('Unsupported audio format')
157 if 'artist' in changes:
158 audio.tags.pop('artists', None)
159 for field, key in (
160 ('explicit', 'ITUNESADVISORY'),
161 ('compilation', 'compilation'),
162 ):
163 if field in changes:
164 audio.tags.pop(key, None)
165 if changes[field] is not None:
166 audio.tags[key] = '1' if changes[field] else '0'
167 audio.save()