More dharma stuff.
[clinton/xbmc-groove.git] / default.py
1 import urllib, urllib2, re, xbmcplugin, xbmcgui, xbmc, sys, os, time, pprint, shutil, xbmcaddon
2
3 MODE_SEARCH_SONGS = 1
4 MODE_SEARCH_ALBUMS = 2
5 MODE_SEARCH_ARTISTS = 3
6 MODE_POPULAR = 4
7 MODE_FAVORITES = 5
8 MODE_PLAYLISTS = 6
9 MODE_ALBUM = 7
10 MODE_ARTIST = 8
11 MODE_PLAYLIST = 9
12 MODE_SONG = 10
13 MODE_FAVORITE = 11
14 MODE_UNFAVORITE = 12
15 MODE_SIMILAR_SONG = 13
16 MODE_SIMILAR_ARTIST = 14
17 MODE_FROWN = 15
18
19 lastID = 0
20
21 baseDir = os.getcwd()
22 resDir = xbmc.translatePath(os.path.join(baseDir, 'resources'))
23 libDir = xbmc.translatePath(os.path.join(resDir, 'lib'))
24 imgDir = xbmc.translatePath(os.path.join(resDir, 'img'))
25 thumbDir = os.path.join('special://masterprofile/addon_data/', os.path.join(os.path.basename(os.getcwd()), 'thumb'))
26 favoritesCache = xbmc.translatePath('special://masterprofile/addon_data/', os.path.join(os.path.basename(os.getcwd()), 'favorites.dmp'))
27
28 sys.path.append (libDir)
29 from GrooveAPI import *
30 groovesharkApi = GrooveAPI()
31
32 class _Info:
33 def __init__( self, *args, **kwargs ):
34 self.__dict__.update( kwargs )
35
36 class Groveshark:
37
38 albumImg = xbmc.translatePath(os.path.join(imgDir, 'album.png'))
39 artistImg = xbmc.translatePath(os.path.join(imgDir, 'artist.png'))
40 favoritesImg = xbmc.translatePath(os.path.join(imgDir, 'favorites.png'))
41 playlistImg = xbmc.translatePath(os.path.join(imgDir, 'playlist.png'))
42 popularImg = xbmc.translatePath(os.path.join(imgDir, 'popular.png'))
43 songImg = xbmc.translatePath(os.path.join(imgDir, 'song.png'))
44 defImg = xbmc.translatePath(os.path.join(imgDir, 'default.tbn'))
45 fanImg = xbmc.translatePath(os.path.join(baseDir, 'fanart.png'))
46
47 settings = xbmcaddon.Addon(id='plugin.audio.groove')
48 songsearchlimit = settings.getSetting('songsearchlimit')
49 albumsearchlimit = settings.getSetting('albumsearchlimit')
50 artistsearchlimit = settings.getSetting('artistsearchlimit')
51 username = settings.getSetting('username')
52 password = settings.getSetting('password')
53
54 def __init__( self ):
55 self._handle = int(sys.argv[1])
56
57 def categories(self):
58
59 xbmc.log(self.username + ", limits: " + str(self.songsearchlimit) + ", " + str(self.albumsearchlimit) + ", " + str(self.artistsearchlimit))
60
61 userid = self._get_login()
62
63 # Setup
64 groovesharkApi.setRemoveDuplicates(True)
65 xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
66 if os.path.isdir(thumbDir) == False:
67 os.makedirs(thumbDir)
68
69 self._add_dir('Search songs', '', MODE_SEARCH_SONGS, self.songImg, 0)
70 self._add_dir('Search albums', '', MODE_SEARCH_ALBUMS, self.albumImg, 0)
71 self._add_dir('Search artists', '', MODE_SEARCH_ARTISTS, self.artistImg, 0)
72 self._add_dir('Popular', '', MODE_POPULAR, self.popularImg, 0)
73 if (userid != 0):
74 self._add_dir('Favorites', '', MODE_FAVORITES, self.favoritesImg, 0)
75 self._add_dir('Playlists', '', MODE_PLAYLISTS, self.playlistImg, 0)
76
77 def searchSongs(self):
78 query = self._get_keyboard(default="", heading="Search songs")
79 if (query):
80 songs = groovesharkApi.searchSongs(query, limit = self.songsearchlimit)
81 if (len(songs) > 0):
82 self._add_songs_directory(songs)
83 else:
84 dialog = xbmcgui.Dialog()
85 dialog.ok('Grooveshark', 'No matching songs.')
86 self.categories()
87
88 def searchAlbums(self):
89 query = self._get_keyboard(default="", heading="Search albums")
90 if (query):
91 albums = groovesharkApi.searchAlbums(query, limit = self.albumsearchlimit)
92 if (len(albums) > 0):
93 self._add_albums_directory(albums)
94 else:
95 dialog = xbmcgui.Dialog()
96 dialog.ok('Grooveshark', 'No matching albums.')
97 self.categories()
98
99 def searchArtists(self):
100 query = self._get_keyboard(default="", heading="Search artists")
101 if (query):
102 artists = groovesharkApi.searchArtists(query, limit = self.artistsearchlimit)
103 if (len(artists) > 0):
104 self._add_artists_directory(artists)
105 else:
106 dialog = xbmcgui.Dialog()
107 dialog.ok('Grooveshark', 'No matching artists.')
108 self.categories()
109
110 def favorites(self):
111 favorites = self._get_favorites()
112 if (len(favorites) > 0):
113 self._add_songs_directory(favorites)
114 else:
115 dialog = xbmcgui.Dialog()
116 dialog.ok('Grooveshark', 'You have no favorites.')
117 self.categories()
118
119 def popular(self):
120 popular = groovesharkApi.popularGetSongs(limit = self.songsearchlimit)
121 if (len(popular) > 0):
122 self._add_songs_directory(popular)
123 else:
124 dialog = xbmcgui.Dialog()
125 dialog.ok('Grooveshark', 'No popular songs.')
126 self.categories()
127
128 def playlists(self):
129 userid = self._get_login()
130 if (userid != 0):
131 playlists = groovesharkApi.userGetPlaylists()
132 if (len(playlists) > 0):
133 self._add_playlists_directory(playlists)
134 else:
135 dialog = xbmcgui.Dialog()
136 dialog.ok('Grooveshark', 'You have no playlists.')
137 self.categories()
138
139 def favorite(self, songid):
140 userid = self._get_login()
141 if (userid != 0):
142 xbmc.log("Favorite playSong: " + str(songid))
143 groovesharkApi.favoriteSong(songID = songid)
144 os.remove(favoritesCache)
145 else:
146 dialog = xbmcgui.Dialog()
147 dialog.ok('Grooveshark', 'You must be logged in', 'to add favorites.')
148
149 def unfavorite(self, songid):
150 userid = self._get_login()
151 if (userid != 0):
152 xbmc.log("Unfavorite playSong: " + str(songid))
153 groovesharkApi.unfavoriteSong(songID = songid)
154 os.remove(favoritesCache)
155 else:
156 dialog = xbmcgui.Dialog()
157 dialog.ok('Grooveshark', 'You must be logged in', 'to remove favorites.')
158
159 def frown(self, songid):
160 userid = self._get_login()
161 if (userid != 0):
162 xbmc.log("Frown playSong: " + str(songid))
163 if groovesharkApi.radioFrown(songId = songid) != True:
164 xbmc.log("Unable to frown song " + str(songid))
165 else:
166 dialog = xbmcgui.Dialog()
167 dialog.ok('Grooveshark', 'You must be logged in', 'to frown a song.')
168
169 def similarSong(self, songid):
170 userid = self._get_login()
171 if (userid != 0):
172 xbmc.log("Frown playSong: " + str(songid))
173 if groovesharkApi.radioSong(songId = songid) and groovesharkApi.radioStartSongs() == True:
174 self.playNext()
175 else:
176 dialog = xbmcgui.Dialog()
177 dialog.ok('Grooveshark', 'Cannot start radio')
178 else:
179 dialog = xbmcgui.Dialog()
180 dialog.ok('Grooveshark', 'You must be logged in', 'to update radio song.')
181
182 def similarArtist(self, artistId):
183 userid = self._get_login()
184 if (userid != 0):
185 xbmc.log("Add radio artist of playSong: " + str(artistId))
186 if groovesharkApi.radioArtist(artistId = artistId) and groovesharkApi.radioStartArtists() == True:
187 self.playNext()
188 else:
189 dialog = xbmcgui.Dialog()
190 dialog.ok('Grooveshark', 'Cannot start radio')
191 else:
192 dialog = xbmcgui.Dialog()
193 dialog.ok('Grooveshark', 'You must be logged in', 'to update radio artists.')
194
195 def album(self,albumid):
196 album = groovesharkApi.albumGetSongs(albumId = albumid, limit = self.songsearchlimit)
197 self._add_songs_directory(album)
198
199 def artist(self, artistid):
200 albums = groovesharkApi.artistGetAlbums(artistId = artistid, limit = self.albumsearchlimit)
201 self._add_albums_directory(albums)
202
203 def playlist(self, playlistid):
204 userid = self._get_login()
205 if (userid != 0):
206 songs = groovesharkApi.playlistGetSongs(playlistId = playlistid, limit = self.songsearchlimit)
207 self._add_songs_directory(songs)
208 else:
209 dialog = xbmcgui.Dialog()
210 dialog.ok('Grooveshark', 'You must be logged in', 'to get playlists.')
211
212 def playSong(self, item):
213 url = item.getProperty('url')
214 xbmc.log("Playing: " + url)
215 xbmcplugin.setResolvedUrl(handle=int(sys.argv[1]), succeeded=True, listitem=item)
216
217 def playNext(self):
218 item = self._get_song_item(groovesharkApi.radioNextSong()[0])
219 self.playSong(item)
220
221 def songItem(self, id, name, album, artist, duration, thumb, image):
222 url = groovesharkApi.getStreamURL(id)
223 songImg = self._get_icon(image, 'song-' + str(id) + "-image")
224 songThm = self._get_icon(thumb, 'song-' + str(id) + "-thumb")
225 item = xbmcgui.ListItem(label = artist + " - " + album + " - " + name, path=url, thumbnailImage=songThm, iconImage=songImg)
226 item.setInfo( type="music", infoLabels={ "title": name, "duration": duration, "album": album, "artist": artist} )
227 item.setProperty('mimetype', 'audio/mpeg')
228 item.setProperty("IsPlayable", "true")
229 item.setProperty('url', url)
230 item.setProperty('thumb', songThm)
231 item.setProperty('image', songImg)
232
233 return item
234
235 def _get_favorites(self):
236 favorites = []
237 # if the cache does not exist or is older than x hours then reload
238 if (os.path.isfile(favoritesCache) == False) or (time.gmtime() - os.path.gmtime(favoritesCache) > 3*60*60):
239 xbmc.log("Refresh favorites cache")
240 userid = self._get_login()
241 if (userid != 0):
242 favorites = groovesharkApi.userGetFavoriteSongs(userid)
243 f = open(favoritesCache, 'wb')
244 pickle.dump(favorites, f, protocol=pickle.HIGHEST_PROTOCOL)
245 f.close()
246 xbmc.log("Refreshed favorites cache")
247 # if not old then read from cache
248 elif os.path.isfile(favoritesCache):
249 xbmc.log("Existing favorites cache")
250 f = open(favoritesCache, 'rb')
251 favorites = pickle.load(f)
252 f.close()
253
254 return favorites
255
256 def _get_keyboard(self, default="", heading="", hidden=False):
257 kb = xbmc.Keyboard(default, heading, hidden)
258 kb.doModal()
259 if (kb.isConfirmed()):
260 return unicode(kb.getText(), "utf-8")
261 return ''
262
263 def _get_login(self):
264 if (self.username == "" or self.password == ""):
265 dialog = xbmcgui.Dialog()
266 dialog.ok('Grooveshark', 'Unable to login.', 'Check username and password in settings.')
267 return 0
268 else:
269 if groovesharkApi.loggedInStatus() == 1:
270 groovesharkApi.logout()
271 userid = groovesharkApi.loginExt(self.username, self.password)
272 if (userid != 0):
273 xbmc.log("Logged in")
274 return userid
275 else:
276 dialog = xbmcgui.Dialog()
277 dialog.ok('Grooveshark', 'Unable to login.', 'Check username and password in settings.')
278 return 0
279
280 def _get_song_item(self, song):
281 name = song[0]
282 id = song[1]
283 duration = song[2]
284 album = song[3]
285 artist = song[6]
286 thumb = song[8]
287 image = song[9]
288 return self.songItem(id, name, album, artist, duration, thumb, image)
289
290 # File download
291 def _get_icon(self, url, id):
292 localThumb = os.path.join(xbmc.translatePath(os.path.join(thumbDir, str(id)))) + '.tbn'
293 xbmc.log('Downloading ' + url + ' to ' + localThumb)
294 try:
295 if os.path.isfile(localThumb) == False:
296 loc = urllib.URLopener()
297 loc.retrieve(url, localThumb)
298 except:
299 xbmc.log('URL download failed of ' + url + ' to ' + localThumb)
300 return(self.defImg)
301
302 return os.path.join(os.path.join(thumbDir, str(id))) + '.tbn'
303
304 def _add_songs_directory(self, songs):
305 n = len(songs)
306 xbmc.log("Found " + str(n) + " songs...")
307 i = 0
308 while i < n:
309 song = songs[i]
310 item = self._get_song_item(song)
311 songurl = item.getProperty('url')
312 songthumb = item.getProperty('thumb')
313 songimage = item.getProperty('image')
314 songname = song[0]
315 songid = song[1]
316 songduration = song[2]
317 songalbum = song[3]
318 songartist = song[6]
319 songartistid = song[7]
320 u=sys.argv[0]+"?url="+urllib.quote_plus(songurl) \
321 +"&mode="+str(MODE_SONG)+"&name="+urllib.quote_plus(songname)+"&id=" \
322 +str(songid) \
323 +"&album="+urllib.quote_plus(songalbum) \
324 +"&artist="+urllib.quote_plus(songartist) \
325 +"&duration="+str(songduration) \
326 +"&thumb="+urllib.quote_plus(songthumb) \
327 +"&image="+urllib.quote_plus(songimage)
328 fav=sys.argv[0]+"?url="+urllib.quote_plus(songurl)+"&mode="+str(MODE_FAVORITE)+"&name="+urllib.quote_plus(songname)+"&id="+str(songid)
329 unfav=sys.argv[0]+"?url="+urllib.quote_plus(songurl)+"&mode="+str(MODE_UNFAVORITE)+"&name="+urllib.quote_plus(songname)+"&id="+str(songid)
330 similarArtist=sys.argv[0]+"?mode="+str(MODE_SIMILAR_ARTIST)+"&id="+str(songartistid)
331 similarSong=sys.argv[0]+"?mode="+str(MODE_SIMILAR_SONG)+"&id="+str(songid)
332 frown=sys.argv[0]+"?mode="+str(MODE_FROWN)+"&id="+str(songid)
333 menuItems = []
334 menuItems.append(("Grooveshark Favorite", "XBMC.RunPlugin("+fav+")"))
335 menuItems.append(("Not Grooveshark Favorite", "XBMC.RunPlugin("+unfav+")"))
336 menuItems.append(("Listen to similar artist", "XBMC.RunPlugin("+similarArtist+")"))
337 menuItems.append(("Listen to similar song", "XBMC.RunPlugin("+similarSong+")"))
338 menuItems.append(("No thanks!", "XBMC.RunPlugin("+frown+")"))
339 item.addContextMenuItems(menuItems, replaceItems=False)
340 xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=item,isFolder=False)
341 i = i + 1
342 xbmcplugin.setContent(self._handle, 'songs')
343
344 def _add_albums_directory(self, albums):
345 xbmc.log("Found " + str(len(albums)) + " albums...")
346 i = 0
347 while i < len(albums):
348 album = albums[i]
349 albumArtistName = album[0]
350 albumName = album[2]
351 albumID = album[3]
352 albumImage = self._get_icon(album[4], 'album-' + str(albumID))
353 self._add_dir(albumName + " - " + albumArtistName, '', MODE_ALBUM, albumImage, albumID)
354 i = i + 1
355 xbmcplugin.setContent(self._handle, 'albums')
356 xbmcplugin.addSortMethod(self._handle, xbmcplugin.SORT_METHOD_ALBUM_IGNORE_THE)
357
358 def _add_artists_directory(self, artists):
359 xbmc.log("Found " + str(len(artists)) + " artists...")
360 i = 0
361 while i < len(artists):
362 artist = artists[i]
363 artistName = artist[0]
364 artistID = artist[1]
365 self._add_dir(artistName, '', MODE_ARTIST, self.artistImg, artistID)
366 i = i + 1
367 xbmcplugin.setContent(self._handle, 'artists')
368 xbmcplugin.addSortMethod(self._handle, xbmcplugin.SORT_METHOD_ARTIST_IGNORE_THE)
369
370 def _add_playlists_directory(self, playlists):
371 xbmc.log("Found " + str(len(playlists)) + " playlists...")
372 i = 0
373 while i < len(playlists):
374 playlist = playlists[i]
375 playlistName = playlist[0]
376 playlistID = playlist[1]
377 self._add_dir(playlistName, '', MODE_PLAYLIST, self.playlistImg, playlistID)
378 i = i + 1
379 xbmcplugin.setContent(self._handle, 'files')
380 xbmcplugin.addSortMethod(self._handle, xbmcplugin.SORT_METHOD_PLAYLIST_ORDER)
381
382 def _add_dir(self, name, url, mode, iconimage, id):
383 u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&id="+str(id)
384 dir=xbmcgui.ListItem(name, iconImage=iconimage, thumbnailImage=iconimage)
385 dir.setInfo( type="Music", infoLabels={ "title": name } )
386 # Codes from http://xbmc-scripting.googlecode.com/svn/trunk/Script%20Templates/common/gui/codes.py
387 menuItems = []
388 menuItems.append(("Select", "XBMC.executebuiltin(Action(7))"))
389 dir.addContextMenuItems(menuItems, replaceItems=True)
390 return xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=dir,isFolder=True)
391
392
393 def get_params():
394 param=[]
395 paramstring=sys.argv[2]
396 if len(paramstring)>=2:
397 params=sys.argv[2]
398 cleanedparams=params.replace('?','')
399 if (params[len(params)-1]=='/'):
400 params=params[0:len(params)-2]
401 pairsofparams=cleanedparams.split('&')
402 param={}
403 for i in range(len(pairsofparams)):
404 splitparams={}
405 splitparams=pairsofparams[i].split('=')
406 if (len(splitparams))==2:
407 param[splitparams[0]]=splitparams[1]
408 print param
409 return param
410
411 grooveshark = Groveshark();
412
413 params=get_params()
414 url=None
415 name=None
416 mode=None
417 id=None
418
419 try: url=urllib.unquote_plus(params["url"])
420 except: pass
421 try: name=urllib.unquote_plus(params["name"])
422 except: pass
423 try: mode=int(params["mode"])
424 except: pass
425 try: id=int(params["id"])
426 except: pass
427
428 if (id > 0):
429 lastID = id
430
431 if mode==None:
432 grooveshark.categories()
433
434 elif mode==MODE_SEARCH_SONGS:
435 grooveshark.searchSongs()
436
437 elif mode==MODE_SEARCH_ALBUMS:
438 grooveshark.searchAlbums()
439
440 elif mode==MODE_SEARCH_ARTISTS:
441 grooveshark.searchArtists()
442
443 elif mode==MODE_POPULAR:
444 grooveshark.popular()
445
446 elif mode==MODE_PLAYLISTS:
447 grooveshark.playlists()
448
449 elif mode==MODE_FAVORITES:
450 grooveshark.favorites()
451
452 elif mode==MODE_SONG:
453 try: name=urllib.unquote_plus(params["name"])
454 except: pass
455 try: album=urllib.unquote_plus(params["album"])
456 except: pass
457 try: artist=urllib.unquote_plus(params["artist"])
458 except: pass
459 try: duration=int(params["duration"])
460 except: pass
461 try: thumb=urllib.unquote_plus(params["thumb"])
462 except: pass
463 try: image=urllib.unquote_plus(params["image"])
464 except: pass
465 song = grooveshark.songItem(id, name, album, artist, duration, thumb, image)
466 grooveshark.playSong(song)
467
468 elif mode==MODE_ARTIST:
469 grooveshark.artist(lastID)
470
471 elif mode==MODE_ALBUM:
472 grooveshark.album(lastID)
473
474 elif mode==MODE_PLAYLIST:
475 grooveshark.playlist(lastID)
476
477 elif mode==MODE_FAVORITE:
478 grooveshark.favorite(lastID)
479
480 elif mode==MODE_UNFAVORITE:
481 grooveshark.unfavorite(lastID)
482
483 elif mode==MODE_SIMILAR_ARTIST:
484 grooveshark.similarArtist(lastID)
485
486 elif mode==MODE_SIMILAR_SONG:
487 grooveshark.similarSong(lastID)
488
489 elif mode==MODE_FROWN:
490 grooveshark.frown(lastID)
491
492 if (mode < MODE_SONG):
493 xbmcplugin.endOfDirectory(int(sys.argv[1]))