Fix for multiuser environment.
[clinton/xbmc-groove.git] / default.py
CommitLineData
2d388879 1# Copyright 2011 Stephen Denham
2
3# This file is part of xbmc-groove.
4#
5# xbmc-groove is free software: you can redistribute it and/or modify
6# it under the terms of the GNU General Public License as published by
7# the Free Software Foundation, either version 3 of the License, or
8# (at your option) any later version.
9#
10# xbmc-groove is distributed in the hope that it will be useful,
11# but WITHOUT ANY WARRANTY; without even the implied warranty of
12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13# GNU General Public License for more details.
14#
15# You should have received a copy of the GNU General Public License
16# along with xbmc-groove. If not, see <http://www.gnu.org/licenses/>.
17
18
88955d32 19import urllib, sys, os, shutil, re, pickle, time, xbmcaddon, xbmcplugin, xbmcgui, xbmc
2d388879 20
b26b96e6 21__addon__ = xbmcaddon.Addon('plugin.audio.groove')
2d388879 22__addonname__ = __addon__.getAddonInfo('name')
23__cwd__ = __addon__.getAddonInfo('path')
24__author__ = __addon__.getAddonInfo('author')
25__version__ = __addon__.getAddonInfo('version')
26__language__ = __addon__.getLocalizedString
9f9eadcd 27__debugging__ = __addon__.getSetting('debug')
5e72534b 28
8817bb2e 29MODE_SEARCH_SONGS = 1
30MODE_SEARCH_ALBUMS = 2
31MODE_SEARCH_ARTISTS = 3
86f629ea 32MODE_SEARCH_ARTISTS_ALBUMS = 4
33MODE_SEARCH_PLAYLISTS = 5
97289139 34MODE_ARTIST_POPULAR = 6
35MODE_POPULAR_SONGS = 7
36MODE_FAVORITES = 8
37MODE_PLAYLISTS = 9
38MODE_ALBUM = 10
39MODE_ARTIST = 11
40MODE_PLAYLIST = 12
41MODE_SONG_PAGE = 13
052028f1 42MODE_SIMILAR_ARTISTS = 14
43MODE_SONG = 15
44MODE_FAVORITE = 16
45MODE_UNFAVORITE = 17
46MODE_MAKE_PLAYLIST = 18
47MODE_REMOVE_PLAYLIST = 19
48MODE_RENAME_PLAYLIST = 20
49MODE_REMOVE_PLAYLIST_SONG = 21
50MODE_ADD_PLAYLIST_SONG = 22
7ea6f166 51
38df1fa5 52ACTION_MOVE_LEFT = 1
7ea6f166 53ACTION_MOVE_UP = 3
54ACTION_MOVE_DOWN = 4
55ACTION_PAGE_UP = 5
56ACTION_PAGE_DOWN = 6
57ACTION_SELECT_ITEM = 7
58ACTION_PREVIOUS_MENU = 10
8817bb2e 59
86f629ea 60# Formats for track labels
61ARTIST_ALBUM_NAME_LABEL = 0
62NAME_ALBUM_ARTIST_LABEL = 1
63
f95afae7 64# Stream marking time (seconds)
65STREAM_MARKING_TIME = 30
cd937dea 66
67# Timeout
68STREAM_TIMEOUT = 30
69
f95afae7 70songMarkTime = 0
71player = xbmc.Player()
72playTimer = None
73
2d388879 74baseDir = __cwd__
6ae708d0 75resDir = xbmc.translatePath(os.path.join(baseDir, 'resources'))
8817bb2e 76libDir = xbmc.translatePath(os.path.join(resDir, 'lib'))
77imgDir = xbmc.translatePath(os.path.join(resDir, 'img'))
2d388879 78cacheDir = os.path.join(xbmc.translatePath('special://masterprofile/addon_data/'), os.path.basename(baseDir))
7ce01be6 79thumbDirName = 'thumb'
191f20f2 80thumbDir = os.path.join(xbmc.translatePath('special://masterprofile/addon_data/'), os.path.basename(baseDir), thumbDirName)
4be42357 81
82baseModeUrl = 'plugin://plugin.audio.groove/'
e278f474 83playlistUrl = baseModeUrl + '?mode=' + str(MODE_PLAYLIST)
4be42357 84playlistsUrl = baseModeUrl + '?mode=' + str(MODE_PLAYLISTS)
85favoritesUrl = baseModeUrl + '?mode=' + str(MODE_FAVORITES)
86
b26b96e6 87searchArtistsAlbumsName = __language__(30006)
3d95dfcb 88
7ce01be6 89thumbDef = os.path.join(imgDir, 'default.tbn')
052028f1 90listBackground = os.path.join(imgDir, 'listbackground.png')
8817bb2e 91
92sys.path.append (libDir)
7ce01be6 93from GroovesharkAPI import GrooveAPI
f95afae7 94from threading import Event, Thread
7ce01be6 95
9f9eadcd 96if __debugging__ == 'true':
97 __debugging__ = True
98else:
99 __debugging__ = False
100
a3ad8f73 101try:
9f9eadcd 102 groovesharkApi = GrooveAPI(__debugging__)
7ce01be6 103 if groovesharkApi.pingService() != True:
b26b96e6 104 raise StandardError(__language__(30007))
a3ad8f73 105except:
b26b96e6 106 dialog = xbmcgui.Dialog(__language__(30008),__language__(30009),__language__(30010))
6d909a7d 107 dialog.ok(__language__(30008),__language__(30009))
a3ad8f73 108 sys.exit(-1)
109
f95afae7 110# Mark song as playing or played
cfad7202 111def markSong(songid, duration, streamKey, streamServerID):
f95afae7 112 global songMarkTime
113 global playTimer
114 global player
115 if player.isPlayingAudio():
116 tNow = player.getTime()
117 if tNow >= STREAM_MARKING_TIME and songMarkTime == 0:
cfad7202 118 groovesharkApi.markStreamKeyOver30Secs(streamKey, streamServerID)
f95afae7 119 songMarkTime = tNow
120 elif duration > tNow and duration - tNow < 2 and songMarkTime >= STREAM_MARKING_TIME:
121 playTimer.cancel()
122 songMarkTime = 0
cfad7202 123 groovesharkApi.markSongComplete(songid, streamKey, streamServerID)
f95afae7 124 else:
125 playTimer.cancel()
126 songMarkTime = 0
127
8817bb2e 128class _Info:
129 def __init__( self, *args, **kwargs ):
130 self.__dict__.update( kwargs )
e278f474 131
052028f1 132# Window dialog to select a grooveshark playlist
133class GroovesharkPlaylistSelect(xbmcgui.WindowDialog):
134
135 def __init__(self, items=[]):
136 gap = int(self.getHeight()/100)
137 w = int(self.getWidth()*0.5)
138 h = self.getHeight()-30*gap
139 rw = self.getWidth()
140 rh = self.getHeight()
141 x = rw/2 - w/2
142 y = rh/2 -h/2
143
144 self.imgBg = xbmcgui.ControlImage(x+gap, 5*gap+y, w-2*gap, h-5*gap, listBackground)
145 self.addControl(self.imgBg)
146
53ec8584 147 self.playlistControl = xbmcgui.ControlList(2*gap+x, y+3*gap+30, w-4*gap, h-10*gap, textColor='0xFFFFFFFF', selectedColor='0xFFFF4242')
148 self.playlistControl.setItemHeight(50)
052028f1 149 self.addControl(self.playlistControl)
150
151 self.lastPos = 0
152 self.isSelecting = False
153 self.selected = -1
154 listitems = []
155 for playlist in items:
156 listitems.append(xbmcgui.ListItem(playlist[0]))
b26b96e6 157 listitems.append(xbmcgui.ListItem(__language__(30011)))
052028f1 158 self.playlistControl.addItems(listitems)
159 self.setFocus(self.playlistControl)
160 self.playlistControl.selectItem(0)
161 item = self.playlistControl.getListItem(self.lastPos)
162 item.select(True)
163
164 # Highlight selected item
165 def setHighlight(self):
166 if self.isSelecting:
167 return
168 else:
169 self.isSelecting = True
170
171 pos = self.playlistControl.getSelectedPosition()
172 if pos >= 0:
173 item = self.playlistControl.getListItem(self.lastPos)
174 item.select(False)
175 item = self.playlistControl.getListItem(pos)
176 item.select(True)
177 self.lastPos = pos
178 self.isSelecting = False
179
180 # Control - select
181 def onControl(self, control):
182 if control == self.playlistControl:
183 self.selected = self.playlistControl.getSelectedPosition()
184 self.close()
185
186 # Action - close or up/down
187 def onAction(self, action):
188 if action == ACTION_PREVIOUS_MENU:
189 self.selected = -1
190 self.close()
191 elif action == ACTION_MOVE_UP or action == ACTION_MOVE_DOWN or action == ACTION_PAGE_UP or action == ACTION_PAGE_DOWN == 6:
192 self.setFocus(self.playlistControl)
193 self.setHighlight()
f95afae7 194
195
196class PlayTimer(Thread):
197 # interval -- floating point number specifying the number of seconds to wait before executing function
198 # function -- the function (or callable object) to be executed
199
200 # iterations -- integer specifying the number of iterations to perform
201 # args -- list of positional arguments passed to function
202 # kwargs -- dictionary of keyword arguments passed to function
203
204 def __init__(self, interval, function, iterations=0, args=[], kwargs={}):
205 Thread.__init__(self)
206 self.interval = interval
207 self.function = function
208 self.iterations = iterations
209 self.args = args
210 self.kwargs = kwargs
211 self.finished = Event()
212
213 def run(self):
214 count = 0
215 while not self.finished.isSet() and (self.iterations <= 0 or count < self.iterations):
216 self.finished.wait(self.interval)
217 if not self.finished.isSet():
218 self.function(*self.args, **self.kwargs)
219 count += 1
220
221 def cancel(self):
222 self.finished.set()
223
224 def setIterations(self, iterations):
225 self.iterations = iterations
226
227
228 def getTime(self):
229 return self.iterations * self.interval
230
231
5e72534b 232class Grooveshark:
973b4c6c 233
7ea6f166 234 albumImg = xbmc.translatePath(os.path.join(imgDir, 'album.png'))
235 artistImg = xbmc.translatePath(os.path.join(imgDir, 'artist.png'))
86f629ea 236 artistsAlbumsImg = xbmc.translatePath(os.path.join(imgDir, 'artistsalbums.png'))
7ea6f166 237 favoritesImg = xbmc.translatePath(os.path.join(imgDir, 'favorites.png'))
238 playlistImg = xbmc.translatePath(os.path.join(imgDir, 'playlist.png'))
86f629ea 239 usersplaylistsImg = xbmc.translatePath(os.path.join(imgDir, 'usersplaylists.png'))
7ea6f166 240 popularSongsImg = xbmc.translatePath(os.path.join(imgDir, 'popularSongs.png'))
97289139 241 popularSongsArtistImg = xbmc.translatePath(os.path.join(imgDir, 'popularSongsArtist.png'))
7ea6f166 242 songImg = xbmc.translatePath(os.path.join(imgDir, 'song.png'))
243 defImg = xbmc.translatePath(os.path.join(imgDir, 'default.tbn'))
57ffc218 244 fanImg = xbmc.translatePath(os.path.join(baseDir, 'fanart.jpg'))
8817bb2e 245
2254a6b5 246 settings = xbmcaddon.Addon(id='plugin.audio.groove')
7ce01be6 247 songsearchlimit = int(settings.getSetting('songsearchlimit'))
248 albumsearchlimit = int(settings.getSetting('albumsearchlimit'))
249 artistsearchlimit = int(settings.getSetting('artistsearchlimit'))
97289139 250 songspagelimit = int(settings.getSetting('songspagelimit'))
2254a6b5 251 username = settings.getSetting('username')
252 password = settings.getSetting('password')
5e72534b 253
38df1fa5 254 userid = 0
4be42357 255
8817bb2e 256 def __init__( self ):
257 self._handle = int(sys.argv[1])
7ce01be6 258 if os.path.isdir(cacheDir) == False:
259 os.makedirs(cacheDir)
9f9eadcd 260 if __debugging__ :
5e72534b 261 xbmc.log(__language__(30012) + " " + cacheDir)
164e42d8 262 artDir = xbmc.translatePath(thumbDir)
263 if os.path.isdir(artDir) == False:
3a794693 264 os.makedirs(artDir)
9f9eadcd 265 if __debugging__ :
5e72534b 266 xbmc.log(__language__(30012) + " " + artDir)
052028f1 267
e278f474 268 # Top-level menu
8817bb2e 269 def categories(self):
2254a6b5 270
38df1fa5 271 self.userid = self._get_login()
b738088f 272
273 # Setup
6ae708d0 274 xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
6ae708d0 275
b26b96e6 276 self._add_dir(__language__(30013), '', MODE_SEARCH_SONGS, self.songImg, 0)
277 self._add_dir(__language__(30014), '', MODE_SEARCH_ALBUMS, self.albumImg, 0)
278 self._add_dir(__language__(30015), '', MODE_SEARCH_ARTISTS, self.artistImg, 0)
3d95dfcb 279 self._add_dir(searchArtistsAlbumsName, '', MODE_SEARCH_ARTISTS_ALBUMS, self.artistsAlbumsImg, 0)
f95afae7 280 # Not supported by key
281 #self._add_dir("Search for user's playlists...", '', MODE_SEARCH_PLAYLISTS, self.usersplaylistsImg, 0)
b26b96e6 282 self._add_dir(__language__(30016), '', MODE_ARTIST_POPULAR, self.popularSongsArtistImg, 0)
283 self._add_dir(__language__(30017), '', MODE_POPULAR_SONGS, self.popularSongsImg, 0)
38df1fa5 284 if (self.userid != 0):
b26b96e6 285 self._add_dir(__language__(30018), '', MODE_FAVORITES, self.favoritesImg, 0)
286 self._add_dir(__language__(30019), '', MODE_PLAYLISTS, self.playlistImg, 0)
e278f474 287
288 # Search for songs
8817bb2e 289 def searchSongs(self):
b26b96e6 290 query = self._get_keyboard(default="", heading=__language__(30020))
7ea6f166 291 if (query != ''):
7ce01be6 292 songs = groovesharkApi.getSongSearchResults(query, limit = self.songsearchlimit)
8817bb2e 293 if (len(songs) > 0):
6ae708d0 294 self._add_songs_directory(songs)
8817bb2e 295 else:
296 dialog = xbmcgui.Dialog()
b26b96e6 297 dialog.ok(__language__(30008), __language__(30021))
8817bb2e 298 self.categories()
7ea6f166 299 else:
300 self.categories()
8817bb2e 301
e278f474 302 # Search for albums
8817bb2e 303 def searchAlbums(self):
b26b96e6 304 query = self._get_keyboard(default="", heading=__language__(30022))
7ea6f166 305 if (query != ''):
7ce01be6 306 albums = groovesharkApi.getAlbumSearchResults(query, limit = self.albumsearchlimit)
8817bb2e 307 if (len(albums) > 0):
6ae708d0 308 self._add_albums_directory(albums)
8817bb2e 309 else:
310 dialog = xbmcgui.Dialog()
b26b96e6 311 dialog.ok(__language__(30008), __language__(30023))
8817bb2e 312 self.categories()
7ea6f166 313 else:
314 self.categories()
8817bb2e 315
e278f474 316 # Search for artists
8817bb2e 317 def searchArtists(self):
b26b96e6 318 query = self._get_keyboard(default="", heading=__language__(30024))
7ea6f166 319 if (query != ''):
7ce01be6 320 artists = groovesharkApi.getArtistSearchResults(query, limit = self.artistsearchlimit)
8817bb2e 321 if (len(artists) > 0):
6ae708d0 322 self._add_artists_directory(artists)
8817bb2e 323 else:
324 dialog = xbmcgui.Dialog()
b26b96e6 325 dialog.ok(__language__(30008), __language__(30025))
8817bb2e 326 self.categories()
7ea6f166 327 else:
328 self.categories()
86f629ea 329
330 # Search for playlists
331 def searchPlaylists(self):
b26b96e6 332 query = self._get_keyboard(default="", heading=__language__(30026))
86f629ea 333 if (query != ''):
f95afae7 334 playlists = groovesharkApi.getUserPlaylistsByUsername(query)
86f629ea 335 if (len(playlists) > 0):
336 self._add_playlists_directory(playlists)
337 else:
338 dialog = xbmcgui.Dialog()
b26b96e6 339 dialog.ok(__language__(30008), __language__(30027))
86f629ea 340 self.categories()
341 else:
342 self.categories()
343
344 # Search for artists albums
3d95dfcb 345 def searchArtistsAlbums(self, artistName = None):
346 if artistName == None or artistName == searchArtistsAlbumsName:
b26b96e6 347 query = self._get_keyboard(default="", heading=__language__(30028))
99f72740 348 else:
349 query = artistName
86f629ea 350 if (query != ''):
351 artists = groovesharkApi.getArtistSearchResults(query, limit = self.artistsearchlimit)
352 if (len(artists) > 0):
353 artist = artists[0]
354 artistID = artist[1]
9f9eadcd 355 if __debugging__ :
5e72534b 356 xbmc.log("Found " + artist[0] + "...")
8d7ba769 357 albums = groovesharkApi.getArtistAlbums(artistID, self.albumsearchlimit)
86f629ea 358 if (len(albums) > 0):
052028f1 359 self._add_albums_directory(albums, artistID)
86f629ea 360 else:
361 dialog = xbmcgui.Dialog()
b26b96e6 362 dialog.ok(__language__(30008), __language__(30029))
86f629ea 363 self.categories()
364 else:
365 dialog = xbmcgui.Dialog()
b26b96e6 366 dialog.ok(__language__(30008), __language__(30030))
86f629ea 367 self.categories()
368 else:
369 self.categories()
370
e278f474 371 # Get my favorites
8817bb2e 372 def favorites(self):
36cc00d7 373 userid = self._get_login()
374 if (userid != 0):
7ce01be6 375 favorites = groovesharkApi.getUserFavoriteSongs()
36cc00d7 376 if (len(favorites) > 0):
052028f1 377 self._add_songs_directory(favorites, isFavorites=True)
36cc00d7 378 else:
379 dialog = xbmcgui.Dialog()
b26b96e6 380 dialog.ok(__language__(30008), __language__(30031))
36cc00d7 381 self.categories()
8817bb2e 382
e278f474 383 # Get popular songs
36cc00d7 384 def popularSongs(self):
7ce01be6 385 popular = groovesharkApi.getPopularSongsToday(limit = self.songsearchlimit)
8817bb2e 386 if (len(popular) > 0):
6ae708d0 387 self._add_songs_directory(popular)
8817bb2e 388 else:
389 dialog = xbmcgui.Dialog()
b26b96e6 390 dialog.ok(__language__(30008), __language__(30032))
8817bb2e 391 self.categories()
36cc00d7 392
e278f474 393 # Get my playlists
8817bb2e 394 def playlists(self):
395 userid = self._get_login()
396 if (userid != 0):
7ce01be6 397 playlists = groovesharkApi.getUserPlaylists()
8817bb2e 398 if (len(playlists) > 0):
6ae708d0 399 self._add_playlists_directory(playlists)
8817bb2e 400 else:
401 dialog = xbmcgui.Dialog()
b26b96e6 402 dialog.ok(__language__(30008), __language__(30033))
8817bb2e 403 self.categories()
7ea6f166 404 else:
405 dialog = xbmcgui.Dialog()
b26b96e6 406 dialog.ok(__language__(30008), __language__(30034), __language__(30035))
7ea6f166 407
e278f474 408 # Make songs a favorite
8817bb2e 409 def favorite(self, songid):
410 userid = self._get_login()
411 if (userid != 0):
9f9eadcd 412 if __debugging__ :
5e72534b 413 xbmc.log("Favorite song: " + str(songid))
7ce01be6 414 groovesharkApi.addUserFavoriteSong(songID = songid)
b26b96e6 415 xbmc.executebuiltin('XBMC.Notification(' + __language__(30008) + ', ' + __language__(30036) + ', 1000, ' + thumbDef + ')')
8817bb2e 416 else:
417 dialog = xbmcgui.Dialog()
b26b96e6 418 dialog.ok(__language__(30008), __language__(30034), __language__(30037))
052028f1 419
420 # Remove song from favorites
421 def unfavorite(self, songid, prevMode=0):
f95afae7 422 userid = self._get_login()
052028f1 423 if (userid != 0):
9f9eadcd 424 if __debugging__ :
5e72534b 425 xbmc.log("Unfavorite song: " + str(songid) + ', previous mode was ' + str(prevMode))
f95afae7 426 groovesharkApi.removeUserFavoriteSongs(songIDs = songid)
b26b96e6 427 xbmc.executebuiltin('XBMC.Notification(' + __language__(30008) + ', ' + __language__(30038) + ', 1000, ' + thumbDef + ')')
052028f1 428 # Refresh to remove item from directory
429 if (int(prevMode) == MODE_FAVORITES):
430 xbmc.executebuiltin("Container.Refresh(" + favoritesUrl + ")")
431 else:
432 dialog = xbmcgui.Dialog()
b26b96e6 433 dialog.ok(__language__(30008), __language__(30034), __language__(30039))
052028f1 434
e278f474 435
436 # Show selected album
36cc00d7 437 def album(self, albumid):
7ce01be6 438 album = groovesharkApi.getAlbumSongs(albumid, limit = self.songsearchlimit)
86f629ea 439 self._add_songs_directory(album, trackLabelFormat=NAME_ALBUM_ARTIST_LABEL)
e278f474 440
441 # Show selected artist
8817bb2e 442 def artist(self, artistid):
7ce01be6 443 albums = groovesharkApi.getArtistAlbums(artistid, limit = self.albumsearchlimit)
5d3b12f2 444 self._add_albums_directory(albums, artistid, True)
8817bb2e 445
e278f474 446 # Show selected playlist
e6f8730b 447 def playlist(self, playlistid, playlistname):
8817bb2e 448 userid = self._get_login()
449 if (userid != 0):
e6f8730b 450 songs = groovesharkApi.getPlaylistSongs(playlistid)
052028f1 451 self._add_songs_directory(songs, trackLabelFormat=NAME_ALBUM_ARTIST_LABEL, playlistid=playlistid, playlistname=playlistname)
8817bb2e 452 else:
453 dialog = xbmcgui.Dialog()
b26b96e6 454 dialog.ok(__language__(30008), __language__(30034), __language__(30040))
8817bb2e 455
97289139 456 # Show popular songs of the artist
457 def artistPopularSongs(self):
b26b96e6 458 query = self._get_keyboard(default="", heading=__language__(30041))
97289139 459 if (query != ''):
460 artists = groovesharkApi.getArtistSearchResults(query, limit = self.artistsearchlimit)
461 if (len(artists) > 0):
462 artist = artists[0]
463 artistID = artist[1]
9f9eadcd 464 if __debugging__ :
5e72534b 465 xbmc.log("Found " + artist[0] + "...")
97289139 466 songs = groovesharkApi.getArtistPopularSongs(artistID, limit = self.songsearchlimit)
467 if (len(songs) > 0):
468 self._add_songs_directory(songs, trackLabelFormat=NAME_ALBUM_ARTIST_LABEL)
469 else:
470 dialog = xbmcgui.Dialog()
b26b96e6 471 dialog.ok(__language__(30008), __language__(30042))
97289139 472 self.categories()
473 else:
474 dialog = xbmcgui.Dialog()
b26b96e6 475 dialog.ok(__language__(30008), __language__(30043))
97289139 476 self.categories()
477 else:
478 self.categories()
479
e278f474 480 # Play a song
6ae708d0 481 def playSong(self, item):
f95afae7 482 global playTimer
483 global player
484 if item != None:
f7eadea2 485 # Get stream as it could have expired
a9e5e6c4 486 item.select(True)
48e0c138 487 url = ''
9f9eadcd 488 songid = item.getProperty('songid')
48e0c138 489 stream = groovesharkApi.getSubscriberStreamKey(songid)
490 if stream != False:
491 url = stream['url']
9f9eadcd 492 key = stream['StreamKey']
493 server = stream['StreamServerID']
f7eadea2 494 duration = int(self._setDuration(stream['uSecs']))
a9e5e6c4 495 stream = [songid, duration, url, key, server]
496 self._setSongStream(stream)
497 if url != '':
498 item.setPath(url)
499 xbmcplugin.setResolvedUrl(handle=int(sys.argv[1]), succeeded=True, listitem=item)
500 if __debugging__ :
501 xbmc.log("Grooveshark playing: " + url)
502 # Wait for play then start timer
503 seconds = 0
504 while seconds < STREAM_TIMEOUT:
505 try:
506 if player.isPlayingAudio() == True:
507 if playTimer != None:
508 playTimer.cancel()
509 songMarkTime = 0
510 playTimer = PlayTimer(1, markSong, self._setDuration(duration), [songid, duration, key, server])
511 playTimer.start()
512 break
513 except: pass
514 time.sleep(1)
515 seconds = seconds + 1
516 else:
517 xbmc.log("No song URL")
48e0c138 518 else:
a9e5e6c4 519 xbmc.log("No song stream")
7ce01be6 520 else:
b26b96e6 521 xbmc.executebuiltin('XBMC.Notification(' + __language__(30008) + ', ' + __language__(30044) + ', 1000, ' + thumbDef + ')')
f95afae7 522
e278f474 523 # Make a song directory item
7a57b8d1 524 def songItem(self, songid, name, album, artist, coverart, trackLabelFormat=ARTIST_ALBUM_NAME_LABEL, tracknumber=1):
7ce01be6 525
a9e5e6c4 526 stream = self._getSongStream(songid)
f7eadea2 527 if stream != False:
a9e5e6c4 528 duration = stream[1]
529 url = stream[2]
530 key = stream[3]
531 server = stream[4]
f7eadea2 532 songImg = self._get_icon(coverart, 'song-' + str(songid) + "-image")
533 if int(trackLabelFormat) == NAME_ALBUM_ARTIST_LABEL:
534 trackLabel = name + " - " + album + " - " + artist
535 else:
536 trackLabel = artist + " - " + album + " - " + name
537 item = xbmcgui.ListItem(label = trackLabel, thumbnailImage=songImg, iconImage=songImg)
538 item.setPath(url)
7a57b8d1 539 item.setInfo( type="music", infoLabels={ "title": name, "album": album, "artist": artist, "duration": duration, "tracknumber" : tracknumber} )
f7eadea2 540 item.setProperty('mimetype', 'audio/mpeg')
541 item.setProperty("IsPlayable", "true")
542 item.setProperty('songid', str(songid))
543 item.setProperty('coverart', songImg)
544 item.setProperty('title', name)
545 item.setProperty('album', album)
546 item.setProperty('artist', artist)
547 item.setProperty('duration', str(duration))
548 item.setProperty('key', str(key))
549 item.setProperty('server', str(server))
a03bc739 550 item.setProperty('fanart_image', self.fanImg)
f7eadea2 551 return item
552 else:
553 xbmc.log("No song URL")
554 return None
2254a6b5 555
97289139 556 # Next page of songs
5e72534b 557 def songPage(self, offset, trackLabelFormat, playlistid = 0, playlistname = ''):
558 self._add_songs_directory([], trackLabelFormat, offset, playlistid = playlistid, playlistname = playlistname)
052028f1 559
560 # Make a playlist from an album
561 def makePlaylist(self, albumid, name):
f95afae7 562 userid = self._get_login()
052028f1 563 if (userid != 0):
564 re.split(' - ',name,1)
565 nameTokens = re.split(' - ',name,1) # suggested name
b26b96e6 566 name = self._get_keyboard(default=nameTokens[0], heading=__language__(30045))
052028f1 567 if name != '':
568 album = groovesharkApi.getAlbumSongs(albumid, limit = self.songsearchlimit)
569 songids = []
570 for song in album:
571 songids.append(song[1])
f95afae7 572 if groovesharkApi.createPlaylist(name, songids) == 0:
052028f1 573 dialog = xbmcgui.Dialog()
b26b96e6 574 dialog.ok(__language__(30008), __language__(30046), name)
052028f1 575 else:
b26b96e6 576 xbmc.executebuiltin('XBMC.Notification(' + __language__(30008) + ',' + __language__(30047)+ ', 1000, ' + thumbDef + ')')
052028f1 577 else:
578 dialog = xbmcgui.Dialog()
b26b96e6 579 dialog.ok(__language__(30008), __language__(30034), __language__(30048))
052028f1 580
581 # Rename a playlist
582 def renamePlaylist(self, playlistid, name):
f95afae7 583 userid = self._get_login()
052028f1 584 if (userid != 0):
b26b96e6 585 newname = self._get_keyboard(default=name, heading=__language__(30049))
052028f1 586 if newname == '':
587 return
f95afae7 588 elif groovesharkApi.playlistRename(playlistid, newname) == 0:
052028f1 589 dialog = xbmcgui.Dialog()
b26b96e6 590 dialog.ok(__language__(30008), __language__(30050), name)
052028f1 591 else:
592 # Refresh to show new item name
593 xbmc.executebuiltin("Container.Refresh")
594 else:
595 dialog = xbmcgui.Dialog()
b26b96e6 596 dialog.ok(__language__(30008), __language__(30034), __language__(30051))
052028f1 597
598 # Remove a playlist
599 def removePlaylist(self, playlistid, name):
600 dialog = xbmcgui.Dialog()
b26b96e6 601 if dialog.yesno(__language__(30008), name, __language__(30052)) == True:
f95afae7 602 userid = self._get_login()
052028f1 603 if (userid != 0):
f95afae7 604 if groovesharkApi.playlistDelete(playlistid) == 0:
052028f1 605 dialog = xbmcgui.Dialog()
b26b96e6 606 dialog.ok(__language__(30008), __language__(30053), name)
052028f1 607 else:
608 # Refresh to remove item from directory
609 xbmc.executebuiltin("Container.Refresh(" + playlistsUrl + ")")
610 else:
611 dialog = xbmcgui.Dialog()
b26b96e6 612 dialog.ok(__language__(30008), __language__(30034), __language__(30054))
052028f1 613
614 # Add song to playlist
615 def addPlaylistSong(self, songid):
f95afae7 616 userid = self._get_login()
052028f1 617 if (userid != 0):
618 playlists = groovesharkApi.getUserPlaylists()
619 if (len(playlists) > 0):
620 ret = 0
621 # Select the playlist
622 playlistSelect = GroovesharkPlaylistSelect(items=playlists)
623 playlistSelect.setFocus(playlistSelect.playlistControl)
624 playlistSelect.doModal()
625 i = playlistSelect.selected
626 del playlistSelect
627 if i > -1:
628 # Add a new playlist
629 if i >= len(playlists):
b26b96e6 630 name = self._get_keyboard(default='', heading=__language__(30055))
052028f1 631 if name != '':
632 songIds = []
633 songIds.append(songid)
f95afae7 634 if groovesharkApi.createPlaylist(name, songIds) == 0:
052028f1 635 dialog = xbmcgui.Dialog()
b26b96e6 636 dialog.ok(__language__(30008), __language__(30056), name)
052028f1 637 else:
b26b96e6 638 xbmc.executebuiltin('XBMC.Notification(' + __language__(30008) + ',' + __language__(30057) + ', 1000, ' + thumbDef + ')')
052028f1 639 # Existing playlist
640 else:
641 playlist = playlists[i]
642 playlistid = playlist[1]
9f9eadcd 643 if __debugging__ :
5e72534b 644 xbmc.log("Add song " + str(songid) + " to playlist " + str(playlistid))
f95afae7 645 songIDs=[]
646 songs = groovesharkApi.getPlaylistSongs(playlistid)
647 for song in songs:
648 songIDs.append(song[1])
649 songIDs.append(songid)
650 ret = groovesharkApi.setPlaylistSongs(playlistid, songIDs)
651 if ret == False:
052028f1 652 dialog = xbmcgui.Dialog()
b26b96e6 653 dialog.ok(__language__(30008), __language__(30058))
052028f1 654 else:
b26b96e6 655 xbmc.executebuiltin('XBMC.Notification(' + __language__(30008) + ',' + __language__(30059) + ', 1000, ' + thumbDef + ')')
052028f1 656 else:
657 dialog = xbmcgui.Dialog()
b26b96e6 658 dialog.ok(__language__(30008), __language__(30060))
052028f1 659 self.categories()
660 else:
661 dialog = xbmcgui.Dialog()
b26b96e6 662 dialog.ok(__language__(30008), __language__(30034), __language__(30061))
052028f1 663
664 # Remove song from playlist
f95afae7 665 def removePlaylistSong(self, playlistid, playlistname, songid):
e6f8730b 666 dialog = xbmcgui.Dialog()
b26b96e6 667 if dialog.yesno(__language__(30008), __language__(30062), __language__(30063)) == True:
f95afae7 668 userid = self._get_login()
052028f1 669 if (userid != 0):
f95afae7 670 songs = groovesharkApi.getPlaylistSongs(playlistID)
671 songIDs=[]
672 for song in songs:
673 if (song[1] != songid):
674 songIDs.append(song[1])
675 ret = groovesharkApi.setPlaylistSongs(playlistID, songIDs)
676 if ret == False:
052028f1 677 dialog = xbmcgui.Dialog()
b26b96e6 678 dialog.ok(__language__(30008), __language__(30064), __language__(30065))
052028f1 679 else:
680 # Refresh to remove item from directory
b26b96e6 681 xbmc.executebuiltin('XBMC.Notification(' + __language__(30008) + ',' + __language__(30066)+ ', 1000, ' + thumbDef + ')')
3b4634df 682 xbmc.executebuiltin("Container.Update(" + playlistUrl + "&id="+str(playlistid) + "&name=" + str(playlistname) + ")")
052028f1 683 else:
684 dialog = xbmcgui.Dialog()
b26b96e6 685 dialog.ok(__language__(30008), __language__(30034), __language__(30067))
052028f1 686
687 # Find similar artists to searched artist
688 def similarArtists(self, artistId):
f95afae7 689 similar = groovesharkApi.getSimilarArtists(artistId, limit = self.artistsearchlimit)
052028f1 690 if (len(similar) > 0):
691 self._add_artists_directory(similar)
692 else:
693 dialog = xbmcgui.Dialog()
b26b96e6 694 dialog.ok(__language__(30008), __language__(30068))
052028f1 695 self.categories()
5e72534b 696
e278f474 697 # Get keyboard input
8817bb2e 698 def _get_keyboard(self, default="", heading="", hidden=False):
3cfead3c 699 kb = xbmc.Keyboard(default, heading, hidden)
700 kb.doModal()
701 if (kb.isConfirmed()):
702 return unicode(kb.getText(), "utf-8")
703 return ''
8817bb2e 704
e278f474 705 # Login to grooveshark
f95afae7 706 def _get_login(self):
2254a6b5 707 if (self.username == "" or self.password == ""):
8817bb2e 708 dialog = xbmcgui.Dialog()
4faaea26 709 dialog.ok(__language__(30008), __language__(30069), __language__(30070), __language__(30082))
8817bb2e 710 return 0
711 else:
38df1fa5 712 if self.userid == 0:
f95afae7 713 uid = groovesharkApi.login(self.username, self.password)
38df1fa5 714 if (uid != 0):
38df1fa5 715 return uid
8817bb2e 716 else:
717 dialog = xbmcgui.Dialog()
4faaea26 718 dialog.ok(__language__(30008), __language__(30069), __language__(30070), __language__(30082))
8817bb2e 719 return 0
720
6ae708d0 721 # File download
7ce01be6 722 def _get_icon(self, url, songid):
723 if url != 'None':
724 localThumb = os.path.join(xbmc.translatePath(os.path.join(thumbDir, str(songid)))) + '.tbn'
725 try:
726 if os.path.isfile(localThumb) == False:
727 loc = urllib.URLopener()
728 loc.retrieve(url, localThumb)
729 except:
730 shutil.copy2(thumbDef, localThumb)
731 return os.path.join(os.path.join(thumbDir, str(songid))) + '.tbn'
732 else:
733 return thumbDef
e278f474 734
735 # Add songs to directory
5e72534b 736 def _add_songs_directory(self, songs, trackLabelFormat=ARTIST_ALBUM_NAME_LABEL, offset=0, playlistid=0, playlistname='', isFavorites=False):
97289139 737
738 totalSongs = len(songs)
5e72534b 739 offset = int(offset)
740 start = 0
741 end = totalSongs
97289139 742
743 # No pages needed
5e72534b 744 if offset == 0 and totalSongs <= self.songspagelimit:
9f9eadcd 745 if __debugging__ :
5e72534b 746 xbmc.log("Found " + str(totalSongs) + " songs...")
97289139 747 # Pages
748 else:
5e72534b 749 # Cache all next pages songs
750 if offset == 0:
97289139 751 self._setSavedSongs(songs)
752 else:
753 songs = self._getSavedSongs()
754 totalSongs = len(songs)
755
756 if totalSongs > 0:
5e72534b 757 start = offset
758 end = min(start + self.songspagelimit,totalSongs)
97289139 759
5e72534b 760 n = start
761 items = end - start
762 while n < end:
763 song = songs[n]
f7eadea2 764 name = song[0]
6ae708d0 765 songid = song[1]
f7eadea2 766 album = song[2]
767 artist = song[4]
768 coverart = song[6]
7a57b8d1 769 item = self.songItem(songid, name, album, artist, coverart, trackLabelFormat, (n+1))
f7eadea2 770 if item != None:
5e72534b 771 coverart = item.getProperty('coverart')
772 songname = song[0]
773 songalbum = song[2]
774 songartist = song[4]
775 u=sys.argv[0]+"?mode="+str(MODE_SONG)+"&name="+urllib.quote_plus(songname)+"&id="+str(songid) \
776 +"&album="+urllib.quote_plus(songalbum) \
777 +"&artist="+urllib.quote_plus(songartist) \
778 +"&coverart="+urllib.quote_plus(coverart)
779 fav=sys.argv[0]+"?mode="+str(MODE_FAVORITE)+"&name="+urllib.quote_plus(songname)+"&id="+str(songid)
780 unfav=sys.argv[0]+"?mode="+str(MODE_UNFAVORITE)+"&name="+urllib.quote_plus(songname)+"&id="+str(songid)+"&prevmode="
781 menuItems = []
782 if isFavorites == True:
783 unfav = unfav +str(MODE_FAVORITES)
784 else:
785 menuItems.append((__language__(30071), "XBMC.RunPlugin("+fav+")"))
786 menuItems.append((__language__(30072), "XBMC.RunPlugin("+unfav+")"))
787 if playlistid > 0:
3b4634df 788 rmplaylstsong=sys.argv[0]+"?playlistid="+str(playlistid)+"&id="+str(songid)+"&mode="+str(MODE_REMOVE_PLAYLIST_SONG)+"&name="+str(playlistname)
5e72534b 789 menuItems.append((__language__(30073), "XBMC.RunPlugin("+rmplaylstsong+")"))
790 else:
791 addplaylstsong=sys.argv[0]+"?id="+str(songid)+"&mode="+str(MODE_ADD_PLAYLIST_SONG)
792 menuItems.append((__language__(30074), "XBMC.RunPlugin("+addplaylstsong+")"))
793 item.addContextMenuItems(menuItems, replaceItems=False)
794 xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=item,isFolder=False, totalItems=items)
f95afae7 795 else:
5e72534b 796 end = min(end + 1,totalSongs)
9f9eadcd 797 if __debugging__ :
5e72534b 798 xbmc.log(song[0] + " does not exist.")
799 n = n + 1
97289139 800
5e72534b 801 if totalSongs > end:
3b4634df 802 u=sys.argv[0]+"?mode="+str(MODE_SONG_PAGE)+"&id=playlistid"+"&offset="+str(end)+"&label="+str(trackLabelFormat)+"&name="+str(playlistname)
5e72534b 803 self._add_dir(__language__(30075) + '...', u, MODE_SONG_PAGE, self.songImg, 0, totalSongs - end)
cb06c186 804
8817bb2e 805 xbmcplugin.setContent(self._handle, 'songs')
31731635 806 xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
e278f474 807
808 # Add albums to directory
5d3b12f2 809 def _add_albums_directory(self, albums, artistid=0, isverified=False):
31731635 810 n = len(albums)
5e72534b 811 itemsExisting = n
9f9eadcd 812 if __debugging__ :
5e72534b 813 xbmc.log("Found " + str(n) + " albums...")
8817bb2e 814 i = 0
31731635 815 while i < n:
8817bb2e 816 album = albums[i]
8817bb2e 817 albumID = album[3]
5d3b12f2 818 if isverified or groovesharkApi.getDoesAlbumExist(albumID):
5e72534b 819 albumArtistName = album[0]
820 albumName = album[2]
821 albumImage = self._get_icon(album[4], 'album-' + str(albumID))
822 self._add_dir(albumName + " - " + albumArtistName, '', MODE_ALBUM, albumImage, albumID, itemsExisting)
823 else:
824 itemsExisting = itemsExisting - 1
8817bb2e 825 i = i + 1
f95afae7 826 # Not supported by key
827 #if artistid > 0:
828 # self._add_dir('Similar artists...', '', MODE_SIMILAR_ARTISTS, self.artistImg, artistid)
8817bb2e 829 xbmcplugin.setContent(self._handle, 'albums')
830 xbmcplugin.addSortMethod(self._handle, xbmcplugin.SORT_METHOD_ALBUM_IGNORE_THE)
31731635 831 xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
e278f474 832
833 # Add artists to directory
6ae708d0 834 def _add_artists_directory(self, artists):
31731635 835 n = len(artists)
5e72534b 836 itemsExisting = n
9f9eadcd 837 if __debugging__ :
5e72534b 838 xbmc.log("Found " + str(n) + " artists...")
8817bb2e 839 i = 0
31731635 840 while i < n:
8817bb2e 841 artist = artists[i]
8817bb2e 842 artistID = artist[1]
5e72534b 843 if groovesharkApi.getDoesArtistExist(artistID):
844 artistName = artist[0]
845 self._add_dir(artistName, '', MODE_ARTIST, self.artistImg, artistID, itemsExisting)
846 else:
847 itemsExisting = itemsExisting - 1
8817bb2e 848 i = i + 1
849 xbmcplugin.setContent(self._handle, 'artists')
850 xbmcplugin.addSortMethod(self._handle, xbmcplugin.SORT_METHOD_ARTIST_IGNORE_THE)
31731635 851 xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
e278f474 852
853 # Add playlists to directory
6ae708d0 854 def _add_playlists_directory(self, playlists):
31731635 855 n = len(playlists)
9f9eadcd 856 if __debugging__ :
5e72534b 857 xbmc.log("Found " + str(n) + " playlists...")
8817bb2e 858 i = 0
31731635 859 while i < n:
8817bb2e 860 playlist = playlists[i]
861 playlistName = playlist[0]
862 playlistID = playlist[1]
3b4634df 863 self._add_dir(playlistName, '', MODE_PLAYLIST, self.playlistImg, playlistID, n)
8817bb2e 864 i = i + 1
865 xbmcplugin.setContent(self._handle, 'files')
86f629ea 866 xbmcplugin.addSortMethod(self._handle, xbmcplugin.SORT_METHOD_LABEL)
31731635 867 xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
3fcef5ba 868
e278f474 869 # Add whatever directory
3b4634df 870 def _add_dir(self, name, url, mode, iconimage, itemId, items=1):
052028f1 871
97289139 872 if url == '':
3b4634df 873 u=sys.argv[0]+"?mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&id="+str(itemId)
97289139 874 else:
875 u = url
3b4634df 876 directory=xbmcgui.ListItem(name, iconImage=iconimage, thumbnailImage=iconimage)
877 directory.setInfo( type="Music", infoLabels={ "title": name } )
a03bc739 878 directory.setProperty('fanart_image', self.fanImg)
052028f1 879
880 # Custom menu items
f95afae7 881 menuItems = []
882 if mode == MODE_ALBUM:
3b4634df 883 mkplaylst=sys.argv[0]+"?mode="+str(MODE_MAKE_PLAYLIST)+"&name="+name+"&id="+str(itemId)
b26b96e6 884 menuItems.append((__language__(30076), "XBMC.RunPlugin("+mkplaylst+")"))
f95afae7 885 if mode == MODE_PLAYLIST:
3b4634df 886 rmplaylst=sys.argv[0]+"?mode="+str(MODE_REMOVE_PLAYLIST)+"&name="+urllib.quote_plus(name)+"&id="+str(itemId)
b26b96e6 887 menuItems.append((__language__(30077), "XBMC.RunPlugin("+rmplaylst+")"))
3b4634df 888 mvplaylst=sys.argv[0]+"?mode="+str(MODE_RENAME_PLAYLIST)+"&name="+urllib.quote_plus(name)+"&id="+str(itemId)
b26b96e6 889 menuItems.append((__language__(30078), "XBMC.RunPlugin("+mvplaylst+")"))
5e72534b 890
3b4634df 891 directory.addContextMenuItems(menuItems, replaceItems=False)
052028f1 892
3b4634df 893 return xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=directory,isFolder=True, totalItems=items)
97289139 894
895 def _getSavedSongs(self):
896 path = os.path.join(cacheDir, 'songs.dmp')
897 try:
898 f = open(path, 'rb')
899 songs = pickle.load(f)
900 f.close()
901 except:
902 songs = []
903 pass
904 return songs
905
906 def _setSavedSongs(self, songs):
907 try:
908 # Create the 'data' directory if it doesn't exist.
909 if not os.path.exists(cacheDir):
910 os.makedirs(cacheDir)
911 path = os.path.join(cacheDir, 'songs.dmp')
912 f = open(path, 'wb')
913 pickle.dump(songs, f, protocol=pickle.HIGHEST_PROTOCOL)
914 f.close()
915 except:
916 xbmc.log("An error occurred saving songs")
917 pass
f95afae7 918
9f9eadcd 919 # Duration to seconds
cfad7202 920 def _setDuration(self, usecs):
921 if usecs < 60000000:
922 usecs = usecs * 10 # Some durations are 10x to small
a9e5e6c4 923 return int(usecs / 1000000)
924
925 def _getSongStream(self, songid):
3b4634df 926 idSong = int(songid)
a9e5e6c4 927 stream = None
928 streams = []
929 path = os.path.join(cacheDir, 'streams.dmp')
930 try:
931 f = open(path, 'rb')
932 streams = pickle.load(f)
933 for song in streams:
3b4634df 934 if song[0] == idSong:
a9e5e6c4 935 duration = song[1]
936 url = song[2]
937 key = song[3]
938 server = song[4]
3b4634df 939 stream = [idSong, duration, url, key, server]
a9e5e6c4 940 if __debugging__ :
3b4634df 941 xbmc.log("Found " + str(idSong) + " in stream cache")
a9e5e6c4 942 break;
943 f.close()
944 except:
945 pass
946
947 # Not in cache
948 if stream == None:
949 stream = groovesharkApi.getSubscriberStreamKey(songid)
950 if stream != False and stream['url'] != '':
951 duration = self._setDuration(stream['uSecs'])
952 url = stream['url']
953 key = stream['StreamKey']
954 server = stream['StreamServerID']
3b4634df 955 stream = [idSong, duration, url, key, server]
e0a32693 956 self._addSongStream(stream)
a9e5e6c4 957
958 return stream
959
e0a32693 960 def _addSongStream(self, stream):
961 streams = self._getStreams()
962 streams.append(stream)
963 path = os.path.join(cacheDir, 'streams.dmp')
a9e5e6c4 964 try:
a9e5e6c4 965 f = open(path, 'wb')
966 pickle.dump(streams, f, protocol=pickle.HIGHEST_PROTOCOL)
967 f.close()
e0a32693 968 if __debugging__ :
969 xbmc.log("Added " + str(stream[0]) + " to stream cache")
a9e5e6c4 970 except:
e0a32693 971 xbmc.log("An error occurred adding to stream")
a9e5e6c4 972
973 def _setSongStream(self, stream):
3b4634df 974 idStream = int(stream[0])
a9e5e6c4 975 stream[1] = self._setDuration(stream[1])
e0a32693 976 streams = self._getStreams()
a9e5e6c4 977 path = os.path.join(cacheDir, 'streams.dmp')
e0a32693 978 i = 0
979
980 for song in streams:
3b4634df 981 if song[0] == idStream:
e0a32693 982 streams[i] = stream
983 try:
984 f = open(path, 'wb')
a9e5e6c4 985 pickle.dump(streams, f, protocol=pickle.HIGHEST_PROTOCOL)
e0a32693 986 f.close()
987 if __debugging__ :
3b4634df 988 xbmc.log("Updated " + str(idStream) + " in stream cache")
a9e5e6c4 989 break;
e0a32693 990 except:
991 xbmc.log("An error occurred setting stream")
992 i = i + 1
993
994 def _getStreams(self):
995 path = os.path.join(cacheDir, 'streams.dmp')
996 try:
997 f = open(path, 'rb')
998 streams = pickle.load(f)
a9e5e6c4 999 f.close()
1000 except:
e0a32693 1001 streams = []
1002 pass
1003 return streams
1004
97289139 1005
e278f474 1006# Parse URL parameters
8817bb2e 1007def get_params():
1008 param=[]
1009 paramstring=sys.argv[2]
9f9eadcd 1010 if __debugging__ :
5e72534b 1011 xbmc.log(paramstring)
8817bb2e 1012 if len(paramstring)>=2:
1013 params=sys.argv[2]
1014 cleanedparams=params.replace('?','')
1015 if (params[len(params)-1]=='/'):
1016 params=params[0:len(params)-2]
1017 pairsofparams=cleanedparams.split('&')
1018 param={}
1019 for i in range(len(pairsofparams)):
1020 splitparams={}
1021 splitparams=pairsofparams[i].split('=')
1022 if (len(splitparams))==2:
1023 param[splitparams[0]]=splitparams[1]
8817bb2e 1024 return param
1025
e278f474 1026# Main
5e72534b 1027grooveshark = Grooveshark();
e278f474 1028
8817bb2e 1029params=get_params()
8817bb2e 1030mode=None
8817bb2e 1031try: mode=int(params["mode"])
1032except: pass
3b4634df 1033itemId=0
1034try: itemId=int(params["id"])
7ce01be6 1035except: pass
052028f1 1036name = None
1037try: name=urllib.unquote_plus(params["name"])
1038except: pass
e278f474 1039
1040# Call function for URL
8817bb2e 1041if mode==None:
1042 grooveshark.categories()
1043
1044elif mode==MODE_SEARCH_SONGS:
1045 grooveshark.searchSongs()
1046
1047elif mode==MODE_SEARCH_ALBUMS:
1048 grooveshark.searchAlbums()
1049
1050elif mode==MODE_SEARCH_ARTISTS:
1051 grooveshark.searchArtists()
86f629ea 1052
1053elif mode==MODE_SEARCH_ARTISTS_ALBUMS:
a2e75b14 1054 grooveshark.searchArtistsAlbums(name)
86f629ea 1055
1056elif mode==MODE_SEARCH_PLAYLISTS:
1057 grooveshark.searchPlaylists()
8817bb2e 1058
36cc00d7 1059elif mode==MODE_POPULAR_SONGS:
1060 grooveshark.popularSongs()
97289139 1061
1062elif mode==MODE_ARTIST_POPULAR:
a2e75b14 1063 grooveshark.artistPopularSongs()
8817bb2e 1064
8817bb2e 1065elif mode==MODE_FAVORITES:
1066 grooveshark.favorites()
1067
e278f474 1068elif mode==MODE_PLAYLISTS:
1069 grooveshark.playlists()
97289139 1070
1071elif mode==MODE_SONG_PAGE:
5e72534b 1072 try: offset=urllib.unquote_plus(params["offset"])
97289139 1073 except: pass
1074 try: label=urllib.unquote_plus(params["label"])
1075 except: pass
3b4634df 1076 grooveshark.songPage(offset, label, itemId, name)
e278f474 1077
8817bb2e 1078elif mode==MODE_SONG:
8817bb2e 1079 try: album=urllib.unquote_plus(params["album"])
1080 except: pass
1081 try: artist=urllib.unquote_plus(params["artist"])
1082 except: pass
7ce01be6 1083 try: coverart=urllib.unquote_plus(params["coverart"])
8817bb2e 1084 except: pass
3b4634df 1085 song = grooveshark.songItem(itemId, name, album, artist, coverart)
3fcef5ba 1086 grooveshark.playSong(song)
8817bb2e 1087
1088elif mode==MODE_ARTIST:
3b4634df 1089 grooveshark.artist(itemId)
8817bb2e 1090
1091elif mode==MODE_ALBUM:
3b4634df 1092 grooveshark.album(itemId)
8817bb2e 1093
1094elif mode==MODE_PLAYLIST:
3b4634df 1095 grooveshark.playlist(itemId, name)
8817bb2e 1096
1097elif mode==MODE_FAVORITE:
3b4634df 1098 grooveshark.favorite(itemId)
97289139 1099
052028f1 1100elif mode==MODE_UNFAVORITE:
1101 try: prevMode=int(urllib.unquote_plus(params["prevmode"]))
1102 except:
1103 prevMode = 0
3b4634df 1104 grooveshark.unfavorite(itemId, prevMode)
052028f1 1105
1106elif mode==MODE_SIMILAR_ARTISTS:
3b4634df 1107 grooveshark.similarArtists(itemId)
052028f1 1108
1109elif mode==MODE_MAKE_PLAYLIST:
3b4634df 1110 grooveshark.makePlaylist(itemId, name)
052028f1 1111
1112elif mode==MODE_REMOVE_PLAYLIST:
3b4634df 1113 grooveshark.removePlaylist(itemId, name)
052028f1 1114
1115elif mode==MODE_RENAME_PLAYLIST:
3b4634df 1116 grooveshark.renamePlaylist(itemId, name)
052028f1 1117
1118elif mode==MODE_REMOVE_PLAYLIST_SONG:
1119 try: playlistID=urllib.unquote_plus(params["playlistid"])
1120 except: pass
3b4634df 1121 grooveshark.removePlaylistSong(playlistID, name, itemId)
052028f1 1122
1123elif mode==MODE_ADD_PLAYLIST_SONG:
3b4634df 1124 grooveshark.addPlaylistSong(itemId)
052028f1 1125
e278f474 1126if mode < MODE_SONG:
8817bb2e 1127 xbmcplugin.endOfDirectory(int(sys.argv[1]))