1 # -*- coding: utf-8 -*-
2 # Copyright (c) 2013, 2014 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
24 import collections.abc # python >= 3.3
28 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}$'
31 regexp = re.compile(UUID_RE, re.IGNORECASE)
32 if regexp.match(uuid):
34 raise WrongUUID4(uuid)
36 class MetaException(Exception):
37 """Generic Meta Exception"""
40 class WrongUUID4(MetaException):
44 def wrapper(*args, **kwargs):
47 kwargs.pop('mbid', None)
48 kwargs.pop('musicbrainz_artistid', None)
49 kwargs.pop('musicbrainz_albumartistid', None)
55 """Generic Class for Meta object
56 Meta(name=<str>[, mbid=UUID4])
60 def __init__(self, **kwargs):
61 self.__name = None #TODO: should be immutable
63 self.__aliases = set()
64 self.log = logging.getLogger(__name__)
65 if 'name' not in kwargs or not kwargs.get('name'):
66 raise MetaException('Need a "name" argument')
68 self.__name = kwargs.pop('name')
69 if 'mbid' in kwargs and kwargs.get('mbid'):
71 is_uuid4(kwargs.get('mbid'))
72 self.__mbid = kwargs.pop('mbid').upper()
74 self.log.warning('Wrong mbid {}:{}'.format(self.__name,
76 # mbid immutable as hash rests on
77 self.__dict__.update(**kwargs)
80 fmt = '{0}(name={1.name!r}, mbid={1.mbid!r})'
81 return fmt.format(self.__class__.__name__, self)
84 return self.__name.__str__()
86 def __eq__(self, other):
88 Perform mbid equality test
90 #if hasattr(other, 'mbid'): # better isinstance?
91 if isinstance(other, Meta) and self.mbid and other.mbid:
92 return self.mbid == other.mbid
93 elif isinstance(other, Meta):
94 return bool(self.names & other.names)
95 elif getattr(other, '__str__', None):
96 # is other.__str__() in self.__name or self.__aliases
97 return other.__str__() in self.names
102 return hash(self.mbid)
103 return hash(self.__name)
105 def add_alias(self, other):
106 if getattr(other, '__str__', None):
107 if callable(other.__str__) and other.__str__() != self.name:
108 self.__aliases |= {other.__str__()}
109 elif isinstance(other, Meta):
110 if other.name != self.name:
111 self.__aliases |= other.__aliases
113 raise MetaException('No __str__ method found in {!r}'.format(other))
125 return self.__aliases
129 return self.__aliases | {self.__name,}
141 def __init__(self, name=None, mbid=None, **kwargs):
142 """Artist object built from a mapping dict containing at least an
144 >>> trk = {'artist':'Art Name',
145 >>> 'albumartist': 'Alb Art Name', # optional
146 >>> 'musicbrainz_artistid': '<UUID4>' , # optional
147 >>> 'musicbrainz_albumartistid': '<UUID4>', # optional
149 >>> artobj0 = Artist(**trk)
150 >>> artobj1 = Artist(name='Tool')
152 name = kwargs.get('artist', name).split(', ')[0]
153 mbid = kwargs.get('musicbrainz_artistid', mbid)
154 if (kwargs.get('albumartist', False) and
155 kwargs.get('albumartist') != 'Various Artists'):
156 name = kwargs.get('albumartist').split(', ')[0]
157 if (kwargs.get('musicbrainz_albumartistid', False) and
158 kwargs.get('musicbrainz_albumartistid') != '89ad4ac3-39f7-470e-963a-56509c546377'):
159 mbid = kwargs.get('musicbrainz_albumartistid').split(', ')[0]
160 super().__init__(name=name, mbid=mbid)
162 class MetaContainer(collections.abc.Set):
164 def __init__(self, iterable):
165 self.elements = lst = []
166 for value in iterable:
172 inlst.add_alias(value)
175 return iter(self.elements)
177 def __contains__(self, value):
178 return value in self.elements
181 return len(self.elements)
184 return repr(self.elements)
187 # vim: ai ts=4 sw=4 sts=4 expandtab