7528a13225963b4a4fb789c30fd10663fa55b5a8
[clinton/xbmc-groove.git] / default.py
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
19 import urllib, urllib2, sys, os, shutil, re, pickle, time, traceback, xbmcaddon, xbmcplugin, xbmcgui, xbmc
20
21 __addon__ = xbmcaddon.Addon('plugin.audio.groove')
22 __addonname__ = __addon__.getAddonInfo('name')
23 __cwd__ = __addon__.getAddonInfo('path')
24 __author__ = __addon__.getAddonInfo('author')
25 __version__ = __addon__.getAddonInfo('version')
26 __language__ = __addon__.getLocalizedString
27 __debugging__ = __addon__.getSetting('debug')
28
29 MODE_SEARCH_SONGS = 1
30 MODE_SEARCH_ALBUMS = 2
31 MODE_SEARCH_ARTISTS = 3
32 MODE_SEARCH_ARTISTS_ALBUMS = 4
33 MODE_SEARCH_PLAYLISTS = 5
34 MODE_ARTIST_POPULAR = 6
35 MODE_POPULAR_SONGS = 7
36 MODE_FAVORITES = 8
37 MODE_PLAYLISTS = 9
38 MODE_ALBUM = 10
39 MODE_ARTIST = 11
40 MODE_PLAYLIST = 12
41 MODE_SONG_PAGE = 13
42 MODE_SIMILAR_ARTISTS = 14
43 MODE_SONG = 15
44 MODE_FAVORITE = 16
45 MODE_UNFAVORITE = 17
46 MODE_MAKE_PLAYLIST = 18
47 MODE_REMOVE_PLAYLIST = 19
48 MODE_RENAME_PLAYLIST = 20
49 MODE_REMOVE_PLAYLIST_SONG = 21
50 MODE_ADD_PLAYLIST_SONG = 22
51
52 ACTION_MOVE_LEFT = 1
53 ACTION_MOVE_UP = 3
54 ACTION_MOVE_DOWN = 4
55 ACTION_PAGE_UP = 5
56 ACTION_PAGE_DOWN = 6
57 ACTION_SELECT_ITEM = 7
58 ACTION_PREVIOUS_MENU = 10
59
60 # Formats for track labels
61 ARTIST_ALBUM_NAME_LABEL = 0
62 NAME_ALBUM_ARTIST_LABEL = 1
63
64 # Stream marking time (seconds)
65 STREAM_MARKING_TIME = 30
66
67 # Timeout
68 STREAM_TIMEOUT = 30
69
70 songMarkTime = 0
71 player = xbmc.Player()
72 playTimer = None
73
74 baseDir = __cwd__
75 resDir = xbmc.translatePath(os.path.join(baseDir, 'resources'))
76 libDir = xbmc.translatePath(os.path.join(resDir, 'lib'))
77 imgDir = xbmc.translatePath(os.path.join(resDir, 'img'))
78 cacheDir = os.path.join(xbmc.translatePath('special://masterprofile/addon_data/'), os.path.basename(baseDir))
79 tempDir = xbmc.translatePath('special://temp')
80 thumbDirName = 'thumb'
81 thumbDir = os.path.join(xbmc.translatePath('special://masterprofile/addon_data/'), os.path.basename(baseDir), thumbDirName)
82
83 baseModeUrl = 'plugin://plugin.audio.groove/'
84 playlistUrl = baseModeUrl + '?mode=' + str(MODE_PLAYLIST)
85 playlistsUrl = baseModeUrl + '?mode=' + str(MODE_PLAYLISTS)
86 favoritesUrl = baseModeUrl + '?mode=' + str(MODE_FAVORITES)
87
88 searchArtistsAlbumsName = __language__(30006)
89
90 thumbDef = os.path.join(imgDir, 'default.tbn')
91 listBackground = os.path.join(imgDir, 'listbackground.png')
92
93 sys.path.append (libDir)
94 from GroovesharkAPI import GrooveAPI
95 from threading import Event, Thread
96
97 if __debugging__ == 'true':
98 __debugging__ = True
99 else:
100 __debugging__ = False
101
102 try:
103 groovesharkApi = GrooveAPI(__debugging__, tempDir)
104 if groovesharkApi.pingService() != True:
105 raise StandardError(__language__(30007))
106 except:
107 print "Exception on initialisation"
108 print '-'*60
109 traceback.print_exc()
110 print '-'*60
111 dialog = xbmcgui.Dialog(__language__(30008),__language__(30009),__language__(30010))
112 dialog.ok(__language__(30008),__language__(30009))
113 sys.exit(-1)
114
115 # Mark song as playing or played
116 def markSong(songid, duration, streamKey, streamServerID):
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:
123 groovesharkApi.markStreamKeyOver30Secs(streamKey, streamServerID)
124 songMarkTime = tNow
125 elif duration > tNow and duration - tNow < 2 and songMarkTime >= STREAM_MARKING_TIME:
126 playTimer.cancel()
127 songMarkTime = 0
128 groovesharkApi.markSongComplete(songid, streamKey, streamServerID)
129 else:
130 playTimer.cancel()
131 songMarkTime = 0
132
133 class _Info:
134 def __init__( self, *args, **kwargs ):
135 self.__dict__.update( kwargs )
136
137 # Window dialog to select a grooveshark playlist
138 class 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
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)
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]))
162 listitems.append(xbmcgui.ListItem(__language__(30011)))
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()
199
200
201 class 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
237 class Grooveshark:
238
239 albumImg = xbmc.translatePath(os.path.join(imgDir, 'album.png'))
240 artistImg = xbmc.translatePath(os.path.join(imgDir, 'artist.png'))
241 artistsAlbumsImg = xbmc.translatePath(os.path.join(imgDir, 'artistsalbums.png'))
242 favoritesImg = xbmc.translatePath(os.path.join(imgDir, 'favorites.png'))
243 playlistImg = xbmc.translatePath(os.path.join(imgDir, 'playlist.png'))
244 usersplaylistsImg = xbmc.translatePath(os.path.join(imgDir, 'usersplaylists.png'))
245 popularSongsImg = xbmc.translatePath(os.path.join(imgDir, 'popularSongs.png'))
246 popularSongsArtistImg = xbmc.translatePath(os.path.join(imgDir, 'popularSongsArtist.png'))
247 songImg = xbmc.translatePath(os.path.join(imgDir, 'song.png'))
248 defImg = xbmc.translatePath(os.path.join(imgDir, 'default.tbn'))
249 fanImg = xbmc.translatePath(os.path.join(baseDir, 'fanart.jpg'))
250
251 settings = xbmcaddon.Addon(id='plugin.audio.groove')
252 songsearchlimit = int(settings.getSetting('songsearchlimit'))
253 albumsearchlimit = int(settings.getSetting('albumsearchlimit'))
254 artistsearchlimit = int(settings.getSetting('artistsearchlimit'))
255 songspagelimit = int(settings.getSetting('songspagelimit'))
256 username = settings.getSetting('username')
257 password = settings.getSetting('password')
258
259 userid = 0
260
261 def __init__( self ):
262 self._handle = int(sys.argv[1])
263 if os.path.isdir(cacheDir) == False:
264 os.makedirs(cacheDir)
265 if __debugging__ :
266 xbmc.log(__language__(30012) + " " + cacheDir)
267 artDir = xbmc.translatePath(thumbDir)
268 if os.path.isdir(artDir) == False:
269 os.makedirs(artDir)
270 if __debugging__ :
271 xbmc.log(__language__(30012) + " " + artDir)
272
273 # Top-level menu
274 def categories(self):
275
276 self.userid = self._get_login()
277
278 # Setup
279 xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
280
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)
284 self._add_dir(searchArtistsAlbumsName, '', MODE_SEARCH_ARTISTS_ALBUMS, self.artistsAlbumsImg, 0)
285 # Not supported by key
286 #self._add_dir("Search for user's playlists...", '', MODE_SEARCH_PLAYLISTS, self.usersplaylistsImg, 0)
287 self._add_dir(__language__(30016), '', MODE_ARTIST_POPULAR, self.popularSongsArtistImg, 0)
288 self._add_dir(__language__(30017), '', MODE_POPULAR_SONGS, self.popularSongsImg, 0)
289 if (self.userid != 0):
290 self._add_dir(__language__(30018), '', MODE_FAVORITES, self.favoritesImg, 0)
291 self._add_dir(__language__(30019), '', MODE_PLAYLISTS, self.playlistImg, 0)
292
293 # Search for songs
294 def searchSongs(self):
295 query = self._get_keyboard(default="", heading=__language__(30020))
296 if (query != ''):
297 songs = groovesharkApi.getSongSearchResults(query, limit = self.songsearchlimit)
298 if (len(songs) > 0):
299 self._add_songs_directory(songs)
300 else:
301 dialog = xbmcgui.Dialog()
302 dialog.ok(__language__(30008), __language__(30021))
303 self.categories()
304 else:
305 self.categories()
306
307 # Search for albums
308 def searchAlbums(self):
309 query = self._get_keyboard(default="", heading=__language__(30022))
310 if (query != ''):
311 albums = groovesharkApi.getAlbumSearchResults(query, limit = self.albumsearchlimit)
312 if (len(albums) > 0):
313 self._add_albums_directory(albums)
314 else:
315 dialog = xbmcgui.Dialog()
316 dialog.ok(__language__(30008), __language__(30023))
317 self.categories()
318 else:
319 self.categories()
320
321 # Search for artists
322 def searchArtists(self):
323 query = self._get_keyboard(default="", heading=__language__(30024))
324 if (query != ''):
325 artists = groovesharkApi.getArtistSearchResults(query, limit = self.artistsearchlimit)
326 if (len(artists) > 0):
327 self._add_artists_directory(artists)
328 else:
329 dialog = xbmcgui.Dialog()
330 dialog.ok(__language__(30008), __language__(30025))
331 self.categories()
332 else:
333 self.categories()
334
335 # Search for playlists
336 def searchPlaylists(self):
337 query = self._get_keyboard(default="", heading=__language__(30026))
338 if (query != ''):
339 playlists = groovesharkApi.getUserPlaylistsByUsername(query)
340 if (len(playlists) > 0):
341 self._add_playlists_directory(playlists)
342 else:
343 dialog = xbmcgui.Dialog()
344 dialog.ok(__language__(30008), __language__(30027))
345 self.categories()
346 else:
347 self.categories()
348
349 # Search for artists albums
350 def searchArtistsAlbums(self, artistName = None):
351 if artistName == None or artistName == searchArtistsAlbumsName:
352 query = self._get_keyboard(default="", heading=__language__(30028))
353 else:
354 query = artistName
355 if (query != ''):
356 artists = groovesharkApi.getArtistSearchResults(query, limit = self.artistsearchlimit)
357 if (len(artists) > 0):
358 artist = artists[0]
359 artistID = artist[1]
360 if __debugging__ :
361 xbmc.log("Found " + artist[0] + "...")
362 albums = groovesharkApi.getArtistAlbums(artistID, self.albumsearchlimit)
363 if (len(albums) > 0):
364 self._add_albums_directory(albums, artistID)
365 else:
366 dialog = xbmcgui.Dialog()
367 dialog.ok(__language__(30008), __language__(30029))
368 self.categories()
369 else:
370 dialog = xbmcgui.Dialog()
371 dialog.ok(__language__(30008), __language__(30030))
372 self.categories()
373 else:
374 self.categories()
375
376 # Get my favorites
377 def favorites(self):
378 userid = self._get_login()
379 if (userid != 0):
380 favorites = groovesharkApi.getUserFavoriteSongs()
381 if (len(favorites) > 0):
382 self._add_songs_directory(favorites, isFavorites=True)
383 else:
384 dialog = xbmcgui.Dialog()
385 dialog.ok(__language__(30008), __language__(30031))
386 self.categories()
387
388 # Get popular songs
389 def popularSongs(self):
390 popular = groovesharkApi.getPopularSongsToday(limit = self.songsearchlimit)
391 if (len(popular) > 0):
392 self._add_songs_directory(popular)
393 else:
394 dialog = xbmcgui.Dialog()
395 dialog.ok(__language__(30008), __language__(30032))
396 self.categories()
397
398 # Get my playlists
399 def playlists(self):
400 userid = self._get_login()
401 if (userid != 0):
402 playlists = groovesharkApi.getUserPlaylists()
403 if (len(playlists) > 0):
404 self._add_playlists_directory(playlists)
405 else:
406 dialog = xbmcgui.Dialog()
407 dialog.ok(__language__(30008), __language__(30033))
408 self.categories()
409 else:
410 dialog = xbmcgui.Dialog()
411 dialog.ok(__language__(30008), __language__(30034), __language__(30035))
412
413 # Make songs a favorite
414 def favorite(self, songid):
415 userid = self._get_login()
416 if (userid != 0):
417 if __debugging__ :
418 xbmc.log("Favorite song: " + str(songid))
419 groovesharkApi.addUserFavoriteSong(songID = songid)
420 xbmc.executebuiltin('XBMC.Notification(' + __language__(30008) + ', ' + __language__(30036) + ', 1000, ' + thumbDef + ')')
421 else:
422 dialog = xbmcgui.Dialog()
423 dialog.ok(__language__(30008), __language__(30034), __language__(30037))
424
425 # Remove song from favorites
426 def unfavorite(self, songid, prevMode=0):
427 userid = self._get_login()
428 if (userid != 0):
429 if __debugging__ :
430 xbmc.log("Unfavorite song: " + str(songid) + ', previous mode was ' + str(prevMode))
431 groovesharkApi.removeUserFavoriteSongs(songIDs = songid)
432 xbmc.executebuiltin('XBMC.Notification(' + __language__(30008) + ', ' + __language__(30038) + ', 1000, ' + thumbDef + ')')
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()
438 dialog.ok(__language__(30008), __language__(30034), __language__(30039))
439
440
441 # Show selected album
442 def album(self, albumid):
443 album = groovesharkApi.getAlbumSongs(albumid, limit = self.songsearchlimit)
444 self._add_songs_directory(album, trackLabelFormat=NAME_ALBUM_ARTIST_LABEL)
445
446 # Show selected artist
447 def artist(self, artistid):
448 albums = groovesharkApi.getArtistAlbums(artistid, limit = self.albumsearchlimit)
449 self._add_albums_directory(albums, artistid, True)
450
451 # Show selected playlist
452 def playlist(self, playlistid, playlistname):
453 userid = self._get_login()
454 if (userid != 0):
455 songs = groovesharkApi.getPlaylistSongs(playlistid)
456 self._add_songs_directory(songs, trackLabelFormat=NAME_ALBUM_ARTIST_LABEL, playlistid=playlistid, playlistname=playlistname)
457 else:
458 dialog = xbmcgui.Dialog()
459 dialog.ok(__language__(30008), __language__(30034), __language__(30040))
460
461 # Show popular songs of the artist
462 def artistPopularSongs(self):
463 query = self._get_keyboard(default="", heading=__language__(30041))
464 if (query != ''):
465 artists = groovesharkApi.getArtistSearchResults(query, limit = self.artistsearchlimit)
466 if (len(artists) > 0):
467 artist = artists[0]
468 artistID = artist[1]
469 if __debugging__ :
470 xbmc.log("Found " + artist[0] + "...")
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()
476 dialog.ok(__language__(30008), __language__(30042))
477 self.categories()
478 else:
479 dialog = xbmcgui.Dialog()
480 dialog.ok(__language__(30008), __language__(30043))
481 self.categories()
482 else:
483 self.categories()
484
485 # Play a song
486 def playSong(self, item):
487 global playTimer
488 global player
489 if item != None:
490 # Get stream as it could have expired
491 item.select(True)
492 url = ''
493 songid = item.getProperty('songid')
494 stream = groovesharkApi.getSubscriberStreamKey(songid)
495 if stream != False:
496 url = stream['url']
497 key = stream['StreamKey']
498 server = stream['StreamServerID']
499 duration = int(self._setDuration(stream['uSecs']))
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")
523 else:
524 xbmc.log("No song stream")
525 else:
526 xbmc.executebuiltin('XBMC.Notification(' + __language__(30008) + ', ' + __language__(30044) + ', 1000, ' + thumbDef + ')')
527
528 # Make a song directory item
529 def songItem(self, songid, name, album, artist, coverart, trackLabelFormat=ARTIST_ALBUM_NAME_LABEL, tracknumber=1):
530
531 stream = self._getSongStream(songid)
532 if stream != None:
533 duration = stream[1]
534 url = stream[2]
535 key = stream[3]
536 server = stream[4]
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)
544 item.setInfo( type="music", infoLabels={ "title": name, "album": album, "artist": artist, "duration": duration, "tracknumber" : tracknumber} )
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))
555 item.setProperty('fanart_image', self.fanImg)
556 return item
557 else:
558 xbmc.log("No access to song URL")
559 return None
560
561 # Next page of songs
562 def songPage(self, offset, trackLabelFormat, playlistid = 0, playlistname = ''):
563 self._add_songs_directory([], trackLabelFormat, offset, playlistid = playlistid, playlistname = playlistname)
564
565 # Make a playlist from an album
566 def makePlaylist(self, albumid, name):
567 userid = self._get_login()
568 if (userid != 0):
569 re.split(' - ',name,1)
570 nameTokens = re.split(' - ',name,1) # suggested name
571 name = self._get_keyboard(default=nameTokens[0], heading=__language__(30045))
572 if name != '':
573 album = groovesharkApi.getAlbumSongs(albumid, limit = self.songsearchlimit)
574 songids = []
575 for song in album:
576 songids.append(song[1])
577 if groovesharkApi.createPlaylist(name, songids) == 0:
578 dialog = xbmcgui.Dialog()
579 dialog.ok(__language__(30008), __language__(30046), name)
580 else:
581 xbmc.executebuiltin('XBMC.Notification(' + __language__(30008) + ',' + __language__(30047)+ ', 1000, ' + thumbDef + ')')
582 else:
583 dialog = xbmcgui.Dialog()
584 dialog.ok(__language__(30008), __language__(30034), __language__(30048))
585
586 # Rename a playlist
587 def renamePlaylist(self, playlistid, name):
588 userid = self._get_login()
589 if (userid != 0):
590 newname = self._get_keyboard(default=name, heading=__language__(30049))
591 if newname == '':
592 return
593 elif groovesharkApi.playlistRename(playlistid, newname) == 0:
594 dialog = xbmcgui.Dialog()
595 dialog.ok(__language__(30008), __language__(30050), name)
596 else:
597 # Refresh to show new item name
598 xbmc.executebuiltin("Container.Refresh")
599 else:
600 dialog = xbmcgui.Dialog()
601 dialog.ok(__language__(30008), __language__(30034), __language__(30051))
602
603 # Remove a playlist
604 def removePlaylist(self, playlistid, name):
605 dialog = xbmcgui.Dialog()
606 if dialog.yesno(__language__(30008), name, __language__(30052)) == True:
607 userid = self._get_login()
608 if (userid != 0):
609 if groovesharkApi.playlistDelete(playlistid) == 0:
610 dialog = xbmcgui.Dialog()
611 dialog.ok(__language__(30008), __language__(30053), name)
612 else:
613 # Refresh to remove item from directory
614 xbmc.executebuiltin("Container.Refresh(" + playlistsUrl + ")")
615 else:
616 dialog = xbmcgui.Dialog()
617 dialog.ok(__language__(30008), __language__(30034), __language__(30054))
618
619 # Add song to playlist
620 def addPlaylistSong(self, songid):
621 userid = self._get_login()
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):
635 name = self._get_keyboard(default='', heading=__language__(30055))
636 if name != '':
637 songIds = []
638 songIds.append(songid)
639 if groovesharkApi.createPlaylist(name, songIds) == 0:
640 dialog = xbmcgui.Dialog()
641 dialog.ok(__language__(30008), __language__(30056), name)
642 else:
643 xbmc.executebuiltin('XBMC.Notification(' + __language__(30008) + ',' + __language__(30057) + ', 1000, ' + thumbDef + ')')
644 # Existing playlist
645 else:
646 playlist = playlists[i]
647 playlistid = playlist[1]
648 if __debugging__ :
649 xbmc.log("Add song " + str(songid) + " to playlist " + str(playlistid))
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:
657 dialog = xbmcgui.Dialog()
658 dialog.ok(__language__(30008), __language__(30058))
659 else:
660 xbmc.executebuiltin('XBMC.Notification(' + __language__(30008) + ',' + __language__(30059) + ', 1000, ' + thumbDef + ')')
661 else:
662 dialog = xbmcgui.Dialog()
663 dialog.ok(__language__(30008), __language__(30060))
664 self.categories()
665 else:
666 dialog = xbmcgui.Dialog()
667 dialog.ok(__language__(30008), __language__(30034), __language__(30061))
668
669 # Remove song from playlist
670 def removePlaylistSong(self, playlistid, playlistname, songid):
671 dialog = xbmcgui.Dialog()
672 if dialog.yesno(__language__(30008), __language__(30062), __language__(30063)) == True:
673 userid = self._get_login()
674 if (userid != 0):
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:
682 dialog = xbmcgui.Dialog()
683 dialog.ok(__language__(30008), __language__(30064), __language__(30065))
684 else:
685 # Refresh to remove item from directory
686 xbmc.executebuiltin('XBMC.Notification(' + __language__(30008) + ',' + __language__(30066)+ ', 1000, ' + thumbDef + ')')
687 xbmc.executebuiltin("Container.Update(" + playlistUrl + "&id="+str(playlistid) + "&name=" + str(playlistname) + ")")
688 else:
689 dialog = xbmcgui.Dialog()
690 dialog.ok(__language__(30008), __language__(30034), __language__(30067))
691
692 # Find similar artists to searched artist
693 def similarArtists(self, artistId):
694 similar = groovesharkApi.getSimilarArtists(artistId, limit = self.artistsearchlimit)
695 if (len(similar) > 0):
696 self._add_artists_directory(similar)
697 else:
698 dialog = xbmcgui.Dialog()
699 dialog.ok(__language__(30008), __language__(30068))
700 self.categories()
701
702 # Get keyboard input
703 def _get_keyboard(self, default="", heading="", hidden=False):
704 kb = xbmc.Keyboard(default, heading, hidden)
705 kb.doModal()
706 if (kb.isConfirmed()):
707 return unicode(kb.getText(), "utf-8")
708 return ''
709
710 # Login to grooveshark
711 def _get_login(self):
712 if (self.username == "" or self.password == ""):
713 dialog = xbmcgui.Dialog()
714 dialog.ok(__language__(30008), __language__(30069), __language__(30070), __language__(30082))
715 return 0
716 else:
717 uid = groovesharkApi.login(self.username, self.password)
718 if (uid != 0):
719 return uid
720 else:
721 dialog = xbmcgui.Dialog()
722 dialog.ok(__language__(30008), __language__(30069), __language__(30070), __language__(30082))
723 return 0
724
725 # File download
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 headers = { 'User-Agent' : 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.102 Chrome/32.0.1700.102 Safari/537.36' }
732 req = urllib2.Request(url, None, headers)
733 loc = urllib2.urlopen(req)
734 output = open(localThumb,'wb')
735 output.write(loc.read())
736 output.close()
737 except:
738 shutil.copy2(thumbDef, localThumb)
739 return os.path.join(os.path.join(thumbDir, str(songid))) + '.tbn'
740 else:
741 return thumbDef
742
743 # Add songs to directory
744 def _add_songs_directory(self, songs, trackLabelFormat=ARTIST_ALBUM_NAME_LABEL, offset=0, playlistid=0, playlistname='', isFavorites=False):
745
746 totalSongs = len(songs)
747 offset = int(offset)
748 start = 0
749 end = totalSongs
750
751 # No pages needed
752 if offset == 0 and totalSongs <= self.songspagelimit:
753 if __debugging__ :
754 xbmc.log("Found " + str(totalSongs) + " songs...")
755 # Pages
756 else:
757 # Cache all next pages songs
758 if offset == 0:
759 self._setSavedSongs(songs)
760 else:
761 songs = self._getSavedSongs()
762 totalSongs = len(songs)
763
764 if totalSongs > 0:
765 start = offset
766 end = min(start + self.songspagelimit,totalSongs)
767
768 n = start
769 items = end - start
770 while n < end:
771 song = songs[n]
772 name = song[0]
773 songid = song[1]
774 album = song[2]
775 artist = song[4]
776 coverart = song[6]
777 item = self.songItem(songid, name, album, artist, coverart, trackLabelFormat, (n+1))
778 if item != None:
779 coverart = item.getProperty('coverart')
780 songname = song[0]
781 songalbum = song[2]
782 songartist = song[4]
783 u=sys.argv[0]+"?mode="+str(MODE_SONG)+"&name="+urllib.quote_plus(songname)+"&id="+str(songid) \
784 +"&album="+urllib.quote_plus(songalbum) \
785 +"&artist="+urllib.quote_plus(songartist) \
786 +"&coverart="+urllib.quote_plus(coverart)
787 fav=sys.argv[0]+"?mode="+str(MODE_FAVORITE)+"&name="+urllib.quote_plus(songname)+"&id="+str(songid)
788 unfav=sys.argv[0]+"?mode="+str(MODE_UNFAVORITE)+"&name="+urllib.quote_plus(songname)+"&id="+str(songid)+"&prevmode="
789 menuItems = []
790 if isFavorites == True:
791 unfav = unfav +str(MODE_FAVORITES)
792 else:
793 menuItems.append((__language__(30071), "XBMC.RunPlugin("+fav+")"))
794 menuItems.append((__language__(30072), "XBMC.RunPlugin("+unfav+")"))
795 if playlistid > 0:
796 rmplaylstsong=sys.argv[0]+"?playlistid="+str(playlistid)+"&id="+str(songid)+"&mode="+str(MODE_REMOVE_PLAYLIST_SONG)+"&name="+str(playlistname)
797 menuItems.append((__language__(30073), "XBMC.RunPlugin("+rmplaylstsong+")"))
798 else:
799 addplaylstsong=sys.argv[0]+"?id="+str(songid)+"&mode="+str(MODE_ADD_PLAYLIST_SONG)
800 menuItems.append((__language__(30074), "XBMC.RunPlugin("+addplaylstsong+")"))
801 item.addContextMenuItems(menuItems, replaceItems=False)
802 xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=item,isFolder=False, totalItems=items)
803 else:
804 end = min(end + 1,totalSongs)
805 if __debugging__ :
806 xbmc.log(song[0] + " does not exist.")
807 n = n + 1
808
809 if totalSongs > end:
810 u=sys.argv[0]+"?mode="+str(MODE_SONG_PAGE)+"&id=playlistid"+"&offset="+str(end)+"&label="+str(trackLabelFormat)+"&name="+str(playlistname)
811 self._add_dir(__language__(30075) + '...', u, MODE_SONG_PAGE, self.songImg, 0, totalSongs - end)
812
813 xbmcplugin.setContent(self._handle, 'songs')
814 xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
815
816 # Add albums to directory
817 def _add_albums_directory(self, albums, artistid=0, isverified=False):
818 n = len(albums)
819 itemsExisting = n
820 if __debugging__ :
821 xbmc.log("Found " + str(n) + " albums...")
822 i = 0
823 while i < n:
824 album = albums[i]
825 albumID = album[3]
826 if isverified or groovesharkApi.getDoesAlbumExist(albumID):
827 albumArtistName = album[0]
828 albumName = album[2]
829 albumImage = self._get_icon(album[4], 'album-' + str(albumID))
830 self._add_dir(albumName + " - " + albumArtistName, '', MODE_ALBUM, albumImage, albumID, itemsExisting)
831 else:
832 itemsExisting = itemsExisting - 1
833 i = i + 1
834 # Not supported by key
835 #if artistid > 0:
836 # self._add_dir('Similar artists...', '', MODE_SIMILAR_ARTISTS, self.artistImg, artistid)
837 xbmcplugin.setContent(self._handle, 'albums')
838 xbmcplugin.addSortMethod(self._handle, xbmcplugin.SORT_METHOD_ALBUM_IGNORE_THE)
839 xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
840
841 # Add artists to directory
842 def _add_artists_directory(self, artists):
843 n = len(artists)
844 itemsExisting = n
845 if __debugging__ :
846 xbmc.log("Found " + str(n) + " artists...")
847 i = 0
848 while i < n:
849 artist = artists[i]
850 artistID = artist[1]
851 if groovesharkApi.getDoesArtistExist(artistID):
852 artistName = artist[0]
853 self._add_dir(artistName, '', MODE_ARTIST, self.artistImg, artistID, itemsExisting)
854 else:
855 itemsExisting = itemsExisting - 1
856 i = i + 1
857 xbmcplugin.setContent(self._handle, 'artists')
858 xbmcplugin.addSortMethod(self._handle, xbmcplugin.SORT_METHOD_ARTIST_IGNORE_THE)
859 xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
860
861 # Add playlists to directory
862 def _add_playlists_directory(self, playlists):
863 n = len(playlists)
864 if __debugging__ :
865 xbmc.log("Found " + str(n) + " playlists...")
866 i = 0
867 while i < n:
868 playlist = playlists[i]
869 playlistName = playlist[0]
870 playlistID = playlist[1]
871 self._add_dir(playlistName, '', MODE_PLAYLIST, self.playlistImg, playlistID, n)
872 i = i + 1
873 xbmcplugin.setContent(self._handle, 'files')
874 xbmcplugin.addSortMethod(self._handle, xbmcplugin.SORT_METHOD_LABEL)
875 xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
876
877 # Add whatever directory
878 def _add_dir(self, name, url, mode, iconimage, itemId, items=1):
879
880 if url == '':
881 u=sys.argv[0]+"?mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&id="+str(itemId)
882 else:
883 u = url
884 directory=xbmcgui.ListItem(name, iconImage=iconimage, thumbnailImage=iconimage)
885 directory.setInfo( type="Music", infoLabels={ "title": name } )
886 directory.setProperty('fanart_image', self.fanImg)
887
888 # Custom menu items
889 menuItems = []
890 if mode == MODE_ALBUM:
891 mkplaylst=sys.argv[0]+"?mode="+str(MODE_MAKE_PLAYLIST)+"&name="+name+"&id="+str(itemId)
892 menuItems.append((__language__(30076), "XBMC.RunPlugin("+mkplaylst+")"))
893 if mode == MODE_PLAYLIST:
894 rmplaylst=sys.argv[0]+"?mode="+str(MODE_REMOVE_PLAYLIST)+"&name="+urllib.quote_plus(name)+"&id="+str(itemId)
895 menuItems.append((__language__(30077), "XBMC.RunPlugin("+rmplaylst+")"))
896 mvplaylst=sys.argv[0]+"?mode="+str(MODE_RENAME_PLAYLIST)+"&name="+urllib.quote_plus(name)+"&id="+str(itemId)
897 menuItems.append((__language__(30078), "XBMC.RunPlugin("+mvplaylst+")"))
898
899 directory.addContextMenuItems(menuItems, replaceItems=False)
900
901 return xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=directory,isFolder=True, totalItems=items)
902
903 def _getSavedSongs(self):
904 path = os.path.join(cacheDir, 'songs.dmp')
905 try:
906 f = open(path, 'rb')
907 songs = pickle.load(f)
908 f.close()
909 except:
910 songs = []
911 pass
912 return songs
913
914 def _setSavedSongs(self, songs):
915 try:
916 # Create the 'data' directory if it doesn't exist.
917 if not os.path.exists(cacheDir):
918 os.makedirs(cacheDir)
919 path = os.path.join(cacheDir, 'songs.dmp')
920 f = open(path, 'wb')
921 pickle.dump(songs, f, protocol=pickle.HIGHEST_PROTOCOL)
922 f.close()
923 except:
924 xbmc.log("An error occurred saving songs")
925 pass
926
927 # Duration to seconds
928 def _setDuration(self, usecs):
929 if usecs < 60000000:
930 usecs = usecs * 10 # Some durations are 10x to small
931 return int(usecs / 1000000)
932
933 def _getSongStream(self, songid):
934 idSong = int(songid)
935 stream = None
936 streams = []
937 path = os.path.join(cacheDir, 'streams.dmp')
938 try:
939 f = open(path, 'rb')
940 streams = pickle.load(f)
941 for song in streams:
942 if song[0] == idSong:
943 duration = song[1]
944 url = song[2]
945 key = song[3]
946 server = song[4]
947 stream = [idSong, duration, url, key, server]
948 if __debugging__ :
949 xbmc.log("Found " + str(idSong) + " in stream cache")
950 break;
951 f.close()
952 except:
953 pass
954
955 # Not in cache
956 if stream == None:
957 stream = groovesharkApi.getSubscriberStreamKey(songid)
958 if stream != False and stream['url'] != '':
959 duration = self._setDuration(stream['uSecs'])
960 url = stream['url']
961 key = stream['StreamKey']
962 server = stream['StreamServerID']
963 stream = [idSong, duration, url, key, server]
964 self._addSongStream(stream)
965
966 return stream
967
968 def _addSongStream(self, stream):
969 streams = self._getStreams()
970 streams.append(stream)
971 path = os.path.join(cacheDir, 'streams.dmp')
972 try:
973 f = open(path, 'wb')
974 pickle.dump(streams, f, protocol=pickle.HIGHEST_PROTOCOL)
975 f.close()
976 if __debugging__ :
977 xbmc.log("Added " + str(stream[0]) + " to stream cache")
978 except:
979 xbmc.log("An error occurred adding to stream")
980
981 def _setSongStream(self, stream):
982 idStream = int(stream[0])
983 stream[1] = self._setDuration(stream[1])
984 streams = self._getStreams()
985 path = os.path.join(cacheDir, 'streams.dmp')
986 i = 0
987
988 for song in streams:
989 if song[0] == idStream:
990 streams[i] = stream
991 try:
992 f = open(path, 'wb')
993 pickle.dump(streams, f, protocol=pickle.HIGHEST_PROTOCOL)
994 f.close()
995 if __debugging__ :
996 xbmc.log("Updated " + str(idStream) + " in stream cache")
997 break;
998 except:
999 xbmc.log("An error occurred setting stream")
1000 i = i + 1
1001
1002 def _getStreams(self):
1003 path = os.path.join(cacheDir, 'streams.dmp')
1004 try:
1005 f = open(path, 'rb')
1006 streams = pickle.load(f)
1007 f.close()
1008 except:
1009 streams = []
1010 pass
1011 return streams
1012
1013
1014 # Parse URL parameters
1015 def get_params():
1016 param=[]
1017 paramstring=sys.argv[2]
1018 if __debugging__ :
1019 xbmc.log(paramstring)
1020 if len(paramstring)>=2:
1021 params=sys.argv[2]
1022 cleanedparams=params.replace('?','')
1023 if (params[len(params)-1]=='/'):
1024 params=params[0:len(params)-2]
1025 pairsofparams=cleanedparams.split('&')
1026 param={}
1027 for i in range(len(pairsofparams)):
1028 splitparams={}
1029 splitparams=pairsofparams[i].split('=')
1030 if (len(splitparams))==2:
1031 param[splitparams[0]]=splitparams[1]
1032 return param
1033
1034 # Main
1035 grooveshark = Grooveshark();
1036
1037 params=get_params()
1038 mode=None
1039 try: mode=int(params["mode"])
1040 except: pass
1041 itemId=0
1042 try: itemId=int(params["id"])
1043 except: pass
1044 name = None
1045 try: name=urllib.unquote_plus(params["name"])
1046 except: pass
1047
1048 # Call function for URL
1049 if mode==None:
1050 grooveshark.categories()
1051
1052 elif mode==MODE_SEARCH_SONGS:
1053 grooveshark.searchSongs()
1054
1055 elif mode==MODE_SEARCH_ALBUMS:
1056 grooveshark.searchAlbums()
1057
1058 elif mode==MODE_SEARCH_ARTISTS:
1059 grooveshark.searchArtists()
1060
1061 elif mode==MODE_SEARCH_ARTISTS_ALBUMS:
1062 grooveshark.searchArtistsAlbums(name)
1063
1064 elif mode==MODE_SEARCH_PLAYLISTS:
1065 grooveshark.searchPlaylists()
1066
1067 elif mode==MODE_POPULAR_SONGS:
1068 grooveshark.popularSongs()
1069
1070 elif mode==MODE_ARTIST_POPULAR:
1071 grooveshark.artistPopularSongs()
1072
1073 elif mode==MODE_FAVORITES:
1074 grooveshark.favorites()
1075
1076 elif mode==MODE_PLAYLISTS:
1077 grooveshark.playlists()
1078
1079 elif mode==MODE_SONG_PAGE:
1080 try: offset=urllib.unquote_plus(params["offset"])
1081 except: pass
1082 try: label=urllib.unquote_plus(params["label"])
1083 except: pass
1084 grooveshark.songPage(offset, label, itemId, name)
1085
1086 elif mode==MODE_SONG:
1087 try: album=urllib.unquote_plus(params["album"])
1088 except: pass
1089 try: artist=urllib.unquote_plus(params["artist"])
1090 except: pass
1091 try: coverart=urllib.unquote_plus(params["coverart"])
1092 except: pass
1093 song = grooveshark.songItem(itemId, name, album, artist, coverart)
1094 grooveshark.playSong(song)
1095
1096 elif mode==MODE_ARTIST:
1097 grooveshark.artist(itemId)
1098
1099 elif mode==MODE_ALBUM:
1100 grooveshark.album(itemId)
1101
1102 elif mode==MODE_PLAYLIST:
1103 grooveshark.playlist(itemId, name)
1104
1105 elif mode==MODE_FAVORITE:
1106 grooveshark.favorite(itemId)
1107
1108 elif mode==MODE_UNFAVORITE:
1109 try: prevMode=int(urllib.unquote_plus(params["prevmode"]))
1110 except:
1111 prevMode = 0
1112 grooveshark.unfavorite(itemId, prevMode)
1113
1114 elif mode==MODE_SIMILAR_ARTISTS:
1115 grooveshark.similarArtists(itemId)
1116
1117 elif mode==MODE_MAKE_PLAYLIST:
1118 grooveshark.makePlaylist(itemId, name)
1119
1120 elif mode==MODE_REMOVE_PLAYLIST:
1121 grooveshark.removePlaylist(itemId, name)
1122
1123 elif mode==MODE_RENAME_PLAYLIST:
1124 grooveshark.renamePlaylist(itemId, name)
1125
1126 elif mode==MODE_REMOVE_PLAYLIST_SONG:
1127 try: playlistID=urllib.unquote_plus(params["playlistid"])
1128 except: pass
1129 grooveshark.removePlaylistSong(playlistID, name, itemId)
1130
1131 elif mode==MODE_ADD_PLAYLIST_SONG:
1132 grooveshark.addPlaylistSong(itemId)
1133
1134 if mode < MODE_SONG:
1135 xbmcplugin.endOfDirectory(int(sys.argv[1]))