Debian Codegraph @

xl/trax/track.py

raw
1 # -*- coding: utf-8
2 # Copyright (C) 2008-2010 Adam Olsen
3 #
4 # This program is free software; you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation; either version 2, or (at your option)
7 # any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 #
18 #
19 # The developers of the Exaile media player hereby grant permission
20 # for non-GPL compatible GStreamer and Exaile plugins to be used and
21 # distributed together with GStreamer and Exaile. This permission is
22 # above and beyond the permissions granted by the GPL license by which
23 # Exaile is covered. If you modify this code, you may extend this
24 # exception to your version of the code, but you are not obligated to
25 # do so. If you do not wish to do so, delete this exception statement
26 # from your version.
27
28 from copy import deepcopy
29 import logging
30 import operator
31 import re
32 import time
33 from typing import Dict, Generic, List, Optional, TypeVar, Union
34 import unicodedata
35 import weakref
36
37 from gi.repository import Gio
38 from gi.repository import GLib
39
40 from xl.metadata._base import BaseFormat
41 import xl.unicode
42 from xl import event, metadata, settings
43 from xl.metadata.tags import disk_tags
44 from xl.nls import gettext as _
45 from xl.unicode import shave_marks
46
47 logger = logging.getLogger(__name__)
48
49 _K = TypeVar('_K')
50 _V = TypeVar('_V')
51 _V1 = TypeVar('_V1')
52
53 # map chars to appropriate substitutes for sorting
54 _sortcharmap = {
55 'ß': 'ss', # U+00DF
56 'æ': 'ae', # U+00E6
57 'ij': 'ij', # U+0133
58 'ŋ': 'ng', # U+014B
59 'œ': 'oe', # U+0153
60 'ƕ': 'hv', # U+0195
61 'dž': 'dz', # U+01C6
62 'lj': 'lj', # U+01C9
63 'nj': 'nj', # U+01CC
64 'dz': 'dz', # U+01F3
65 'ҥ': 'ng', # U+04A5
66 'ҵ': 'ts', # U+04B5
67 }
68
69 # Cache these here because calling gettext inside get_tag_display
70 # is two orders of magnitude slower.
71 _VARIOUSARTISTSSTR = _("Various Artists")
72 _UNKNOWNSTR = _("Unknown")
73 # TRANSLATORS: String multiple tag values will be joined by
74 _JOINSTR = _(' / ')
75
76 _no_set_raw = {'__basename', '__loc'} | disk_tags
77
78 _unset = object()
79
80
81 class _MetadataCacher(Generic[_K, _V]):
82 """Time- and size-limited LRU cache"""
83
84 class Entry(Generic[_V1]):
85 value: _V1
86 time: float
87
88 def __init__(self, value: _V1, time: float):
89 self.value = value
90 self.time = time
91
92 def __lt__(self, other: '_MetadataCacher.Entry'):
93 return self.time < other.time
94
95 _cache: Dict[_K, Entry[_V]]
96 timeout: int
97 maxentries: int
98 _cleanup_id: Optional[int]
99
100 def __init__(self, timeout: int = 10, maxentries: int = 20):
101 """
102 :param timeout: time (in s) until the cached obj gets removed.
103 :param maxentries: maximum number of objects to cache
104 """
105 self._cache = {}
106 self.timeout = timeout
107 self.maxentries = maxentries
108 self._cleanup_id = None
109
110 def __cleanup(self) -> bool:
111 if self._cleanup_id is not None:
112 GLib.source_remove(self._cleanup_id)
113 self._cleanup_id = None
114 current = time.time()
115 thresh = current - self.timeout
116 self._cache = {k: v for k, v in self._cache.items() if v.time >= thresh}
117 if self._cache:
118 next_expiry = min(self._cache.values()).time
119 timeout = int((next_expiry + self.timeout) - current)
120 self._cleanup_id = GLib.timeout_add_seconds(timeout, self.__cleanup)
121 return False
122
123 def add(self, key: _K, value: _V) -> None:
124 if key in self._cache:
125 return
126 item = self.Entry(value, time.time())
127 self._cache[key] = item
128 if len(self._cache) > self.maxentries:
129 oldest_key = min(self._cache.items(), key=operator.itemgetter(1))[0]
130 del self._cache[oldest_key]
131 if self._cleanup_id is None:
132 self._cleanup_id = GLib.timeout_add_seconds(self.timeout, self.__cleanup)
133
134 def remove(self, key: _K) -> None:
135 try:
136 del self._cache[key]
137 except KeyError:
138 pass
139
140 def get(self, key: _K) -> Optional[_V]:
141 item = self._cache.get(key)
142 if item is None:
143 return None
144 item.time = time.time()
145 return item.value
146
147
148 #: Cache of metadata format objects to speed up get_tag_disk
149 _CACHER: _MetadataCacher['Track', BaseFormat] = _MetadataCacher()
150
151
152 class Track:
153 """
154 Represents a single track.
155 """
156
157 # save a little memory this way
158 __slots__ = [
159 "__tags",
160 "_scan_valid",
161 "_dirty",
162 "__weakref__",
163 "_init",
164 "_is_supported",
165 ]
166 # this is used to enforce the one-track-per-uri rule
167 __tracksdict = weakref.WeakValueDictionary()
168 # store a copy of the settings values here - much faster (0.25 cpu
169 # seconds) (see _the_cuts_cb)
170 __the_cuts = settings.get_option('collection/strip_list', [])
171
172 def __new__(cls, *args, **kwargs):
173 """
174 override the construction of new Track objects so that
175 if there is already a Track for a given uri, we just return
176 that Track instance instead of creating a new one.
177 """
178 # subclassing interferes with the one-track-per-uri scheme and
179 # with save and restore of tracks, so we disallow it.
180 if cls != Track:
181 raise TypeError("Track cannot be subclassed!")
182
183 uri = None
184 if len(args) > 0:
185 uri = args[0]
186 else:
187 uri = kwargs.get("uri")
188
189 # Restore uri from pickled state if possible. This means that
190 # if a given Track is in more than one TrackDB, the first
191 # TrackDB to get loaded takes precedence, and any data in the
192 # second TrackDB is consequently ignored. Thus if at all
193 # possible, Tracks should NOT be persisted in more than one
194 # TrackDB at a time.
195 unpickles = None
196 if uri is None:
197 if len(args) > 2:
198 unpickles = args[2]
199 else:
200 unpickles = kwargs.get("_unpickles")
201 if unpickles is not None:
202 uri = unpickles.get("__loc")
203
204 if uri is not None:
205 uri = Gio.File.new_for_uri(uri).get_uri()
206 try:
207 tr = cls.__tracksdict[uri]
208 tr._init = False
209
210 # if the track *does* happen to be pickled in more than one
211 # place, then we need to preserve any internal tags that aren't
212 # persisted to disk.
213 #
214 # See https://bugs.launchpad.net/exaile/+bug/1054637
215 if unpickles is None:
216 if len(args) > 2:
217 unpickles = args[2]
218 else:
219 unpickles = kwargs.get("_unpickles")
220
221 if unpickles is not None:
222 tags = tr.list_tags()
223 to_set = {
224 tag: values
225 for tag, values in unpickles.items()
226 if tag.startswith('__') and tag not in tags
227 }
228 if to_set:
229 tr.set_tags(**to_set)
230
231 except KeyError:
232 tr = object.__new__(cls)
233 cls.__tracksdict[uri] = tr
234 tr._init = True
235 return tr
236 else:
237 # this should always fail in __init__, and will never be
238 # called in well-formed code.
239 tr = object.__new__(cls)
240 tr._init = True
241 return tr
242
243 def __init__(self, uri: Optional[str] = None, scan: bool = True, _unpickles=None):
244 """
245 :param uri: the location, as either a uri or a file path.
246 :param scan: Whether to try to read tags from the given uri.
247 Use only if the tags need to be set by a
248 different source.
249
250 :param _unpickles: used internally to restore from a pickled
251 state. not for normal use.
252 """
253 # don't re-init if its a reused track. see __new__
254 if self._init is False:
255 return
256
257 self.__tags = {}
258 self._scan_valid = None # whether our last tag read attempt worked
259 self._is_supported = None
260
261 # This is not used by write_tags, this is used by the collection to
262 # indicate that the tags haven't been written to the collection
263 self._dirty = False
264
265 if _unpickles:
266 self._unpickles(_unpickles)
267 self.__register()
268 elif uri:
269 # notify isn't needed here because this is a new track
270 self.set_loc(uri, notify_changed=False)
271 if scan:
272 self.read_tags(notify_changed=False)
273 else:
274 raise ValueError("Cannot create a Track from nothing")
275
276 def __register(self):
277 """
278 Register this instance into the global registry of Track
279 objects.
280 """
281 self.__tracksdict[self.__tags['__loc']] = self
282
283 def __unregister(self):
284 """
285 Unregister this instance from the global registry of
286 Track objects.
287 """
288 try:
289 del self.__tracksdict[self.__tags['__loc']]
290 except KeyError:
291 pass
292
293 def set_loc(self, loc: str, notify_changed: bool = True) -> None:
294 """
295 Sets the location.
296
297 :param loc: the location, as either a uri or a file path.
298 """
299 self.__unregister()
300 gloc = Gio.File.new_for_commandline_arg(loc)
301 self.__tags['__loc'] = gloc.get_uri()
302 self.__register()
303 if notify_changed:
304 event.log_event('track_tags_changed', self, {'__loc'})
305
306 def exists(self):
307 """
308 Returns whether the file exists
309 This can be very slow, use with caution!
310 """
311 return Gio.File.new_for_uri(self.get_loc_for_io()).query_exists(None)
312
313 def get_loc_for_io(self) -> str:
314 """
315 Gets the location as a full uri.
316
317 Safe for IO operations via gio, not suitable for display to users
318 as it may be in non-utf-8 encodings.
319 """
320 return self.__tags['__loc']
321
322 def get_local_path(self):
323 """
324 If the file is accessible on a local filesystem, retrieves
325 the full path to it, otherwise nothing.
326
327 :returns: the file path or None
328 :rtype: string or NoneType
329 """
330 return Gio.File.new_for_uri(self.get_loc_for_io()).get_path()
331
332 def get_basename(self):
333 """
334 Returns the base name of a resource
335 """
336 gfile = Gio.File.new_for_uri(self.get_loc_for_io())
337
338 return gfile.get_basename()
339
340 def get_basename_display(self) -> str:
341 """
342 Return the track basename for display purposes (invalid characters
343 are replaced).
344
345 :rtype: unicode
346 """
347 gfile = Gio.File.new_for_uri(self.get_loc_for_io())
348 path = gfile.get_path()
349 if path: # Local
350 path = GLib.filename_display_basename(path)
351 else: # Non-local
352 path = GLib.filename_display_name(gfile.get_basename())
353 return path
354
355 def get_type(self):
356 """
357 Get the URI schema the file uses, e.g. file, http, smb.
358 """
359 return Gio.File.new_for_uri(self.get_loc_for_io()).get_uri_scheme()
360
361 def write_tags(self):
362 """
363 Writes tags to the file for this Track.
364
365 Returns False if unsuccessful, and a Format object from
366 `xl.metadata` otherwise.
367 """
368 try:
369 f = metadata.get_format(self.get_loc_for_io())
370 if f is None:
371 return False # not a supported type
372 f.write_tags(self.__tags)
373
374 # now that we've written the tags to disk, remove any tags that the
375 # user asked to be deleted
376 to_remove = [k for k, v in self.__tags.items() if v is None]
377 for rm in to_remove:
378 self.__tags.pop(rm)
379
380 return f
381 except IOError:
382 # error writing to the file, probably
383 logger.warning("Could not write tags to file", exc_info=True)
384 return False
385 except Exception:
386 logger.exception("Unknown exception: Could not write tags to file")
387 return False
388
389 def read_tags(self, force=True, notify_changed=True):
390 """
391 Reads tags from the file for this Track.
392
393 :param force: If not True, then only read the tags if the file has
394 be modified.
395
396 Returns False if unsuccessful, and a Format object from
397 `xl.metadata` otherwise.
398 """
399
400 if not self.is_supported():
401 self._scan_valid = False
402 return False
403
404 loc = self.get_loc_for_io()
405 try:
406 # Retrieve file specific metadata
407 gloc = Gio.File.new_for_uri(loc)
408 mtime = (
409 gloc.query_info("time::modified", Gio.FileQueryInfoFlags.NONE, None)
410 .get_modification_date_time()
411 .to_unix()
412 )
413 f = metadata.get_format(loc)
414 if not force and self.__tags.get('__modified', 0) >= mtime:
415 return f
416
417 # Read the tags
418 ntags = f.read_all()
419 ntags['__modified'] = mtime
420
421 # TODO: this probably breaks on non-local files
422 ntags['__basedir'] = gloc.get_parent().get_path()
423
424 if '__rating' in ntags and settings.get_option(
425 'collection/write_rating_to_audio_file_metadata', False
426 ):
427 ntags['__rating'] = int(ntags['__rating'][0])
428
429 # remove tags that could be in the file, but are in fact not
430 # in the file. Retain tags in the DB that aren't supported by
431 # the file format.
432
433 nkeys = set(ntags.keys())
434 ekeys = {k for k in self.__tags if not k.startswith('__')}
435
436 # delete anything that wasn't in the new tags
437 to_del = ekeys - nkeys
438
439 # but if not others set, only delete supported tags
440 if not f.others:
441 to_del &= set(f.tag_mapping.keys())
442
443 for tag in to_del:
444 ntags[tag] = None
445
446 self.set_tags(notify_changed=notify_changed, **ntags)
447
448 self._scan_valid = True
449 return f
450 except Exception:
451 self._scan_valid = False
452 logger.exception("Error reading tags for %s", loc)
453 return False
454
455 def is_local(self):
456 """
457 Determines whether a file is accessible on the local filesystem.
458 """
459 # TODO: determine this better
460 # Maybe use Gio.File.is_native()?
461 if self.get_local_path():
462 return True
463 return False
464
465 def is_supported(self):
466 """
467 Determines if a file has a supported media format
468 """
469 if self._is_supported is None:
470 loc = self.get_loc_for_io()
471 f = metadata.get_format(loc)
472 if f is None:
473 self._is_supported = False
474 else:
475 self._is_supported = True
476
477 return self._is_supported
478
479 def get_size(self):
480 """
481 Get the raw size of the file. Potentially slow.
482 """
483 f = Gio.File.new_for_uri(self.get_loc_for_io())
484 return f.query_info(
485 "standard::size", Gio.FileQueryInfoFlags.NONE, None
486 ).get_size()
487
488 def __repr__(self):
489 return str(self)
490
491 def __str__(self):
492 """
493 returns a string representing the track
494 """
495 vals = map(self.get_tag_display, ('title', 'artist', 'album'))
496 return "<Track %r by %r from %r>" % tuple(vals)
497
498 def _pickles(self):
499 """
500 returns a data repr of the track suitable for pickling
501
502 internal use only please
503 """
504 return deepcopy(self.__tags)
505
506 def _unpickles(self, pickle_obj):
507 """
508 restores the state from the pickle-able repr
509
510 internal use only please
511 """
512 self.__tags = deepcopy(pickle_obj)
513
514 def list_tags(self):
515 """
516 Returns a list of the names of all tags present in this Track.
517 """
518 return [k for k, v in self.__tags.items() if v is not None] + ['__basename']
519
520 def _xform_set_values(self, tag, values):
521 # Handle values that aren't lists
522 if not isinstance(values, list):
523 if not tag.startswith("__"): # internal tags dont have to be lists
524 values = [values]
525
526 if (
527 tag == '__rating'
528 and not isinstance(values, list)
529 and self._write_rating_to_disk()
530 ):
531 values = [values]
532
533 # For lists, filter out empty values
534 if isinstance(values, list):
535 values = [v for v in values if v not in (None, '')]
536
537 if values:
538 return values
539
540 return None
541
542 def set_tag_raw(self, tag, values, notify_changed=True):
543 """
544 Set the raw value of a tag.
545
546 :param tag: The name of the tag to set.
547 :param values: The value or values to set the tag to.
548 :param notify_changed: whether to send a signal to let other
549 parts of Exaile know there has been an update. Only set
550 this to False if you know that no other parts of Exaile
551 need to be updated.
552
553 .. note:: When setting more than one tag, prefer set_tags instead
554
555 .. warning:: Covers and lyrics tags must be set via set_tag_disk
556
557 :returns: True if changed, False otherwise
558 """
559 changed = self.set_tags(notify_changed=notify_changed, **{tag: values})
560 return bool(changed)
561
562 def set_tags(self, notify_changed=True, **kwargs):
563 """
564 Set multiple tags on a track.
565
566 :param notify_changed: whether to send a signal to let other
567 parts of Exaile know there has been an update. Only set
568 this to False if you know that no other parts of Exaile
569 need to be updated.
570
571 Prefer this method over calling set_tag_raw multiple times, as this
572 method will be more efficient.
573
574 .. warning:: Covers and lyrics tags must be set via set_tag_disk
575
576 :returns: Set of tags that have changed
577 """
578
579 # tag changes can cause expensive UI updates, so don't emit the event
580 # if the track hasn't actually changed
581 changed = set()
582
583 for tag, values in kwargs.items():
584 if tag in _no_set_raw:
585 if tag == '__loc':
586 logger.warning(
587 'Setting "__loc" directly is forbidden, use set_loc() instead.'
588 )
589 elif tag == '__basename':
590 logger.warning('Setting "__basename" directly is forbidden.')
591 else:
592 logger.warning(
593 'Cannot set "%s" via set_tag_raw, use set_tag_disk instead', tag
594 )
595 continue
596
597 # Transform and set the value. We do NOT delete the value from the tag
598 # dict (which was done prior to Exaile 4), otherwise we don't know that
599 # the user wanted the tag to be deleted
600 new_value = self._xform_set_values(tag, values)
601 if self.__tags.get(tag, _unset) != new_value:
602 changed.add(tag)
603 self.__tags[tag] = new_value
604
605 if changed:
606 self._dirty = True
607 if notify_changed:
608 event.log_event("track_tags_changed", self, changed)
609
610 return changed
611
612 def get_tag_raw(self, tag, join=False):
613 """
614 Get the raw value of a tag. For non-internal tags, the
615 result will always be a list of unicode strings.
616
617 :param tag: The name of the tag to get
618 :param join: If True, joins lists of values into a
619 single value.
620
621 :returns: None if the tag is not present
622 """
623 if tag == '__basename':
624 value = self.get_basename()
625 elif tag == '__startoffset':
626 # TODO: This is only necessary because some places that deal with
627 # __startoffset don't check for None. Those need to be fixed.
628 value = self.__tags.get(tag, 0)
629 elif tag == '__rating':
630 try:
631 value = self.__tags.get(tag)[0]
632 except TypeError as e:
633 value = self.__tags.get(tag)
634 else:
635 value = self.__tags.get(tag)
636
637 if join and value and not tag.startswith('__'):
638 return self.join_values(value)
639
640 return value
641
642 def get_tag_sort(
643 self, tag, join=True, artist_compilations=False, extend_title=True
644 ):
645 """
646 Get a tag value in a form suitable for sorting.
647
648 :param tag: The name of the tag to get
649 :param join: If True, joins lists of values into a
650 single value.
651 :param artist_compilations: If True, automatically handle
652 albumartist and other compilations detections when
653 tag=="albumartist".
654 :param extend_title: If the title tag is unknown, try to
655 add some identifying information to it.
656 """
657 # The two magic values here are to ensure that compilations
658 # and unknown values are always sorted below all normal
659 # values.
660 value = None
661 sorttag = self.__tags.get(tag + "sort")
662 if sorttag and tag != "albumartist":
663 value = sorttag
664 elif tag == "albumartist":
665 if artist_compilations and self.__tags.get('__compilation'):
666 value = self.__tags.get('albumartist', "\uffff\uffff\uffff\ufffe")
667 else:
668 value = self.__tags.get('albumartist')
669 if value is None:
670 value = self.__tags.get('artist', "\uffff\uffff\uffff\uffff")
671 if sorttag and value not in (
672 "\uffff\uffff\uffff\ufffe",
673 "\uffff\uffff\uffff\uffff",
674 ):
675 value = sorttag
676 else:
677 sorttag = None
678 elif tag in ('tracknumber', 'discnumber'):
679 value = self.split_numerical(self.__tags.get(tag))[0] or 0
680 elif tag in ('__length', '__playcount'):
681 value = self.__tags.get(tag, 0)
682 elif tag == 'bpm':
683 try:
684 value = int(self.__tags.get(tag, [0])[0])
685 except ValueError:
686 digits = re.search(r'\d+\.?\d*', self.__tags.get(tag, [0])[0])
687 if digits:
688 value = float(digits.group())
689 elif tag == '__basename':
690 # TODO: Check if unicode() is required
691 value = self.get_basename()
692 elif tag == '__rating':
693 value = self.get_rating()
694 else:
695 value = self.__tags.get(tag)
696
697 if value is None:
698 value = "\uffff\uffff\uffff\uffff" # unknown
699 if tag == 'title':
700 basename = self.get_basename_display()
701 value = "%s (%s)" % (value, basename)
702 elif not tag.startswith("__") and tag not in (
703 'tracknumber',
704 'discnumber',
705 'bpm',
706 ):
707 if not sorttag:
708 value = self.format_sort(value)
709 else:
710 if isinstance(value, list):
711 value = [self.lower(v + " " + v) for v in value]
712 else:
713 value = self.lower(value + " " + value)
714 if join:
715 value = self.join_values(value)
716
717 return value
718
719 def get_tag_display(
720 self, tag, join=True, artist_compilations=False, extend_title=True
721 ) -> Union[str, List[str]]:
722 """
723 Get a tag value in a form suitable for display.
724
725 :param tag: The name of the tag to get
726 :param join: If True, joins lists of values into a
727 single value.
728 :param artist_compilations: If True, automatically handle
729 albumartist and other compilations detections when
730 tag=="albumartist".
731 :param extend_title: If the title tag is unknown, try to
732 add some identifying information to it.
733 """
734 if tag == '__loc':
735 return Gio.File.new_for_uri(self.__tags['__loc']).get_parse_name()
736
737 value = None
738 if tag == "albumartist":
739 if artist_compilations and self.__tags.get('__compilation'):
740 value = self.__tags.get('albumartist', _VARIOUSARTISTSSTR)
741 else:
742 value = self.__tags.get('albumartist')
743 if value is None:
744 value = self.__tags.get('artist', _UNKNOWNSTR)
745 elif tag in ('tracknumber', 'discnumber'):
746 value = self.split_numerical(self.__tags.get(tag))[0] or ""
747 elif tag in ('__length', '__startoffset', '__stopoffset'):
748 value = self.__tags.get(tag, "")
749 elif tag in ('__rating', '__playcount'):
750 value = self.__tags.get(tag, "0")
751 elif tag == '__bitrate':
752 try:
753 value = int(self.__tags['__bitrate']) // 1000
754 if value == -1:
755 value = ""
756 else:
757 # TRANSLATORS: Bitrate (k here is short for kbps).
758 value = _("%dk") % value
759 except (KeyError, ValueError):
760 value = ""
761 elif tag == '__basename':
762 value = self.get_basename_display()
763 else:
764 value = self.__tags.get(tag)
765
766 if value is None:
767 value = ''
768 if tag == 'title':
769 basename = self.get_basename_display()
770 value = "%s (%s)" % (_UNKNOWNSTR, basename)
771
772 # Convert value to str or List[str]
773 if isinstance(value, list):
774 value = [xl.unicode.to_unicode(x, errors='replace') for x in value]
775 else:
776 value = xl.unicode.to_unicode(value, errors='replace')
777
778 if join:
779 value = self.join_values(value, _JOINSTR)
780
781 return value
782
783 def get_tag_search(
784 self, tag, format=True, artist_compilations=False, extend_title=True
785 ):
786 """
787 Get a tag value suitable for passing to the search system.
788 This includes quoting and list joining.
789
790 :param format: pre-format into a search query.
791 :param artist_compilations: If True, automatically handle
792 albumartist and other compilations detections when
793 tag=="albumartist".
794 :param extend_title: If the title tag is unknown, try to
795 add some identifying information to it.
796
797 :returns: unicode string that is used for searching
798 """
799 extraformat = ""
800 if tag == "albumartist":
801 if artist_compilations and self.__tags.get('__compilation'):
802 value = self.__tags.get('albumartist', None)
803 tag = 'albumartist'
804 extraformat += " ! __compilation==__null__"
805 else:
806 value = self.__tags.get('albumartist')
807 if value is None:
808 value = self.__tags.get('artist')
809 elif tag in ('tracknumber', 'discnumber'):
810 value = self.split_numerical(self.__tags.get(tag))[0]
811 elif tag in (
812 '__length',
813 '__playcount',
814 '__rating',
815 '__startoffset',
816 '__stopoffset',
817 ):
818 value = self.__tags.get(tag, 0)
819 elif tag == '__bitrate':
820 try:
821 value = int(self.__tags['__bitrate']) // 1000
822 if value != -1:
823 # TRANSLATORS: Bitrate (k here is short for kbps).
824 value = [_("%dk") % value, self.__tags['__bitrate']]
825 except (KeyError, ValueError):
826 value = -1
827 elif tag == '__basename':
828 value = self.get_basename_display()
829 else:
830 value = self.__tags.get(tag)
831
832 # Quote arguments
833 if value is None:
834 value = '__null__'
835 if tag == 'title':
836 extraformat += ' __loc==\"%s\"' % self.__tags['__loc']
837 elif format:
838 if isinstance(value, list):
839 value = ['"%s"' % self.quoter(val) for val in value]
840 else:
841 value = '"%s"' % self.quoter(value)
842
843 # Join lists
844 if format:
845 if isinstance(value, list):
846 value = " ".join(['%s==%s' % (tag, v) for v in value])
847 else:
848 value = '%s==%s' % (tag, value)
849 if extraformat:
850 value += extraformat
851
852 # Shave marks from strings
853 if isinstance(value, list):
854 value = [shave_marks(v) for v in value]
855 else:
856 value = shave_marks(value)
857
858 return value
859
860 def _get_format_obj(self):
861 f = _CACHER.get(self)
862 if not f:
863 try:
864 f = metadata.get_format(self.get_loc_for_io())
865 except Exception: # TODO: What exception?
866 return None
867 if not f:
868 return None
869 _CACHER.add(self, f)
870 return f
871
872 def get_tag_disk(self, tag):
873 """
874 Read a tag directly from disk. Can be slow, use with caution.
875
876 Intended for use with large fields like covers and
877 lyrics that shouldn't be loaded to the in-mem db.
878
879 .. warning:: The track instance will not be updated with the new tag
880
881 :returns: None if the tag does not exist
882 """
883 f = self._get_format_obj()
884 if f:
885 try:
886 return f.read_tags([tag])[tag]
887 except KeyError:
888 return None
889
890 def set_tag_disk(self, tag, values):
891 """
892 Set a tag directly to disk. Can be slow, use with caution.
893
894 Intended for use with large fields like covers and
895 lyrics that shouldn't be loaded to the in-mem db.
896
897 .. warning:: The track instance will not be updated with the new tag
898
899 :returns: None if the tag does not exist
900 """
901 f = self._get_format_obj()
902 if f:
903 values = self._xform_set_values(tag, values)
904 f.write_tags({tag: values})
905
906 def list_tags_disk(self):
907 """
908 List all the tags directly from file metadata. Can be slow,
909 use with caution.
910 """
911 f = self._get_format_obj()
912 if f:
913 return f.get_keys_disk()
914
915 ### convenience funcs for rating ###
916 # these dont fit in the normal set of tag access methods,
917 # but are sufficiently useful to warrant inclusion here
918
919 def get_rating(self):
920 """
921 Returns the current track rating as an integer, as
922 determined by the ``rating/maximum`` setting.
923
924 :rtype: int
925 """
926 try:
927 rating = float(self.get_tag_raw('__rating'))
928 except (TypeError, KeyError, ValueError):
929 return 0
930
931 maximum = settings.get_option("rating/maximum", 5)
932 rating = int(round(rating * float(maximum) / 100.0))
933
934 if rating > maximum:
935 return int(maximum)
936 elif rating < 0:
937 return 0
938
939 return rating
940
941 def set_rating(self, rating):
942 """
943 Sets the current track rating from an integer, on the
944 scale determined by the ``rating/maximum`` setting.
945
946 Returns the scaled rating
947 """
948 maximum = settings.get_option("rating/maximum", 5)
949 rating = min(rating, maximum)
950 rating = max(0, rating)
951 rating = 100 * rating / maximum
952 self.set_tags(__rating=rating)
953
954 if self._write_rating_to_disk():
955 self.set_tag_disk('__rating', rating)
956 return rating
957
958 ### Special functions for wrangling tag values ###
959
960 @classmethod
961 def format_sort(cls, values):
962 if isinstance(values, list):
963 return [cls.format_sort(v) for v in values]
964 # order of these is important, both for speed and behavior!
965 values = cls.strip_leading(values)
966 values = cls.strip_marks(values)
967 values = cls.lower(values)
968 values = cls.the_cutter(values)
969 values = cls.expand_doubles(values)
970 return values
971
972 @staticmethod
973 def join_values(values, glue=" / "):
974 """
975 Exaile's standard method to join tag values
976 """
977 if isinstance(values, str):
978 return values
979 if isinstance(values, bytes):
980 logger.warning(
981 "join_values with bytes object is deprecated", stack_info=True
982 )
983 return xl.unicode.to_unicode(values)
984 return glue.join(map(xl.unicode.to_unicode, values))
985
986 @staticmethod
987 def split_numerical(values):
988 """
989 this is used to split a tag like tracknumber that is in int/int
990 format into its separate parts.
991
992 input should be a string of the content, and may also
993 be wrapped in a list.
994 """
995 if not values:
996 return None, 0
997 if isinstance(values, list):
998 val = values[0]
999 else:
1000 val = values
1001 if isinstance(val, int):
1002 return val, 0
1003 split = val.split("/")[:2]
1004 try:
1005 one = int(split[0])
1006 except ValueError:
1007 one = None
1008 try:
1009 two = int(split[1])
1010 except (IndexError, ValueError):
1011 two = 0
1012 return (one, two)
1013
1014 @staticmethod
1015 def strip_leading(value):
1016 """
1017 Strip special chars off the beginning of a field. If
1018 stripping the chars leaves nothing the original field is
1019 returned with only whitespace removed.
1020 """
1021 stripped = xl.unicode.to_unicode(value).lstrip(
1022 " `~!@#$%^&*()_+-={}|[]\\\";'<>?,./"
1023 )
1024 if stripped:
1025 return stripped
1026 else:
1027 return value.lstrip()
1028
1029 @staticmethod
1030 def the_cutter(value):
1031 """
1032 Cut common words like 'the' from the beginning of a tag so that
1033 they sort properly.
1034 """
1035 lowered = value.lower()
1036 for word in Track.__the_cuts:
1037 if not word.endswith("'"):
1038 word += ' '
1039 if lowered.startswith(word):
1040 value = value[len(word) :]
1041 break
1042 return value
1043
1044 @staticmethod
1045 def strip_marks(value):
1046 """
1047 Remove accents, diacritics, etc.
1048 """
1049 # value is appended afterwards so that like-accented values
1050 # will sort together.
1051 normalize = unicodedata.normalize
1052 category = unicodedata.category
1053 return (
1054 ''.join([c for c in normalize('NFD', value) if category(c) != 'Mn'])
1055 + " "
1056 + value
1057 )
1058
1059 @staticmethod
1060 def expand_doubles(value):
1061 """
1062 turns characters like æ into values suitable for sorting,
1063 like 'ae'. see _sortcharmap for the mapping.
1064
1065 value must be a unicode object or this won't replace anything.
1066
1067 value must be in lower-case
1068 """
1069 for k, v in _sortcharmap.items():
1070 value = value.replace(k, v)
1071 return value
1072
1073 # This is slower, don't use it!
1074 # return ''.join((_sortcharmap.get(c, c) for c in value))
1075
1076 @staticmethod
1077 def lower(value):
1078 """
1079 Make tag value lower-case.
1080 """
1081 # add the original string after the lowered val so that
1082 # we sort case-sensitively if the case-insensitive value
1083 # are identical.
1084 return value.lower() + " " + value
1085
1086 @classmethod
1087 def quoter(cls, value):
1088 """
1089 Escape quotes so that it's safe to put the value inside a
1090 "" literal for searches.
1091
1092 Has no effect on non-string values.
1093 """
1094 try:
1095 return value.replace('"', '\\\"')
1096 except AttributeError:
1097 return value
1098
1099 @classmethod
1100 def _the_cuts_cb(cls, name, obj, data):
1101 """
1102 PRIVATE
1103
1104 update the cached the_cutter values
1105 """
1106 if data == "collection/strip_list":
1107 cls._Track__the_cuts = settings.get_option('collection/strip_list', [])
1108
1109 ### Utility method intended for TrackDB ###
1110
1111 @classmethod
1112 def _get_track_count(cls):
1113 '''Internal API, returns number of track objects we have'''
1114 return len(cls._Track__tracksdict)
1115
1116 def _write_rating_to_disk(self):
1117 if not settings.get_option(
1118 'collection/write_rating_to_audio_file_metadata', False
1119 ):
1120 return False
1121
1122 f = self._get_format_obj()
1123 if f is None:
1124 return False
1125
1126 keys = f.tag_mapping
1127 if not '__rating' in keys:
1128 return False
1129
1130 return True
1131
1132
1133 event.add_callback(Track._the_cuts_cb, 'collection_option_set')