]> kaliko git repositories - mpd-sima.git/blob - sima/lib/meta.py
Propagate Artist type
[mpd-sima.git] / sima / lib / meta.py
1 # -*- coding: utf-8 -*-
2 # Copyright (c) 2013, 2014 Jack Kaliko <kaliko@azylum.org>
3 #
4 #  This file is part of sima
5 #
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.
10 #
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.
15 #
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/>.
18 #
19 #
20 """
21 Defines some object to handle audio file metadata
22 """
23
24 import re
25
26 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}$'
27
28 def is_uuid4(uuid):
29     regexp = re.compile(UUID_RE, re.IGNORECASE)
30     if regexp.match(uuid):
31         return True
32     raise WrongUUID4(uuid)
33
34 class MetaException(Exception):
35     """Generic Meta Exception"""
36     pass
37
38 class WrongUUID4(MetaException):
39     pass
40
41
42 class Meta:
43     """Generic Class for Meta object
44     Meta(name=<str>[, mbid=UUID4])
45     """
46
47     def __init__(self, **kwargs):
48         self.__name = None #TODO: should be immutable
49         self.__mbid = None
50         self.__aliases = set()
51         if 'name' not in kwargs or not kwargs.get('name'):
52             raise MetaException('Need a "name" argument')
53         else:
54             self.__name = kwargs.pop('name')
55         if 'mbid' in kwargs and kwargs.get('mbid'):
56             is_uuid4(kwargs.get('mbid'))
57             # mbid immutable as hash rests on
58             self.__mbid = kwargs.pop('mbid')
59         self.__dict__.update(**kwargs)
60
61     def __repr__(self):
62         fmt = '{0}(name={1.name!r}, mbid={1.mbid!r})'
63         return fmt.format(self.__class__.__name__, self)
64
65     def __str__(self):
66         return self.__name.__str__()
67
68     def __eq__(self, other):
69         """
70         Perform mbid equality test
71         """
72         #if hasattr(other, 'mbid'):  # better isinstance?
73         if isinstance(other, Meta) and self.mbid and other.mbid:
74             if self.mbid and other.mbid:
75                 return self.mbid == other.mbid
76         else:
77             return (other.__str__() == self.__str__() or
78                     other.__str__() in self.__aliases)
79         return False
80
81     def __hash__(self):
82         if self.mbid:
83             return hash(self.mbid)
84         return hash(self.__name)
85
86     def add_alias(self, other):
87         if getattr(other, '__str__', None):
88             if callable(other.__str__):
89                 self.__aliases |= {other.__str__()}
90         elif isinstance(other, Meta):
91             self.__aliases |= other.__aliases
92         else:
93             raise MetaException('No __str__ method found in {!r}'.format(other))
94
95     @property
96     def name(self):
97         return self.__name
98
99     @property
100     def mbid(self):
101         return self.__mbid
102
103     @property
104     def aliases(self):
105         return self.__aliases
106
107     @property
108     def names(self):
109         return self.__aliases | {self.__name,}
110
111
112 class Album(Meta):
113
114     @property
115     def album(self):
116         return self.name
117
118 class Artist(Meta):
119
120     def __init__(self, name=None, mbid=None, **kwargs):
121         """Artist object built from a mapping dict containing at least an
122         "artist" entry:
123             >>> trk = {'artist':'Art Name',
124             >>>        'albumartist': 'Alb Art Name',           # optional
125             >>>        'musicbrainz_artistid': '<UUID4>'    ,   # optional
126             >>>        'musicbrainz_albumartistid': '<UUID4>',  # optional
127             >>>       }
128             >>> artobj0 = Artist(**trk)
129             >>> artobj1 = Artist(name='Tool')
130         """
131         name = kwargs.get('artist', name)
132         mbid = kwargs.get('musicbrainz_artistid', mbid)
133         if (kwargs.get('albumartist', False) and
134                 kwargs.get('albumartist') != 'Various Artists'):
135             name = kwargs.get('albumartist').split(', ')[0]
136         if (kwargs.get('musicbrainz_albumartistid', False) and
137                 kwargs.get('musicbrainz_albumartistid') != '89ad4ac3-39f7-470e-963a-56509c546377'):
138             mbid = kwargs.get('musicbrainz_albumartistid').split(', ')[0]
139         super().__init__(name=name, mbid=mbid)
140
141 # VIM MODLINE
142 # vim: ai ts=4 sw=4 sts=4 expandtab