Debian Codegraph @

mediafile/storage/mp3.py

raw
1 import mutagen
2 import mutagen.id3
3
4 from mediafile.utils import Image
5
6 from .base import ListStorageStyle, SoundCheckStorageStyleMixin, StorageStyle
7
8
9 class MP3StorageStyle(StorageStyle):
10 """Store data in ID3 frames."""
11
12 formats = ["MP3", "AIFF", "DSF", "WAVE"]
13
14 def __init__(self, key, id3_lang=None, **kwargs):
15 """Create a new ID3 storage style. `id3_lang` is the value for
16 the language field of newly created frames.
17 """
18 self.id3_lang = id3_lang
19 super().__init__(key, **kwargs)
20
21 def fetch(self, mutagen_file):
22 try:
23 return mutagen_file[self.key].text[0]
24 except (KeyError, IndexError):
25 return None
26
27 def store(self, mutagen_file, value):
28 frame = mutagen.id3.Frames[self.key](encoding=3, text=[value])
29 mutagen_file.tags.setall(self.key, [frame])
30
31
32 class MP3PeopleStorageStyle(MP3StorageStyle):
33 """Store list of people in ID3 frames."""
34
35 def __init__(self, key, involvement="", **kwargs):
36 self.involvement = involvement
37 super().__init__(key, **kwargs)
38
39 def _matching_people(self, mutagen_file):
40 values = []
41 for frame in mutagen_file.tags.getall(self.key):
42 for pair in frame.people:
43 if pair[0].lower() == self.involvement.lower() and len(pair) > 1:
44 values.append(pair[1])
45 return values
46
47 def _other_people(self, mutagen_file):
48 values = []
49 for frame in mutagen_file.tags.getall(self.key):
50 for pair in frame.people:
51 if pair[0].lower() != self.involvement.lower():
52 values.append(pair)
53 return values
54
55 def _store_people(self, mutagen_file, values):
56 people = self._other_people(mutagen_file)
57 people.extend([[self.involvement, value] for value in values])
58
59 if people:
60 frame = mutagen.id3.Frames[self.key](
61 encoding=mutagen.id3._specs.Encoding.UTF8,
62 people=people,
63 )
64 mutagen_file.tags.setall(self.key, [frame])
65 else:
66 mutagen_file.tags.delall(self.key)
67
68 def store(self, mutagen_file, value):
69 self._store_people(mutagen_file, [value])
70
71 def fetch(self, mutagen_file):
72 try:
73 return self._matching_people(mutagen_file)[0]
74 except IndexError:
75 return None
76
77 def delete(self, mutagen_file):
78 self._store_people(mutagen_file, [])
79
80
81 class MP3ListPeopleStorageStyle(ListStorageStyle, MP3PeopleStorageStyle):
82 """Store multiple values for one involvement in ID3 people frames."""
83
84 def fetch(self, mutagen_file):
85 return self._matching_people(mutagen_file)
86
87 def store(self, mutagen_file, values):
88 self._store_people(mutagen_file, values)
89
90
91 class MP3ListStorageStyle(ListStorageStyle, MP3StorageStyle):
92 """Store lists of data in multiple ID3 frames."""
93
94 def fetch(self, mutagen_file):
95 try:
96 return mutagen_file[self.key].text
97 except KeyError:
98 return []
99
100 def store(self, mutagen_file, values):
101 frame = mutagen.id3.Frames[self.key](encoding=3, text=values)
102 mutagen_file.tags.setall(self.key, [frame])
103
104
105 class MP3UFIDStorageStyle(MP3StorageStyle):
106 """Store string data in a UFID ID3 frame with a particular owner."""
107
108 def __init__(self, owner, **kwargs):
109 self.owner = owner
110 super().__init__("UFID:" + owner, **kwargs)
111
112 def fetch(self, mutagen_file):
113 try:
114 return mutagen_file[self.key].data
115 except KeyError:
116 return None
117
118 def store(self, mutagen_file, value):
119 # This field type stores text data as encoded data.
120 assert isinstance(value, str)
121 value = value.encode("utf-8")
122
123 frames = mutagen_file.tags.getall(self.key)
124 for frame in frames:
125 # Replace existing frame data.
126 if frame.owner == self.owner:
127 frame.data = value
128 else:
129 # New frame.
130 frame = mutagen.id3._frames.UFID(owner=self.owner, data=value)
131 mutagen_file.tags.setall(self.key, [frame])
132
133
134 class MP3DescStorageStyle(MP3StorageStyle):
135 """Store data in a TXXX (or similar) ID3 frame. The frame is
136 selected based its ``desc`` field.
137 ``attr`` allows to specify name of data accessor property in the frame.
138 Most of frames use `text`.
139 ``multispec`` specifies if frame data is ``mutagen.id3.MultiSpec``
140 which means that the data is being packed in the list.
141 """
142
143 def __init__(self, desc="", key="TXXX", attr="text", multispec=True, **kwargs):
144 assert isinstance(desc, str)
145 self.description = desc
146 self.attr = attr
147 self.multispec = multispec
148 super().__init__(key=key, **kwargs)
149
150 def store(self, mutagen_file, value):
151 frames = mutagen_file.tags.getall(self.key)
152 if self.multispec:
153 value = [value]
154
155 # Try modifying in place.
156 found = False
157 for frame in frames:
158 if frame.desc.lower() == self.description.lower():
159 setattr(frame, self.attr, value)
160 frame.encoding = mutagen.id3._specs.Encoding.UTF8
161 found = True
162
163 # Try creating a new frame.
164 if not found:
165 frame = mutagen.id3.Frames[self.key](
166 desc=self.description,
167 encoding=mutagen.id3._specs.Encoding.UTF8,
168 **{self.attr: value},
169 )
170 if self.id3_lang:
171 frame.lang = self.id3_lang
172 mutagen_file.tags.add(frame)
173
174 def fetch(self, mutagen_file):
175 for frame in mutagen_file.tags.getall(self.key):
176 if frame.desc.lower() == self.description.lower():
177 if not self.multispec:
178 return getattr(frame, self.attr)
179 try:
180 return getattr(frame, self.attr)[0]
181 except IndexError:
182 return None
183
184 def delete(self, mutagen_file):
185 found_frame = None
186 for frame in mutagen_file.tags.getall(self.key):
187 if frame.desc.lower() == self.description.lower():
188 found_frame = frame
189 break
190 if found_frame is not None:
191 del mutagen_file[frame.HashKey]
192
193
194 class MP3ListDescStorageStyle(MP3DescStorageStyle, ListStorageStyle):
195 def __init__(self, desc="", key="TXXX", split_v23=False, **kwargs):
196 self.split_v23 = split_v23
197 super().__init__(desc=desc, key=key, **kwargs)
198
199 def fetch(self, mutagen_file):
200 for frame in mutagen_file.tags.getall(self.key):
201 if frame.desc.lower() == self.description.lower():
202 if mutagen_file.tags.version == (2, 3, 0) and self.split_v23:
203 return sum((el.split("/") for el in frame.text), [])
204 else:
205 return frame.text
206 return []
207
208 def store(self, mutagen_file, values):
209 self.delete(mutagen_file)
210 frame = mutagen.id3.Frames[self.key](
211 desc=self.description,
212 text=values,
213 encoding=mutagen.id3._specs.Encoding.UTF8,
214 )
215 if self.id3_lang:
216 frame.lang = self.id3_lang
217 mutagen_file.tags.add(frame)
218
219
220 class MP3SlashPackStorageStyle(MP3StorageStyle):
221 """Store value as part of pair that is serialized as a slash-
222 separated string.
223 """
224
225 def __init__(self, key, pack_pos=0, **kwargs):
226 super().__init__(key, **kwargs)
227 self.pack_pos = pack_pos
228
229 def _fetch_unpacked(self, mutagen_file):
230 data = self.fetch(mutagen_file)
231 if data:
232 items = str(data).split("/")
233 else:
234 items = []
235 packing_length = 2
236 return list(items) + [None] * (packing_length - len(items))
237
238 def get(self, mutagen_file):
239 return self._fetch_unpacked(mutagen_file)[self.pack_pos]
240
241 def set(self, mutagen_file, value):
242 items = self._fetch_unpacked(mutagen_file)
243 items[self.pack_pos] = value
244 if items[0] is None:
245 items[0] = ""
246 if items[1] is None:
247 items.pop() # Do not store last value
248 self.store(mutagen_file, "/".join(map(str, items)))
249
250 def delete(self, mutagen_file):
251 if self.pack_pos == 0:
252 super().delete(mutagen_file)
253 else:
254 self.set(mutagen_file, None)
255
256
257 class MP3ImageStorageStyle(ListStorageStyle, MP3StorageStyle):
258 """Converts between APIC frames and ``Image`` instances.
259
260 The `get_list` method inherited from ``ListStorageStyle`` returns a
261 list of ``Image``s. Similarly, the `set_list` method accepts a
262 list of ``Image``s as its ``values`` argument.
263 """
264
265 def __init__(self):
266 super().__init__(key="APIC")
267 self.as_type = bytes
268
269 def deserialize(self, apic_frame):
270 """Convert APIC frame into Image."""
271 return Image(data=apic_frame.data, desc=apic_frame.desc, type=apic_frame.type)
272
273 def fetch(self, mutagen_file):
274 return mutagen_file.tags.getall(self.key)
275
276 def store(self, mutagen_file, frames):
277 mutagen_file.tags.setall(self.key, frames)
278
279 def delete(self, mutagen_file):
280 mutagen_file.tags.delall(self.key)
281
282 def serialize(self, image):
283 """Return an APIC frame populated with data from ``image``."""
284 assert isinstance(image, Image)
285 frame = mutagen.id3.Frames[self.key]()
286 frame.data = image.data
287 frame.mime = image.mime_type
288 frame.desc = image.desc or ""
289
290 # For compatibility with OS X/iTunes prefer latin-1 if possible.
291 # See issue #899
292 try:
293 frame.desc.encode("latin-1")
294 except UnicodeEncodeError:
295 frame.encoding = mutagen.id3._specs.Encoding.UTF16
296 else:
297 frame.encoding = mutagen.id3._specs.Encoding.LATIN1
298
299 frame.type = image.type_index
300 return frame
301
302
303 class MP3SoundCheckStorageStyle(SoundCheckStorageStyleMixin, MP3DescStorageStyle):
304 def __init__(self, index=0, **kwargs):
305 super().__init__(**kwargs)
306 self.index = index
307
308
309 class MP3SYLTStorageStyle(MP3StorageStyle):
310 """Storage for SYLT (synchronized lyrics) ID3 frames.
311
312 Reads and writes a list of ``(text, milliseconds)`` tuples, which is the
313 native structure of the ID3v2 SYLT frame (format=2, milliseconds).
314 Returns ``None`` when no SYLT frame is present.
315 """
316
317 def __init__(self):
318 super().__init__(key="SYLT")
319
320 def fetch(self, mutagen_file):
321 frames = mutagen_file.tags.getall("SYLT")
322 if frames:
323 return list(frames[0].text)
324 return None
325
326 def store(self, mutagen_file, value):
327 import mutagen.id3
328
329 if not value:
330 mutagen_file.tags.delall("SYLT")
331 return
332
333 frame = mutagen.id3.SYLT(
334 encoding=3,
335 lang="XXX",
336 format=2,
337 type=1,
338 text=value,
339 )
340 mutagen_file.tags.setall("SYLT", [frame])
341
342 def serialize(self, value):
343 return value
344
345 def deserialize(self, value):
346 return value