Debian Codegraph @

xl/metadata/_base.py

raw
1 # Copyright (C) 2008-2010 Adam Olsen
2 #
3 # This program is free software; you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation; either version 2, or (at your option)
6 # any later version.
7 #
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU General Public License for more details.
12 #
13 # You should have received a copy of the GNU General Public License
14 # along with this program; if not, write to the Free Software
15 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 #
17 #
18 # The developers of the Exaile media player hereby grant permission
19 # for non-GPL compatible GStreamer and Exaile plugins to be used and
20 # distributed together with GStreamer and Exaile. This permission is
21 # above and beyond the permissions granted by the GPL license by which
22 # Exaile is covered. If you modify this code, you may extend this
23 # exception to your version of the code, but you are not obligated to
24 # do so. If you do not wish to do so, delete this exception statement
25 # from your version.
26
27 from collections import namedtuple
28 import copy
29 import threading
30 from typing import Any, ClassVar, Mapping, Sequence
31
32 import logging
33
34 logger = logging.getLogger(__name__)
35
36 from xl import version, settings
37 import mutagen
38
39 version.register('Mutagen', mutagen.version_string)
40
41
42 INFO_TAGS = ['__bitrate', '__length']
43
44 _compute_lock = threading.Lock()
45
46 # Generic description of cover images
47 # - type is a number corresponding to the cover type of ID3 APIC tags,
48 # desc is a string describing the image, mime is a type,
49 # data is the img data
50 # -> if type is None, then the type is not changeable
51 CoverImage = namedtuple('CoverImage', 'type desc mime data')
52
53
54 class NotWritable(Exception):
55 pass
56
57
58 class NotReadable(Exception):
59 pass
60
61
62 class BaseFormat:
63 """
64 Base class for handling loading of metadata from files.
65
66 subclasses using mutagen should set MutagenType and overload
67 the _get_tag, _set_tag, and _del_tag methods as needed.
68
69 subclasses not using mutagen should leave MutagenType as None
70 """
71
72 MutagenType = None
73
74 # This should contain ALL keys supported by this filetype, unless 'others'
75 # is set to True. If others is True, then anything not in tag_mapping will
76 # be written using the Exaile tag name
77 # -> dict k: exaile tag name, v: native tag name
78 tag_mapping: ClassVar[Mapping[str, Any]] = {}
79 others: ClassVar[bool] = True
80 writable: ClassVar[bool] = False
81 case_sensitive: ClassVar[bool] = True
82
83 # Whether _compute_mappings has run
84 _computed: ClassVar[bool]
85 # Reverse of tag_mapping, populated in _compute_mappings
86 _reverse_mapping: ClassVar[Mapping[Any, str]]
87
88 @classmethod
89 def _compute_mappings(cls):
90 with _compute_lock:
91 # this only needs to be run once per class
92 if hasattr(cls, '_computed'):
93 return
94
95 if cls.case_sensitive:
96 cls._reverse_mapping = {v: k for k, v in cls.tag_mapping.items()}
97 else:
98 cls._reverse_mapping = {
99 v.lower(): k for k, v in cls.tag_mapping.items()
100 }
101
102 from .tags import disk_tags
103
104 cls.ignore_tags = set(disk_tags)
105
106 # This comes last to indicate success
107 cls._computed = True
108
109 def __init__(self, loc):
110 """
111 Raises :class:`NotReadable` if the file cannot be
112 opened for some reason.
113
114 :param loc: absolute path to the file to read
115 (note - this may change to accept gio uris in the future)
116 """
117 self.loc = loc
118 self.open = False
119 self.mutagen = None
120 try:
121 self._computed
122 except AttributeError:
123 self.__class__._compute_mappings()
124
125 self.load()
126
127 def load(self):
128 """
129 Loads the tags from the file.
130 """
131 if self.MutagenType:
132 try:
133 self.mutagen = self.MutagenType(self.loc)
134 except Exception:
135 raise NotReadable
136
137 def save(self):
138 """
139 Saves any changes to the tags.
140 """
141 if self.writable and self.mutagen:
142 self.mutagen.save()
143
144 def _del_tag(self, raw, tag):
145 """
146 :param tag: The native tag name
147 """
148 if tag in raw:
149 del raw[tag]
150
151 def _get_raw(self):
152 if self.MutagenType or self.mutagen:
153 return self.mutagen
154 else:
155 return {}
156
157 def _get_tag(self, raw, tag):
158 """
159 :param tag: The native tag name
160 """
161 try:
162 return raw[tag]
163 except KeyError:
164 return None
165
166 def _set_tag(self, raw, tag, value):
167 """
168 :param tag: The native tag name
169 :param value: If None, delete the tag
170 """
171 raw[tag] = value
172
173 def get_keys_disk(self) -> Sequence[str]:
174 """
175 Returns keys of all tags that can be read from disk
176 """
177 return [self._reverse_mapping.get(k, k) for k in self._get_raw().keys()]
178
179 def read_all(self):
180 """
181 Reads all non-blacklisted tags from the file.
182
183 Blacklisted tags include lyrics, covers, and any field starting
184 with __. If you need to read these, call read_tags directly.
185 """
186 tags = INFO_TAGS[:]
187 for t in self.get_keys_disk():
188 if t in self.ignore_tags:
189 continue
190 # __ is used to denote exaile's internal tags, so we skip
191 # loading them to avoid conflicts. usually this shouldn't be
192 # an issue.
193 if self._remove_internal_tag(t):
194 continue
195 tags.append(t)
196 alltags = self.read_tags(tags)
197 return alltags
198
199 def read_tags(self, tags):
200 """
201 get the values for the specified tags.
202
203 returns a dict of the found values. if no value was found for a
204 requested tag it will not exist in the returned dict.
205
206 :param tags: a list of exaile tag names to read
207 :returns: a dictionary of tag/value pairs.
208 """
209 raw = self._get_raw()
210 td = {}
211 for tag in tags:
212 t = None
213 if tag in INFO_TAGS:
214 try:
215 t = self.get_info(tag)
216 except KeyError:
217 pass
218 if t is None and tag in self.tag_mapping:
219 try:
220 t = self._get_tag(raw, self.tag_mapping[tag])
221 if isinstance(t, (str, bytes)):
222 t = [t]
223 elif isinstance(t, list):
224 pass
225 elif t is not None:
226 t = [str(u) for u in t]
227 except (KeyError, TypeError):
228 logger.debug("Unexpected error reading `%s`", tag, exc_info=True)
229 if t is None and self.others and tag not in self.tag_mapping:
230 try:
231 t = self._get_tag(raw, tag)
232 if isinstance(t, (str, bytes)):
233 t = [t]
234 elif t is not None:
235 t = [str(u) for u in t]
236 except (KeyError, TypeError):
237 logger.debug("Unexpected error reading `%s`", tag, exc_info=True)
238
239 if t:
240 td[tag] = t
241 return td
242
243 def write_tags(self, tagdict):
244 """
245 Write a set of tags to the file. Raises a NotWritable exception
246 if the format does not support writing tags.
247
248 When calling this function, we assume the following:
249
250 * tagdict has all keys that you wish to write, keys are exaile tag
251 names or custom tag names and values are the tags to write (lists
252 of unicode strings)
253 * if a value is None, then that tag will be deleted from the file
254 * Will not modify/delete tags that are NOT in tagdict
255 * Will not write tags that start with '__'
256
257 :param tagdict: A dictionary of tag/value pairs to write.
258 """
259 if not self.MutagenType or not self.writable:
260 raise NotWritable
261 else:
262 tagdict = copy.deepcopy(tagdict)
263 raw = self._get_raw()
264 # Add tags if it doesn't have them. Mutagen will throw an exception
265 # if the file already contains tags.
266 if getattr(raw, 'tags', None) is None:
267 try:
268 raw.add_tags()
269 except Exception:
270 # XXX: Not sure needed since we're already checking for
271 # existence of tags.
272 pass
273
274 # tags starting with __ are internal and should not be written
275 # -> this covers INFO_TAGS, which also shouldn't be written
276 for tag in list(tagdict.keys()):
277 if self._remove_internal_tag(tag):
278 del tagdict[tag]
279
280 # Only modify the tags we were told to modify
281 # -> if the value is None, delete the tag
282 for tag, value in tagdict.items():
283 rtag = self.tag_mapping.get(tag)
284 if rtag:
285 if value is not None:
286 self._set_tag(raw, rtag, value)
287 else:
288 self._del_tag(raw, rtag)
289 elif self.others:
290 if value is not None:
291 self._set_tag(raw, tag, value)
292 else:
293 self._del_tag(raw, tag)
294
295 self.save()
296
297 def get_info(self, info):
298 # TODO: add sample rate? filesize?
299 if info == "__length":
300 return self.get_length()
301 elif info == "__bitrate":
302 return self.get_bitrate()
303 else:
304 raise KeyError
305
306 def get_length(self):
307 try:
308 return self.mutagen.info.length
309 except AttributeError:
310 try:
311 return self._get_raw()['__length']
312 except (KeyError, TypeError):
313 return None
314
315 def get_bitrate(self):
316 try:
317 return self.mutagen.info.bitrate
318 except AttributeError:
319 try:
320 return self._get_raw()['__bitrate']
321 except (KeyError, TypeError):
322 return None
323
324 def _stars_to_rating(self, data: int) -> int:
325 # exactly the same
326 return int(data)
327
328 def _rating_to_stars(self, data: int) -> int:
329 # mapping according to kid3
330 # 0: 0
331 # 1: 1 - 29
332 # 2: 30 - 49
333 # 3: 50 - 69
334 # 4: 70 - 89
335 # 5: 90 -
336 if data <= 0:
337 # 0
338 rating = 0
339 elif data <= 29:
340 # 1
341 rating = 20
342 elif data <= 49:
343 # 2
344 rating = 40
345 elif data <= 69:
346 # 3
347 rating = 60
348 elif data <= 89:
349 # 4
350 rating = 80
351 else:
352 # 5
353 rating = 100
354 return rating
355
356 def _remove_internal_tag(self, tag):
357 if tag.startswith("__") and (
358 tag != '__rating'
359 or not settings.get_option(
360 'collection/write_rating_to_audio_file_metadata', False
361 )
362 ):
363 return True
364
365 return False
366
367
368 class CaseInsensitiveBaseFormat(BaseFormat):
369 case_sensitive = False
370
371 def get_keys_disk(self):
372 """
373 Returns keys of all tags that can be read from disk
374 """
375 return [self._reverse_mapping.get(k.lower(), k) for k in self._get_raw().keys()]
376
377
378 # vim: et sts=4 sw=4