check artist name when multiple artists may be returned
[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 # check for artist name match, first result is sometimes not the closest lexical match
359 artist = next ((a for a in artists if a[0].lower() == query.lower()), artists[0])
360 artistID = artist[1]
361 if __debugging__ :
362 xbmc.log("Found " + artist[0] + "...")
363 albums = groovesharkApi.getArtistAlbums(artistID, self.albumsearchlimit)
364 if (len(albums) > 0):
365 self._add_albums_directory(albums, artistID)
366 else:
367 dialog = xbmcgui.Dialog()
368 dialog.ok(__language__(30008), __language__(30029))
369 self.categories()
370 else:
371 dialog = xbmcgui.Dialog()
372 dialog.ok(__language__(30008), __language__(30030))
373 self.categories()
374 else:
375 self.categories()
376
377 # Get my favorites
378 def favorites(self):
379 userid = self._get_login()
380 if (userid != 0):
381 favorites = groovesharkApi.getUserFavoriteSongs()
382 if (len(favorites) > 0):
383 self._add_songs_directory(favorites, isFavorites=True)
384 else:
385 dialog = xbmcgui.Dialog()
386 dialog.ok(__language__(30008), __language__(30031))
387 self.categories()
388
389 # Get popular songs
390 def popularSongs(self):
391 popular = groovesharkApi.getPopularSongsToday(limit = self.songsearchlimit)
392 if (len(popular) > 0):
393 self._add_songs_directory(popular)
394 else:
395 dialog = xbmcgui.Dialog()
396 dialog.ok(__language__(30008), __language__(30032))
397 self.categories()
398
399 # Get my playlists
400 def playlists(self):
401 userid = self._get_login()
402 if (userid != 0):
403 playlists = groovesharkApi.getUserPlaylists()
404 if (len(playlists) > 0):
405 self._add_playlists_directory(playlists)
406 else:
407 dialog = xbmcgui.Dialog()
408 dialog.ok(__language__(30008), __language__(30033))
409 self.categories()
410 else:
411 dialog = xbmcgui.Dialog()
412 dialog.ok(__language__(30008), __language__(30034), __language__(30035))
413
414 # Make songs a favorite
415 def favorite(self, songid):
416 userid = self._get_login()
417 if (userid != 0):
418 if __debugging__ :
419 xbmc.log("Favorite song: " + str(songid))
420 groovesharkApi.addUserFavoriteSong(songID = songid)
421 xbmc.executebuiltin('XBMC.Notification(' + __language__(30008) + ', ' + __language__(30036) + ', 1000, ' + thumbDef + ')')
422 else:
423 dialog = xbmcgui.Dialog()
424 dialog.ok(__language__(30008), __language__(30034), __language__(30037))
425
426 # Remove song from favorites
427 def unfavorite(self, songid, prevMode=0):
428 userid = self._get_login()
429 if (userid != 0):
430 if __debugging__ :
431 xbmc.log("Unfavorite song: " + str(songid) + ', previous mode was ' + str(prevMode))
432 groovesharkApi.removeUserFavoriteSongs(songIDs = songid)
433 xbmc.executebuiltin('XBMC.Notification(' + __language__(30008) + ', ' + __language__(30038) + ', 1000, ' + thumbDef + ')')
434 # Refresh to remove item from directory
435 if (int(prevMode) == MODE_FAVORITES):
436 xbmc.executebuiltin("Container.Refresh(" + favoritesUrl + ")")
437 else:
438 dialog = xbmcgui.Dialog()
439 dialog.ok(__language__(30008), __language__(30034), __language__(30039))
440
441
442 # Show selected album
443 def album(self, albumid):
444 album = groovesharkApi.getAlbumSongs(albumid, limit = self.songsearchlimit)
445 self._add_songs_directory(album, trackLabelFormat=NAME_ALBUM_ARTIST_LABEL)
446
447 # Show selected artist
448 def artist(self, artistid):
449 albums = groovesharkApi.getArtistAlbums(artistid, limit = self.albumsearchlimit)
450 self._add_albums_directory(albums, artistid, True)
451
452 # Show selected playlist
453 def playlist(self, playlistid, playlistname):
454 userid = self._get_login()
455 if (userid != 0):
456 songs = groovesharkApi.getPlaylistSongs(playlistid)
457 self._add_songs_directory(songs, trackLabelFormat=NAME_ALBUM_ARTIST_LABEL, playlistid=playlistid, playlistname=playlistname)
458 else:
459 dialog = xbmcgui.Dialog()
460 dialog.ok(__language__(30008), __language__(30034), __language__(30040))
461
462 # Show popular songs of the artist
463 def artistPopularSongs(self):
464 query = self._get_keyboard(default="", heading=__language__(30041))
465 if (query != ''):
466 artists = groovesharkApi.getArtistSearchResults(query, limit = self.artistsearchlimit)
467 if (len(artists) > 0):
468 # check for exact artist name match, sometimes a more
469 # popular artist is returned first (e.g. 'Angel Dust'
470 # gets you 'Faith No More' because of their popular
471 # album 'Angel Dust')
472 artist = next ((a for a in artists if a[0].lower() == query.lower()), artists[0])
473 artistID = artist[1]
474 if __debugging__ :
475 xbmc.log("Found " + artist[0] + "...")
476 songs = groovesharkApi.getArtistPopularSongs(artistID, limit = self.songsearchlimit)
477 if (len(songs) > 0):
478 self._add_songs_directory(songs, trackLabelFormat=NAME_ALBUM_ARTIST_LABEL)
479 else:
480 dialog = xbmcgui.Dialog()
481 dialog.ok(__language__(30008), __language__(30042))
482 self.categories()
483 else:
484 dialog = xbmcgui.Dialog()
485 dialog.ok(__language__(30008), __language__(30043))
486 self.categories()
487 else:
488 self.categories()
489
490 # Play a song
491 def playSong(self, item):
492 global playTimer
493 global player
494 if item != None:
495 # Get stream as it could have expired
496 item.select(True)
497 url = ''
498 songid = item.getProperty('songid')
499 stream = groovesharkApi.getSubscriberStreamKey(songid)
500 if stream != False:
501 url = stream['url']
502 key = stream['StreamKey']
503 server = stream['StreamServerID']
504 duration = int(self._setDuration(stream['uSecs']))
505 stream = [songid, duration, url, key, server]
506 self._setSongStream(stream)
507 if url != '':
508 item.setPath(url)
509 xbmcplugin.setResolvedUrl(handle=int(sys.argv[1]), succeeded=True, listitem=item)
510 if __debugging__ :
511 xbmc.log("Grooveshark playing: " + url)
512 # Wait for play then start timer
513 seconds = 0
514 while seconds < STREAM_TIMEOUT:
515 try:
516 if player.isPlayingAudio() == True:
517 if playTimer != None:
518 playTimer.cancel()
519 songMarkTime = 0
520 playTimer = PlayTimer(1, markSong, self._setDuration(duration), [songid, duration, key, server])
521 playTimer.start()
522 break
523 except: pass
524 time.sleep(1)
525 seconds = seconds + 1
526 else:
527 xbmc.log("No song URL")
528 else:
529 xbmc.log("No song stream")
530 else:
531 xbmc.executebuiltin('XBMC.Notification(' + __language__(30008) + ', ' + __language__(30044) + ', 1000, ' + thumbDef + ')')
532
533 # Make a song directory item
534 def songItem(self, songid, name, album, artist, coverart, trackLabelFormat=ARTIST_ALBUM_NAME_LABEL, tracknumber=1):
535
536 stream = self._getSongStream(songid)
537 if stream != None:
538 duration = stream[1]
539 url = stream[2]
540 key = stream[3]
541 server = stream[4]
542 songImg = self._get_icon(coverart, 'song-' + str(songid) + "-image")
543 if int(trackLabelFormat) == NAME_ALBUM_ARTIST_LABEL:
544 trackLabel = name + " - " + album + " - " + artist
545 else:
546 trackLabel = artist + " - " + album + " - " + name
547 item = xbmcgui.ListItem(label = trackLabel, thumbnailImage=songImg, iconImage=songImg)
548 item.setPath(url)
549 item.setInfo( type="music", infoLabels={ "title": name, "album": album, "artist": artist, "duration": duration, "tracknumber" : tracknumber} )
550 item.setProperty('mimetype', 'audio/mpeg')
551 item.setProperty("IsPlayable", "true")
552 item.setProperty('songid', str(songid))
553 item.setProperty('coverart', songImg)
554 item.setProperty('title', name)
555 item.setProperty('album', album)
556 item.setProperty('artist', artist)
557 item.setProperty('duration', str(duration))
558 item.setProperty('key', str(key))
559 item.setProperty('server', str(server))
560 item.setProperty('fanart_image', self.fanImg)
561 return item
562 else:
563 xbmc.log("No access to song URL")
564 return None
565
566 # Next page of songs
567 def songPage(self, offset, trackLabelFormat, playlistid = 0, playlistname = ''):
568 self._add_songs_directory([], trackLabelFormat, offset, playlistid = playlistid, playlistname = playlistname)
569
570 # Make a playlist from an album
571 def makePlaylist(self, albumid, name):
572 userid = self._get_login()
573 if (userid != 0):
574 re.split(' - ',name,1)
575 nameTokens = re.split(' - ',name,1) # suggested name
576 name = self._get_keyboard(default=nameTokens[0], heading=__language__(30045))
577 if name != '':
578 album = groovesharkApi.getAlbumSongs(albumid, limit = self.songsearchlimit)
579 songids = []
580 for song in album:
581 songids.append(song[1])
582 if groovesharkApi.createPlaylist(name, songids) == 0:
583 dialog = xbmcgui.Dialog()
584 dialog.ok(__language__(30008), __language__(30046), name)
585 else:
586 xbmc.executebuiltin('XBMC.Notification(' + __language__(30008) + ',' + __language__(30047)+ ', 1000, ' + thumbDef + ')')
587 else:
588 dialog = xbmcgui.Dialog()
589 dialog.ok(__language__(30008), __language__(30034), __language__(30048))
590
591 # Rename a playlist
592 def renamePlaylist(self, playlistid, name):
593 userid = self._get_login()
594 if (userid != 0):
595 newname = self._get_keyboard(default=name, heading=__language__(30049))
596 if newname == '':
597 return
598 elif groovesharkApi.playlistRename(playlistid, newname) == 0:
599 dialog = xbmcgui.Dialog()
600 dialog.ok(__language__(30008), __language__(30050), name)
601 else:
602 # Refresh to show new item name
603 xbmc.executebuiltin("Container.Refresh")
604 else:
605 dialog = xbmcgui.Dialog()
606 dialog.ok(__language__(30008), __language__(30034), __language__(30051))
607
608 # Remove a playlist
609 def removePlaylist(self, playlistid, name):
610 dialog = xbmcgui.Dialog()
611 if dialog.yesno(__language__(30008), name, __language__(30052)) == True:
612 userid = self._get_login()
613 if (userid != 0):
614 if groovesharkApi.playlistDelete(playlistid) == 0:
615 dialog = xbmcgui.Dialog()
616 dialog.ok(__language__(30008), __language__(30053), name)
617 else:
618 # Refresh to remove item from directory
619 xbmc.executebuiltin("Container.Refresh(" + playlistsUrl + ")")
620 else:
621 dialog = xbmcgui.Dialog()
622 dialog.ok(__language__(30008), __language__(30034), __language__(30054))
623
624 # Add song to playlist
625 def addPlaylistSong(self, songid):
626 userid = self._get_login()
627 if (userid != 0):
628 playlists = groovesharkApi.getUserPlaylists()
629 if (len(playlists) > 0):
630 ret = 0
631 # Select the playlist
632 playlistSelect = GroovesharkPlaylistSelect(items=playlists)
633 playlistSelect.setFocus(playlistSelect.playlistControl)
634 playlistSelect.doModal()
635 i = playlistSelect.selected
636 del playlistSelect
637 if i > -1:
638 # Add a new playlist
639 if i >= len(playlists):
640 name = self._get_keyboard(default='', heading=__language__(30055))
641 if name != '':
642 songIds = []
643 songIds.append(songid)
644 if groovesharkApi.createPlaylist(name, songIds) == 0:
645 dialog = xbmcgui.Dialog()
646 dialog.ok(__language__(30008), __language__(30056), name)
647 else:
648 xbmc.executebuiltin('XBMC.Notification(' + __language__(30008) + ',' + __language__(30057) + ', 1000, ' + thumbDef + ')')
649 # Existing playlist
650 else:
651 playlist = playlists[i]
652 playlistid = playlist[1]
653 if __debugging__ :
654 xbmc.log("Add song " + str(songid) + " to playlist " + str(playlistid))
655 songIDs=[]
656 songs = groovesharkApi.getPlaylistSongs(playlistid)
657 for song in songs:
658 songIDs.append(song[1])
659 songIDs.append(songid)
660 ret = groovesharkApi.setPlaylistSongs(playlistid, songIDs)
661 if ret == False:
662 dialog = xbmcgui.Dialog()
663 dialog.ok(__language__(30008), __language__(30058))
664 else:
665 xbmc.executebuiltin('XBMC.Notification(' + __language__(30008) + ',' + __language__(30059) + ', 1000, ' + thumbDef + ')')
666 else:
667 dialog = xbmcgui.Dialog()
668 dialog.ok(__language__(30008), __language__(30060))
669 self.categories()
670 else:
671 dialog = xbmcgui.Dialog()
672 dialog.ok(__language__(30008), __language__(30034), __language__(30061))
673
674 # Remove song from playlist
675 def removePlaylistSong(self, playlistid, playlistname, songid):
676 dialog = xbmcgui.Dialog()
677 if dialog.yesno(__language__(30008), __language__(30062), __language__(30063)) == True:
678 userid = self._get_login()
679 if (userid != 0):
680 songs = groovesharkApi.getPlaylistSongs(playlistID)
681 songIDs=[]
682 for song in songs:
683 if (song[1] != songid):
684 songIDs.append(song[1])
685 ret = groovesharkApi.setPlaylistSongs(playlistID, songIDs)
686 if ret == False:
687 dialog = xbmcgui.Dialog()
688 dialog.ok(__language__(30008), __language__(30064), __language__(30065))
689 else:
690 # Refresh to remove item from directory
691 xbmc.executebuiltin('XBMC.Notification(' + __language__(30008) + ',' + __language__(30066)+ ', 1000, ' + thumbDef + ')')
692 xbmc.executebuiltin("Container.Update(" + playlistUrl + "&id="+str(playlistid) + "&name=" + str(playlistname) + ")")
693 else:
694 dialog = xbmcgui.Dialog()
695 dialog.ok(__language__(30008), __language__(30034), __language__(30067))
696
697 # Find similar artists to searched artist
698 def similarArtists(self, artistId):
699 similar = groovesharkApi.getSimilarArtists(artistId, limit = self.artistsearchlimit)
700 if (len(similar) > 0):
701 self._add_artists_directory(similar)
702 else:
703 dialog = xbmcgui.Dialog()
704 dialog.ok(__language__(30008), __language__(30068))
705 self.categories()
706
707 # Get keyboard input
708 def _get_keyboard(self, default="", heading="", hidden=False):
709 kb = xbmc.Keyboard(default, heading, hidden)
710 kb.doModal()
711 if (kb.isConfirmed()):
712 return unicode(kb.getText(), "utf-8")
713 return ''
714
715 # Login to grooveshark
716 def _get_login(self):
717 if (self.username == "" or self.password == ""):
718 dialog = xbmcgui.Dialog()
719 dialog.ok(__language__(30008), __language__(30069), __language__(30070), __language__(30082))
720 return 0
721 else:
722 uid = groovesharkApi.login(self.username, self.password)
723 if (uid != 0):
724 return uid
725 else:
726 dialog = xbmcgui.Dialog()
727 dialog.ok(__language__(30008), __language__(30069), __language__(30070), __language__(30082))
728 return 0
729
730 # File download
731 def _get_icon(self, url, songid):
732 if url != 'None':
733 localThumb = os.path.join(xbmc.translatePath(os.path.join(thumbDir, str(songid)))) + '.tbn'
734 try:
735 if os.path.isfile(localThumb) == False:
736 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' }
737 req = urllib2.Request(url, None, headers)
738 loc = urllib2.urlopen(req)
739 output = open(localThumb,'wb')
740 output.write(loc.read())
741 output.close()
742 except:
743 shutil.copy2(thumbDef, localThumb)
744 return os.path.join(os.path.join(thumbDir, str(songid))) + '.tbn'
745 else:
746 return thumbDef
747
748 # Add songs to directory
749 def _add_songs_directory(self, songs, trackLabelFormat=ARTIST_ALBUM_NAME_LABEL, offset=0, playlistid=0, playlistname='', isFavorites=False):
750
751 totalSongs = len(songs)
752 offset = int(offset)
753 start = 0
754 end = totalSongs
755
756 # No pages needed
757 if offset == 0 and totalSongs <= self.songspagelimit:
758 if __debugging__ :
759 xbmc.log("Found " + str(totalSongs) + " songs...")
760 # Pages
761 else:
762 # Cache all next pages songs
763 if offset == 0:
764 self._setSavedSongs(songs)
765 else:
766 songs = self._getSavedSongs()
767 totalSongs = len(songs)
768
769 if totalSongs > 0:
770 start = offset
771 end = min(start + self.songspagelimit,totalSongs)
772
773 n = start
774 items = end - start
775 while n < end:
776 song = songs[n]
777 name = song[0]
778 songid = song[1]
779 album = song[2]
780 artist = song[4]
781 coverart = song[6]
782 item = self.songItem(songid, name, album, artist, coverart, trackLabelFormat, (n+1))
783 if item != None:
784 coverart = item.getProperty('coverart')
785 songname = song[0]
786 songalbum = song[2]
787 songartist = song[4]
788 u=sys.argv[0]+"?mode="+str(MODE_SONG)+"&name="+urllib.quote_plus(songname)+"&id="+str(songid) \
789 +"&album="+urllib.quote_plus(songalbum) \
790 +"&artist="+urllib.quote_plus(songartist) \
791 +"&coverart="+urllib.quote_plus(coverart)
792 fav=sys.argv[0]+"?mode="+str(MODE_FAVORITE)+"&name="+urllib.quote_plus(songname)+"&id="+str(songid)
793 unfav=sys.argv[0]+"?mode="+str(MODE_UNFAVORITE)+"&name="+urllib.quote_plus(songname)+"&id="+str(songid)+"&prevmode="
794 menuItems = []
795 if isFavorites == True:
796 unfav = unfav +str(MODE_FAVORITES)
797 else:
798 menuItems.append((__language__(30071), "XBMC.RunPlugin("+fav+")"))
799 menuItems.append((__language__(30072), "XBMC.RunPlugin("+unfav+")"))
800 if playlistid > 0:
801 rmplaylstsong=sys.argv[0]+"?playlistid="+str(playlistid)+"&id="+str(songid)+"&mode="+str(MODE_REMOVE_PLAYLIST_SONG)+"&name="+str(playlistname)
802 menuItems.append((__language__(30073), "XBMC.RunPlugin("+rmplaylstsong+")"))
803 else:
804 addplaylstsong=sys.argv[0]+"?id="+str(songid)+"&mode="+str(MODE_ADD_PLAYLIST_SONG)
805 menuItems.append((__language__(30074), "XBMC.RunPlugin("+addplaylstsong+")"))
806 item.addContextMenuItems(menuItems, replaceItems=False)
807 xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=item,isFolder=False, totalItems=items)
808 else:
809 end = min(end + 1,totalSongs)
810 if __debugging__ :
811 xbmc.log(song[0] + " does not exist.")
812 n = n + 1
813
814 if totalSongs > end:
815 u=sys.argv[0]+"?mode="+str(MODE_SONG_PAGE)+"&id=playlistid"+"&offset="+str(end)+"&label="+str(trackLabelFormat)+"&name="+str(playlistname)
816 self._add_dir(__language__(30075) + '...', u, MODE_SONG_PAGE, self.songImg, 0, totalSongs - end)
817
818 xbmcplugin.setContent(self._handle, 'songs')
819 xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
820
821 # Add albums to directory
822 def _add_albums_directory(self, albums, artistid=0, isverified=False):
823 n = len(albums)
824 itemsExisting = n
825 if __debugging__ :
826 xbmc.log("Found " + str(n) + " albums...")
827 i = 0
828 while i < n:
829 album = albums[i]
830 albumID = album[3]
831 if isverified:
832 albumArtistName = album[0]
833 albumName = album[2]
834 albumImage = self._get_icon(album[4], 'album-' + str(albumID))
835 self._add_dir(albumName + " - " + albumArtistName, '', MODE_ALBUM, albumImage, albumID, itemsExisting)
836 else:
837 itemsExisting = itemsExisting - 1
838 i = i + 1
839 # Not supported by key
840 #if artistid > 0:
841 # self._add_dir('Similar artists...', '', MODE_SIMILAR_ARTISTS, self.artistImg, artistid)
842 xbmcplugin.setContent(self._handle, 'albums')
843 xbmcplugin.addSortMethod(self._handle, xbmcplugin.SORT_METHOD_ALBUM_IGNORE_THE)
844 xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
845
846 # Add artists to directory
847 def _add_artists_directory(self, artists):
848 n = len(artists)
849 itemsExisting = n
850 if __debugging__ :
851 xbmc.log("Found " + str(n) + " artists...")
852 i = 0
853 while i < n:
854 artist = artists[i]
855 artistID = artist[1]
856 artistName = artist[0]
857 self._add_dir(artistName, '', MODE_ARTIST, self.artistImg, artistID, itemsExisting)
858 i = i + 1
859 xbmcplugin.setContent(self._handle, 'artists')
860 xbmcplugin.addSortMethod(self._handle, xbmcplugin.SORT_METHOD_ARTIST_IGNORE_THE)
861 xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
862
863 # Add playlists to directory
864 def _add_playlists_directory(self, playlists):
865 n = len(playlists)
866 if __debugging__ :
867 xbmc.log("Found " + str(n) + " playlists...")
868 i = 0
869 while i < n:
870 playlist = playlists[i]
871 playlistName = playlist[0]
872 playlistID = playlist[1]
873 self._add_dir(playlistName, '', MODE_PLAYLIST, self.playlistImg, playlistID, n)
874 i = i + 1
875 xbmcplugin.setContent(self._handle, 'files')
876 xbmcplugin.addSortMethod(self._handle, xbmcplugin.SORT_METHOD_LABEL)
877 xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
878
879 # Add whatever directory
880 def _add_dir(self, name, url, mode, iconimage, itemId, items=1):
881
882 if url == '':
883 u=sys.argv[0]+"?mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&id="+str(itemId)
884 else:
885 u = url
886 directory=xbmcgui.ListItem(name, iconImage=iconimage, thumbnailImage=iconimage)
887 directory.setInfo( type="Music", infoLabels={ "title": name } )
888 directory.setProperty('fanart_image', self.fanImg)
889
890 # Custom menu items
891 menuItems = []
892 if mode == MODE_ALBUM:
893 mkplaylst=sys.argv[0]+"?mode="+str(MODE_MAKE_PLAYLIST)+"&name="+name+"&id="+str(itemId)
894 menuItems.append((__language__(30076), "XBMC.RunPlugin("+mkplaylst+")"))
895 if mode == MODE_PLAYLIST:
896 rmplaylst=sys.argv[0]+"?mode="+str(MODE_REMOVE_PLAYLIST)+"&name="+urllib.quote_plus(name)+"&id="+str(itemId)
897 menuItems.append((__language__(30077), "XBMC.RunPlugin("+rmplaylst+")"))
898 mvplaylst=sys.argv[0]+"?mode="+str(MODE_RENAME_PLAYLIST)+"&name="+urllib.quote_plus(name)+"&id="+str(itemId)
899 menuItems.append((__language__(30078), "XBMC.RunPlugin("+mvplaylst+")"))
900
901 directory.addContextMenuItems(menuItems, replaceItems=False)
902
903 return xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=directory,isFolder=True, totalItems=items)
904
905 def _getSavedSongs(self):
906 path = os.path.join(cacheDir, 'songs.dmp')
907 try:
908 f = open(path, 'rb')
909 songs = pickle.load(f)
910 f.close()
911 except:
912 songs = []
913 pass
914 return songs
915
916 def _setSavedSongs(self, songs):
917 try:
918 # Create the 'data' directory if it doesn't exist.
919 if not os.path.exists(cacheDir):
920 os.makedirs(cacheDir)
921 path = os.path.join(cacheDir, 'songs.dmp')
922 f = open(path, 'wb')
923 pickle.dump(songs, f, protocol=pickle.HIGHEST_PROTOCOL)
924 f.close()
925 except:
926 xbmc.log("An error occurred saving songs")
927 pass
928
929 # Duration to seconds
930 def _setDuration(self, usecs):
931 if usecs < 60000000:
932 usecs = usecs * 10 # Some durations are 10x to small
933 return int(usecs / 1000000)
934
935 def _getSongStream(self, songid):
936 idSong = int(songid)
937 stream = None
938 streams = {}
939 path = os.path.join(cacheDir, 'streams.dmp')
940 try:
941 f = open(path, 'rb')
942 streams = pickle.load(f)
943 song = streams[songid]
944
945 duration = song[1]
946 url = song[2]
947 key = song[3]
948 server = song[4]
949 stream = [idSong, duration, url, key, server]
950
951 if __debugging__ :
952 xbmc.log("Found " + str(idSong) + " in stream cache")
953
954 f.close()
955 except:
956 pass
957
958 # Not in cache
959 if stream == None:
960 stream = groovesharkApi.getSubscriberStreamKey(songid)
961 if stream != False and stream['url'] != '':
962 duration = self._setDuration(stream['uSecs'])
963 url = stream['url']
964 key = stream['StreamKey']
965 server = stream['StreamServerID']
966 stream = [idSong, duration, url, key, server]
967 self._addSongStream(stream)
968
969 return stream
970
971 def _addSongStream(self, stream):
972 streams = self._getStreams()
973 streams[int(stream[0])] = stream
974 path = os.path.join(cacheDir, 'streams.dmp')
975 try:
976 f = open(path, 'wb')
977 pickle.dump(streams, f, protocol=pickle.HIGHEST_PROTOCOL)
978 f.close()
979 if __debugging__ :
980 xbmc.log("Added " + str(stream[0]) + " to stream cache")
981 except:
982 xbmc.log("An error occurred adding to stream")
983
984 def _setSongStream(self, stream):
985 idStream = int(stream[0])
986 stream[1] = self._setDuration(stream[1])
987 streams = self._getStreams()
988 path = os.path.join(cacheDir, 'streams.dmp')
989
990 try:
991 streams[idStream] = stream
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
998 except:
999 xbmc.log("An error occurred setting stream")
1000
1001 def _getStreams(self):
1002 path = os.path.join(cacheDir, 'streams.dmp')
1003 try:
1004 f = open(path, 'rb')
1005 streams = pickle.load(f)
1006 f.close()
1007 except:
1008 streams = {}
1009 pass
1010 return streams
1011
1012
1013 # Parse URL parameters
1014 def get_params():
1015 param=[]
1016 paramstring=sys.argv[2]
1017 if __debugging__ :
1018 xbmc.log(paramstring)
1019 if len(paramstring)>=2:
1020 params=sys.argv[2]
1021 cleanedparams=params.replace('?','')
1022 if (params[len(params)-1]=='/'):
1023 params=params[0:len(params)-2]
1024 pairsofparams=cleanedparams.split('&')
1025 param={}
1026 for i in range(len(pairsofparams)):
1027 splitparams={}
1028 splitparams=pairsofparams[i].split('=')
1029 if (len(splitparams))==2:
1030 param[splitparams[0]]=splitparams[1]
1031 return param
1032
1033 # Main
1034 grooveshark = Grooveshark();
1035
1036 params=get_params()
1037 mode=None
1038 try: mode=int(params["mode"])
1039 except: pass
1040 itemId=0
1041 try: itemId=int(params["id"])
1042 except: pass
1043 name = None
1044 try: name=urllib.unquote_plus(params["name"])
1045 except: pass
1046
1047 # Call function for URL
1048 if mode==None:
1049 grooveshark.categories()
1050
1051 elif mode==MODE_SEARCH_SONGS:
1052 grooveshark.searchSongs()
1053
1054 elif mode==MODE_SEARCH_ALBUMS:
1055 grooveshark.searchAlbums()
1056
1057 elif mode==MODE_SEARCH_ARTISTS:
1058 grooveshark.searchArtists()
1059
1060 elif mode==MODE_SEARCH_ARTISTS_ALBUMS:
1061 grooveshark.searchArtistsAlbums(name)
1062
1063 elif mode==MODE_SEARCH_PLAYLISTS:
1064 grooveshark.searchPlaylists()
1065
1066 elif mode==MODE_POPULAR_SONGS:
1067 grooveshark.popularSongs()
1068
1069 elif mode==MODE_ARTIST_POPULAR:
1070 grooveshark.artistPopularSongs()
1071
1072 elif mode==MODE_FAVORITES:
1073 grooveshark.favorites()
1074
1075 elif mode==MODE_PLAYLISTS:
1076 grooveshark.playlists()
1077
1078 elif mode==MODE_SONG_PAGE:
1079 try: offset=urllib.unquote_plus(params["offset"])
1080 except: pass
1081 try: label=urllib.unquote_plus(params["label"])
1082 except: pass
1083 grooveshark.songPage(offset, label, itemId, name)
1084
1085 elif mode==MODE_SONG:
1086 try: album=urllib.unquote_plus(params["album"])
1087 except: pass
1088 try: artist=urllib.unquote_plus(params["artist"])
1089 except: pass
1090 try: coverart=urllib.unquote_plus(params["coverart"])
1091 except: pass
1092 song = grooveshark.songItem(itemId, name, album, artist, coverart)
1093 grooveshark.playSong(song)
1094
1095 elif mode==MODE_ARTIST:
1096 grooveshark.artist(itemId)
1097
1098 elif mode==MODE_ALBUM:
1099 grooveshark.album(itemId)
1100
1101 elif mode==MODE_PLAYLIST:
1102 grooveshark.playlist(itemId, name)
1103
1104 elif mode==MODE_FAVORITE:
1105 grooveshark.favorite(itemId)
1106
1107 elif mode==MODE_UNFAVORITE:
1108 try: prevMode=int(urllib.unquote_plus(params["prevmode"]))
1109 except:
1110 prevMode = 0
1111 grooveshark.unfavorite(itemId, prevMode)
1112
1113 elif mode==MODE_SIMILAR_ARTISTS:
1114 grooveshark.similarArtists(itemId)
1115
1116 elif mode==MODE_MAKE_PLAYLIST:
1117 grooveshark.makePlaylist(itemId, name)
1118
1119 elif mode==MODE_REMOVE_PLAYLIST:
1120 grooveshark.removePlaylist(itemId, name)
1121
1122 elif mode==MODE_RENAME_PLAYLIST:
1123 grooveshark.renamePlaylist(itemId, name)
1124
1125 elif mode==MODE_REMOVE_PLAYLIST_SONG:
1126 try: playlistID=urllib.unquote_plus(params["playlistid"])
1127 except: pass
1128 grooveshark.removePlaylistSong(playlistID, name, itemId)
1129
1130 elif mode==MODE_ADD_PLAYLIST_SONG:
1131 grooveshark.addPlaylistSong(itemId)
1132
1133 if mode < MODE_SONG:
1134 xbmcplugin.endOfDirectory(int(sys.argv[1]))