1 # -*- coding: utf-8 -*-
2 # Copyright (c) 2013, 2014, 2015 Jack Kaliko <kaliko@azylum.org>
4 # This file is part of sima
6 # sima is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
11 # sima is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with sima. If not, see <http://www.gnu.org/licenses/>.
21 Defines some object to handle audio file metadata
25 from collections.abc import Set # python >= 3.3
27 from collections import Set # python 3.2
31 UUID_RE = r'^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12}$'
32 # The Track Object is collapsing multiple tags into a single string using this
33 # separator. It is used then to split back the string to tags list.
34 SEPARATOR = chr(0x1F) # ASCII Unit Separator
37 regexp = re.compile(UUID_RE, re.IGNORECASE)
38 if regexp.match(uuid):
40 raise WrongUUID4(uuid)
42 class MetaException(Exception):
43 """Generic Meta Exception"""
46 class WrongUUID4(MetaException):
50 def wrapper(*args, **kwargs):
53 kwargs.pop('mbid', None)
54 kwargs.pop('musicbrainz_artistid', None)
55 kwargs.pop('musicbrainz_albumartistid', None)
61 """Generic Class for Meta object
62 Meta(name=<str>[, mbid=UUID4])
66 def __init__(self, **kwargs):
67 self.__name = None #TODO: should be immutable
69 self.__aliases = set()
70 self.log = logging.getLogger(__name__)
71 if 'name' not in kwargs or not kwargs.get('name'):
72 raise MetaException('Need a "name" argument')
74 self.__name = kwargs.pop('name')
75 if 'mbid' in kwargs and kwargs.get('mbid'):
77 is_uuid4(kwargs.get('mbid'))
78 self.__mbid = kwargs.pop('mbid').lower()
80 self.log.warning('Wrong mbid %s:%s', self.__name,
82 # mbid immutable as hash rests on
83 self.__dict__.update(**kwargs)
86 fmt = '{0}(name={1.name!r}, mbid={1.mbid!r})'
87 return fmt.format(self.__class__.__name__, self)
90 return self.__name.__str__()
92 def __eq__(self, other):
94 Perform mbid equality test
96 #if hasattr(other, 'mbid'): # better isinstance?
97 if isinstance(other, Meta) and self.mbid and other.mbid:
98 return self.mbid == other.mbid
99 elif isinstance(other, Meta):
100 return bool(self.names & other.names)
101 elif getattr(other, '__str__', None):
102 # is other.__str__() in self.__name or self.__aliases
103 return other.__str__() in self.names
108 return hash(self.mbid)
109 return hash(self.__name)
111 def add_alias(self, other):
112 if getattr(other, '__str__', None):
113 if callable(other.__str__) and other.__str__() != self.name:
114 self.__aliases |= {other.__str__()}
115 elif isinstance(other, Meta):
116 if other.name != self.name:
117 self.__aliases |= other.__aliases
119 raise MetaException('No __str__ method found in {!r}'.format(other))
131 return self.__aliases
135 return self.__aliases | {self.__name,}
147 def __init__(self, name=None, mbid=None, **kwargs):
148 """Artist object built from a mapping dict containing at least an
150 >>> trk = {'artist':'Art Name',
151 >>> 'albumartist': 'Alb Art Name', # optional
152 >>> 'musicbrainz_artistid': '<UUID4>', # optional
153 >>> 'musicbrainz_albumartistid': '<UUID4>', # optional
155 >>> artobj0 = Artist(**trk)
156 >>> artobj1 = Artist(name='Tool')
158 if kwargs.get('artist', False):
159 name = kwargs.get('artist').split(SEPARATOR)[0]
160 if kwargs.get('musicbrainz_artistid', False):
161 mbid = kwargs.get('musicbrainz_artistid').split(SEPARATOR)[0]
162 if (kwargs.get('albumartist', False) and
163 kwargs.get('albumartist') != 'Various Artists'):
164 name = kwargs.get('albumartist').split(SEPARATOR)[0]
165 if (kwargs.get('musicbrainz_albumartistid', False) and
166 kwargs.get('musicbrainz_albumartistid') != '89ad4ac3-39f7-470e-963a-56509c546377'):
167 mbid = kwargs.get('musicbrainz_albumartistid').split(SEPARATOR)[0]
168 super().__init__(name=name, mbid=mbid)
170 class MetaContainer(Set):
172 def __init__(self, iterable):
173 self.elements = lst = []
174 for value in iterable:
180 inlst.add_alias(value)
183 return iter(self.elements)
185 def __contains__(self, value):
186 return value in self.elements
189 return len(self.elements)
192 return repr(self.elements)
195 # vim: ai ts=4 sw=4 sts=4 expandtab