]> kaliko git repositories - mpd-sima.git/blob - sima/lib/meta.py
Merge Album type in Meta module
[mpd-sima.git] / sima / lib / meta.py
1 # -*- coding: utf-8 -*-
2
3 from .simastr import SimaStr
4 from .track import Track
5
6 class MetaException(Exception):
7     pass
8
9 class NotSameArtist(MetaException):
10     pass
11
12
13 class Meta:
14
15     def __init__(self, **kwargs):
16         self.name = None
17         self.mbid = None
18         if 'name' not in kwargs:
19             raise MetaException('need at least a "name" argument')
20         self.__dict__.update(kwargs)
21
22     def __repr__(self):
23         fmt = '{0}(name="{1.name}", mbid="{1.mbid}")'
24         return fmt.format(self.__class__.__name__, self)
25
26     def __str__(self):
27         return str(self.name)
28
29     def __eq__(self, other):
30         """
31         Perform mbid equality test if present,
32         else fallback on fuzzy equality
33         """
34         if hasattr(other, 'mbid'):
35             if other.mbid and self.mbid:
36                 return self.mbid == other.mbid
37         return SimaStr(str(self)) == SimaStr(str(other))
38
39     def __hash__(self):
40         if self.mbid is not None:
41             return hash(self.mbid)
42         else:
43             return id(self)
44
45
46 class Album(Meta):
47     __hash__ = Meta.__hash__
48
49     def __init__(self, **kwargs):
50         super().__init__(**kwargs)
51
52     def __eq__(self, other):
53         """
54         Perform mbid equality test if present,
55         else fallback on self.name equality
56         """
57         if hasattr(other, 'mbid'):
58             if other.mbid and self.mbid:
59                 return self.mbid == other.mbid
60         return str(self) == str(other)
61
62     @property
63     def album(self):
64         return self.name
65
66
67 class Artist(Meta):
68
69     def __init__(self, **kwargs):
70         self._aliases = []
71         super().__init__(**kwargs)
72
73     def append(self, name):
74         self._aliases.append(name)
75
76     @property
77     def names(self):
78         return self._aliases + [self.name]
79
80     def __add__(self, other):
81         if isinstance(other, Artist):
82             if self.mbid == other.mbid:
83                 res = Artist(**self.__dict__)
84                 res._aliases.extend(other.names)
85                 return res
86             else:
87                 raise NotSameArtist('different mbids: {0} and {1}'.format(self, other))
88
89
90 class TrackMB(Track):
91
92     def __init__(self, **kwargs):
93         super().__init__(**kwargs)
94         if hasattr(self, 'musicbrainz_artistid'):
95             self.artist = Artist(mbid=self.musicbrainz_artistid,
96                                  name=self.artist)
97
98 # vim: ai ts=4 sw=4 sts=4 expandtab
99