X-Git-Url: http://git.hcoop.net/clinton/xbmc-groove.git/blobdiff_plain/3fcef5ba80eb63c54c4220ff91ebf79ac4390957..99f72740161d15018a0784933ef0276d2c10c2a8:/default.py diff --git a/default.py b/default.py dissimilarity index 73% index b0a86e9..a4609db 100644 --- a/default.py +++ b/default.py @@ -1,515 +1,597 @@ -import urllib, urllib2, re, xbmcplugin, xbmcgui, xbmc, sys, os, time - -# plugin constants -__plugin__ = "Grooveshark" -__author__ = "Stephen Denham" -__url__ = "" -__svn_url__ = "" -__version__ = "0.0.1" -__svn_revision__ = "" -__XBMC_Revision__ = "" - -MODE_SEARCH_SONGS = 1 -MODE_SEARCH_ALBUMS = 2 -MODE_SEARCH_ARTISTS = 3 -MODE_POPULAR = 4 -MODE_FAVORITES = 5 -MODE_PLAYLISTS = 6 -MODE_ALBUM = 7 -MODE_ARTIST = 8 -MODE_PLAYLIST = 9 -MODE_SONG = 10 -MODE_FAVORITE = 11 -MODE_UNFAVORITE = 12 -MODE_SIMILAR_SONG = 13 -MODE_SIMILAR_ARTIST = 14 -MODE_FROWN = 15 - -songsearchlimit = 0 -albumsearchlimit = 0 -artistsearchlimit = 0 - -lastID = 0 - -resDir = xbmc.translatePath(os.path.join(os.getcwd(), 'resources')) -libDir = xbmc.translatePath(os.path.join(resDir, 'lib')) -imgDir = xbmc.translatePath(os.path.join(resDir, 'img')) -thumbDir = os.path.join('special://masterprofile/plugin_data/music', os.path.basename(os.getcwd())) - -sys.path.append (libDir) -from GrooveAPI import * -groovesharkApi = GrooveAPI() - -class _Info: - def __init__( self, *args, **kwargs ): - self.__dict__.update( kwargs ) - -class GrovesharkPlayer(xbmc.Player): - # Player Class: calls function when song changes or playback ends - def __init__(self, *args, **kwargs): - xbmc.Player.__init__(self) - self.function = kwargs[ "function" ] - - def onPlayBackStopped(self): - print "onPlayBackStopped" - xbmc.sleep(300) - if (not xbmc.Player().isPlayingAudio()): - self.function(stop=1) - - def onPlayBackEnded(self): - print "onPlayBackEnded" - xbmc.sleep(300) - if (not xbmc.Player().isPlayingAudio()): - self.function(stop=0) - - def onPlayBackStarted(self): - print "onPlayBackStarted" - -class Groveshark: - - albumImg = xbmc.translatePath(os.path.join(imgDir, 'album.png')) - artistImg = xbmc.translatePath(os.path.join(imgDir, 'artist.png')) - favoritesImg = xbmc.translatePath(os.path.join(imgDir, 'favorites.png')) - playlistImg = xbmc.translatePath(os.path.join(imgDir, 'playlist.png')) - popularImg = xbmc.translatePath(os.path.join(imgDir, 'popular.png')) - songImg = xbmc.translatePath(os.path.join(imgDir, 'song.png')) - - songsearchlimit = xbmcplugin.getSetting('songsearchlimit') - albumsearchlimit = xbmcplugin.getSetting('albumsearchlimit') - artistsearchlimit = xbmcplugin.getSetting('artistsearchlimit') - - musicplaylist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC) - - def __init__( self ): - self._handle = int(sys.argv[1]) - - def categories(self): - - userid = self._get_login() - - # Setup - groovesharkApi.setRemoveDuplicates(True) - - self._add_dir('Search songs', '', MODE_SEARCH_SONGS, self.songImg, 0) - self._add_dir('Search albums', '', MODE_SEARCH_ALBUMS, self.albumImg, 0) - self._add_dir('Search artists', '', MODE_SEARCH_ARTISTS, self.artistImg, 0) - self._add_dir('Popular', '', MODE_POPULAR, self.popularImg, 0) - if (userid != 0): - self._add_dir('Favorites', '', MODE_FAVORITES, self.favoritesImg, 0) - self._add_dir('Playlists', '', MODE_PLAYLISTS, self.playlistImg, 0) - - def searchSongs(self): - query = self._get_keyboard(default="", heading="Search songs") - if (query): - songs = groovesharkApi.searchSongs(query, limit = xbmcplugin.getSetting('songsearchlimit')) - if (len(songs) > 0): - self._get_songs(songs) - else: - dialog = xbmcgui.Dialog() - dialog.ok('Grooveshark', 'No matching songs.') - self.categories() - - def searchAlbums(self): - query = self._get_keyboard(default="", heading="Search albums") - if (query): - albums = groovesharkApi.searchAlbums(query, limit = xbmcplugin.getSetting('albumsearchlimit')) - if (len(albums) > 0): - self._get_albums(albums) - else: - dialog = xbmcgui.Dialog() - dialog.ok('Grooveshark', 'No matching albums.') - self.categories() - - def searchArtists(self): - query = self._get_keyboard(default="", heading="Search artists") - if (query): - artists = groovesharkApi.searchArtists(query, limit = xbmcplugin.getSetting('artistsearchlimit')) - if (len(artists) > 0): - self._get_artists(artists) - else: - dialog = xbmcgui.Dialog() - dialog.ok('Grooveshark', 'No matching artists.') - self.categories() - - def favorites(self): - userid = self._get_login() - if (userid != 0): - favorites = groovesharkApi.userGetFavoriteSongs(userid) - if (len(favorites) > 0): - self._get_songs(favorites) - else: - dialog = xbmcgui.Dialog() - dialog.ok('Grooveshark', 'You have no favorites.') - self.categories() - - def popular(self): - popular = groovesharkApi.popularGetSongs(limit = xbmcplugin.getSetting('songsearchlimit')) - if (len(popular) > 0): - self._get_songs(popular) - else: - dialog = xbmcgui.Dialog() - dialog.ok('Grooveshark', 'No popular songs.') - self.categories() - - def playlists(self): - userid = self._get_login() - if (userid != 0): - playlists = groovesharkApi.userGetPlaylists() - if (len(playlists) > 0): - self._get_playlists(playlists) - else: - dialog = xbmcgui.Dialog() - dialog.ok('Grooveshark', 'You have no playlists.') - self.categories() - - def favorite(self, songid): - userid = self._get_login() - if (userid != 0): - xbmc.log("Favorite playSong: " + str(songid)) - groovesharkApi.favoriteSong(songID = songid) - else: - dialog = xbmcgui.Dialog() - dialog.ok('Grooveshark', 'You must be logged in', 'to add favorites.') - - def unfavorite(self, songid): - userid = self._get_login() - if (userid != 0): - xbmc.log("Unfavorite playSong: " + str(songid)) - groovesharkApi.unfavoriteSong(songID = songid) - else: - dialog = xbmcgui.Dialog() - dialog.ok('Grooveshark', 'You must be logged in', 'to remove favorites.') - - def frown(self, songid): - userid = self._get_login() - if (userid != 0): - xbmc.log("Frown playSong: " + str(songid)) - if groovesharkApi.radioFrown(songId = songid) != True: - xbmc.log("Unable to frown song " + str(songid)) - else: - dialog = xbmcgui.Dialog() - dialog.ok('Grooveshark', 'You must be logged in', 'to frown a song.') - - def similarSong(self, songid): - userid = self._get_login() - if (userid != 0): - xbmc.log("Frown playSong: " + str(songid)) - if groovesharkApi.radioSong(songId = songid) and groovesharkApi.radioStartSongs() == True: - self.playRadio() - else: - dialog = xbmcgui.Dialog() - dialog.ok('Grooveshark', 'Cannot start radio') - else: - dialog = xbmcgui.Dialog() - dialog.ok('Grooveshark', 'You must be logged in', 'to update radio song.') - - def similarArtist(self, artistId): - userid = self._get_login() - if (userid != 0): - xbmc.log("Add radio artist of playSong: " + str(artistId)) - if groovesharkApi.radioArtist(artistId = artistId) and groovesharkApi.radioStartArtists() == True: - self.playRadio() - else: - dialog = xbmcgui.Dialog() - dialog.ok('Grooveshark', 'Cannot start radio') - else: - dialog = xbmcgui.Dialog() - dialog.ok('Grooveshark', 'You must be logged in', 'to update radio artists.') - - def album(self,albumid): - album = groovesharkApi.albumGetSongs(albumId = albumid, limit = xbmcplugin.getSetting('songsearchlimit')) - self._get_songs(album) - - def artist(self, artistid): - albums = groovesharkApi.artistGetAlbums(artistId = artistid, limit = xbmcplugin.getSetting('albumsearchlimit')) - self._get_albums(albums) - - def playlist(self, playlistid): - userid = self._get_login() - if (userid != 0): - songs = groovesharkApi.playlistGetSongs(playlistId = playlistid, limit = xbmcplugin.getSetting('songsearchlimit')) - self._get_songs(songs) - else: - dialog = xbmcgui.Dialog() - dialog.ok('Grooveshark', 'You must be logged in', 'to get playlists.') - - def playSong(self, songItem): - url = songItem.getProperty('url') - xbmc.log("Playing: " + url) - player = GrovesharkPlayer(xbmc.PLAYER_CORE_PAPLAYER, function=self._add_next) - player.play(url, songItem, False) - - def playRadio(self): - song = self._get_next() - self._get_next() - self.playSong(song) - - def songItem(self, url, name, album, artist, duration, thumb, image): - songItem = xbmcgui.ListItem(label = name, path=url, thumbnailImage=thumb, iconImage=image) - songItem.setInfo( type="Music", infoLabels={ "title": name, "duration": duration, "album": album, "artist": artist} ) - songItem.setProperty('mimetype', 'audio/mpeg') - songItem.setProperty('url', url) - return songItem - - def _get_keyboard(self, default="", heading="", hidden=False): - kb = xbmc.Keyboard(default, heading, hidden) - kb.doModal() - if (kb.isConfirmed()): - return unicode(kb.getText(), "utf-8") - return '' - - def _get_login(self): - username = xbmcplugin.getSetting('username') - password = xbmcplugin.getSetting('password') - if (username == "" or password == ""): - dialog = xbmcgui.Dialog() - dialog.ok('Grooveshark', 'Unable to login.', 'Check username and password in settings.') - return 0 - else: - if groovesharkApi.loggedInStatus() == 1: - groovesharkApi.logout() - userid = groovesharkApi.loginExt(username, password) - if (userid != 0): - xbmc.log("Logged in") - return userid - else: - dialog = xbmcgui.Dialog() - dialog.ok('Grooveshark', 'Unable to login.', 'Check username and password in settings.') - return 0 - - def _get_next(self): - song = groovesharkApi.radioNextSong()[0] - print song - url = groovesharkApi.getStreamURL(song[1]) - songImg = self._get_thumb(song[9], str(song[1]) + "-image") - if songImg == "": - songImg = song[9] - songThm = self._get_thumb(song[5], str(song[1]) + "-thumb") - if songThm == "": - songThm = song[5] - item = self.songItem(url, song[0], song[3], song[6], song[2], songThm, songImg) - self.musicplaylist.add(url, item) - print item - return item - - def _get_songs(self, songs): - xbmc.log("Found " + str(len(songs)) + " songs...") - i = 0 - while i < len(songs): - song = songs[i] - songName = song[0] - songID = song[1] - songDuration = song[2] - songAlbum = song[3] - songArtist = song[6] - songArtistId = song[7] - songThumb = song[8] - songImage = song[9] - songUrl = groovesharkApi.getStreamURL(songID) - self._add_song(songID, songName, songUrl, songDuration, songAlbum, songArtist, songArtistId, songThumb, songImage) - i = i + 1 - xbmcplugin.setContent(self._handle, 'songs') - - def _get_albums(self, albums): - xbmc.log("Found " + str(len(albums)) + " albums...") - i = 0 - while i < len(albums): - album = albums[i] - albumArtistName = album[0] - albumName = album[2] - albumID = album[3] - albumImage = album[4] - self._add_dir(albumName + " - " + albumArtistName, '', MODE_ALBUM, albumImage, albumID) - i = i + 1 - xbmcplugin.setContent(self._handle, 'albums') - xbmcplugin.addSortMethod(self._handle, xbmcplugin.SORT_METHOD_ALBUM_IGNORE_THE) - - def _get_artists(self, artists): - xbmc.log("Found " + str(len(artists)) + " artists...") - i = 0 - while i < len(artists): - artist = artists[i] - artistName = artist[0] - artistID = artist[1] - self._add_dir(artistName, '', MODE_ARTIST, self.artistImg, artistID) - i = i + 1 - xbmcplugin.setContent(self._handle, 'artists') - xbmcplugin.addSortMethod(self._handle, xbmcplugin.SORT_METHOD_ARTIST_IGNORE_THE) - - def _get_playlists(self, playlists): - xbmc.log("Found " + str(len(playlists)) + " playlists...") - i = 0 - while i < len(playlists): - playlist = playlists[i] - playlistName = playlist[0] - playlistID = playlist[1] - self._add_dir(playlistName, '', MODE_PLAYLIST, self.playlistImg, playlistID) - i = i + 1 - xbmcplugin.setContent(self._handle, 'files') - xbmcplugin.addSortMethod(self._handle, xbmcplugin.SORT_METHOD_PLAYLIST_ORDER) - - # File download - def _get_thumb(self, url, id): - # Get the channel icon - localThumb = os.path.join(xbmc.translatePath(os.path.join(thumbDir, str(id)))) + '.tbn' - try: - if os.path.isfile(localThumb) == False: - loc = urllib.URLopener() - loc.retrieve(url, localThumb) - except: - xbmc.log('URL download failed of ' + url + ' to ' + localThumb) - return "" - - return os.path.join(os.path.join(thumbDir, str(id))) + '.tbn' - - def _add_song(self, songid, songname, songurl, songduration, songalbum, songartist, songartistid, songthumb, songimage): - songImg = self._get_thumb(songimage, str(songid) + "-image") - if songImg == "": - songImg = songimage - songThm = self._get_thumb(songthumb, str(songid) + "-thumb") - if songThm == "": - songThm = songthumb - u=sys.argv[0]+"?url="+urllib.quote_plus(songurl)+"&mode="+str(MODE_SONG)+"&name="+urllib.quote_plus(songname)+"&id="+str(songid) \ - +"&album="+urllib.quote_plus(songalbum) \ - +"&artist="+urllib.quote_plus(songartist) \ - +"&duration="+str(songduration) \ - +"&thumb="+urllib.quote_plus(songThm) \ - +"&image="+urllib.quote_plus(songImg) - songItem = xbmcgui.ListItem(label = songartist + " - " + songalbum + " - " + songname, iconImage=songImg, thumbnailImage=songThm, path=songurl) - songItem.setInfo( type="Music", infoLabels={ "title": songname, "duration": songduration, "album": songalbum, "artist": songartist} ) - fav=sys.argv[0]+"?url="+urllib.quote_plus(songurl)+"&mode="+str(MODE_FAVORITE)+"&name="+urllib.quote_plus(songname)+"&id="+str(songid) - unfav=sys.argv[0]+"?url="+urllib.quote_plus(songurl)+"&mode="+str(MODE_UNFAVORITE)+"&name="+urllib.quote_plus(songname)+"&id="+str(songid) - similarArtist=sys.argv[0]+"?mode="+str(MODE_SIMILAR_ARTIST)+"&id="+str(songartistid) - similarSong=sys.argv[0]+"?mode="+str(MODE_SIMILAR_SONG)+"&id="+str(songid) - frown=sys.argv[0]+"?mode="+str(MODE_FROWN)+"&id="+str(songid) - menuItems = [] - menuItems.append(("Grooveshark Favorite", "XBMC.RunPlugin("+fav+")")) - menuItems.append(("Not Grooveshark Favorite", "XBMC.RunPlugin("+unfav+")")) - menuItems.append(("Listen to similar artist", "XBMC.RunPlugin("+similarArtist+")")) - menuItems.append(("Listen to similar song", "XBMC.RunPlugin("+similarSong+")")) - menuItems.append(("No thanks!", "XBMC.RunPlugin("+frown+")")) - songItem.addContextMenuItems(menuItems, replaceItems=False) - xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=songItem,isFolder=False) - return songItem - - def _add_next(self, stop=0): - print "_add_next " + str(stop) - if stop == 1: - groovesharkApi.radioEnabled = False - self.playlist.clear() - elif groovesharkApi.radioTurnedOn() == True: - next = self._get_next() - self.playlist.add(url, next) - - def _add_dir(self, name, url, mode, iconimage, id): - u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&id="+str(id) - dir=xbmcgui.ListItem(name, iconImage=iconimage, thumbnailImage=iconimage) - dir.setInfo( type="Music", infoLabels={ "title": name } ) - # Codes from http://xbmc-scripting.googlecode.com/svn/trunk/Script%20Templates/common/gui/codes.py - menuItems = [] - menuItems.append(("Select", "XBMC.executebuiltin(Action(7))")) - dir.addContextMenuItems(menuItems, replaceItems=True) - return xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=dir,isFolder=True) - - -def get_params(): - param=[] - paramstring=sys.argv[2] - if len(paramstring)>=2: - params=sys.argv[2] - cleanedparams=params.replace('?','') - if (params[len(params)-1]=='/'): - params=params[0:len(params)-2] - pairsofparams=cleanedparams.split('&') - param={} - for i in range(len(pairsofparams)): - splitparams={} - splitparams=pairsofparams[i].split('=') - if (len(splitparams))==2: - param[splitparams[0]]=splitparams[1] - print param - return param - -grooveshark = Groveshark(); - -params=get_params() -url=None -name=None -mode=None -id=None - -try: url=urllib.unquote_plus(params["url"]) -except: pass -try: name=urllib.unquote_plus(params["name"]) -except: pass -try: mode=int(params["mode"]) -except: pass -try: id=int(params["id"]) -except: pass - -if (id > 0): - lastID = id - -if mode==None: - grooveshark.categories() - -elif mode==MODE_SEARCH_SONGS: - grooveshark.searchSongs() - -elif mode==MODE_SEARCH_ALBUMS: - grooveshark.searchAlbums() - -elif mode==MODE_SEARCH_ARTISTS: - grooveshark.searchArtists() - -elif mode==MODE_POPULAR: - grooveshark.popular() - -elif mode==MODE_PLAYLISTS: - grooveshark.playlists() - -elif mode==MODE_FAVORITES: - grooveshark.favorites() - -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"]) - except: pass - try: duration=int(params["duration"]) - except: pass - try: thumb=urllib.unquote_plus(params["thumb"]) - except: pass - try: image=urllib.unquote_plus(params["image"]) - except: pass - song = grooveshark.songItem(url, name, album, artist, duration, thumb, image) - grooveshark.playSong(song) - -elif mode==MODE_ARTIST: - grooveshark.artist(lastID) - -elif mode==MODE_ALBUM: - grooveshark.album(lastID) - -elif mode==MODE_PLAYLIST: - grooveshark.playlist(lastID) - -elif mode==MODE_FAVORITE: - grooveshark.favorite(lastID) - -elif mode==MODE_UNFAVORITE: - grooveshark.unfavorite(lastID) - -elif mode==MODE_SIMILAR_ARTIST: - grooveshark.similarArtist(lastID) - -elif mode==MODE_SIMILAR_SONG: - grooveshark.similarSong(lastID) - -elif mode==MODE_FROWN: - grooveshark.frown(lastID) - -if (mode < MODE_SONG): - xbmcplugin.endOfDirectory(int(sys.argv[1])) +import urllib, sys, os, shutil, re, time, xbmcaddon, xbmcplugin, xbmcgui, xbmc, pickle +MODE_SEARCH_SONGS = 1 +MODE_SEARCH_ALBUMS = 2 +MODE_SEARCH_ARTISTS = 3 +MODE_SEARCH_ARTISTS_ALBUMS = 4 +MODE_SEARCH_PLAYLISTS = 5 +MODE_ARTIST_POPULAR = 6 +MODE_POPULAR_SONGS = 7 +MODE_FAVORITES = 8 +MODE_PLAYLISTS = 9 +MODE_ALBUM = 10 +MODE_ARTIST = 11 +MODE_PLAYLIST = 12 +MODE_SONG_PAGE = 13 +MODE_SONG = 14 +MODE_FAVORITE = 15 + +ACTION_MOVE_LEFT = 1 +ACTION_MOVE_UP = 3 +ACTION_MOVE_DOWN = 4 +ACTION_PAGE_UP = 5 +ACTION_PAGE_DOWN = 6 +ACTION_SELECT_ITEM = 7 +ACTION_PREVIOUS_MENU = 10 + +# Formats for track labels +ARTIST_ALBUM_NAME_LABEL = 0 +NAME_ALBUM_ARTIST_LABEL = 1 + +baseDir = os.getcwd() +resDir = xbmc.translatePath(os.path.join(baseDir, 'resources')) +libDir = xbmc.translatePath(os.path.join(resDir, 'lib')) +imgDir = xbmc.translatePath(os.path.join(resDir, 'img')) +cacheDir = os.path.join(xbmc.translatePath('special://masterprofile/addon_data/'), os.path.basename(os.getcwd())) +thumbDirName = 'thumb' +thumbDir = os.path.join('special://masterprofile/addon_data/', os.path.basename(os.getcwd()), thumbDirName) + +baseModeUrl = 'plugin://plugin.audio.groove/' +playlistUrl = baseModeUrl + '?mode=' + str(MODE_PLAYLIST) +playlistsUrl = baseModeUrl + '?mode=' + str(MODE_PLAYLISTS) +favoritesUrl = baseModeUrl + '?mode=' + str(MODE_FAVORITES) + +thumbDef = os.path.join(imgDir, 'default.tbn') + +sys.path.append (libDir) +from GroovesharkAPI import GrooveAPI + +try: + groovesharkApi = GrooveAPI() + if groovesharkApi.pingService() != True: + raise StandardError('No Grooveshark service') +except: + dialog = xbmcgui.Dialog() + dialog.ok('Grooveshark XBMC', 'Unable to connect with Grooveshark.', 'Please try again later') + sys.exit(-1) + + +class _Info: + def __init__( self, *args, **kwargs ): + self.__dict__.update( kwargs ) + + +class Groveshark: + + albumImg = xbmc.translatePath(os.path.join(imgDir, 'album.png')) + artistImg = xbmc.translatePath(os.path.join(imgDir, 'artist.png')) + artistsAlbumsImg = xbmc.translatePath(os.path.join(imgDir, 'artistsalbums.png')) + favoritesImg = xbmc.translatePath(os.path.join(imgDir, 'favorites.png')) + playlistImg = xbmc.translatePath(os.path.join(imgDir, 'playlist.png')) + usersplaylistsImg = xbmc.translatePath(os.path.join(imgDir, 'usersplaylists.png')) + popularSongsImg = xbmc.translatePath(os.path.join(imgDir, 'popularSongs.png')) + popularSongsArtistImg = xbmc.translatePath(os.path.join(imgDir, 'popularSongsArtist.png')) + songImg = xbmc.translatePath(os.path.join(imgDir, 'song.png')) + defImg = xbmc.translatePath(os.path.join(imgDir, 'default.tbn')) + fanImg = xbmc.translatePath(os.path.join(baseDir, 'fanart.png')) + + settings = xbmcaddon.Addon(id='plugin.audio.groove') + songsearchlimit = int(settings.getSetting('songsearchlimit')) + albumsearchlimit = int(settings.getSetting('albumsearchlimit')) + artistsearchlimit = int(settings.getSetting('artistsearchlimit')) + songspagelimit = int(settings.getSetting('songspagelimit')) + username = settings.getSetting('username') + password = settings.getSetting('password') + userid = 0 + + def __init__( self ): + self._handle = int(sys.argv[1]) + if os.path.isdir(cacheDir) == False: + os.makedirs(cacheDir) + xbmc.log("Made " + cacheDir) + artDir = xbmc.translatePath(thumbDir) + if os.path.isdir(artDir) == False: + os.makedirs(artDir) + xbmc.log("Made " + artDir) + + # Top-level menu + def categories(self): + + self.userid = self._get_login() + + # Setup + xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg) + + self._add_dir('Search for songs...', '', MODE_SEARCH_SONGS, self.songImg, 0) + 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("Search for artist's albums...", '', 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) + if (self.userid != 0): + self._add_dir('My favorites', '', MODE_FAVORITES, self.favoritesImg, 0) + self._add_dir('My playlists', '', MODE_PLAYLISTS, self.playlistImg, 0) + + # Search for songs + def searchSongs(self): + query = self._get_keyboard(default="", heading="Search for songs") + if (query != ''): + songs = groovesharkApi.getSongSearchResults(query, limit = self.songsearchlimit) + if (len(songs) > 0): + self._add_songs_directory(songs) + else: + dialog = xbmcgui.Dialog() + dialog.ok('Grooveshark XBMC', 'No matching songs.') + self.categories() + else: + self.categories() + + # Search for albums + def searchAlbums(self): + query = self._get_keyboard(default="", heading="Search for albums") + if (query != ''): + albums = groovesharkApi.getAlbumSearchResults(query, limit = self.albumsearchlimit) + if (len(albums) > 0): + self._add_albums_directory(albums) + else: + dialog = xbmcgui.Dialog() + dialog.ok('Grooveshark XBMC', 'No matching albums.') + self.categories() + else: + self.categories() + + # Search for artists + def searchArtists(self): + query = self._get_keyboard(default="", heading="Search for artists") + if (query != ''): + artists = groovesharkApi.getArtistSearchResults(query, limit = self.artistsearchlimit) + if (len(artists) > 0): + self._add_artists_directory(artists) + else: + dialog = xbmcgui.Dialog() + dialog.ok('Grooveshark XBMC', 'No matching artists.') + self.categories() + else: + self.categories() + + # Search for playlists + def searchPlaylists(self): + query = self._get_keyboard(default="", heading="Username") + if (query != ''): + playlists = groovesharkApi.getUserPlaylistsEx(query) + if (len(playlists) > 0): + self._add_playlists_directory(playlists) + else: + dialog = xbmcgui.Dialog() + dialog.ok('Grooveshark XBMC', 'No Grooveshark playlists found.') + self.categories() + else: + self.categories() + + # Search for artists albums + def searchArtistsAlbums(self, artistName = ""): + if artistName == "": + query = self._get_keyboard(default="", heading="Search for artist's albums") + else: + query = artistName + if (query != ''): + artists = groovesharkApi.getArtistSearchResults(query, limit = self.artistsearchlimit) + if (len(artists) > 0): + artist = artists[0] + artistID = artist[1] + xbmc.log("Found " + artist[0] + "...") + albums = groovesharkApi.getArtistAlbums(artistID, limit = self.albumsearchlimit) + if (len(albums) > 0): + self._add_albums_directory(albums) + else: + dialog = xbmcgui.Dialog() + dialog.ok('Grooveshark XBMC', 'No matching albums.') + self.categories() + else: + dialog = xbmcgui.Dialog() + dialog.ok('Grooveshark XBMC', 'No matching artists.') + self.categories() + else: + self.categories() + + # Get my favorites + def favorites(self): + userid = self._get_login() + if (userid != 0): + favorites = groovesharkApi.getUserFavoriteSongs() + if (len(favorites) > 0): + self._add_songs_directory(favorites) + else: + dialog = xbmcgui.Dialog() + dialog.ok('Grooveshark XBMC', 'You have no favorites.') + self.categories() + + # Get popular songs + def popularSongs(self): + popular = groovesharkApi.getPopularSongsToday(limit = self.songsearchlimit) + if (len(popular) > 0): + self._add_songs_directory(popular) + else: + dialog = xbmcgui.Dialog() + dialog.ok('Grooveshark XBMC', 'No popular songs.') + self.categories() + + # Get my playlists + def playlists(self): + userid = self._get_login() + if (userid != 0): + playlists = groovesharkApi.getUserPlaylists() + if (len(playlists) > 0): + self._add_playlists_directory(playlists) + 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 see your Grooveshark playlists.') + + # Make songs a favorite + def favorite(self, songid): + userid = self._get_login() + if (userid != 0): + xbmc.log("Favorite song: " + str(songid)) + groovesharkApi.addUserFavoriteSong(songID = songid) + xbmc.executebuiltin('XBMC.Notification(Grooveshark XBMC, Added to favorites, 1000, ' + thumbDef + ')') + else: + dialog = xbmcgui.Dialog() + dialog.ok('Grooveshark XBMC', 'You must be logged in', 'to add favorites.') + + # Show selected album + def album(self, albumid): + album = groovesharkApi.getAlbumSongs(albumid, limit = self.songsearchlimit) + self._add_songs_directory(album, trackLabelFormat=NAME_ALBUM_ARTIST_LABEL) + + # Show selected artist + def artist(self, artistid): + albums = groovesharkApi.getArtistAlbums(artistid, limit = self.albumsearchlimit) + self._add_albums_directory(albums) + + # Show selected playlist + def playlist(self, playlistid): + userid = self._get_login() + if (userid != 0): + songs = groovesharkApi.getPlaylistSongs(playlistid) + self._add_songs_directory(songs, trackLabelFormat=NAME_ALBUM_ARTIST_LABEL) + else: + dialog = xbmcgui.Dialog() + dialog.ok('Grooveshark XBMC', 'You must be logged in', 'to get Grooveshark playlists.') + + # Show popular songs of the artist + def artistPopularSongs(self): + query = self._get_keyboard(default="", heading="Artist") + if (query != ''): + artists = groovesharkApi.getArtistSearchResults(query, limit = self.artistsearchlimit) + if (len(artists) > 0): + artist = artists[0] + artistID = artist[1] + xbmc.log("Found " + artist[0] + "...") + songs = groovesharkApi.getArtistPopularSongs(artistID, limit = self.songsearchlimit) + if (len(songs) > 0): + self._add_songs_directory(songs, trackLabelFormat=NAME_ALBUM_ARTIST_LABEL) + else: + dialog = xbmcgui.Dialog() + dialog.ok('Grooveshark XBMC', 'No popular songs.') + self.categories() + else: + dialog = xbmcgui.Dialog() + dialog.ok('Grooveshark XBMC', 'No matching artists.') + self.categories() + else: + self.categories() + + # Play a song + def playSong(self, item): + songid = item.getProperty('songid') + song = groovesharkApi.getSongURLFromSongID(songid) + if song != '': + item.setPath(song) + xbmc.log("Playing: " + song) + xbmcplugin.setResolvedUrl(handle=int(sys.argv[1]), succeeded=True, listitem=item) + 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: + trackLabel = name + " - " + album + " - " + artist + else: + trackLabel = artist + " - " + album + " - " + name + item = xbmcgui.ListItem(label = trackLabel, thumbnailImage=songImg, iconImage=songImg) + item.setInfo( type="music", infoLabels={ "title": name, "album": album, "artist": artist} ) + item.setProperty('mimetype', 'audio/mpeg') + item.setProperty("IsPlayable", "true") + item.setProperty('songid', str(songid)) + item.setProperty('coverart', songImg) + item.setProperty('title', name) + item.setProperty('album', album) + item.setProperty('artist', artist) + + return item + + # Next page of songs + def songPage(self, page, trackLabelFormat): + self._add_songs_directory([], trackLabelFormat, page) + + # Get keyboard input + def _get_keyboard(self, default="", heading="", hidden=False): + kb = xbmc.Keyboard(default, heading, hidden) + kb.doModal() + if (kb.isConfirmed()): + return unicode(kb.getText(), "utf-8") + return '' + + # Login to grooveshark + def _get_login(self): + if (self.username == "" or self.password == ""): + dialog = xbmcgui.Dialog() + dialog.ok('Grooveshark XBMC', 'Unable to login.', 'Check username and password in settings.') + return 0 + else: + if self.userid == 0: + uid = groovesharkApi.login(self.username, self.password) + if (uid != 0): + return uid + else: + dialog = xbmcgui.Dialog() + dialog.ok('Grooveshark XBMC', 'Unable to login.', 'Check username and password in settings.') + return 0 + + # Get a song directory item + def _get_song_item(self, song, trackLabelFormat): + name = song[0] + songid = song[1] + album = song[2] + artist = song[4] + coverart = song[6] + return self.songItem(songid, name, album, artist, coverart, trackLabelFormat) + + # File download + def _get_icon(self, url, songid): + if url != 'None': + localThumb = os.path.join(xbmc.translatePath(os.path.join(thumbDir, str(songid)))) + '.tbn' + try: + if os.path.isfile(localThumb) == False: + loc = urllib.URLopener() + loc.retrieve(url, localThumb) + except: + shutil.copy2(thumbDef, localThumb) + return os.path.join(os.path.join(thumbDir, str(songid))) + '.tbn' + else: + return thumbDef + + # Add songs to directory + def _add_songs_directory(self, songs, trackLabelFormat=ARTIST_ALBUM_NAME_LABEL, page=0): + + totalSongs = len(songs) + page = int(page) + + # No pages needed + if page == 0 and totalSongs <= self.songspagelimit: + xbmc.log("Found " + str(totalSongs) + " songs...") + # Pages + else: + # Cache all songs + if page == 0: + self._setSavedSongs(songs) + else: + songs = self._getSavedSongs() + totalSongs = len(songs) + + if totalSongs > 0: + start = page * self.songspagelimit + end = start + self.songspagelimit + songs = songs[start:end] + + for song in songs: + item = self._get_song_item(song, trackLabelFormat) + coverart = item.getProperty('coverart') + songname = song[0] + 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) + menuItems = [] + menuItems.append(("Grooveshark favorite", "XBMC.RunPlugin("+fav+")")) + item.addContextMenuItems(menuItems, replaceItems=False) + xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=item,isFolder=False, totalItems=len(songs)) + + 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) + 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): + n = len(albums) + xbmc.log("Found " + str(n) + " albums...") + i = 0 + while i < n: + album = albums[i] + albumArtistName = album[0] + albumName = album[2] + albumID = album[3] + albumImage = self._get_icon(album[4], 'album-' + str(albumID)) + self._add_dir(albumName + " - " + albumArtistName, '', MODE_ALBUM, albumImage, albumID, n) + i = i + 1 + xbmcplugin.setContent(self._handle, 'albums') + xbmcplugin.addSortMethod(self._handle, xbmcplugin.SORT_METHOD_ALBUM_IGNORE_THE) + xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg) + + # Add artists to directory + def _add_artists_directory(self, artists): + n = len(artists) + xbmc.log("Found " + str(n) + " artists...") + i = 0 + while i < n: + artist = artists[i] + artistName = artist[0] + artistID = artist[1] + self._add_dir(artistName, '', MODE_ARTIST, self.artistImg, artistID, n) + i = i + 1 + xbmcplugin.setContent(self._handle, 'artists') + xbmcplugin.addSortMethod(self._handle, xbmcplugin.SORT_METHOD_ARTIST_IGNORE_THE) + xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg) + + # Add playlists to directory + def _add_playlists_directory(self, playlists): + n = len(playlists) + xbmc.log("Found " + str(n) + " playlists...") + i = 0 + while i < n: + playlist = playlists[i] + playlistName = playlist[0] + playlistID = playlist[1] + dir = self._add_dir(playlistName, '', MODE_PLAYLIST, self.playlistImg, playlistID, n) + i = i + 1 + xbmcplugin.setContent(self._handle, 'files') + xbmcplugin.addSortMethod(self._handle, xbmcplugin.SORT_METHOD_LABEL) + xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg) + + # 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 } ) + return xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=dir,isFolder=True, totalItems=items) + + def _getSavedSongs(self): + path = os.path.join(cacheDir, 'songs.dmp') + try: + f = open(path, 'rb') + songs = pickle.load(f) + f.close() + except: + songs = [] + pass + return songs + + def _setSavedSongs(self, songs): + try: + # Create the 'data' directory if it doesn't exist. + if not os.path.exists(cacheDir): + os.makedirs(cacheDir) + path = os.path.join(cacheDir, 'songs.dmp') + f = open(path, 'wb') + pickle.dump(songs, f, protocol=pickle.HIGHEST_PROTOCOL) + f.close() + except: + xbmc.log("An error occurred saving songs") + pass + + + +# Parse URL parameters +def get_params(): + param=[] + paramstring=sys.argv[2] + xbmc.log(paramstring) + if len(paramstring)>=2: + params=sys.argv[2] + cleanedparams=params.replace('?','') + if (params[len(params)-1]=='/'): + params=params[0:len(params)-2] + pairsofparams=cleanedparams.split('&') + param={} + for i in range(len(pairsofparams)): + splitparams={} + splitparams=pairsofparams[i].split('=') + if (len(splitparams))==2: + param[splitparams[0]]=splitparams[1] + return param + +# Main +grooveshark = Groveshark(); + +params=get_params() +mode=None +try: mode=int(params["mode"]) +except: pass +id=0 +try: id=int(params["id"]) +except: pass + +# Call function for URL +if mode==None: + grooveshark.categories() + +elif mode==MODE_SEARCH_SONGS: + grooveshark.searchSongs() + +elif mode==MODE_SEARCH_ALBUMS: + grooveshark.searchAlbums() + +elif mode==MODE_SEARCH_ARTISTS: + grooveshark.searchArtists() + +elif mode==MODE_SEARCH_ARTISTS_ALBUMS: + grooveshark.searchArtistsAlbums() + +elif mode==MODE_SEARCH_PLAYLISTS: + grooveshark.searchPlaylists() + +elif mode==MODE_POPULAR_SONGS: + grooveshark.popularSongs() + +elif mode==MODE_ARTIST_POPULAR: + try: name=urllib.unquote_plus(params["name"]) + except: + name = "" + pass + grooveshark.artistPopularSongs(name) + +elif mode==MODE_FAVORITES: + grooveshark.favorites() + +elif mode==MODE_PLAYLISTS: + grooveshark.playlists() + +elif mode==MODE_SONG_PAGE: + try: page=urllib.unquote_plus(params["page"]) + except: pass + try: label=urllib.unquote_plus(params["label"]) + except: pass + grooveshark.songPage(page, label) + +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"]) + except: pass + try: coverart=urllib.unquote_plus(params["coverart"]) + except: pass + song = grooveshark.songItem(id, name, album, artist, coverart) + grooveshark.playSong(song) + +elif mode==MODE_ARTIST: + grooveshark.artist(id) + +elif mode==MODE_ALBUM: + grooveshark.album(id) + +elif mode==MODE_PLAYLIST: + grooveshark.playlist(id) + +elif mode==MODE_FAVORITE: + grooveshark.favorite(id) + +if mode < MODE_SONG: + xbmcplugin.endOfDirectory(int(sys.argv[1]))