]> kaliko git repositories - mpd-sima.git/blob - sima/lib/meta.py
New option to disable use of mbid
[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 def mbidfilter(func):
42     def wrapper(*args, **kwargs):
43         cls = args[0]
44         if not cls.use_mbid:
45             kwargs.pop('mbid', None)
46             kwargs.pop('musicbrainz_artistid', None)
47             kwargs.pop('musicbrainz_albumartistid', None)
48         func(*args, **kwargs)
49     return wrapper
50
51
52 class Meta:
53     """Generic Class for Meta object
54     Meta(name=<str>[, mbid=UUID4])
55     """
56     use_mbid = True
57
58     def __init__(self, **kwargs):
59         self.__name = None #TODO: should be immutable
60         self.__mbid = None
61         self.__aliases = set()
62         if 'name' not in kwargs or not kwargs.get('name'):
63             raise MetaException('Need a "name" argument')
64         else:
65             self.__name = kwargs.pop('name')
66         if 'mbid' in kwargs and kwargs.get('mbid'):
67             is_uuid4(kwargs.get('mbid'))
68             # mbid immutable as hash rests on
69             self.__mbid = kwargs.pop('mbid')
70         self.__dict__.update(**kwargs)
71
72     def __repr__(self):
73         fmt = '{0}(name={1.name!r}, mbid={1.mbid!r})'
74         return fmt.format(self.__class__.__name__, self)
75
76     def __str__(self):
77         return self.__name.__str__()
78
79     def __eq__(self, other):
80         """
81         Perform mbid equality test
82         """
83         #if hasattr(other, 'mbid'):  # better isinstance?
84         if isinstance(other, Meta) and self.mbid and other.mbid:
85             if self.mbid and other.mbid:
86                 return self.mbid == other.mbid
87         else:
88             return (other.__str__() == self.__str__() or
89                     other.__str__() in self.__aliases)
90         return False
91
92     def __hash__(self):
93         if self.mbid:
94             return hash(self.mbid)
95         return hash(self.__name)
96
97     def add_alias(self, other):
98         if getattr(other, '__str__', None):
99             if callable(other.__str__):
100                 self.__aliases |= {other.__str__()}
101         elif isinstance(other, Meta):
102             self.__aliases |= other.__aliases
103         else:
104             raise MetaException('No __str__ method found in {!r}'.format(other))
105
106     @property
107     def name(self):
108         return self.__name
109
110     @property
111     def mbid(self):
112         return self.__mbid
113
114     @property
115     def aliases(self):
116         return self.__aliases
117
118     @property
119     def names(self):
120         return self.__aliases | {self.__name,}
121
122
123 class Album(Meta):
124
125     @property
126     def album(self):
127         return self.name
128
129 class Artist(Meta):
130
131     @mbidfilter
132     def __init__(self, name=None, mbid=None, **kwargs):
133         """Artist object built from a mapping dict containing at least an
134         "artist" entry:
135             >>> trk = {'artist':'Art Name',
136             >>>        'albumartist': 'Alb Art Name',           # optional
137             >>>        'musicbrainz_artistid': '<UUID4>'    ,   # optional
138             >>>        'musicbrainz_albumartistid': '<UUID4>',  # optional
139             >>>       }
140             >>> artobj0 = Artist(**trk)
141             >>> artobj1 = Artist(name='Tool')
142         """
143         name = kwargs.get('artist', name)
144         mbid = kwargs.get('musicbrainz_artistid', mbid)
145         if (kwargs.get('albumartist', False) and
146                 kwargs.get('albumartist') != 'Various Artists'):
147             name = kwargs.get('albumartist').split(', ')[0]
148         if (kwargs.get('musicbrainz_albumartistid', False) and
149                 kwargs.get('musicbrainz_albumartistid') != '89ad4ac3-39f7-470e-963a-56509c546377'):
150             mbid = kwargs.get('musicbrainz_albumartistid').split(', ')[0]
151         super().__init__(name=name, mbid=mbid)
152
153 # VIM MODLINE
154 # vim: ai ts=4 sw=4 sts=4 expandtab