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