Debian Codegraph @

mediafile/fields.py

raw
1 # MediaField is a descriptor that represents a single logical field. It
2 # aggregates several StorageStyles describing how to access the data for
3 # each file type.
4 import datetime
5 import re
6
7 from mediafile.utils import Image, safe_cast
8
9 from .constants import ImageType
10 from .storage import (
11 APEv2ImageStorageStyle,
12 ASFImageStorageStyle,
13 FlacImageStorageStyle,
14 MP3ImageStorageStyle,
15 MP4ImageStorageStyle,
16 VorbisImageStorageStyle,
17 )
18
19
20 class MediaField:
21 """A descriptor providing access to a particular (abstract) metadata
22 field.
23 """
24
25 def __init__(self, *styles, **kwargs):
26 """Creates a new MediaField.
27
28 :param styles: `StorageStyle` instances that describe the strategy
29 for reading and writing the field in particular
30 formats. There must be at least one style for
31 each possible file format.
32
33 :param out_type: the type of the value that should be returned when
34 getting this property.
35
36 """
37 self.out_type = kwargs.get("out_type", str)
38 self._styles = styles
39
40 def styles(self, mutagen_file):
41 """Yields the list of storage styles of this field that can
42 handle the MediaFile's format.
43 """
44 for style in self._styles:
45 if mutagen_file.__class__.__name__ in style.formats:
46 yield style
47
48 def __get__(self, mediafile, owner=None):
49 out = None
50 for style in self.styles(mediafile.mgfile):
51 out = style.get(mediafile.mgfile)
52 if out:
53 break
54 return safe_cast(self.out_type, out)
55
56 def __set__(self, mediafile, value):
57 if value is None:
58 value = self._none_value()
59 for style in self.styles(mediafile.mgfile):
60 if not style.read_only:
61 style.set(mediafile.mgfile, value)
62
63 def __delete__(self, mediafile):
64 for style in self.styles(mediafile.mgfile):
65 style.delete(mediafile.mgfile)
66
67 def _none_value(self):
68 """Get an appropriate "null" value for this field's type. This
69 is used internally when setting the field to None.
70 """
71 if self.out_type is int:
72 return 0
73 elif self.out_type is float:
74 return 0.0
75 elif self.out_type is bool:
76 return False
77 elif self.out_type is str:
78 return ""
79
80
81 class ListMediaField(MediaField):
82 """Property descriptor that retrieves a list of multiple values from
83 a tag.
84
85 Uses ``get_list`` and set_list`` methods of its ``StorageStyle``
86 strategies to do the actual work.
87 """
88
89 def __get__(self, mediafile, _=None):
90 for style in self.styles(mediafile.mgfile):
91 values = style.get_list(mediafile.mgfile)
92 if values:
93 return [safe_cast(self.out_type, value) for value in values]
94 return None
95
96 def __set__(self, mediafile, values):
97 for style in self.styles(mediafile.mgfile):
98 if not style.read_only:
99 style.set_list(mediafile.mgfile, values)
100
101 def single_field(self):
102 """Returns a ``MediaField`` descriptor that gets and sets the
103 first item.
104 """
105 options = {"out_type": self.out_type}
106 return MediaField(*self._styles, **options)
107
108
109 class DateField(MediaField):
110 """Descriptor that handles serializing and deserializing dates
111
112 The getter parses value from tags into a ``datetime.date`` instance
113 and setter serializes such an instance into a string.
114
115 For granular access to year, month, and day, use the ``*_field``
116 methods to create corresponding `DateItemField`s.
117 """
118
119 def __init__(self, *date_styles, **kwargs):
120 """``date_styles`` is a list of ``StorageStyle``s to store and
121 retrieve the whole date from. The ``year`` option is an
122 additional list of fallback styles for the year. The year is
123 always set on this style, but is only retrieved if the main
124 storage styles do not return a value.
125 """
126 super().__init__(*date_styles)
127 year_style = kwargs.get("year", None)
128 if year_style:
129 self._year_field = MediaField(*year_style)
130
131 def __get__(self, mediafile, owner=None):
132 year, month, day = self._get_date_tuple(mediafile)
133 if not year:
134 return None
135 try:
136 return datetime.date(year, month or 1, day or 1)
137 except ValueError: # Out of range values.
138 return None
139
140 def __set__(self, mediafile, date):
141 if date is None:
142 self._set_date_tuple(mediafile, None, None, None)
143 else:
144 self._set_date_tuple(mediafile, date.year, date.month, date.day)
145
146 def __delete__(self, mediafile):
147 super().__delete__(mediafile)
148 if hasattr(self, "_year_field"):
149 self._year_field.__delete__(mediafile)
150
151 def _get_date_tuple(self, mediafile):
152 """Get a 3-item sequence representing the date consisting of a
153 year, month, and day number. Each number is either an integer or
154 None.
155 """
156 # Get the underlying data and split on hyphens and slashes.
157 datestring = super().__get__(mediafile, None)
158 if isinstance(datestring, str):
159 datestring = re.sub(r"[Tt ].*$", "", str(datestring))
160 items = re.split("[-/]", str(datestring))
161 else:
162 items = []
163
164 # Ensure that we have exactly 3 components, possibly by
165 # truncating or padding.
166 items = items[:3]
167 if len(items) < 3:
168 items += [None] * (3 - len(items))
169
170 # Use year field if year is missing.
171 if not items[0] and hasattr(self, "_year_field"):
172 items[0] = self._year_field.__get__(mediafile)
173
174 # Convert each component to an integer if possible.
175 items_ = []
176 for item in items:
177 try:
178 items_.append(int(item))
179 except (TypeError, ValueError):
180 items_.append(None)
181 return items_
182
183 def _set_date_tuple(self, mediafile, year, month=None, day=None):
184 """Set the value of the field given a year, month, and day
185 number. Each number can be an integer or None to indicate an
186 unset component.
187 """
188 if year is None:
189 self.__delete__(mediafile)
190 return
191
192 date = [f"{int(year):04d}"]
193 if month:
194 date.append(f"{int(month):02d}")
195 if month and day:
196 date.append(f"{int(day):02d}")
197 date = map(str, date)
198 super().__set__(mediafile, "-".join(date))
199
200 if hasattr(self, "_year_field"):
201 self._year_field.__set__(mediafile, year)
202
203 def year_field(self):
204 return DateItemField(self, 0)
205
206 def month_field(self):
207 return DateItemField(self, 1)
208
209 def day_field(self):
210 return DateItemField(self, 2)
211
212
213 class DateItemField(MediaField):
214 """Descriptor that gets and sets constituent parts of a `DateField`:
215 the month, day, or year.
216 """
217
218 def __init__(self, date_field, item_pos):
219 self.date_field = date_field
220 self.item_pos = item_pos
221
222 def __get__(self, mediafile, _):
223 return self.date_field._get_date_tuple(mediafile)[self.item_pos]
224
225 def __set__(self, mediafile, value):
226 items = self.date_field._get_date_tuple(mediafile)
227 items[self.item_pos] = value
228 self.date_field._set_date_tuple(mediafile, *items)
229
230 def __delete__(self, mediafile):
231 self.__set__(mediafile, None)
232
233
234 class CoverArtField(MediaField):
235 """A descriptor that provides access to the *raw image data* for the
236 cover image on a file. This is used for backwards compatibility: the
237 full `ImageListField` provides richer `Image` objects.
238
239 When there are multiple images we try to pick the most likely to be a front
240 cover.
241 """
242
243 def __init__(self):
244 pass
245
246 def __get__(self, mediafile, _):
247 candidates = mediafile.images
248 if candidates:
249 return self.guess_cover_image(candidates).data
250 else:
251 return None
252
253 @staticmethod
254 def guess_cover_image(candidates):
255 if len(candidates) == 1:
256 return candidates[0]
257 try:
258 return next(c for c in candidates if c.type == ImageType.front)
259 except StopIteration:
260 return candidates[0]
261
262 def __set__(self, mediafile, data):
263 if data:
264 mediafile.images = [Image(data=data)]
265 else:
266 mediafile.images = []
267
268 def __delete__(self, mediafile):
269 delattr(mediafile, "images")
270
271
272 class QNumberField(MediaField):
273 """Access integer-represented Q number fields.
274
275 Access a fixed-point fraction as a float. The stored value is shifted by
276 `fraction_bits` binary digits to the left and then rounded, yielding a
277 simple integer.
278 """
279
280 def __init__(self, fraction_bits, *args, **kwargs):
281 super().__init__(out_type=int, *args, **kwargs)
282 self.__fraction_bits = fraction_bits
283
284 def __get__(self, mediafile, owner=None):
285 q_num = super().__get__(mediafile, owner)
286 if q_num is None:
287 return None
288 return q_num / pow(2, self.__fraction_bits)
289
290 def __set__(self, mediafile, value):
291 q_num = round(value * pow(2, self.__fraction_bits))
292 q_num = int(q_num) # needed for py2.7
293 super().__set__(mediafile, q_num)
294
295
296 class ImageListField(ListMediaField):
297 """Descriptor to access the list of images embedded in tags.
298
299 The getter returns a list of `Image` instances obtained from
300 the tags. The setter accepts a list of `Image` instances to be
301 written to the tags.
302 """
303
304 def __init__(self):
305 # The storage styles used here must implement the
306 # `ListStorageStyle` interface and get and set lists of
307 # `Image`s.
308 super().__init__(
309 MP3ImageStorageStyle(),
310 MP4ImageStorageStyle(),
311 ASFImageStorageStyle(),
312 VorbisImageStorageStyle(),
313 FlacImageStorageStyle(),
314 APEv2ImageStorageStyle(),
315 out_type=Image,
316 )