X-Git-Url: https://git.hcoop.net/clinton/xbmc-groove.git/blobdiff_plain/3d95dfcbec3ae55a873f541d768285dd707a7043..c52e3923fe2ee6f795c93d73d6f7aaba805ef9a7:/default.py diff --git a/default.py b/default.py index f07928a..ff6d2bd 100644 --- a/default.py +++ b/default.py @@ -1,4 +1,4 @@ -import urllib, sys, os, shutil, re, time, xbmcaddon, xbmcplugin, xbmcgui, xbmc, pickle +import urllib, sys, os, shutil, re, pickle, time, tempfile, xbmcaddon, xbmcplugin, xbmcgui, xbmc MODE_SEARCH_SONGS = 1 MODE_SEARCH_ALBUMS = 2 MODE_SEARCH_ARTISTS = 3 @@ -12,8 +12,15 @@ MODE_ALBUM = 10 MODE_ARTIST = 11 MODE_PLAYLIST = 12 MODE_SONG_PAGE = 13 -MODE_SONG = 14 -MODE_FAVORITE = 15 +MODE_SIMILAR_ARTISTS = 14 +MODE_SONG = 15 +MODE_FAVORITE = 16 +MODE_UNFAVORITE = 17 +MODE_MAKE_PLAYLIST = 18 +MODE_REMOVE_PLAYLIST = 19 +MODE_RENAME_PLAYLIST = 20 +MODE_REMOVE_PLAYLIST_SONG = 21 +MODE_ADD_PLAYLIST_SONG = 22 ACTION_MOVE_LEFT = 1 ACTION_MOVE_UP = 3 @@ -27,6 +34,13 @@ ACTION_PREVIOUS_MENU = 10 ARTIST_ALBUM_NAME_LABEL = 0 NAME_ALBUM_ARTIST_LABEL = 1 +# Stream marking time (seconds) +STREAM_MARKING_TIME = 30 + +songMarkTime = 0 +player = xbmc.Player() +playTimer = None + baseDir = os.getcwd() resDir = xbmc.translatePath(os.path.join(baseDir, 'resources')) libDir = xbmc.translatePath(os.path.join(resDir, 'lib')) @@ -43,9 +57,11 @@ favoritesUrl = baseModeUrl + '?mode=' + str(MODE_FAVORITES) searchArtistsAlbumsName = "Search for artist's albums..." thumbDef = os.path.join(imgDir, 'default.tbn') +listBackground = os.path.join(imgDir, 'listbackground.png') sys.path.append (libDir) from GroovesharkAPI import GrooveAPI +from threading import Event, Thread try: groovesharkApi = GrooveAPI() @@ -56,12 +72,127 @@ except: dialog.ok('Grooveshark XBMC', 'Unable to connect with Grooveshark.', 'Please try again later') sys.exit(-1) - +# Mark song as playing or played +def markSong(songid, duration): + global songMarkTime + global playTimer + global player + if player.isPlayingAudio(): + tNow = player.getTime() + if tNow >= STREAM_MARKING_TIME and songMarkTime == 0: + groovesharkApi.markStreamKeyOver30Secs() + songMarkTime = tNow + elif duration > tNow and duration - tNow < 2 and songMarkTime >= STREAM_MARKING_TIME: + playTimer.cancel() + songMarkTime = 0 + groovesharkApi.markSongComplete(songid) + else: + playTimer.cancel() + songMarkTime = 0 + class _Info: def __init__( self, *args, **kwargs ): self.__dict__.update( kwargs ) - +# Window dialog to select a grooveshark playlist +class GroovesharkPlaylistSelect(xbmcgui.WindowDialog): + + def __init__(self, items=[]): + gap = int(self.getHeight()/100) + w = int(self.getWidth()*0.5) + h = self.getHeight()-30*gap + rw = self.getWidth() + rh = self.getHeight() + x = rw/2 - w/2 + y = rh/2 -h/2 + + self.imgBg = xbmcgui.ControlImage(x+gap, 5*gap+y, w-2*gap, h-5*gap, listBackground) + self.addControl(self.imgBg) + + 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) + self.addControl(self.playlistControl) + + self.lastPos = 0 + self.isSelecting = False + self.selected = -1 + listitems = [] + for playlist in items: + listitems.append(xbmcgui.ListItem(playlist[0])) + listitems.append(xbmcgui.ListItem('New...')) + self.playlistControl.addItems(listitems) + self.setFocus(self.playlistControl) + self.playlistControl.selectItem(0) + item = self.playlistControl.getListItem(self.lastPos) + item.select(True) + + # Highlight selected item + def setHighlight(self): + if self.isSelecting: + return + else: + self.isSelecting = True + + pos = self.playlistControl.getSelectedPosition() + if pos >= 0: + item = self.playlistControl.getListItem(self.lastPos) + item.select(False) + item = self.playlistControl.getListItem(pos) + item.select(True) + self.lastPos = pos + self.isSelecting = False + + # Control - select + def onControl(self, control): + if control == self.playlistControl: + self.selected = self.playlistControl.getSelectedPosition() + self.close() + + # Action - close or up/down + def onAction(self, action): + if action == ACTION_PREVIOUS_MENU: + self.selected = -1 + self.close() + elif action == ACTION_MOVE_UP or action == ACTION_MOVE_DOWN or action == ACTION_PAGE_UP or action == ACTION_PAGE_DOWN == 6: + self.setFocus(self.playlistControl) + self.setHighlight() + + +class PlayTimer(Thread): + # interval -- floating point number specifying the number of seconds to wait before executing function + # function -- the function (or callable object) to be executed + + # iterations -- integer specifying the number of iterations to perform + # args -- list of positional arguments passed to function + # kwargs -- dictionary of keyword arguments passed to function + + def __init__(self, interval, function, iterations=0, args=[], kwargs={}): + Thread.__init__(self) + self.interval = interval + self.function = function + self.iterations = iterations + self.args = args + self.kwargs = kwargs + self.finished = Event() + + def run(self): + count = 0 + while not self.finished.isSet() and (self.iterations <= 0 or count < self.iterations): + self.finished.wait(self.interval) + if not self.finished.isSet(): + self.function(*self.args, **self.kwargs) + count += 1 + + def cancel(self): + self.finished.set() + + def setIterations(self, iterations): + self.iterations = iterations + + + def getTime(self): + return self.iterations * self.interval + + class Groveshark: albumImg = xbmc.translatePath(os.path.join(imgDir, 'album.png')) @@ -94,7 +225,7 @@ class Groveshark: if os.path.isdir(artDir) == False: os.makedirs(artDir) xbmc.log("Made " + artDir) - + # Top-level menu def categories(self): @@ -107,16 +238,17 @@ class Groveshark: self._add_dir('Search for albums...', '', MODE_SEARCH_ALBUMS, self.albumImg, 0) self._add_dir('Search for artists...', '', MODE_SEARCH_ARTISTS, self.artistImg, 0) self._add_dir(searchArtistsAlbumsName, '', MODE_SEARCH_ARTISTS_ALBUMS, self.artistsAlbumsImg, 0) - self._add_dir("Search for user's playlists...", '', MODE_SEARCH_PLAYLISTS, self.usersplaylistsImg, 0) - self._add_dir('Popular songs for artist...', '', MODE_ARTIST_POPULAR, self.popularSongsArtistImg, 0) - self._add_dir('Popular songs', '', MODE_POPULAR_SONGS, self.popularSongsImg, 0) + # Not supported by key + #self._add_dir("Search for user's playlists...", '', MODE_SEARCH_PLAYLISTS, self.usersplaylistsImg, 0) + self._add_dir('Popular Grooveshark songs for artist...', '', MODE_ARTIST_POPULAR, self.popularSongsArtistImg, 0) + self._add_dir('Popular Grooveshark songs', '', MODE_POPULAR_SONGS, self.popularSongsImg, 0) if (self.userid != 0): - self._add_dir('My favorites', '', MODE_FAVORITES, self.favoritesImg, 0) - self._add_dir('My playlists', '', MODE_PLAYLISTS, self.playlistImg, 0) + self._add_dir('My Grooveshark favorites', '', MODE_FAVORITES, self.favoritesImg, 0) + self._add_dir('My Grooveshark playlists', '', MODE_PLAYLISTS, self.playlistImg, 0) # Search for songs def searchSongs(self): - query = self._get_keyboard(default="", heading="Search for songs") + query = self._get_keyboard(default="", heading='Search for songs powered by Grooveshark') if (query != ''): songs = groovesharkApi.getSongSearchResults(query, limit = self.songsearchlimit) if (len(songs) > 0): @@ -130,7 +262,7 @@ class Groveshark: # Search for albums def searchAlbums(self): - query = self._get_keyboard(default="", heading="Search for albums") + query = self._get_keyboard(default="", heading='Search for albums powered by Grooveshark') if (query != ''): albums = groovesharkApi.getAlbumSearchResults(query, limit = self.albumsearchlimit) if (len(albums) > 0): @@ -144,7 +276,7 @@ class Groveshark: # Search for artists def searchArtists(self): - query = self._get_keyboard(default="", heading="Search for artists") + query = self._get_keyboard(default="", heading='Search for artists powered by Grooveshark') if (query != ''): artists = groovesharkApi.getArtistSearchResults(query, limit = self.artistsearchlimit) if (len(artists) > 0): @@ -160,7 +292,7 @@ class Groveshark: def searchPlaylists(self): query = self._get_keyboard(default="", heading="Username") if (query != ''): - playlists = groovesharkApi.getUserPlaylistsEx(query) + playlists = groovesharkApi.getUserPlaylistsByUsername(query) if (len(playlists) > 0): self._add_playlists_directory(playlists) else: @@ -173,7 +305,7 @@ class Groveshark: # Search for artists albums def searchArtistsAlbums(self, artistName = None): if artistName == None or artistName == searchArtistsAlbumsName: - query = self._get_keyboard(default="", heading="Search for artist's albums") + query = self._get_keyboard(default="", heading="Search for artist's albums powered by Grooveshark") else: query = artistName if (query != ''): @@ -184,7 +316,7 @@ class Groveshark: xbmc.log("Found " + artist[0] + "...") albums = groovesharkApi.getArtistAlbums(artistID, limit = self.albumsearchlimit) if (len(albums) > 0): - self._add_albums_directory(albums) + self._add_albums_directory(albums, artistID) else: dialog = xbmcgui.Dialog() dialog.ok('Grooveshark XBMC', 'No matching albums.') @@ -202,7 +334,7 @@ class Groveshark: if (userid != 0): favorites = groovesharkApi.getUserFavoriteSongs() if (len(favorites) > 0): - self._add_songs_directory(favorites) + self._add_songs_directory(favorites, isFavorites=True) else: dialog = xbmcgui.Dialog() dialog.ok('Grooveshark XBMC', 'You have no favorites.') @@ -243,6 +375,21 @@ class Groveshark: else: dialog = xbmcgui.Dialog() dialog.ok('Grooveshark XBMC', 'You must be logged in', 'to add favorites.') + + # Remove song from favorites + def unfavorite(self, songid, prevMode=0): + userid = self._get_login() + if (userid != 0): + xbmc.log("Unfavorite song: " + str(songid) + ', previous mode was ' + str(prevMode)) + groovesharkApi.removeUserFavoriteSongs(songIDs = songid) + xbmc.executebuiltin('XBMC.Notification(Grooveshark XBMC, Removed from Grooveshark favorites, 1000, ' + thumbDef + ')') + # Refresh to remove item from directory + if (int(prevMode) == MODE_FAVORITES): + xbmc.executebuiltin("Container.Refresh(" + favoritesUrl + ")") + else: + dialog = xbmcgui.Dialog() + dialog.ok('Grooveshark XBMC', 'You must be logged in', 'to remove Grooveshark favorites.') + # Show selected album def album(self, albumid): @@ -252,14 +399,14 @@ class Groveshark: # Show selected artist def artist(self, artistid): albums = groovesharkApi.getArtistAlbums(artistid, limit = self.albumsearchlimit) - self._add_albums_directory(albums) + self._add_albums_directory(albums, artistid) # Show selected playlist - def playlist(self, playlistid): + def playlist(self, playlistid, playlistname): userid = self._get_login() if (userid != 0): songs = groovesharkApi.getPlaylistSongs(playlistid) - self._add_songs_directory(songs, trackLabelFormat=NAME_ALBUM_ARTIST_LABEL) + self._add_songs_directory(songs, trackLabelFormat=NAME_ALBUM_ARTIST_LABEL, playlistid=playlistid, playlistname=playlistname) else: dialog = xbmcgui.Dialog() dialog.ok('Grooveshark XBMC', 'You must be logged in', 'to get Grooveshark playlists.') @@ -289,24 +436,43 @@ class Groveshark: # Play a song def playSong(self, item): - songid = item.getProperty('songid') - song = groovesharkApi.getSongURLFromSongID(songid) - if song != '': - item.setPath(song) - xbmc.log("Playing: " + song) + global playTimer + global player + if item != None: + songid = item.getProperty('songid') + stream = groovesharkApi.getSubscriberStreamKey(songid) + url = stream['url'] + item.setPath(url) + xbmc.log("Grooveshark playing: " + url) xbmcplugin.setResolvedUrl(handle=int(sys.argv[1]), succeeded=True, listitem=item) + # Wait for play then start time + seconds = 0 + while seconds < STREAM_MARKING_TIME: + try: + if player.isPlayingAudio() == True: + if playTimer != None: + playTimer.cancel() + songMarkTime = 0 + duration = int(item.getProperty('duration')) + playTimer = PlayTimer(1, markSong, duration, [songid, duration]) + playTimer.start() + break + except: pass + time.sleep(1) + seconds = seconds + 1 else: xbmc.executebuiltin('XBMC.Notification(Grooveshark XBMC, Unable to play song, 1000, ' + thumbDef + ')') - + # Make a song directory item def songItem(self, songid, name, album, artist, coverart, trackLabelFormat=ARTIST_ALBUM_NAME_LABEL): songImg = self._get_icon(coverart, 'song-' + str(songid) + "-image") - if trackLabelFormat == NAME_ALBUM_ARTIST_LABEL: + if int(trackLabelFormat) == NAME_ALBUM_ARTIST_LABEL: trackLabel = name + " - " + album + " - " + artist else: trackLabel = artist + " - " + album + " - " + name + duration = self._getSongDuration(songid) item = xbmcgui.ListItem(label = trackLabel, thumbnailImage=songImg, iconImage=songImg) - item.setInfo( type="music", infoLabels={ "title": name, "album": album, "artist": artist} ) + item.setInfo( type="music", infoLabels={ "title": name, "album": album, "artist": artist, "duration": duration} ) item.setProperty('mimetype', 'audio/mpeg') item.setProperty("IsPlayable", "true") item.setProperty('songid', str(songid)) @@ -314,12 +480,149 @@ class Groveshark: item.setProperty('title', name) item.setProperty('album', album) item.setProperty('artist', artist) + item.setProperty('duration', str(duration)) return item # Next page of songs - def songPage(self, page, trackLabelFormat): - self._add_songs_directory([], trackLabelFormat, page) + def songPage(self, page, trackLabelFormat, playlistid = 0, playlistname = ''): + self._add_songs_directory([], trackLabelFormat, page, playlistid = playlistid, playlistname = playlistname) + + # Make a playlist from an album + def makePlaylist(self, albumid, name): + userid = self._get_login() + if (userid != 0): + re.split(' - ',name,1) + nameTokens = re.split(' - ',name,1) # suggested name + name = self._get_keyboard(default=nameTokens[0], heading="Grooveshark playlist name") + if name != '': + album = groovesharkApi.getAlbumSongs(albumid, limit = self.songsearchlimit) + songids = [] + for song in album: + songids.append(song[1]) + if groovesharkApi.createPlaylist(name, songids) == 0: + dialog = xbmcgui.Dialog() + dialog.ok('Grooveshark XBMC', 'Cannot create Grooveshark playlist ', name) + else: + xbmc.executebuiltin('XBMC.Notification(Grooveshark XBMC, Grooveshark playlist created, 1000, ' + thumbDef + ')') + else: + dialog = xbmcgui.Dialog() + dialog.ok('Grooveshark XBMC', 'You must be logged in ', ' to create a Grooveshark playlist.') + + # Rename a playlist + def renamePlaylist(self, playlistid, name): + userid = self._get_login() + if (userid != 0): + newname = self._get_keyboard(default=name, heading="Grooveshark playlist name") + if newname == '': + return + elif groovesharkApi.playlistRename(playlistid, newname) == 0: + dialog = xbmcgui.Dialog() + dialog.ok('Grooveshark XBMC', 'Cannot rename Grooveshark playlist ', name) + else: + # Refresh to show new item name + xbmc.executebuiltin("Container.Refresh") + else: + dialog = xbmcgui.Dialog() + dialog.ok('Grooveshark XBMC', 'You must be logged in ', ' to rename a Grooveshark playlist.') + + # Remove a playlist + def removePlaylist(self, playlistid, name): + dialog = xbmcgui.Dialog() + if dialog.yesno('Grooveshark XBMC', name, 'Delete this Grooveshark playlist?') == True: + userid = self._get_login() + if (userid != 0): + if groovesharkApi.playlistDelete(playlistid) == 0: + dialog = xbmcgui.Dialog() + dialog.ok('Grooveshark XBMC', 'Cannot remove Grooveshark playlist ', name) + else: + # Refresh to remove item from directory + xbmc.executebuiltin("Container.Refresh(" + playlistsUrl + ")") + else: + dialog = xbmcgui.Dialog() + dialog.ok('Grooveshark XBMC', 'You must be logged in ', ' to delete a Grooveshark playlist.') + + # Add song to playlist + def addPlaylistSong(self, songid): + userid = self._get_login() + if (userid != 0): + playlists = groovesharkApi.getUserPlaylists() + if (len(playlists) > 0): + ret = 0 + # Select the playlist + playlistSelect = GroovesharkPlaylistSelect(items=playlists) + playlistSelect.setFocus(playlistSelect.playlistControl) + playlistSelect.doModal() + i = playlistSelect.selected + del playlistSelect + if i > -1: + # Add a new playlist + if i >= len(playlists): + name = self._get_keyboard(default='', heading="Grooveshark playlist name") + if name != '': + songIds = [] + songIds.append(songid) + if groovesharkApi.createPlaylist(name, songIds) == 0: + dialog = xbmcgui.Dialog() + dialog.ok('Grooveshark XBMC', 'Cannot create Grooveshark playlist ', name) + else: + xbmc.executebuiltin('XBMC.Notification(Grooveshark XBMC, Grooveshark playlist created, 1000, ' + thumbDef + ')') + # Existing playlist + else: + playlist = playlists[i] + playlistid = playlist[1] + xbmc.log("Add song " + str(songid) + " to playlist " + str(playlistid)) + songIDs=[] + songs = groovesharkApi.getPlaylistSongs(playlistid) + for song in songs: + songIDs.append(song[1]) + songIDs.append(songid) + ret = groovesharkApi.setPlaylistSongs(playlistid, songIDs) + if ret == False: + dialog = xbmcgui.Dialog() + dialog.ok('Grooveshark XBMC', 'Cannot add to playlist ') + else: + xbmc.executebuiltin('XBMC.Notification(Grooveshark XBMC, Added song to Grooveshark playlist, 1000, ' + thumbDef + ')') + else: + dialog = xbmcgui.Dialog() + dialog.ok('Grooveshark XBMC', 'You have no Grooveshark playlists.') + self.categories() + else: + dialog = xbmcgui.Dialog() + dialog.ok('Grooveshark XBMC', 'You must be logged in', 'to add a song to a Grooveshark playlist.') + + # Remove song from playlist + def removePlaylistSong(self, playlistid, playlistname, songid): + dialog = xbmcgui.Dialog() + if dialog.yesno('Grooveshark XBMC', 'Delete this song from', 'the Grooveshark playlist?') == True: + userid = self._get_login() + if (userid != 0): + songs = groovesharkApi.getPlaylistSongs(playlistID) + songIDs=[] + for song in songs: + if (song[1] != songid): + songIDs.append(song[1]) + ret = groovesharkApi.setPlaylistSongs(playlistID, songIDs) + if ret == False: + dialog = xbmcgui.Dialog() + dialog.ok('Grooveshark XBMC', 'Failed to remove', 'song from Grooveshark playlist.') + else: + # Refresh to remove item from directory + xbmc.executebuiltin('XBMC.Notification(Grooveshark XBMC, Removed song from Grooveshark playlist, 1000, ' + thumbDef + ')') + xbmc.executebuiltin("Container.Update(" + playlistUrl + "&id="+str(playlistid) + "&name=" + playlistname + ")") + else: + dialog = xbmcgui.Dialog() + dialog.ok('Grooveshark XBMC', 'You must be logged in', 'to delete a song from a Grooveshark playlist.') + + # Find similar artists to searched artist + def similarArtists(self, artistId): + similar = groovesharkApi.getSimilarArtists(artistId, limit = self.artistsearchlimit) + if (len(similar) > 0): + self._add_artists_directory(similar) + else: + dialog = xbmcgui.Dialog() + dialog.ok('Grooveshark XBMC', 'No similar artists.') + self.categories() # Get keyboard input def _get_keyboard(self, default="", heading="", hidden=False): @@ -369,7 +672,7 @@ class Groveshark: return thumbDef # Add songs to directory - def _add_songs_directory(self, songs, trackLabelFormat=ARTIST_ALBUM_NAME_LABEL, page=0): + def _add_songs_directory(self, songs, trackLabelFormat=ARTIST_ALBUM_NAME_LABEL, page=0, playlistid=0, playlistname='', isFavorites=False): totalSongs = len(songs) page = int(page) @@ -391,6 +694,7 @@ class Groveshark: end = start + self.songspagelimit songs = songs[start:end] + id = 0 for song in songs: item = self._get_song_item(song, trackLabelFormat) coverart = item.getProperty('coverart') @@ -398,26 +702,40 @@ class Groveshark: songid = song[1] songalbum = song[2] songartist = song[4] + + u=sys.argv[0]+"?mode="+str(MODE_SONG)+"&name="+urllib.quote_plus(songname)+"&id="+str(songid) \ +"&album="+urllib.quote_plus(songalbum) \ +"&artist="+urllib.quote_plus(songartist) \ +"&coverart="+urllib.quote_plus(coverart) fav=sys.argv[0]+"?mode="+str(MODE_FAVORITE)+"&name="+urllib.quote_plus(songname)+"&id="+str(songid) + unfav=sys.argv[0]+"?mode="+str(MODE_UNFAVORITE)+"&name="+urllib.quote_plus(songname)+"&id="+str(songid)+"&prevmode=" menuItems = [] - menuItems.append(("Grooveshark favorite", "XBMC.RunPlugin("+fav+")")) + if isFavorites == True: + unfav = unfav +str(MODE_FAVORITES) + else: + menuItems.append(("Grooveshark favorite", "XBMC.RunPlugin("+fav+")")) + menuItems.append(("Not Grooveshark favorite", "XBMC.RunPlugin("+unfav+")")) + if playlistid > 0: + rmplaylstsong=sys.argv[0]+"?playlistid="+str(playlistid)+"&id="+str(songid)+"&mode="+str(MODE_REMOVE_PLAYLIST_SONG)+"&name="+playlistname + menuItems.append(("Remove from Grooveshark playlist", "XBMC.RunPlugin("+rmplaylstsong+")")) + else: + addplaylstsong=sys.argv[0]+"?id="+str(songid)+"&mode="+str(MODE_ADD_PLAYLIST_SONG) + menuItems.append(("Add to Grooveshark playlist", "XBMC.RunPlugin("+addplaylstsong+")")) item.addContextMenuItems(menuItems, replaceItems=False) xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=item,isFolder=False, totalItems=len(songs)) + id = id + 1 page = page + 1 if totalSongs > page * self.songspagelimit: - u=sys.argv[0]+"?mode="+str(MODE_SONG_PAGE)+"&id=0"+"&page="+str(page)+"&label="+str(trackLabelFormat) + u=sys.argv[0]+"?mode="+str(MODE_SONG_PAGE)+"&id=playlistid"+"&page="+str(page)+"&label="+str(trackLabelFormat)+"&name="+playlistname self._add_dir('More songs...', u, MODE_SONG_PAGE, self.songImg, 0, totalSongs - (page * self.songspagelimit)) xbmcplugin.setContent(self._handle, 'songs') xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg) # Add albums to directory - def _add_albums_directory(self, albums): + def _add_albums_directory(self, albums, artistid=0): n = len(albums) xbmc.log("Found " + str(n) + " albums...") i = 0 @@ -429,6 +747,9 @@ class Groveshark: albumImage = self._get_icon(album[4], 'album-' + str(albumID)) self._add_dir(albumName + " - " + albumArtistName, '', MODE_ALBUM, albumImage, albumID, n) i = i + 1 + # Not supported by key + #if artistid > 0: + # self._add_dir('Similar artists...', '', MODE_SIMILAR_ARTISTS, self.artistImg, artistid) xbmcplugin.setContent(self._handle, 'albums') xbmcplugin.addSortMethod(self._handle, xbmcplugin.SORT_METHOD_ALBUM_IGNORE_THE) xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg) @@ -465,12 +786,27 @@ class Groveshark: # Add whatever directory def _add_dir(self, name, url, mode, iconimage, id, items=1): + if url == '': u=sys.argv[0]+"?mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&id="+str(id) else: u = url dir=xbmcgui.ListItem(name, iconImage=iconimage, thumbnailImage=iconimage) dir.setInfo( type="Music", infoLabels={ "title": name } ) + + # Custom menu items + menuItems = [] + if mode == MODE_ALBUM: + mkplaylst=sys.argv[0]+"?mode="+str(MODE_MAKE_PLAYLIST)+"&name="+name+"&id="+str(id) + menuItems.append(("Make Grooveshark playlist", "XBMC.RunPlugin("+mkplaylst+")")) + # Broken rename/delete are broken in API + if mode == MODE_PLAYLIST: + rmplaylst=sys.argv[0]+"?mode="+str(MODE_REMOVE_PLAYLIST)+"&name="+urllib.quote_plus(name)+"&id="+str(id) + menuItems.append(("Delete Grooveshark playlist", "XBMC.RunPlugin("+rmplaylst+")")) + mvplaylst=sys.argv[0]+"?mode="+str(MODE_RENAME_PLAYLIST)+"&name="+urllib.quote_plus(name)+"&id="+str(id) + menuItems.append(("Rename Grooveshark playlist", "XBMC.RunPlugin("+mvplaylst+")")) + dir.addContextMenuItems(menuItems, replaceItems=False) + return xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=dir,isFolder=True, totalItems=items) def _getSavedSongs(self): @@ -496,9 +832,50 @@ class Groveshark: except: xbmc.log("An error occurred saving songs") pass - + def _getSongDuration(self, songid): + path = os.path.join(cacheDir, 'duration.dmp') + id = int(songid) + durations = [] + duration = -1 + + # Try cache first + try: + f = open(path, 'rb') + durations = pickle.load(f) + for song in durations: + if song[0] == id: + duration = song[1] + f.close() + except: + pass + + if duration < 0: + stream = groovesharkApi.getSubscriberStreamKey(songid) + usecs = stream['uSecs'] + if usecs < 60000000: + usecs = usecs * 10 # Some durations are 10x to small + duration = usecs / 1000000 + song = [id, duration] + durations.append(song) + self._setSongDuration(durations) + + return duration + + def _setSongDuration(self, durations): + try: + # Create the 'data' directory if it doesn't exist. + if not os.path.exists(cacheDir): + os.makedirs(cacheDir) + path = os.path.join(cacheDir, 'duration.dmp') + f = open(path, 'wb') + pickle.dump(durations, f, protocol=pickle.HIGHEST_PROTOCOL) + f.close() + except: + xbmc.log("An error occurred saving durations") + pass + # Parse URL parameters def get_params(): param=[] @@ -528,6 +905,9 @@ except: pass id=0 try: id=int(params["id"]) except: pass +name = None +try: name=urllib.unquote_plus(params["name"]) +except: pass # Call function for URL if mode==None: @@ -543,10 +923,6 @@ elif mode==MODE_SEARCH_ARTISTS: grooveshark.searchArtists() elif mode==MODE_SEARCH_ARTISTS_ALBUMS: - try: name=urllib.unquote_plus(params["name"]) - except: - name = None - pass grooveshark.searchArtistsAlbums(name) elif mode==MODE_SEARCH_PLAYLISTS: @@ -569,11 +945,9 @@ elif mode==MODE_SONG_PAGE: except: pass try: label=urllib.unquote_plus(params["label"]) except: pass - grooveshark.songPage(page, label) + grooveshark.songPage(page, label, id, name) elif mode==MODE_SONG: - try: name=urllib.unquote_plus(params["name"]) - except: pass try: album=urllib.unquote_plus(params["album"]) except: pass try: artist=urllib.unquote_plus(params["artist"]) @@ -590,10 +964,36 @@ elif mode==MODE_ALBUM: grooveshark.album(id) elif mode==MODE_PLAYLIST: - grooveshark.playlist(id) + grooveshark.playlist(id, name) elif mode==MODE_FAVORITE: grooveshark.favorite(id) +elif mode==MODE_UNFAVORITE: + try: prevMode=int(urllib.unquote_plus(params["prevmode"])) + except: + prevMode = 0 + grooveshark.unfavorite(id, prevMode) + +elif mode==MODE_SIMILAR_ARTISTS: + grooveshark.similarArtists(id) + +elif mode==MODE_MAKE_PLAYLIST: + grooveshark.makePlaylist(id, name) + +elif mode==MODE_REMOVE_PLAYLIST: + grooveshark.removePlaylist(id, name) + +elif mode==MODE_RENAME_PLAYLIST: + grooveshark.renamePlaylist(id, name) + +elif mode==MODE_REMOVE_PLAYLIST_SONG: + try: playlistID=urllib.unquote_plus(params["playlistid"]) + except: pass + grooveshark.removePlaylistSong(playlistID, name, id) + +elif mode==MODE_ADD_PLAYLIST_SONG: + grooveshark.addPlaylistSong(id) + if mode < MODE_SONG: xbmcplugin.endOfDirectory(int(sys.argv[1]))