song: convert to a subclass of dict.
[nephilim.git] / nephilim / song.py
blobc9c1145f0dced944fa32d974d062f1b5ec9fba47
2 # Copyright (C) 2009 Anton Khirnov <wyskas@gmail.com>
4 # Nephilim is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
9 # Nephilim is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
14 # You should have received a copy of the GNU General Public License
15 # along with Nephilim. If not, see <http://www.gnu.org/licenses/>.
18 from PyQt4 import QtCore
19 import os
21 from common import sec2min
23 class Song(dict):
24 """Song provides a dictionary-like wrapper around song metadata.
25 Its instances _shouldn't_ be stored, use SongRef or PlaylistEntryRef for that."""
27 def __init__(self, data):
28 # decode all strings to unicode
29 for tag in data:
30 if isinstance(data[tag], str):
31 data[tag] = data[tag].decode('utf-8')
33 dict.__init__(self, data)
35 def __eq__(self, other):
36 if not isinstance(other, Song):
37 return NotImplemented
38 return self['file'] == other['file']
40 def __ne__(self, other):
41 if not isinstance(other, Song):
42 return NotImplemented
43 return self['file'] != other['file']
45 def __getitem__(self, key):
46 try:
47 return dict.__getitem__(self, key)
48 except KeyError:
49 if key == 'tracknum':
50 try:
51 return int(self['track'])
52 except ValueError:
53 try:
54 return int(self['track'].split('/')[0])
55 except ValueError:
56 return 0
57 elif key == 'length':
58 return sec2min(int(self['time']))
59 elif key == 'id':
60 return '-1'
61 elif key == 'title':
62 return self['file']
63 return ''
65 def __nonzero__(self):
66 return bool(self['file'])
68 def expand_tags(self, str):
69 """Expands tags in form $tag in str."""
70 ret = str
71 ret = ret.replace('$title', self['title']) #to ensure that it is set to at least filename
72 for tag in self.keys() + ['tracknum', 'length', 'id']:
73 ret = ret.replace('$' + tag, unicode(self[tag]))
74 ret = ret.replace('$songdir', os.path.dirname(self['file']))
75 return ret
78 class SongRef:
79 """SongRef stores only a reference to the song (uri) instead
80 of full metadata to conserve memory. Song's tags can be accessed
81 as in Song, but it requires a call to MPD for each tag. """
82 path = None
83 mpclient = None
85 def __init__(self, mpclient, path):
86 self.mpclient = mpclient
87 self.path = path
89 def __getitem__(self, key):
90 return self.song()[key]
92 def __nonzero__(self):
93 return bool(self.path)
95 def song(self):
96 try:
97 return Song(self.mpclient.find('file', self.path)[0])
98 except IndexError:
99 return Song({})
101 class PlaylistEntryRef:
102 """This class stores a reference to a playlist entry instead of full
103 metadata to conserve memory. Song's tags can be accessed
104 as in Song, but it requires a call to MPD for each tag. """
105 id = None
106 mpclient = None
108 def __init__(self, mpclient, id):
109 self.mpclient = mpclient
110 self.id = id
112 def __getitem__(self, key):
113 return self.song()[key]
115 def __nonzero__(self):
116 return self.id != '-1'
118 def song(self):
119 try:
120 return Song(self.mpclient.playlistid(id)[0])
121 except IndexError:
122 return Song({})