Add search of artist's albums.
[clinton/xbmc-groove.git] / default.py
... / ...
CommitLineData
1import urllib, sys, os, shutil, re, time, xbmcaddon, xbmcplugin, xbmcgui, xbmc
2MODE_SEARCH_SONGS = 1
3MODE_SEARCH_ALBUMS = 2
4MODE_SEARCH_ARTISTS = 3
5MODE_SEARCH_ARTISTS_ALBUMS = 4
6MODE_SEARCH_PLAYLISTS = 5
7MODE_POPULAR_SONGS = 6
8MODE_FAVORITES = 7
9MODE_PLAYLISTS = 8
10MODE_ALBUM = 9
11MODE_ARTIST = 10
12MODE_PLAYLIST = 11
13MODE_SONG = 12
14MODE_FAVORITE = 13
15
16ACTION_MOVE_LEFT = 1
17ACTION_MOVE_UP = 3
18ACTION_MOVE_DOWN = 4
19ACTION_PAGE_UP = 5
20ACTION_PAGE_DOWN = 6
21ACTION_SELECT_ITEM = 7
22ACTION_PREVIOUS_MENU = 10
23
24# Formats for track labels
25ARTIST_ALBUM_NAME_LABEL = 0
26NAME_ALBUM_ARTIST_LABEL = 1
27
28baseDir = os.getcwd()
29resDir = xbmc.translatePath(os.path.join(baseDir, 'resources'))
30libDir = xbmc.translatePath(os.path.join(resDir, 'lib'))
31imgDir = xbmc.translatePath(os.path.join(resDir, 'img'))
32cacheDir = os.path.join(xbmc.translatePath('special://masterprofile/addon_data/'), os.path.basename(os.getcwd()))
33thumbDirName = 'thumb'
34thumbDir = os.path.join('special://masterprofile/addon_data/', os.path.basename(os.getcwd()), thumbDirName)
35
36baseModeUrl = 'plugin://plugin.audio.groove/'
37playlistUrl = baseModeUrl + '?mode=' + str(MODE_PLAYLIST)
38playlistsUrl = baseModeUrl + '?mode=' + str(MODE_PLAYLISTS)
39favoritesUrl = baseModeUrl + '?mode=' + str(MODE_FAVORITES)
40
41thumbDef = os.path.join(imgDir, 'default.tbn')
42
43sys.path.append (libDir)
44from GroovesharkAPI import GrooveAPI
45
46try:
47 groovesharkApi = GrooveAPI()
48 if groovesharkApi.pingService() != True:
49 raise StandardError('No Grooveshark service')
50except:
51 dialog = xbmcgui.Dialog()
52 dialog.ok('Grooveshark XBMC', 'Unable to connect with Grooveshark.', 'Please try again later')
53 sys.exit(-1)
54
55
56class _Info:
57 def __init__( self, *args, **kwargs ):
58 self.__dict__.update( kwargs )
59
60
61class Groveshark:
62
63 albumImg = xbmc.translatePath(os.path.join(imgDir, 'album.png'))
64 artistImg = xbmc.translatePath(os.path.join(imgDir, 'artist.png'))
65 artistsAlbumsImg = xbmc.translatePath(os.path.join(imgDir, 'artistsalbums.png'))
66 favoritesImg = xbmc.translatePath(os.path.join(imgDir, 'favorites.png'))
67 playlistImg = xbmc.translatePath(os.path.join(imgDir, 'playlist.png'))
68 usersplaylistsImg = xbmc.translatePath(os.path.join(imgDir, 'usersplaylists.png'))
69 popularSongsImg = xbmc.translatePath(os.path.join(imgDir, 'popularSongs.png'))
70 songImg = xbmc.translatePath(os.path.join(imgDir, 'song.png'))
71 defImg = xbmc.translatePath(os.path.join(imgDir, 'default.tbn'))
72 fanImg = xbmc.translatePath(os.path.join(baseDir, 'fanart.png'))
73
74 settings = xbmcaddon.Addon(id='plugin.audio.groove')
75 songsearchlimit = int(settings.getSetting('songsearchlimit'))
76 albumsearchlimit = int(settings.getSetting('albumsearchlimit'))
77 artistsearchlimit = int(settings.getSetting('artistsearchlimit'))
78 username = settings.getSetting('username')
79 password = settings.getSetting('password')
80 userid = 0
81
82 def __init__( self ):
83 self._handle = int(sys.argv[1])
84 if os.path.isdir(cacheDir) == False:
85 os.makedirs(cacheDir)
86 xbmc.log("Made " + cacheDir)
87 artDir = xbmc.translatePath(thumbDir)
88 if os.path.isdir(artDir) == False:
89 os.makedirs(artDir)
90 xbmc.log("Made " + artDir)
91
92 # Top-level menu
93 def categories(self):
94
95 self.userid = self._get_login()
96
97 # Setup
98 xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
99
100 self._add_dir('Search for songs...', '', MODE_SEARCH_SONGS, self.songImg, 0)
101 self._add_dir('Search for albums...', '', MODE_SEARCH_ALBUMS, self.albumImg, 0)
102 self._add_dir('Search for artists...', '', MODE_SEARCH_ARTISTS, self.artistImg, 0)
103 self._add_dir("Search for artist's albums...", '', MODE_SEARCH_ARTISTS_ALBUMS, self.artistsAlbumsImg, 0)
104 self._add_dir("Search for user's playlists...", '', MODE_SEARCH_PLAYLISTS, self.usersplaylistsImg, 0)
105 self._add_dir('Popular songs', '', MODE_POPULAR_SONGS, self.popularSongsImg, 0)
106 if (self.userid != 0):
107 self._add_dir('My favorites', '', MODE_FAVORITES, self.favoritesImg, 0)
108 self._add_dir('My playlists', '', MODE_PLAYLISTS, self.playlistImg, 0)
109
110 # Search for songs
111 def searchSongs(self):
112 query = self._get_keyboard(default="", heading="Search for songs")
113 if (query != ''):
114 songs = groovesharkApi.getSongSearchResults(query, limit = self.songsearchlimit)
115 if (len(songs) > 0):
116 self._add_songs_directory(songs)
117 else:
118 dialog = xbmcgui.Dialog()
119 dialog.ok('Grooveshark XBMC', 'No matching songs.')
120 self.categories()
121 else:
122 self.categories()
123
124 # Search for albums
125 def searchAlbums(self):
126 query = self._get_keyboard(default="", heading="Search for albums")
127 if (query != ''):
128 albums = groovesharkApi.getAlbumSearchResults(query, limit = self.albumsearchlimit)
129 if (len(albums) > 0):
130 self._add_albums_directory(albums)
131 else:
132 dialog = xbmcgui.Dialog()
133 dialog.ok('Grooveshark XBMC', 'No matching albums.')
134 self.categories()
135 else:
136 self.categories()
137
138 # Search for artists
139 def searchArtists(self):
140 query = self._get_keyboard(default="", heading="Search for artists")
141 if (query != ''):
142 artists = groovesharkApi.getArtistSearchResults(query, limit = self.artistsearchlimit)
143 if (len(artists) > 0):
144 self._add_artists_directory(artists)
145 else:
146 dialog = xbmcgui.Dialog()
147 dialog.ok('Grooveshark XBMC', 'No matching artists.')
148 self.categories()
149 else:
150 self.categories()
151
152 # Search for playlists
153 def searchPlaylists(self):
154 query = self._get_keyboard(default="", heading="Search for user's playlists")
155 if (query != ''):
156 playlists = groovesharkApi.getUserPlaylistsEx(query)
157 if (len(playlists) > 0):
158 self._add_playlists_directory(playlists)
159 else:
160 dialog = xbmcgui.Dialog()
161 dialog.ok('Grooveshark XBMC', 'No Grooveshark playlists found.')
162 self.categories()
163 else:
164 self.categories()
165
166 # Search for artists albums
167 def searchArtistsAlbums(self):
168 query = self._get_keyboard(default="", heading="Search for artist's albums")
169 if (query != ''):
170 artists = groovesharkApi.getArtistSearchResults(query, limit = self.artistsearchlimit)
171 if (len(artists) > 0):
172 artist = artists[0]
173 artistID = artist[1]
174 xbmc.log("Found " + artist[0] + "...")
175 albums = groovesharkApi.getArtistAlbums(artistID, limit = self.albumsearchlimit)
176 if (len(albums) > 0):
177 self._add_albums_directory(albums)
178 else:
179 dialog = xbmcgui.Dialog()
180 dialog.ok('Grooveshark XBMC', 'No matching albums.')
181 self.categories()
182 else:
183 dialog = xbmcgui.Dialog()
184 dialog.ok('Grooveshark XBMC', 'No matching artists.')
185 self.categories()
186 else:
187 self.categories()
188
189 # Get my favorites
190 def favorites(self):
191 userid = self._get_login()
192 if (userid != 0):
193 favorites = groovesharkApi.getUserFavoriteSongs()
194 if (len(favorites) > 0):
195 self._add_songs_directory(favorites)
196 else:
197 dialog = xbmcgui.Dialog()
198 dialog.ok('Grooveshark XBMC', 'You have no favorites.')
199 self.categories()
200
201 # Get popular songs
202 def popularSongs(self):
203 popular = groovesharkApi.getPopularSongsToday(limit = self.songsearchlimit)
204 if (len(popular) > 0):
205 self._add_songs_directory(popular)
206 else:
207 dialog = xbmcgui.Dialog()
208 dialog.ok('Grooveshark XBMC', 'No popular songs.')
209 self.categories()
210
211 # Get my playlists
212 def playlists(self):
213 userid = self._get_login()
214 if (userid != 0):
215 playlists = groovesharkApi.getUserPlaylists()
216 if (len(playlists) > 0):
217 self._add_playlists_directory(playlists)
218 else:
219 dialog = xbmcgui.Dialog()
220 dialog.ok('Grooveshark XBMC', 'You have no Grooveshark playlists.')
221 self.categories()
222 else:
223 dialog = xbmcgui.Dialog()
224 dialog.ok('Grooveshark XBMC', 'You must be logged in ', ' to see your Grooveshark playlists.')
225
226 # Make songs a favorite
227 def favorite(self, songid):
228 userid = self._get_login()
229 if (userid != 0):
230 xbmc.log("Favorite song: " + str(songid))
231 groovesharkApi.addUserFavoriteSong(songID = songid)
232 xbmc.executebuiltin('XBMC.Notification(Grooveshark XBMC, Added to favorites, 1000, ' + thumbDef + ')')
233 else:
234 dialog = xbmcgui.Dialog()
235 dialog.ok('Grooveshark XBMC', 'You must be logged in', 'to add favorites.')
236
237 # Show selected album
238 def album(self, albumid):
239 album = groovesharkApi.getAlbumSongs(albumid, limit = self.songsearchlimit)
240 self._add_songs_directory(album, trackLabelFormat=NAME_ALBUM_ARTIST_LABEL)
241
242 # Show selected artist
243 def artist(self, artistid):
244 albums = groovesharkApi.getArtistAlbums(artistid, limit = self.albumsearchlimit)
245 self._add_albums_directory(albums)
246
247 # Show selected playlist
248 def playlist(self, playlistid):
249 userid = self._get_login()
250 if (userid != 0):
251 songs = groovesharkApi.getPlaylistSongs(playlistid)
252 self._add_songs_directory(songs, trackLabelFormat=NAME_ALBUM_ARTIST_LABEL)
253 else:
254 dialog = xbmcgui.Dialog()
255 dialog.ok('Grooveshark XBMC', 'You must be logged in', 'to get Grooveshark playlists.')
256
257 # Play a song
258 def playSong(self, item):
259 songid = item.getProperty('songid')
260 song = groovesharkApi.getSongURLFromSongID(songid)
261 if song != '':
262 item.setPath(song)
263 xbmc.log("Playing: " + song)
264 xbmcplugin.setResolvedUrl(handle=int(sys.argv[1]), succeeded=True, listitem=item)
265 else:
266 xbmc.executebuiltin('XBMC.Notification(Grooveshark XBMC, Unable to play song, 1000, ' + thumbDef + ')')
267
268 # Make a song directory item
269 def songItem(self, songid, name, album, artist, coverart, trackLabelFormat=ARTIST_ALBUM_NAME_LABEL):
270 songImg = self._get_icon(coverart, 'song-' + str(songid) + "-image")
271 if trackLabelFormat == NAME_ALBUM_ARTIST_LABEL:
272 trackLabel = name + " - " + album + " - " + artist
273 else:
274 trackLabel = artist + " - " + album + " - " + name
275 item = xbmcgui.ListItem(label = trackLabel, thumbnailImage=songImg, iconImage=songImg)
276 item.setInfo( type="music", infoLabels={ "title": name, "album": album, "artist": artist} )
277 item.setProperty('mimetype', 'audio/mpeg')
278 item.setProperty("IsPlayable", "true")
279 item.setProperty('songid', str(songid))
280 item.setProperty('coverart', songImg)
281 item.setProperty('title', name)
282 item.setProperty('album', album)
283 item.setProperty('artist', artist)
284
285 return item
286
287 # Get keyboard input
288 def _get_keyboard(self, default="", heading="", hidden=False):
289 kb = xbmc.Keyboard(default, heading, hidden)
290 kb.doModal()
291 if (kb.isConfirmed()):
292 return unicode(kb.getText(), "utf-8")
293 return ''
294
295 # Login to grooveshark
296 def _get_login(self):
297 if (self.username == "" or self.password == ""):
298 dialog = xbmcgui.Dialog()
299 dialog.ok('Grooveshark XBMC', 'Unable to login.', 'Check username and password in settings.')
300 return 0
301 else:
302 if self.userid == 0:
303 uid = groovesharkApi.login(self.username, self.password)
304 if (uid != 0):
305 return uid
306 else:
307 dialog = xbmcgui.Dialog()
308 dialog.ok('Grooveshark XBMC', 'Unable to login.', 'Check username and password in settings.')
309 return 0
310
311 # Get a song directory item
312 def _get_song_item(self, song, trackLabelFormat):
313 name = song[0]
314 songid = song[1]
315 album = song[2]
316 artist = song[4]
317 coverart = song[6]
318 return self.songItem(songid, name, album, artist, coverart, trackLabelFormat)
319
320 # File download
321 def _get_icon(self, url, songid):
322 if url != 'None':
323 localThumb = os.path.join(xbmc.translatePath(os.path.join(thumbDir, str(songid)))) + '.tbn'
324 try:
325 if os.path.isfile(localThumb) == False:
326 loc = urllib.URLopener()
327 loc.retrieve(url, localThumb)
328 except:
329 shutil.copy2(thumbDef, localThumb)
330 return os.path.join(os.path.join(thumbDir, str(songid))) + '.tbn'
331 else:
332 return thumbDef
333
334 # Add songs to directory
335 def _add_songs_directory(self, songs, trackLabelFormat=ARTIST_ALBUM_NAME_LABEL):
336 n = len(songs)
337 xbmc.log("Found " + str(n) + " songs...")
338 i = 0
339 while i < n:
340 song = songs[i]
341 item = self._get_song_item(song, trackLabelFormat)
342 coverart = item.getProperty('coverart')
343 songname = song[0]
344 songid = song[1]
345 songalbum = song[2]
346 songartist = song[4]
347 u=sys.argv[0]+"?mode="+str(MODE_SONG)+"&name="+urllib.quote_plus(songname)+"&id="+str(songid) \
348 +"&album="+urllib.quote_plus(songalbum) \
349 +"&artist="+urllib.quote_plus(songartist) \
350 +"&coverart="+urllib.quote_plus(coverart)
351 fav=sys.argv[0]+"?mode="+str(MODE_FAVORITE)+"&name="+urllib.quote_plus(songname)+"&id="+str(songid)
352 menuItems = []
353 menuItems.append(("Grooveshark favorite", "XBMC.RunPlugin("+fav+")"))
354 item.addContextMenuItems(menuItems, replaceItems=False)
355 xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=item,isFolder=False, totalItems=n)
356 i = i + 1
357
358 xbmcplugin.setContent(self._handle, 'songs')
359 xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
360
361 # Add albums to directory
362 def _add_albums_directory(self, albums):
363 n = len(albums)
364 xbmc.log("Found " + str(n) + " albums...")
365 i = 0
366 while i < n:
367 album = albums[i]
368 albumArtistName = album[0]
369 albumName = album[2]
370 albumID = album[3]
371 albumImage = self._get_icon(album[4], 'album-' + str(albumID))
372 self._add_dir(albumName + " - " + albumArtistName, '', MODE_ALBUM, albumImage, albumID, n)
373 i = i + 1
374 xbmcplugin.setContent(self._handle, 'albums')
375 xbmcplugin.addSortMethod(self._handle, xbmcplugin.SORT_METHOD_ALBUM_IGNORE_THE)
376 xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
377
378 # Add artists to directory
379 def _add_artists_directory(self, artists):
380 n = len(artists)
381 xbmc.log("Found " + str(n) + " artists...")
382 i = 0
383 while i < n:
384 artist = artists[i]
385 artistName = artist[0]
386 artistID = artist[1]
387 self._add_dir(artistName, '', MODE_ARTIST, self.artistImg, artistID, n)
388 i = i + 1
389 xbmcplugin.setContent(self._handle, 'artists')
390 xbmcplugin.addSortMethod(self._handle, xbmcplugin.SORT_METHOD_ARTIST_IGNORE_THE)
391 xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
392
393 # Add playlists to directory
394 def _add_playlists_directory(self, playlists):
395 n = len(playlists)
396 xbmc.log("Found " + str(n) + " playlists...")
397 i = 0
398 while i < n:
399 playlist = playlists[i]
400 playlistName = playlist[0]
401 playlistID = playlist[1]
402 dir = self._add_dir(playlistName, '', MODE_PLAYLIST, self.playlistImg, playlistID, n)
403 i = i + 1
404 xbmcplugin.setContent(self._handle, 'files')
405 xbmcplugin.addSortMethod(self._handle, xbmcplugin.SORT_METHOD_LABEL)
406 xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
407
408 # Add whatever directory
409 def _add_dir(self, name, url, mode, iconimage, id, items=1):
410
411 u=sys.argv[0]+"?mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&id="+str(id)
412 dir=xbmcgui.ListItem(name, iconImage=iconimage, thumbnailImage=iconimage)
413 dir.setInfo( type="Music", infoLabels={ "title": name } )
414 return xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=dir,isFolder=True, totalItems=items)
415
416
417# Parse URL parameters
418def get_params():
419 param=[]
420 paramstring=sys.argv[2]
421 xbmc.log(paramstring)
422 if len(paramstring)>=2:
423 params=sys.argv[2]
424 cleanedparams=params.replace('?','')
425 if (params[len(params)-1]=='/'):
426 params=params[0:len(params)-2]
427 pairsofparams=cleanedparams.split('&')
428 param={}
429 for i in range(len(pairsofparams)):
430 splitparams={}
431 splitparams=pairsofparams[i].split('=')
432 if (len(splitparams))==2:
433 param[splitparams[0]]=splitparams[1]
434 return param
435
436# Main
437grooveshark = Groveshark();
438
439params=get_params()
440mode=None
441try: mode=int(params["mode"])
442except: pass
443id=0
444try: id=int(params["id"])
445except: pass
446
447# Call function for URL
448if mode==None:
449 grooveshark.categories()
450
451elif mode==MODE_SEARCH_SONGS:
452 grooveshark.searchSongs()
453
454elif mode==MODE_SEARCH_ALBUMS:
455 grooveshark.searchAlbums()
456
457elif mode==MODE_SEARCH_ARTISTS:
458 grooveshark.searchArtists()
459
460elif mode==MODE_SEARCH_ARTISTS_ALBUMS:
461 grooveshark.searchArtistsAlbums()
462
463elif mode==MODE_SEARCH_PLAYLISTS:
464 grooveshark.searchPlaylists()
465
466elif mode==MODE_POPULAR_SONGS:
467 grooveshark.popularSongs()
468
469elif mode==MODE_FAVORITES:
470 grooveshark.favorites()
471
472elif mode==MODE_PLAYLISTS:
473 grooveshark.playlists()
474
475elif mode==MODE_SONG:
476 try: name=urllib.unquote_plus(params["name"])
477 except: pass
478 try: album=urllib.unquote_plus(params["album"])
479 except: pass
480 try: artist=urllib.unquote_plus(params["artist"])
481 except: pass
482 try: coverart=urllib.unquote_plus(params["coverart"])
483 except: pass
484 song = grooveshark.songItem(id, name, album, artist, coverart)
485 grooveshark.playSong(song)
486
487elif mode==MODE_ARTIST:
488 grooveshark.artist(id)
489
490elif mode==MODE_ALBUM:
491 grooveshark.album(id)
492
493elif mode==MODE_PLAYLIST:
494 grooveshark.playlist(id)
495
496elif mode==MODE_FAVORITE:
497 grooveshark.favorite(id)
498
499if mode < MODE_SONG:
500 xbmcplugin.endOfDirectory(int(sys.argv[1]))