summaryrefslogtreecommitdiff
path: root/clMonty.py
blob: bd2df1de04dd1e954006b42eacfd9ca200f914de (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
from PyQt4 import QtCore
from traceback import *
from clSong import Song
from traceback import print_exc
from misc import *
import mpd

class Monty(QtCore.QObject):
	_client=None
	_listeners=None

	" caching"
	_curLib=None
	_curPlaylist=None
	_curSong=None

	_curSongID=None
	_curTime=None
	_curState=None
	_curVolume=None

	_timerID=None

	events={
		'onSongChange':'oldSongID, newSongID',
		'onTimeChange':'oldTime, newTime',
		'onStateChange':'oldState, newState',
		'onVolumeChange':'oldVolume, newVolume',
		'onConnect':'',
		'onDisconnect':'',
		'onReady':'',	# when connected, and initialisation is ready
	}

	def __init__(self):
		QtCore.QObject.__init__(self)
		self._client=None
		self._listeners={}
		
		self._curSongID=-1
		self._curTime=-1
		self._curState=-1
		self._curVolume=-1
		self._curLib=[]
		self._curPlaylist=[]

		for event in self.events:
			self._listeners[event]=[]

	def connect(self, host, port):
		if self._client:
			return
		self._client = mpd.MPDClient()
		try:
			self._client.connect(host, port)
		except:
			self._client=None
			return False
		print "Connected to "+host+":"+str(port)+""
		print "MPD version: "+self._client.mpd_version
		
		self._raiseEvent('onConnect', None)
		try:
			self._updateLib()
			self._updatePlaylist()
			self._timerID=self.startTimer(300)
		except Exception:
			print_exc()
		self._raiseEvent('onStateChange', {'oldState':'stop', 'newState':self.getStatus()['state']})
		self._raiseEvent('onReady', None)
		doEvents()
		return True

	def disconnect(self):
		self._client.close()
		self._client.disconnect()
		self._client=None
		self._killTimer(self.timerID)
	
	def isConnected(self):
		return self._client!=None

	def listPlaylist(self):
		if self.isConnected()==False:
			return None
		return self._curPlaylist

	def listLibrary(self):
		if self.isConnected()==False:
			return None
		return self._curLib

	def getCurrentSong(self):
		if self.isConnected()==False:
			return None
		return self._curSong
		

	def getStatus(self):
		try:
			if self.isConnected()==False:
				return None
			ret=self._retrieve(self._client.status)
			if 'time' in ret:
				len=int(ret['time'][ret['time'].find(':')+1:])
				cur=int(ret['time'][:ret['time'].find(':')])
				ret['length']=len
				ret['time']=cur
			return ret
		except Exception, d:
			print_exc()
			return None
	
	_retrMutex=QtCore.QMutex()
	_cnt=0
	def _retrieve(self, method):
		"""makes sure only one call is made at a time to mpd"""
		self._cnt+=1
		self._retrMutex.lock()
		try:
			ret=method()
		except:
			self._retrMutex.unlock()
			self._cnt-=1
			raise

		self._retrMutex.unlock()
		self._cnt-=1
		return ret

	def play(self, index):
		self._client.playid(index)
	
	def pause(self):
		self._client.pause(1)
	def resume(self):
		self._client.pause(0)
	def next(self):
		self._client.next()
	def previous(self):
		self._client.previous()
	def stop(self):
		self._client.stop()

	def seek(self, time):
		self._client.seekid(self._curSongID, time)
	
	def deleteFromPlaylist(self, list):
		self._client.command_list_ok_begin()
		for id in list:
			self._client.deleteid(id)
		self._client.command_list_end()
		self._updatePlaylist()
	
	def addToPlaylist(self, paths):
		self._client.command_list_ok_begin()
		for path in paths:
			self._client.add(path)
		self._client.command_list_end()
		self._updatePlaylist()

	def setVolume(self, volume):
		self._client.setvol(volume)

	
	def addListener(self, event, callback):
		if not(event in self.events):
			raise Exception("Unknown event "+event)

		self._listeners[event].append(callback)


	def _updateLib(self):
		self._curLib=self._arrayToSongArray(self._retrieve(self._client.listallinfo))
	def _updatePlaylist(self):
		self._curPlaylist=self._arrayToSongArray(self._retrieve(self._client.playlistinfo))
	def _arrayToSongArray(self, array):
		return map(lambda entry: Song(entry)
			, filter(lambda entry: not('directory' in entry), array)
			)
	def _updateCurrentSong(self):
		self._curSong=self._retrieve(self._client.currentsong)
		if self._curSong==None:
			return
		self._curSong=Song(self._curSong)

	def _raiseEvent(self, event, params):
		if not(event in self.events):
			raise Exception("Unknown raised event "+event)

		for listener in self._listeners[event]:
			listener(params)
	
	def timerEvent(self, event):
		try:
			self._updateCurrentSong()
			status=self.getStatus()
		except:
			self._curSong=None

		song=self._curSong
		if song==None or status==None:
			self._client=None
			self._raiseEvent('onDisconnect', None)
			self.killTimer(self._timerID)
			return
		
		" check if song has changed"
		if song.getID()>=0:
			curID=song.getID()
			if curID!=self._curSongID:
				self._raiseEvent('onSongChange', {'oldSongID':self._curSongID, 'newSongID':curID})
				self._curSongID=curID

		" check if the time has changed"
		if 'time' in status:
			curTime=status['time']
			if curTime!=self._curTime:
				self._raiseEvent('onTimeChange', {'oldTime':self._curTime, 'newTime':curTime})
				self._curTime=curTime

		" check if the playing state has changed"
		if 'state' in status:
			curState=status['state']
			if curState!=self._curState:
				self._raiseEvent('onStateChange', {'oldState':self._curState, 'newState':curState})
				self._curState=curState

		" check if the volume has changed"
		if 'state' in status:
			curVolume=int(status['volume'])
			if curVolume!=self._curVolume:
				self._raiseEvent('onVolumeChange', {'oldVolume':self._curVolume, 'newVolume':curVolume})
				self._curVolume=curVolume

monty=Monty()