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