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