Session creation exception handling.
[clinton/xbmc-groove.git] / default.py
CommitLineData
e278f474 1import urllib, sys, os, shutil, re, xbmcaddon, xbmcplugin, xbmcgui, xbmc
8817bb2e 2
8817bb2e 3MODE_SEARCH_SONGS = 1
4MODE_SEARCH_ALBUMS = 2
5MODE_SEARCH_ARTISTS = 3
36cc00d7 6MODE_POPULAR_SONGS = 4
8817bb2e 7MODE_FAVORITES = 5
8MODE_PLAYLISTS = 6
9MODE_ALBUM = 7
10MODE_ARTIST = 8
11MODE_PLAYLIST = 9
406ab447 12MODE_SIMILAR_ARTISTS = 10
13MODE_SONG = 11
14MODE_FAVORITE = 12
15MODE_UNFAVORITE = 13
36cc00d7 16MODE_MAKE_PLAYLIST = 14
17MODE_REMOVE_PLAYLIST = 15
18MODE_RENAME_PLAYLIST = 16
4be42357 19MODE_REMOVE_PLAYLIST_SONG = 17
7ea6f166 20MODE_ADD_PLAYLIST_SONG = 18
21
38df1fa5 22ACTION_MOVE_LEFT = 1
7ea6f166 23ACTION_MOVE_UP = 3
24ACTION_MOVE_DOWN = 4
25ACTION_PAGE_UP = 5
26ACTION_PAGE_DOWN = 6
27ACTION_SELECT_ITEM = 7
28ACTION_PREVIOUS_MENU = 10
8817bb2e 29
6ae708d0 30baseDir = os.getcwd()
31resDir = xbmc.translatePath(os.path.join(baseDir, 'resources'))
8817bb2e 32libDir = xbmc.translatePath(os.path.join(resDir, 'lib'))
33imgDir = xbmc.translatePath(os.path.join(resDir, 'img'))
973b4c6c 34thumbDir = os.path.join('special://masterprofile/addon_data/', os.path.join(os.path.basename(os.getcwd()), 'thumb'))
4be42357 35
36baseModeUrl = 'plugin://plugin.audio.groove/'
e278f474 37playlistUrl = baseModeUrl + '?mode=' + str(MODE_PLAYLIST)
4be42357 38playlistsUrl = baseModeUrl + '?mode=' + str(MODE_PLAYLISTS)
39favoritesUrl = baseModeUrl + '?mode=' + str(MODE_FAVORITES)
40
3cfead3c 41thumbDef = os.path.join(os.path.basename(os.getcwd()), 'default.tbn')
7ea6f166 42listBackground = os.path.join(imgDir, 'listbackground.png')
8817bb2e 43
44sys.path.append (libDir)
e278f474 45from GrooveAPI import GrooveAPI
a3ad8f73 46try:
47 groovesharkApi = GrooveAPI()
48except:
49 dialog = xbmcgui.Dialog()
50 dialog.ok('Grooveshark XBMC', 'Unable to connect with Grooveshark.', 'Please try again later')
51 sys.exit(-1)
52
8817bb2e 53
54class _Info:
55 def __init__( self, *args, **kwargs ):
56 self.__dict__.update( kwargs )
e278f474 57
58# Window dialog to select a grooveshark playlist
7ea6f166 59class GroovesharkPlaylistSelect(xbmcgui.WindowDialog):
60
38df1fa5 61 def __init__(self, items=[]):
38df1fa5 62 gap = int(self.getHeight()/100)
aa0c1263 63 w = int(self.getWidth()*0.5)
38df1fa5 64 h = self.getHeight()-30*gap
7ea6f166 65 rw = self.getWidth()
66 rh = self.getHeight()
67 x = rw/2 - w/2
68 y = rh/2 -h/2
69
38df1fa5 70 self.imgBg = xbmcgui.ControlImage(x+gap, 5*gap+y, w-2*gap, h-5*gap, listBackground)
7ea6f166 71 self.addControl(self.imgBg)
aa0c1263 72
cb06c186 73 self.playlistControl = xbmcgui.ControlList(2*gap+x, y+3*gap+30, w-4*gap, h-10*gap, textColor='0xFFFFFFFF', selectedColor='0xFFFF4242', itemTextYOffset=0, itemHeight=50, alignmentY = 0)
38df1fa5 74 self.addControl(self.playlistControl)
75
7ea6f166 76 self.lastPos = 0
77 self.isSelecting = False
38df1fa5 78 self.selected = -1
7ea6f166 79 listitems = []
7ea6f166 80 for playlist in items:
7ea6f166 81 listitems.append(xbmcgui.ListItem(playlist[0]))
38df1fa5 82 listitems.append(xbmcgui.ListItem('New...'))
83 self.playlistControl.addItems(listitems)
84 self.setFocus(self.playlistControl)
aa0c1263 85 self.playlistControl.selectItem(0)
38df1fa5 86 item = self.playlistControl.getListItem(self.lastPos)
7ea6f166 87 item.select(True)
88
89 # Highlight selected item
90 def setHighlight(self):
91 if self.isSelecting:
92 return
93 else:
94 self.isSelecting = True
95
38df1fa5 96 pos = self.playlistControl.getSelectedPosition()
7ea6f166 97 if pos >= 0:
38df1fa5 98 item = self.playlistControl.getListItem(self.lastPos)
7ea6f166 99 item.select(False)
38df1fa5 100 item = self.playlistControl.getListItem(pos)
7ea6f166 101 item.select(True)
102 self.lastPos = pos
103 self.isSelecting = False
104
e278f474 105 # Control - select
aa0c1263 106 def onControl(self, control):
107 if control == self.playlistControl:
108 self.selected = self.playlistControl.getSelectedPosition()
109 self.close()
e278f474 110
111 # Action - close or up/down
7ea6f166 112 def onAction(self, action):
aa0c1263 113 if action == ACTION_PREVIOUS_MENU:
114 self.selected = -1
115 self.close()
116 elif action == ACTION_MOVE_UP or action == ACTION_MOVE_DOWN or action == ACTION_PAGE_UP or action == ACTION_PAGE_DOWN == 6:
117 self.setFocus(self.playlistControl)
118 self.setHighlight()
7ea6f166 119
8817bb2e 120class Groveshark:
973b4c6c 121
7ea6f166 122 albumImg = xbmc.translatePath(os.path.join(imgDir, 'album.png'))
123 artistImg = xbmc.translatePath(os.path.join(imgDir, 'artist.png'))
124 favoritesImg = xbmc.translatePath(os.path.join(imgDir, 'favorites.png'))
125 playlistImg = xbmc.translatePath(os.path.join(imgDir, 'playlist.png'))
126 popularSongsImg = xbmc.translatePath(os.path.join(imgDir, 'popularSongs.png'))
127 songImg = xbmc.translatePath(os.path.join(imgDir, 'song.png'))
128 defImg = xbmc.translatePath(os.path.join(imgDir, 'default.tbn'))
2254a6b5 129 fanImg = xbmc.translatePath(os.path.join(baseDir, 'fanart.png'))
8817bb2e 130
2254a6b5 131 settings = xbmcaddon.Addon(id='plugin.audio.groove')
973b4c6c 132 songsearchlimit = settings.getSetting('songsearchlimit')
133 albumsearchlimit = settings.getSetting('albumsearchlimit')
134 artistsearchlimit = settings.getSetting('artistsearchlimit')
2254a6b5 135 username = settings.getSetting('username')
136 password = settings.getSetting('password')
38df1fa5 137 userid = 0
4be42357 138
8817bb2e 139 def __init__( self ):
140 self._handle = int(sys.argv[1])
b738088f 141
e278f474 142 # Top-level menu
8817bb2e 143 def categories(self):
2254a6b5 144
38df1fa5 145 self.userid = self._get_login()
b738088f 146
147 # Setup
6ae708d0 148 xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
149 if os.path.isdir(thumbDir) == False:
150 os.makedirs(thumbDir)
151
e278f474 152 self._add_dir('Search songs...', '', MODE_SEARCH_SONGS, self.songImg, 0)
153 self._add_dir('Search albums...', '', MODE_SEARCH_ALBUMS, self.albumImg, 0)
154 self._add_dir('Search artists...', '', MODE_SEARCH_ARTISTS, self.artistImg, 0)
36cc00d7 155 self._add_dir('Popular songs', '', MODE_POPULAR_SONGS, self.popularSongsImg, 0)
38df1fa5 156 if (self.userid != 0):
3fcef5ba 157 self._add_dir('Favorites', '', MODE_FAVORITES, self.favoritesImg, 0)
158 self._add_dir('Playlists', '', MODE_PLAYLISTS, self.playlistImg, 0)
e278f474 159
160 # Search for songs
8817bb2e 161 def searchSongs(self):
162 query = self._get_keyboard(default="", heading="Search songs")
7ea6f166 163 if (query != ''):
4be42357 164 groovesharkApi.setRemoveDuplicates(True)
2254a6b5 165 songs = groovesharkApi.searchSongs(query, limit = self.songsearchlimit)
8817bb2e 166 if (len(songs) > 0):
6ae708d0 167 self._add_songs_directory(songs)
8817bb2e 168 else:
169 dialog = xbmcgui.Dialog()
38df1fa5 170 dialog.ok('Grooveshark XBMC', 'No matching songs.')
8817bb2e 171 self.categories()
7ea6f166 172 else:
173 self.categories()
8817bb2e 174
e278f474 175 # Search for albums
8817bb2e 176 def searchAlbums(self):
177 query = self._get_keyboard(default="", heading="Search albums")
7ea6f166 178 if (query != ''):
2254a6b5 179 albums = groovesharkApi.searchAlbums(query, limit = self.albumsearchlimit)
8817bb2e 180 if (len(albums) > 0):
6ae708d0 181 self._add_albums_directory(albums)
8817bb2e 182 else:
183 dialog = xbmcgui.Dialog()
38df1fa5 184 dialog.ok('Grooveshark XBMC', 'No matching albums.')
8817bb2e 185 self.categories()
7ea6f166 186 else:
187 self.categories()
8817bb2e 188
e278f474 189 # Search for artists
8817bb2e 190 def searchArtists(self):
191 query = self._get_keyboard(default="", heading="Search artists")
7ea6f166 192 if (query != ''):
2254a6b5 193 artists = groovesharkApi.searchArtists(query, limit = self.artistsearchlimit)
8817bb2e 194 if (len(artists) > 0):
6ae708d0 195 self._add_artists_directory(artists)
8817bb2e 196 else:
197 dialog = xbmcgui.Dialog()
38df1fa5 198 dialog.ok('Grooveshark XBMC', 'No matching artists.')
8817bb2e 199 self.categories()
7ea6f166 200 else:
201 self.categories()
8817bb2e 202
e278f474 203 # Get my favorites
8817bb2e 204 def favorites(self):
36cc00d7 205 userid = self._get_login()
206 if (userid != 0):
207 favorites = groovesharkApi.userGetFavoriteSongs(userid)
208 if (len(favorites) > 0):
4be42357 209 self._add_songs_directory(favorites, isFavorites=True)
36cc00d7 210 else:
211 dialog = xbmcgui.Dialog()
38df1fa5 212 dialog.ok('Grooveshark XBMC', 'You have no favorites.')
36cc00d7 213 self.categories()
8817bb2e 214
e278f474 215 # Get popular songs
36cc00d7 216 def popularSongs(self):
2254a6b5 217 popular = groovesharkApi.popularGetSongs(limit = self.songsearchlimit)
8817bb2e 218 if (len(popular) > 0):
6ae708d0 219 self._add_songs_directory(popular)
8817bb2e 220 else:
221 dialog = xbmcgui.Dialog()
38df1fa5 222 dialog.ok('Grooveshark XBMC', 'No popular songs.')
8817bb2e 223 self.categories()
36cc00d7 224
e278f474 225 # Get my playlists
8817bb2e 226 def playlists(self):
227 userid = self._get_login()
228 if (userid != 0):
229 playlists = groovesharkApi.userGetPlaylists()
230 if (len(playlists) > 0):
6ae708d0 231 self._add_playlists_directory(playlists)
8817bb2e 232 else:
233 dialog = xbmcgui.Dialog()
38df1fa5 234 dialog.ok('Grooveshark XBMC', 'You have no Grooveshark playlists.')
8817bb2e 235 self.categories()
7ea6f166 236 else:
237 dialog = xbmcgui.Dialog()
38df1fa5 238 dialog.ok('Grooveshark XBMC', 'You must be logged in ', ' to see your Grooveshark playlists.')
7ea6f166 239
e278f474 240 # Make songs a favorite
8817bb2e 241 def favorite(self, songid):
242 userid = self._get_login()
243 if (userid != 0):
406ab447 244 xbmc.log("Favorite song: " + str(songid))
8817bb2e 245 groovesharkApi.favoriteSong(songID = songid)
38df1fa5 246 xbmc.executebuiltin('XBMC.Notification(Grooveshark XBMC, Added to favorites, 1000, ' + thumbDef + ')')
8817bb2e 247 else:
248 dialog = xbmcgui.Dialog()
38df1fa5 249 dialog.ok('Grooveshark XBMC', 'You must be logged in', 'to add favorites.')
8817bb2e 250
e278f474 251 # Remove song from favorites
252 def unfavorite(self, songid, prevMode=0):
8817bb2e 253 userid = self._get_login()
254 if (userid != 0):
4be42357 255 xbmc.log("Unfavorite song: " + str(songid) + ', previous mode was ' + str(prevMode))
8817bb2e 256 groovesharkApi.unfavoriteSong(songID = songid)
aa0c1263 257 xbmc.executebuiltin('XBMC.Notification(Grooveshark XBMC, Removed from Grooveshark favorites, 1000, ' + thumbDef + ')')
e278f474 258 # Refresh to remove item from directory
4be42357 259 if (int(prevMode) == MODE_FAVORITES):
cb06c186 260 xbmc.executebuiltin("Container.Refresh(" + favoritesUrl + ")")
8817bb2e 261 else:
262 dialog = xbmcgui.Dialog()
aa0c1263 263 dialog.ok('Grooveshark XBMC', 'You must be logged in', 'to remove Grooveshark favorites.')
3fcef5ba 264
e278f474 265 # 'Frown' a song
3fcef5ba 266 def frown(self, songid):
267 userid = self._get_login()
268 if (userid != 0):
406ab447 269 xbmc.log("Frown song: " + str(songid))
3fcef5ba 270 if groovesharkApi.radioFrown(songId = songid) != True:
271 xbmc.log("Unable to frown song " + str(songid))
3cfead3c 272 else:
38df1fa5 273 xbmc.executebuiltin('XBMC.Notification(Grooveshark XBMC, Frowned, 1000, ' + thumbDef + ')')
3fcef5ba 274 else:
275 dialog = xbmcgui.Dialog()
aa0c1263 276 dialog.ok('Grooveshark XBMC', 'You must be logged in', 'to frown a Grooveshark song.')
3fcef5ba 277
e278f474 278 # Find similar artists to searched artist
406ab447 279 def similarArtists(self, artistId):
280 similar = groovesharkApi.artistGetSimilar(artistId, limit = self.artistsearchlimit)
281 if (len(similar) > 0):
282 self._add_artists_directory(similar)
3fcef5ba 283 else:
284 dialog = xbmcgui.Dialog()
38df1fa5 285 dialog.ok('Grooveshark XBMC', 'No similar artists.')
406ab447 286 self.categories()
e278f474 287
288 # Make a playlist from an album
36cc00d7 289 def makePlaylist(self, albumid, name):
290 userid = self._get_login()
291 if (userid != 0):
3cfead3c 292 re.split(' - ',name,1)
e278f474 293 nameTokens = re.split(' - ',name,1) # suggested name
38df1fa5 294 name = self._get_keyboard(default=nameTokens[0], heading="Grooveshark playlist name")
3cfead3c 295 if name != '':
4be42357 296 groovesharkApi.setRemoveDuplicates(True)
3cfead3c 297 album = groovesharkApi.albumGetSongs(albumid, self.songsearchlimit)
298 songids = []
299 for song in album:
300 songids.append(song[1])
38df1fa5 301 if groovesharkApi.playlistCreateUnique(name, songids) == 0:
3cfead3c 302 dialog = xbmcgui.Dialog()
38df1fa5 303 dialog.ok('Grooveshark XBMC', 'Cannot create Grooveshark playlist ', name)
3cfead3c 304 else:
38df1fa5 305 xbmc.executebuiltin('XBMC.Notification(Grooveshark XBMC, Grooveshark playlist created, 1000, ' + thumbDef + ')')
36cc00d7 306 else:
307 dialog = xbmcgui.Dialog()
38df1fa5 308 dialog.ok('Grooveshark XBMC', 'You must be logged in ', ' to create a Grooveshark playlist.')
e278f474 309
310 # Rename a playlist
311 def renamePlaylist(self, playlistid, name):
312 userid = self._get_login()
313 if (userid != 0):
314 newname = self._get_keyboard(default=name, heading="Grooveshark playlist name")
315 if newname == '':
316 return
317 elif groovesharkApi.playlistRename(playlistid, newname) == 0:
318 dialog = xbmcgui.Dialog()
319 dialog.ok('Grooveshark XBMC', 'Cannot rename Grooveshark playlist ', name)
320 else:
321 # Refresh to show new item name
322 xbmc.executebuiltin("Container.Refresh")
323 else:
324 dialog = xbmcgui.Dialog()
325 dialog.ok('Grooveshark XBMC', 'You must be logged in ', ' to rename a Grooveshark playlist.')
326
327 # Remove a playlist
36cc00d7 328 def removePlaylist(self, playlistid, name):
329 dialog = xbmcgui.Dialog()
38df1fa5 330 if dialog.yesno('Grooveshark XBMC', name, 'Delete this Grooveshark playlist?') == True:
36cc00d7 331 userid = self._get_login()
332 if (userid != 0):
e278f474 333 if groovesharkApi.playlistDelete(playlistid) == 0:
4be42357 334 dialog = xbmcgui.Dialog()
e278f474 335 dialog.ok('Grooveshark XBMC', 'Cannot remove Grooveshark playlist ', name)
4be42357 336 else:
e278f474 337 # Refresh to remove item from directory
338 xbmc.executebuiltin("Container.Refresh(" + playlistsUrl + ")")
7ea6f166 339 else:
340 dialog = xbmcgui.Dialog()
e278f474 341 dialog.ok('Grooveshark XBMC', 'You must be logged in ', ' to delete a Grooveshark playlist.')
7ea6f166 342
e278f474 343 # Add song to playlist
7ea6f166 344 def addPlaylistSong(self, songid):
345 userid = self._get_login()
346 if (userid != 0):
347 playlists = groovesharkApi.userGetPlaylists()
348 if (len(playlists) > 0):
38df1fa5 349 ret = 0
e278f474 350 # Select the playlist
38df1fa5 351 playlistSelect = GroovesharkPlaylistSelect(items=playlists)
352 playlistSelect.setFocus(playlistSelect.playlistControl)
7ea6f166 353 playlistSelect.doModal()
38df1fa5 354 i = playlistSelect.selected
7ea6f166 355 del playlistSelect
38df1fa5 356 if i > -1:
e278f474 357 # Add a new playlist
38df1fa5 358 if i >= len(playlists):
359 name = self._get_keyboard(default='', heading="Grooveshark playlist name")
360 if name != '':
361 songIds = []
362 songIds.append(songid)
363 if groovesharkApi.playlistCreateUnique(name, songIds) == 0:
364 dialog = xbmcgui.Dialog()
365 dialog.ok('Grooveshark XBMC', 'Cannot create Grooveshark playlist ', name)
366 else:
367 xbmc.executebuiltin('XBMC.Notification(Grooveshark XBMC, Grooveshark playlist created, 1000, ' + thumbDef + ')')
368 # Existing playlist
369 else:
370 playlist = playlists[i]
371 playlistid = playlist[1]
372 xbmc.log("Add song " + str(songid) + " to playlist " + str(playlistid))
373 ret = groovesharkApi.playlistAddSong(playlistid, songid, 0)
374 if ret == 0:
375 dialog = xbmcgui.Dialog()
376 dialog.ok('Grooveshark XBMC', 'Cannot add to playlist ')
377 else:
378 xbmc.executebuiltin('XBMC.Notification(Grooveshark XBMC, Added song to Grooveshark playlist, 1000, ' + thumbDef + ')')
4be42357 379 else:
380 dialog = xbmcgui.Dialog()
38df1fa5 381 dialog.ok('Grooveshark XBMC', 'You have no Grooveshark playlists.')
7ea6f166 382 self.categories()
383 else:
384 dialog = xbmcgui.Dialog()
38df1fa5 385 dialog.ok('Grooveshark XBMC', 'You must be logged in ', ' to add a song to a Grooveshark playlist.')
4be42357 386
e278f474 387 # Remove song from playlist
388 def removePlaylistSong(self, playlistid, playlistname, songpos):
389 dialog = xbmcgui.Dialog()
390 if dialog.yesno('Grooveshark XBMC', 'Delete this song from the Grooveshark playlist?') == True:
391 userid = self._get_login()
392 if (userid != 0):
393 if groovesharkApi.playlistDeleteSong(playlistid, songpos) == 0:
394 dialog = xbmcgui.Dialog()
395 dialog.ok('Grooveshark XBMC', 'Failed to remove ', ' song from Grooveshark playlist.')
396 else:
397 # Refresh to remove item from directory
398 xbmc.executebuiltin("Container.Refresh(" + playlistUrl + "&id="+str(playlistid) + "&name=" + playlistname + ")")
36cc00d7 399 else:
e278f474 400 dialog = xbmcgui.Dialog()
401 dialog.ok('Grooveshark XBMC', 'You must be logged in ', ' to delete a song from a Grooveshark playlist.')
402
403 # Show selected album
36cc00d7 404 def album(self, albumid):
4be42357 405 groovesharkApi.setRemoveDuplicates(True)
2254a6b5 406 album = groovesharkApi.albumGetSongs(albumId = albumid, limit = self.songsearchlimit)
6ae708d0 407 self._add_songs_directory(album)
e278f474 408
409 # Show selected artist
8817bb2e 410 def artist(self, artistid):
2254a6b5 411 albums = groovesharkApi.artistGetAlbums(artistId = artistid, limit = self.albumsearchlimit)
406ab447 412 self._add_albums_directory(albums, artistid)
8817bb2e 413
e278f474 414 # Show selected playlist
4be42357 415 def playlist(self, playlistid, playlistname):
8817bb2e 416 userid = self._get_login()
417 if (userid != 0):
2254a6b5 418 songs = groovesharkApi.playlistGetSongs(playlistId = playlistid, limit = self.songsearchlimit)
4be42357 419 self._add_songs_directory(songs, playlistid, playlistname)
8817bb2e 420 else:
421 dialog = xbmcgui.Dialog()
38df1fa5 422 dialog.ok('Grooveshark XBMC', 'You must be logged in', 'to get Grooveshark playlists.')
8817bb2e 423
e278f474 424 # Play a song
6ae708d0 425 def playSong(self, item):
e278f474 426 url = groovesharkApi.getStreamURL(item.getProperty('id'))
427 item.setPath(url)
9b1d8c96 428 xbmc.log("Playing: " + url)
2254a6b5 429 xbmcplugin.setResolvedUrl(handle=int(sys.argv[1]), succeeded=True, listitem=item)
3fcef5ba 430
e278f474 431 # Make a song directory item
6ae708d0 432 def songItem(self, id, name, album, artist, duration, thumb, image):
e6ccfeca 433 # Only try to get the image
434 if image != "":
435 songImg = self._get_icon(image, 'song-' + str(id) + "-image")
436 songThm = songImg
437 else:
438 songThm = self._get_icon(thumb, 'song-' + str(id) + "-thumb")
439 songImg = songThm
e278f474 440 item = xbmcgui.ListItem(label = artist + " - " + album + " - " + name, thumbnailImage=songThm, iconImage=songImg)
2254a6b5 441 item.setInfo( type="music", infoLabels={ "title": name, "duration": duration, "album": album, "artist": artist} )
442 item.setProperty('mimetype', 'audio/mpeg')
443 item.setProperty("IsPlayable", "true")
e278f474 444 item.setProperty('id', str(id))
6ae708d0 445 item.setProperty('thumb', songThm)
446 item.setProperty('image', songImg)
6ae708d0 447 return item
2254a6b5 448
e278f474 449 # Get keyboard input
8817bb2e 450 def _get_keyboard(self, default="", heading="", hidden=False):
3cfead3c 451 kb = xbmc.Keyboard(default, heading, hidden)
452 kb.doModal()
453 if (kb.isConfirmed()):
454 return unicode(kb.getText(), "utf-8")
455 return ''
8817bb2e 456
e278f474 457 # Login to grooveshark
8817bb2e 458 def _get_login(self):
2254a6b5 459 if (self.username == "" or self.password == ""):
8817bb2e 460 dialog = xbmcgui.Dialog()
38df1fa5 461 dialog.ok('Grooveshark XBMC', 'Unable to login.', 'Check username and password in settings.')
8817bb2e 462 return 0
463 else:
38df1fa5 464 if self.userid == 0:
465 uid = groovesharkApi.loginExt(self.username, self.password)
466 if (uid != 0):
38df1fa5 467 return uid
8817bb2e 468 else:
469 dialog = xbmcgui.Dialog()
38df1fa5 470 dialog.ok('Grooveshark XBMC', 'Unable to login.', 'Check username and password in settings.')
8817bb2e 471 return 0
472
e278f474 473 # Get a song directory item
6ae708d0 474 def _get_song_item(self, song):
475 name = song[0]
476 id = song[1]
477 duration = song[2]
478 album = song[3]
479 artist = song[6]
480 thumb = song[8]
481 image = song[9]
482 return self.songItem(id, name, album, artist, duration, thumb, image)
483
484 # File download
485 def _get_icon(self, url, id):
6ae708d0 486 localThumb = os.path.join(xbmc.translatePath(os.path.join(thumbDir, str(id)))) + '.tbn'
487 try:
488 if os.path.isfile(localThumb) == False:
e6ccfeca 489 xbmc.log('Downloading ' + url + ' to ' + localThumb)
6ae708d0 490 loc = urllib.URLopener()
491 loc.retrieve(url, localThumb)
492 except:
cd371e5d 493 shutil.copy2(self.defImg, localThumb)
6ae708d0 494
495 return os.path.join(os.path.join(thumbDir, str(id))) + '.tbn'
e278f474 496
497 # Add songs to directory
4be42357 498 def _add_songs_directory(self, songs, playlistid=0, playlistname='', isFavorites=False):
6ae708d0 499 n = len(songs)
500 xbmc.log("Found " + str(n) + " songs...")
8817bb2e 501 i = 0
6ae708d0 502 while i < n:
8817bb2e 503 song = songs[i]
6ae708d0 504 item = self._get_song_item(song)
6ae708d0 505 songthumb = item.getProperty('thumb')
506 songimage = item.getProperty('image')
507 songname = song[0]
508 songid = song[1]
509 songduration = song[2]
510 songalbum = song[3]
511 songartist = song[6]
e278f474 512 u=sys.argv[0]+"?mode="+str(MODE_SONG)+"&name="+urllib.quote_plus(songname)+"&id="+str(songid) \
6ae708d0 513 +"&album="+urllib.quote_plus(songalbum) \
514 +"&artist="+urllib.quote_plus(songartist) \
515 +"&duration="+str(songduration) \
516 +"&thumb="+urllib.quote_plus(songthumb) \
517 +"&image="+urllib.quote_plus(songimage)
e278f474 518 fav=sys.argv[0]+"?mode="+str(MODE_FAVORITE)+"&name="+urllib.quote_plus(songname)+"&id="+str(songid)
519 unfav=sys.argv[0]+"?mode="+str(MODE_UNFAVORITE)+"&name="+urllib.quote_plus(songname)+"&id="+str(songid)+"&prevmode="
6ae708d0 520 menuItems = []
4be42357 521 if isFavorites == True:
522 unfav = unfav +str(MODE_FAVORITES)
523 else:
7ea6f166 524 menuItems.append(("Grooveshark favorite", "XBMC.RunPlugin("+fav+")"))
525 menuItems.append(("Not Grooveshark favorite", "XBMC.RunPlugin("+unfav+")"))
4be42357 526 if playlistid > 0:
527 rmplaylstsong=sys.argv[0]+"?playlistid="+str(playlistid)+"&id="+str(i+1)+"&mode="+str(MODE_REMOVE_PLAYLIST_SONG)+"&name="+playlistname
aa0c1263 528 menuItems.append(("Remove from Grooveshark playlist", "XBMC.RunPlugin("+rmplaylstsong+")"))
7ea6f166 529 else:
530 addplaylstsong=sys.argv[0]+"?id="+str(songid)+"&mode="+str(MODE_ADD_PLAYLIST_SONG)
531 menuItems.append(("Add to Grooveshark playlist", "XBMC.RunPlugin("+addplaylstsong+")"))
6ae708d0 532 item.addContextMenuItems(menuItems, replaceItems=False)
e278f474 533 xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=item,isFolder=False, totalItems=n)
8817bb2e 534 i = i + 1
cb06c186 535
8817bb2e 536 xbmcplugin.setContent(self._handle, 'songs')
31731635 537 xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
e278f474 538
539 # Add albums to directory
406ab447 540 def _add_albums_directory(self, albums, artistid=0):
31731635 541 n = len(albums)
542 xbmc.log("Found " + str(n) + " albums...")
8817bb2e 543 i = 0
31731635 544 while i < n:
8817bb2e 545 album = albums[i]
546 albumArtistName = album[0]
547 albumName = album[2]
548 albumID = album[3]
2254a6b5 549 albumImage = self._get_icon(album[4], 'album-' + str(albumID))
31731635 550 self._add_dir(albumName + " - " + albumArtistName, '', MODE_ALBUM, albumImage, albumID, n)
8817bb2e 551 i = i + 1
406ab447 552 if artistid > 0:
553 self._add_dir('Similar artists...', '', MODE_SIMILAR_ARTISTS, self.artistImg, artistid)
8817bb2e 554 xbmcplugin.setContent(self._handle, 'albums')
555 xbmcplugin.addSortMethod(self._handle, xbmcplugin.SORT_METHOD_ALBUM_IGNORE_THE)
31731635 556 xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
e278f474 557
558 # Add artists to directory
6ae708d0 559 def _add_artists_directory(self, artists):
31731635 560 n = len(artists)
561 xbmc.log("Found " + str(n) + " artists...")
8817bb2e 562 i = 0
31731635 563 while i < n:
8817bb2e 564 artist = artists[i]
565 artistName = artist[0]
566 artistID = artist[1]
31731635 567 self._add_dir(artistName, '', MODE_ARTIST, self.artistImg, artistID, n)
8817bb2e 568 i = i + 1
569 xbmcplugin.setContent(self._handle, 'artists')
570 xbmcplugin.addSortMethod(self._handle, xbmcplugin.SORT_METHOD_ARTIST_IGNORE_THE)
31731635 571 xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
e278f474 572
573 # Add playlists to directory
6ae708d0 574 def _add_playlists_directory(self, playlists):
31731635 575 n = len(playlists)
576 xbmc.log("Found " + str(n) + " playlists...")
8817bb2e 577 i = 0
31731635 578 while i < n:
8817bb2e 579 playlist = playlists[i]
580 playlistName = playlist[0]
581 playlistID = playlist[1]
31731635 582 self._add_dir(playlistName, '', MODE_PLAYLIST, self.playlistImg, playlistID, n)
8817bb2e 583 i = i + 1
584 xbmcplugin.setContent(self._handle, 'files')
585 xbmcplugin.addSortMethod(self._handle, xbmcplugin.SORT_METHOD_PLAYLIST_ORDER)
31731635 586 xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
3fcef5ba 587
e278f474 588 # Add whatever directory
31731635 589 def _add_dir(self, name, url, mode, iconimage, id, items=1):
e278f474 590
591 u=sys.argv[0]+"?mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&id="+str(id)
8817bb2e 592 dir=xbmcgui.ListItem(name, iconImage=iconimage, thumbnailImage=iconimage)
b738088f 593 dir.setInfo( type="Music", infoLabels={ "title": name } )
e278f474 594
595 # Custom menu items
8817bb2e 596 menuItems = []
36cc00d7 597 if mode == MODE_ALBUM:
598 mkplaylst=sys.argv[0]+"?mode="+str(MODE_MAKE_PLAYLIST)+"&name="+name+"&id="+str(id)
599 menuItems.append(("Make Grooveshark playlist", "XBMC.RunPlugin("+mkplaylst+")"))
600 if mode == MODE_PLAYLIST:
601 rmplaylst=sys.argv[0]+"?mode="+str(MODE_REMOVE_PLAYLIST)+"&name="+urllib.quote_plus(name)+"&id="+str(id)
aa0c1263 602 menuItems.append(("Delete Grooveshark playlist", "XBMC.RunPlugin("+rmplaylst+")"))
36cc00d7 603 mvplaylst=sys.argv[0]+"?mode="+str(MODE_RENAME_PLAYLIST)+"&name="+urllib.quote_plus(name)+"&id="+str(id)
aa0c1263 604 menuItems.append(("Rename Grooveshark playlist", "XBMC.RunPlugin("+mvplaylst+")"))
e278f474 605
7ea6f166 606 dir.addContextMenuItems(menuItems, replaceItems=False)
31731635 607 return xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=dir,isFolder=True, totalItems=items)
6ae708d0 608
e278f474 609
610# Parse URL parameters
8817bb2e 611def get_params():
612 param=[]
613 paramstring=sys.argv[2]
e278f474 614 xbmc.log(paramstring)
8817bb2e 615 if len(paramstring)>=2:
616 params=sys.argv[2]
617 cleanedparams=params.replace('?','')
618 if (params[len(params)-1]=='/'):
619 params=params[0:len(params)-2]
620 pairsofparams=cleanedparams.split('&')
621 param={}
622 for i in range(len(pairsofparams)):
623 splitparams={}
624 splitparams=pairsofparams[i].split('=')
625 if (len(splitparams))==2:
626 param[splitparams[0]]=splitparams[1]
8817bb2e 627 return param
628
e278f474 629# Main
8817bb2e 630grooveshark = Groveshark();
e278f474 631
8817bb2e 632params=get_params()
8817bb2e 633mode=None
8817bb2e 634try: mode=int(params["mode"])
635except: pass
8817bb2e 636
e278f474 637if mode > MODE_FAVORITES:
638 name=None
639 id=None
640 try: name=urllib.unquote_plus(params["name"])
641 except: pass
642 try: id=int(params["id"])
643 except: pass
644
645# Call function for URL
8817bb2e 646if mode==None:
647 grooveshark.categories()
648
649elif mode==MODE_SEARCH_SONGS:
650 grooveshark.searchSongs()
651
652elif mode==MODE_SEARCH_ALBUMS:
653 grooveshark.searchAlbums()
654
655elif mode==MODE_SEARCH_ARTISTS:
656 grooveshark.searchArtists()
657
36cc00d7 658elif mode==MODE_POPULAR_SONGS:
659 grooveshark.popularSongs()
8817bb2e 660
8817bb2e 661elif mode==MODE_FAVORITES:
662 grooveshark.favorites()
663
e278f474 664elif mode==MODE_PLAYLISTS:
665 grooveshark.playlists()
666
8817bb2e 667elif mode==MODE_SONG:
8817bb2e 668 try: album=urllib.unquote_plus(params["album"])
669 except: pass
670 try: artist=urllib.unquote_plus(params["artist"])
671 except: pass
672 try: duration=int(params["duration"])
673 except: pass
b738088f 674 try: thumb=urllib.unquote_plus(params["thumb"])
675 except: pass
676 try: image=urllib.unquote_plus(params["image"])
677 except: pass
6ae708d0 678 song = grooveshark.songItem(id, name, album, artist, duration, thumb, image)
3fcef5ba 679 grooveshark.playSong(song)
8817bb2e 680
681elif mode==MODE_ARTIST:
4be42357 682 grooveshark.artist(id)
8817bb2e 683
684elif mode==MODE_ALBUM:
4be42357 685 grooveshark.album(id)
8817bb2e 686
687elif mode==MODE_PLAYLIST:
4be42357 688 grooveshark.playlist(id, name)
8817bb2e 689
690elif mode==MODE_FAVORITE:
4be42357 691 grooveshark.favorite(id)
8817bb2e 692
693elif mode==MODE_UNFAVORITE:
e278f474 694 try: prevMode=int(urllib.unquote_plus(params["prevmode"]))
695 except:
696 prevMode = 0
4be42357 697 grooveshark.unfavorite(id, prevMode)
3fcef5ba 698
406ab447 699elif mode==MODE_SIMILAR_ARTISTS:
4be42357 700 grooveshark.similarArtists(id)
3fcef5ba 701
36cc00d7 702elif mode==MODE_MAKE_PLAYLIST:
4be42357 703 grooveshark.makePlaylist(id, name)
36cc00d7 704
705elif mode==MODE_REMOVE_PLAYLIST:
4be42357 706 grooveshark.removePlaylist(id, name)
36cc00d7 707
708elif mode==MODE_RENAME_PLAYLIST:
4be42357 709 grooveshark.renamePlaylist(id, name)
36cc00d7 710
4be42357 711elif mode==MODE_REMOVE_PLAYLIST_SONG:
712 try: playlistID=urllib.unquote_plus(params["playlistid"])
713 except: pass
714 grooveshark.removePlaylistSong(playlistID, name, id)
36cc00d7 715
7ea6f166 716elif mode==MODE_ADD_PLAYLIST_SONG:
717 grooveshark.addPlaylistSong(id)
718
e278f474 719if mode < MODE_SONG:
8817bb2e 720 xbmcplugin.endOfDirectory(int(sys.argv[1]))