Version for new API.
authorstephendenham <stephendenham@2dec19e3-eb1d-4749-8193-008c8bba0994>
Fri, 14 Jan 2011 12:10:07 +0000 (12:10 +0000)
committerstephendenham <stephendenham@2dec19e3-eb1d-4749-8193-008c8bba0994>
Fri, 14 Jan 2011 12:10:07 +0000 (12:10 +0000)
git-svn-id: svn://svn.code.sf.net/p/xbmc-groove/code@32 2dec19e3-eb1d-4749-8193-008c8bba0994

.pydevproject [new file with mode: 0644]
addon.xml
changelog.txt
default.py
description.xml
resources/lib/GroovesharkAPI.py
resources/lib/uuid/__init__.py [new file with mode: 0644]

diff --git a/.pydevproject b/.pydevproject
new file mode 100644 (file)
index 0000000..7848f52
--- /dev/null
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<?eclipse-pydev version="1.0"?>
+
+<pydev_project>
+<pydev_property name="org.python.pydev.PYTHON_PROJECT_INTERPRETER">Default</pydev_property>
+<pydev_property name="org.python.pydev.PYTHON_PROJECT_VERSION">python 2.6</pydev_property>
+<pydev_pathproperty name="org.python.pydev.PROJECT_SOURCE_PATH">
+<path>/xbmc-groove</path>
+<path>/xbmc-groove/resources/lib</path>
+<path>/xbmc-groove/resources/lib/simplejson</path>
+</pydev_pathproperty>
+
+</pydev_project>
index fd9e4a8..4cb3f96 100644 (file)
--- a/addon.xml
+++ b/addon.xml
@@ -1,6 +1,6 @@
 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
 <addon id="plugin.audio.groove" name="Grooveshark XBMC"
-       version="0.1.5" provider-name="Stephen Denham">
+       version="0.2.0" provider-name="Stephen Denham">
        <requires>
                <import addon="xbmc.python" version="1.0" />
        </requires>
index 6432b49..622f6dc 100644 (file)
@@ -1,3 +1,7 @@
+0.2.0:
+
+Major changes to use new Grooveshark API.
+
 0.1.5:
 
 Big song listing performance improvement.
index 5c98792..11580b8 100644 (file)
@@ -1,5 +1,4 @@
-import urllib, sys, os, shutil, re, xbmcaddon, xbmcplugin, xbmcgui, xbmc
-
+import urllib, sys, os, shutil, re, time, xbmcaddon, xbmcplugin, xbmcgui, xbmc
 MODE_SEARCH_SONGS = 1
 MODE_SEARCH_ALBUMS = 2
 MODE_SEARCH_ARTISTS = 3
@@ -9,15 +8,8 @@ MODE_PLAYLISTS = 6
 MODE_ALBUM = 7
 MODE_ARTIST = 8
 MODE_PLAYLIST = 9
-MODE_SIMILAR_ARTISTS = 10
 MODE_SONG = 11
 MODE_FAVORITE = 12
-MODE_UNFAVORITE = 13
-MODE_MAKE_PLAYLIST = 14
-MODE_REMOVE_PLAYLIST = 15
-MODE_RENAME_PLAYLIST = 16
-MODE_REMOVE_PLAYLIST_SONG = 17
-MODE_ADD_PLAYLIST_SONG = 18
 
 ACTION_MOVE_LEFT = 1
 ACTION_MOVE_UP = 3
@@ -31,20 +23,24 @@ 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'))
-thumbDir = os.path.join('special://masterprofile/addon_data/', os.path.join(os.path.basename(os.getcwd()), 'thumb'))
+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(os.path.basename(os.getcwd()), 'default.tbn')
-listBackground = os.path.join(imgDir, 'listbackground.png')
+thumbDef = os.path.join(imgDir, 'default.tbn')
 
 sys.path.append (libDir)
-from GrooveAPI import GrooveAPI
+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')
@@ -55,68 +51,7 @@ 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 Groveshark:
     
     albumImg = xbmc.translatePath(os.path.join(imgDir, 'album.png'))
@@ -129,15 +64,22 @@ class Groveshark:
     fanImg = xbmc.translatePath(os.path.join(baseDir, 'fanart.png'))
 
     settings = xbmcaddon.Addon(id='plugin.audio.groove')
-    songsearchlimit = settings.getSetting('songsearchlimit')
-    albumsearchlimit = settings.getSetting('albumsearchlimit')
-    artistsearchlimit = settings.getSetting('artistsearchlimit')
+    songsearchlimit = int(settings.getSetting('songsearchlimit'))
+    albumsearchlimit = int(settings.getSetting('albumsearchlimit'))
+    artistsearchlimit = int(settings.getSetting('artistsearchlimit'))
     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)
+        if os.path.isdir(thumbDir) == False:
+            arttDir = os.path.join(cacheDir, thumbDirName)
+            os.makedirs(arttDir)
+            xbmc.log("Made " + arttDir)
 
     # Top-level menu
     def categories(self):
@@ -146,8 +88,6 @@ class Groveshark:
         
         # Setup
         xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
-        if os.path.isdir(thumbDir) == False:
-            os.makedirs(thumbDir)
         
         self._add_dir('Search songs...', '', MODE_SEARCH_SONGS, self.songImg, 0)
         self._add_dir('Search albums...', '', MODE_SEARCH_ALBUMS, self.albumImg, 0)
@@ -161,8 +101,7 @@ class Groveshark:
     def searchSongs(self):
         query = self._get_keyboard(default="", heading="Search songs")
         if (query != ''):
-            groovesharkApi.setRemoveDuplicates(True)
-            songs = groovesharkApi.searchSongs(query, limit = self.songsearchlimit)
+            songs = groovesharkApi.getSongSearchResults(query, limit = self.songsearchlimit)
             if (len(songs) > 0):
                 self._add_songs_directory(songs)
             else:
@@ -176,7 +115,7 @@ class Groveshark:
     def searchAlbums(self):
         query = self._get_keyboard(default="", heading="Search albums")
         if (query != ''): 
-            albums = groovesharkApi.searchAlbums(query, limit = self.albumsearchlimit)
+            albums = groovesharkApi.getAlbumSearchResults(query, limit = self.albumsearchlimit)
             if (len(albums) > 0):
                 self._add_albums_directory(albums)
             else:
@@ -190,7 +129,7 @@ class Groveshark:
     def searchArtists(self):
         query = self._get_keyboard(default="", heading="Search artists")
         if (query != ''): 
-            artists = groovesharkApi.searchArtists(query, limit = self.artistsearchlimit)
+            artists = groovesharkApi.getArtistSearchResults(query, limit = self.artistsearchlimit)
             if (len(artists) > 0):
                 self._add_artists_directory(artists)
             else:
@@ -204,9 +143,9 @@ class Groveshark:
     def favorites(self):
         userid = self._get_login()
         if (userid != 0):
-            favorites = groovesharkApi.userGetFavoriteSongs(userid)
+            favorites = groovesharkApi.getUserFavoriteSongs()
             if (len(favorites) > 0):
-                self._add_songs_directory(favorites, isFavorites=True)
+                self._add_songs_directory(favorites)
             else:
                 dialog = xbmcgui.Dialog()
                 dialog.ok('Grooveshark XBMC', 'You have no favorites.')
@@ -214,7 +153,7 @@ class Groveshark:
     
     # Get popular songs
     def popularSongs(self):
-        popular = groovesharkApi.popularGetSongs(limit = self.songsearchlimit)
+        popular = groovesharkApi.getPopularSongsToday(limit = self.songsearchlimit)
         if (len(popular) > 0):
             self._add_songs_directory(popular)
         else:
@@ -226,7 +165,7 @@ class Groveshark:
     def playlists(self):
         userid = self._get_login()
         if (userid != 0):
-            playlists = groovesharkApi.userGetPlaylists()
+            playlists = groovesharkApi.getUserPlaylists()
             if (len(playlists) > 0):
                 self._add_playlists_directory(playlists)
             else:
@@ -242,208 +181,56 @@ class Groveshark:
         userid = self._get_login()
         if (userid != 0):
             xbmc.log("Favorite song: " + str(songid))
-            groovesharkApi.favoriteSong(songID = 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.')
-    
-    # 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.unfavoriteSong(songID = 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.')
-
-    # 'Frown' a song
-    def frown(self, songid):
-        userid = self._get_login()
-        if (userid != 0):
-            xbmc.log("Frown song: " + str(songid))
-            if groovesharkApi.radioFrown(songId = songid) != True:
-                xbmc.log("Unable to frown song " + str(songid))
-            else:
-                xbmc.executebuiltin('XBMC.Notification(Grooveshark XBMC, Frowned, 1000, ' + thumbDef + ')')
-        else:
-            dialog = xbmcgui.Dialog()
-            dialog.ok('Grooveshark XBMC', 'You must be logged in', 'to frown a Grooveshark song.')
-
-    # Find similar artists to searched artist
-    def similarArtists(self, artistId):
-        similar = groovesharkApi.artistGetSimilar(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()
-    
-    # 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 != '':
-                groovesharkApi.setRemoveDuplicates(True)
-                album = groovesharkApi.albumGetSongs(albumid, self.songsearchlimit)
-                songids = []
-                for song in album:
-                    songids.append(song[1])
-                if groovesharkApi.playlistCreateUnique(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.userGetPlaylists()
-            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.playlistCreateUnique(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))
-                        ret = groovesharkApi.playlistAddSong(playlistid, songid, 0)
-                        if ret == 0:
-                            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, songpos):
-        dialog = xbmcgui.Dialog()
-        if dialog.yesno('Grooveshark XBMC', 'Delete this song from the Grooveshark playlist?') == True:
-            userid = self._get_login()
-            if (userid != 0):
-                if groovesharkApi.playlistDeleteSong(playlistid, songpos) == 0:
-                    dialog = xbmcgui.Dialog()
-                    dialog.ok('Grooveshark XBMC', 'Failed to remove ', ' song from Grooveshark playlist.')
-                else:
-                    # Refresh to remove item from directory
-                    xbmc.executebuiltin("Container.Refresh(" + 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.')
 
     # Show selected album
     def album(self, albumid):
-        groovesharkApi.setRemoveDuplicates(True)
-        album = groovesharkApi.albumGetSongs(albumId = albumid, limit = self.songsearchlimit)
+        album = groovesharkApi.getAlbumSongs(albumid, limit = self.songsearchlimit)
         self._add_songs_directory(album)
 
     # Show selected artist
     def artist(self, artistid):
-        albums = groovesharkApi.artistGetAlbums(artistId = artistid, limit = self.albumsearchlimit)
+        albums = groovesharkApi.getArtistAlbums(artistid, limit = self.albumsearchlimit)
         self._add_albums_directory(albums, artistid)
     
     # Show selected playlist
-    def playlist(self, playlistid, playlistname):
+    def playlist(self, playlistid):
         userid = self._get_login()
         if (userid != 0):
-            songs = groovesharkApi.playlistGetSongs(playlistId = playlistid, limit = self.songsearchlimit)
-            self._add_songs_directory(songs, playlistid, playlistname)
+            songs = groovesharkApi.getPlaylistSongs(playlistid)
+            self._add_songs_directory(songs)
         else:
             dialog = xbmcgui.Dialog()
             dialog.ok('Grooveshark XBMC', 'You must be logged in', 'to get Grooveshark playlists.')
             
     # Play a song
     def playSong(self, item):
-        url = groovesharkApi.getStreamURL(item.getProperty('id'))
-        item.setPath(url)
-        xbmc.log("Playing: " + url)
-        xbmcplugin.setResolvedUrl(handle=int(sys.argv[1]), succeeded=True, listitem=item)
+        songid = item.getProperty('songid')
+        song = groovesharkApi.getSongURLFromSongID(songid)
+        if os.path.isfile(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, Cannot play song, 1000, ' + thumbDef + ')')
     
     # Make a song directory item
-    def songItem(self, id, name, album, artist, duration, thumb, image):
-        # Only try to get the image
-        if image != "":
-            songImg = self._get_icon(image, 'song-' + str(id) + "-image")
-            songThm = songImg
-        else:
-            songThm = self._get_icon(thumb, 'song-' + str(id) + "-thumb")
-            songImg = songThm
-        item = xbmcgui.ListItem(label = artist + " - " + album + " - " + name, thumbnailImage=songThm, iconImage=songImg)
-        item.setInfo( type="music", infoLabels={ "title": name, "duration": duration, "album": album, "artist": artist} )
+    def songItem(self, songid, name, album, artist, coverart):
+        songImg = self._get_icon(coverart, 'song-' + str(songid) + "-image")
+        item = xbmcgui.ListItem(label = artist + " - " + album + " - " + name, 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('id', str(id))
-        item.setProperty('thumb', songThm)
-        item.setProperty('image', songImg)
+        item.setProperty('songid', str(songid))
+        item.setProperty('coverart', songImg)
+        item.setProperty('title', name)
+        item.setProperty('album', album)
+        item.setProperty('artist', artist)
+        
         return item
     
     # Get keyboard input
@@ -462,7 +249,7 @@ class Groveshark:
             return 0
         else:
             if self.userid == 0:
-                uid = groovesharkApi.loginExt(self.username, self.password)
+                uid = groovesharkApi.login(self.username, self.password)
             if (uid != 0):
                 return uid
             else:
@@ -473,62 +260,46 @@ class Groveshark:
     # Get a song directory item
     def _get_song_item(self, song):
         name = song[0]
-        id = song[1]
-        duration = song[2]
-        album = song[3]
-        artist = song[6]
-        thumb = song[8]
-        image = song[9]
-        return self.songItem(id, name, album, artist, duration, thumb, image)            
+        songid = song[1]
+        album = song[2]
+        artist = song[4]
+        coverart = song[6]
+        return self.songItem(songid, name, album, artist, coverart)            
         
     # File download            
-    def _get_icon(self, url, id):
-        localThumb = os.path.join(xbmc.translatePath(os.path.join(thumbDir, str(id)))) + '.tbn'
-        try:
-            if os.path.isfile(localThumb) == False:
-                xbmc.log('Downloading ' + url + ' to ' + localThumb)
-                loc = urllib.URLopener()
-                loc.retrieve(url, localThumb)
-        except:
-            shutil.copy2(self.defImg, localThumb)
-
-        return os.path.join(os.path.join(thumbDir, str(id))) + '.tbn'
+    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, playlistid=0, playlistname='', isFavorites=False):
+    def _add_songs_directory(self, songs):
         n = len(songs)
         xbmc.log("Found " + str(n) + " songs...")
         i = 0
         while i < n:
             song = songs[i]
             item = self._get_song_item(song)
-            songthumb = item.getProperty('thumb')
-            songimage = item.getProperty('image')
+            coverart = item.getProperty('coverart')
             songname = song[0]
             songid = song[1]
-            songduration = song[2]
-            songalbum = song[3]
-            songartist = song[6]
+            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) \
-            +"&duration="+str(songduration) \
-            +"&thumb="+urllib.quote_plus(songthumb) \
-            +"&image="+urllib.quote_plus(songimage)
+            +"&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 = []
-            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(i+1)+"&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+")"))
+            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=n)
             i = i + 1
@@ -537,7 +308,7 @@ class Groveshark:
         xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
     
     # Add albums to directory
-    def _add_albums_directory(self, albums, artistid=0):
+    def _add_albums_directory(self, albums):
         n = len(albums)
         xbmc.log("Found " + str(n) + " albums...")
         i = 0
@@ -549,8 +320,6 @@ class Groveshark:
             albumImage = self._get_icon(album[4], 'album-' + str(albumID))
             self._add_dir(albumName + " - " + albumArtistName, '', MODE_ALBUM, albumImage, albumID, n)
             i = i + 1
-        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)
@@ -591,19 +360,6 @@ class Groveshark:
         u=sys.argv[0]+"?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 } )
-        
-        # 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+")"))
-        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)
 
 
@@ -633,14 +389,9 @@ params=get_params()
 mode=None
 try: mode=int(params["mode"])
 except: pass
-
-if mode > MODE_FAVORITES:
-    name=None
-    id=None
-    try: name=urllib.unquote_plus(params["name"])
-    except: pass
-    try: id=int(params["id"])
-    except: pass
+id=0
+try: id=int(params["id"])
+except: pass
 
 # Call function for URL
 if mode==None:
@@ -665,17 +416,15 @@ elif mode==MODE_PLAYLISTS:
     grooveshark.playlists()
 
 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"])
+    try: coverart=urllib.unquote_plus(params["coverart"])
     except: pass
-    try: thumb=urllib.unquote_plus(params["thumb"])
-    except: pass
-    try: image=urllib.unquote_plus(params["image"])
-    except: pass
-    song = grooveshark.songItem(id, name, album, artist, duration, thumb, image)
+    song = grooveshark.songItem(id, name, album, artist, coverart)
     grooveshark.playSong(song)
 
 elif mode==MODE_ARTIST:
@@ -685,36 +434,10 @@ elif mode==MODE_ALBUM:
     grooveshark.album(id)
     
 elif mode==MODE_PLAYLIST:
-    grooveshark.playlist(id, name)
+    grooveshark.playlist(id)
     
 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]))
index e2e5048..a8ccf8b 100644 (file)
@@ -18,7 +18,7 @@
        <title>Grooveshark XBMC.</title>
 
        <!-- (required) Major.minor.build -->
-       <version>0.1.5</version>
+       <version>0.2.0</version>
 
        <!--
                (required) author name & email. at least one author name is required
index fbc0389..e36ffc2 100644 (file)
@@ -1,13 +1,13 @@
-import socket, hmac, urllib, urllib2, pprint, md5, uuid, re, hashlib, time, random, os, pickle
+import socket, hmac, urllib, urllib2, pprint, md5, re, sha, time, random, os, pickle, uuid, tempfile
 
 SESSION_EXPIRY = 518400 # 6 days in seconds
 
 # GrooveAPI constants
 THUMB_URL = 'http://beta.grooveshark.com/static/amazonart/'
-THUMB_URL_DEFAULT = 'http://grooveshark.com/webincludes/logo/Grooveshark_Logo_No-Text.png'
 SONG_LIMIT = 25
 ALBUM_LIMIT = 15
 ARTIST_LIMIT = 15
+SONG_SUFFIX = '.mp3'
 
 # GrooveSong constants
 DOMAIN = "grooveshark.com"
@@ -15,7 +15,6 @@ HOME_URL = "http://listen." + DOMAIN
 API_URL = "http://cowbell." + DOMAIN + "/more.php"
 SERVICE_URL = "http://cowbell." + DOMAIN + "/service.php"
 TOKEN_URL = "http://cowbell." + DOMAIN + "/more.php"
-TOKEN_EXPIRY = 1000
 
 CLIENT_NAME = "gslite"
 CLIENT_VERSION = "20101012.37"
@@ -29,13 +28,12 @@ RANDOM_CHARS = "1234567890abcdef"
 # Get a song
 class GrooveSong:
        
-       def __init__(self, cacheDir):
+       def __init__(self):
 
                import simplejson
                self.simplejson = simplejson
-
-               self.cacheDir = cacheDir
-               self._lastTokenTime = 0
+               
+               self.cacheDir = os.path.join(tempfile.gettempdir(), 'groovesong')
                self._lastSessionTime = 0
                self.uuid = self._getUUID()
                
@@ -96,18 +94,16 @@ class GrooveSong:
 
        #  Make a token ready for a request header
        def _getMethodToken(self, method):
-               if (time.time() - self._lastTokenTime) >= TOKEN_EXPIRY:
-                       self._token = self._getCommunicationToken()
-                       if self._token == None:
-                               return None
-                       self._lastTokenTime = time.time()
-                       self._setSavedSession()
+               self._token = self._getCommunicationToken()
+               if self._token == None:
+                       return None
 
                randomChars = ""
                while 6 > len(randomChars):
                        randomChars = randomChars + random.choice(RANDOM_CHARS)
 
-               token = hashlib.sha1(method + ":" + self._token + ":quitStealinMahShit:" + randomChars).hexdigest()
+               token = sha.new(method + ":" + self._token + ":quitStealinMahShit:" + randomChars).hexdigest()
+
                return randomChars + token
 
        # Generate a communication token
@@ -140,7 +136,7 @@ class GrooveSong:
                
        # Generate a secret key from a sessionID
        def _getSecretKey(self, sessionID):
-               return hashlib.md5(sessionID).hexdigest()
+               return md5.new(sessionID).hexdigest()
        
        # Get a session id from some HTML
        def _getSession(self, html):
@@ -159,14 +155,10 @@ class GrooveSong:
                        session = pickle.load(f)
                        self.sessionID = session['sessionID']
                        self._lastSessionTime = session['lastSessionTime']
-                       self._token = session['token']
-                       self._lastTokenTime = session['lastTokenTime']
                        f.close()
                except:
                        self.sessionID = ''
                        self._lastSessionTime = 0
-                       self._token = ''
-                       self._lastTokenTime = 0
                        pass            
 
        def _setSavedSession(self):                     
@@ -176,7 +168,7 @@ class GrooveSong:
                                os.makedirs(self.cacheDir)
                        path = os.path.join(self.cacheDir, 'session.dmp')
                        f = open(path, 'wb')
-                       session = {'sessionID' : self.sessionID, 'lastSessionTime' : self._lastSessionTime, 'token' : self._token, 'lastTokenTime' : self._lastTokenTime}
+                       session = {'sessionID' : self.sessionID, 'lastSessionTime' : self._lastSessionTime}
                        pickle.dump(session, f, protocol=pickle.HIGHEST_PROTOCOL)
                        f.close()
                except:
@@ -192,9 +184,13 @@ class GrooveSong:
                        "country": {"IPR":"1021","ID":"223", "CC1":"0", "CC2":"0", "CC3":"0", "CC4":"2147483648"}
                        }
                response = self._callRemote("getStreamKeyFromSongIDEx", params)
-               self._lastStreamKey = response["result"]["streamKey"]
-               self._lastStreamServer = response["result"]["ip"]
-               self._lastStreamServerID = response["result"]["streamServerID"]
+               try: 
+                       self._lastStreamKey = response["result"]["streamKey"]
+                       self._lastStreamServer = response["result"]["ip"]
+                       self._lastStreamServerID = response["result"]["streamServerID"]
+                       return True
+               except:
+                       return False
                
        # Tells Grooveshark you have downloaded a song
        def _markSongDownloaded(self, songID):
@@ -206,16 +202,18 @@ class GrooveSong:
 
        # Download a song to a temporary file
        def getSongURL(self, songID):
-               filename = os.path.join(self.cacheDir, songID + '.mp3')
+               filename = os.path.join(self.cacheDir, songID + SONG_SUFFIX)
+               print "Caching song " + songID + " to " + filename
                if os.path.isfile(filename) == False:
-                       self._getStreamDetails(songID)
-                       postData = {"streamKey": self._lastStreamKey}
-                       postData = urllib.urlencode(postData)
-                       urllib.FancyURLopener().retrieve( "http://" + self._lastStreamServer + "/stream.php", filename, data=postData)
-                       self._markSongDownloaded(songID)
+                       if self._getStreamDetails(songID) == True:
+                               postData = {"streamKey": self._lastStreamKey}
+                               postData = urllib.urlencode(postData)
+                               urllib.FancyURLopener().retrieve( "http://" + self._lastStreamServer + "/stream.php", filename, data=postData)
+                               self._markSongDownloaded(songID)
+                       else:
+                               return ''
                return filename
 
-
 # Main API
 class GrooveAPI:
 
@@ -225,11 +223,17 @@ class GrooveAPI:
        lastSessionTime = 0
 
        # Constructor
-       def __init__(self, cacheDir):
+       def __init__(self):
+               
                import simplejson
                self.simplejson = simplejson
                socket.setdefaulttimeout(40)
-               self.cacheDir = cacheDir
+               
+               self.cacheDir = os.path.join(tempfile.gettempdir(), 'grooveapi')
+               if os.path.isdir(self.cacheDir) == False:
+                       os.makedirs(self.cacheDir)
+                       print "Made " + self.cacheDir
+
                self._getSavedSession()
                # session ids last 1 week
                if self.sessionID == '' or time.time()- self.lastSessionTime >= SESSION_EXPIRY:
@@ -263,6 +267,7 @@ class GrooveAPI:
                req = urllib2.Request(url)
                response = urllib2.urlopen(req)
                result = response.read()
+               print "Response..."
                pprint.pprint(result)
                response.close()
                try:
@@ -279,7 +284,7 @@ class GrooveAPI:
                return result['result']['sessionID']
        
        def _getSavedSession(self):
-               path = os.path.join(self.cacheDir, 'grooveapi', 'session.dmp')
+               path = os.path.join(self.cacheDir, 'session.dmp')
                try:
                        f = open(path, 'rb')
                        session = pickle.load(f)
@@ -295,11 +300,10 @@ class GrooveAPI:
 
        def _setSavedSession(self):                     
                try:
-                       dir = os.path.join(self.cacheDir, 'grooveapi')
-                       # Create the 'data' directory if it doesn't exist.
-                       if not os.path.exists(dir):
-                               os.makedirs(dir)
-                       path = os.path.join(dir, 'session.dmp')
+                       # Create the directory if it doesn't exist.
+                       if not os.path.exists(self.cacheDir):
+                               os.makedirs(self.cacheDir)
+                       path = os.path.join(self.cacheDir, 'session.dmp')
                        f = open(path, 'wb')
                        session = { 'sessionID' : self.sessionID, 'lastSessionTime' : self.lastSessionTime, 'userID': self.userID}
                        pickle.dump(session, f, protocol=pickle.HIGHEST_PROTOCOL)
@@ -362,12 +366,29 @@ class GrooveAPI:
                        return self._parseSongs(result)
                else:
                        return []
-       
+               
+       # Get artists albums
+       def getArtistAlbums(self, artistID, limit=ALBUM_LIMIT):
+               result = self._callRemote('getArtistAlbums', {'artistID' : artistID})
+               if 'result' in result:
+                       return self._parseAlbums(result, limit)
+               else:
+                       return []
+
+       # Get album songs
+       def getAlbumSongs(self, albumID, limit=SONG_LIMIT):
+               result = self._callRemote('getAlbumSongsEx', {'albumID' : albumID, 'limit' : limit})
+               if 'result' in result:
+                       return self._parseSongs(result)
+               else:
+                       return []
+               
        # Gets the popular songs
        def getPopularSongsToday(self, limit=SONG_LIMIT):
                result = self._callRemote('getPopularSongsToday', {'limit' : limit})
                if 'result' in result:
-                       return self._parseSongs(result)
+                       # Note limit is broken in the Grooveshark getPopularSongsToday method
+                       return self._parseSongs(result, limit)
                else:
                        return []
 
@@ -387,11 +408,10 @@ class GrooveAPI:
                        return False;
                result = self._callRemote('addUserFavoriteSong', {'sessionID' : self.sessionID, 'songID' : songID})
                return result['result']['success']
-               
+
        # Get the url to link to a song on Grooveshark
        def getSongURLFromSongID(self, songID):
-               cacheDir = os.path.join(self.cacheDir, 'groovesong')
-               song = GrooveSong(cacheDir)
+               song = GrooveSong()
                return song.getSongURL(songID)
 
        # Get the url to link to a song on Grooveshark
@@ -402,10 +422,10 @@ class GrooveAPI:
                        if 'CoverArtFilename' in info and info['CoverArtFilename'] != None:
                                info['CoverArtFilename'] = THUMB_URL+info['CoverArtFilename'].encode('ascii', 'ignore')
                        else:
-                               info['CoverArtFilename'] = THUMB_URL_DEFAULT
+                               info['CoverArtFilename'] = 'None'
                        return info
                else:
-                       return ''
+                       return 'None'
 
        # Gets the playlists of the logged-in user
        def getUserPlaylists(self):
@@ -421,7 +441,7 @@ class GrooveAPI:
        def createPlaylist(self, name, songIDs):
                result = self._callRemote('createPlaylist', {'name' : name, 'songIDs' : songIDs, 'sessionID' : self.sessionID})
                if 'result' in result and result['result']['success'] == True: 
-                       return result['result']['PlaylistID']
+                       return result['result']['playlistID']
                elif 'errors' in result:
                        return 0
 
@@ -429,9 +449,9 @@ class GrooveAPI:
        def setPlaylistSongs(self, playlistID, songIDs):
                result = self._callRemote('setPlaylistSongs', {'playlistID' : playlistID, 'songIDs' : songIDs, 'sessionID' : self.sessionID})
                if 'result' in result and result['result']['success'] == True: 
-                       return True;
+                       return True
                else:
-                       return False;
+                       return False
 
        # Gets the songs of a playlist
        def getPlaylistSongs(self, playlistID):
@@ -440,9 +460,17 @@ class GrooveAPI:
                        return self._parseSongs(result)
                else:
                        return []
+
+       # Check the service
+       def pingService(self,):
+               result = self._callRemote('pingService', {});
+               if 'result' in result and result['result'] != '':
+                       return True
+               else:
+                       return False
        
        # Extract song data     
-       def _parseSongs(self, items):
+       def _parseSongs(self, items, limit=0):
                if 'result' in items:
                        i = 0
                        list = []
@@ -455,6 +483,8 @@ class GrooveAPI:
                        else:
                                l = len(items['result'])
                                index = ''
+                       if limit > 0 and l > limit:
+                               l = limit
                        while(i < l):
                                if index == 'songs':
                                        s = items['result'][index][i]
@@ -468,7 +498,7 @@ class GrooveAPI:
                                elif s['CoverArtFilename'] != None:
                                        coverart = THUMB_URL+s['CoverArtFilename'].encode('ascii', 'ignore')
                                else:
-                                       coverart = THUMB_URL_DEFAULT
+                                       coverart = 'None'
                                list.append([s['SongName'].encode('ascii', 'ignore'),\
                                s['SongID'],\
                                s['AlbumName'].encode('ascii', 'ignore'),\
@@ -497,17 +527,24 @@ class GrooveAPI:
                        return []
 
        # Extract album data    
-       def _parseAlbums(self, items):
+       def _parseAlbums(self, items, limit=0):
                if 'result' in items:
                        i = 0
                        list = []
-                       albums = items['result']['albums']
-                       while(i < len(albums)):
+                       try:
+                               albums = items['result']['albums']
+                       except:
+                               res = items['result'][0]
+                               albums = res['albums']
+                       l = len(albums)
+                       if limit > 0 and l > limit:
+                               l = limit
+                       while(i < l):
                                s = albums[i]
                                if 'CoverArtFilename' in s and s['CoverArtFilename'] != None:
                                        coverart = THUMB_URL+s['CoverArtFilename'].encode('ascii', 'ignore')
                                else:
-                                       coverart = THUMB_URL_DEFAULT
+                                       coverart = 'None'
                                list.append([s['ArtistName'].encode('ascii', 'ignore'),\
                                s['ArtistID'],\
                                s['AlbumName'].encode('ascii', 'ignore'),\
@@ -525,24 +562,27 @@ class GrooveAPI:
                        playlists = items['result']
                        while(i < len(playlists)):
                                s = playlists[i]
-                               list.append([s['PlaylistID'],\
-                               s['Name'].encode('ascii', 'ignore')])
+                               list.append([s['Name'].encode('ascii', 'ignore'), s['PlaylistID']])
                                i = i + 1
                        return list
                else:
                        return []
-               
-
 
 # Test
-import sys
-res = []
-groovesharkApi = GrooveAPI('/tmp')
+#import sys
+#res = []
+#groovesharkApi = GrooveAPI()
+#res = groovesharkApi.pingService()
 #res = groovesharkApi.login(sys.argv[1], sys.argv[2])
+#songIDs = ['23404546','23401810','23401157']
+#res = groovesharkApi.createPlaylist("Test")
+#res = groovesharkApi.setPlaylistSongs(res, songIDs)
+#res = groovesharkApi.getPlaylistSongs(42251632)
 #res = groovesharkApi.getSongSearchResults('jimmy jazz', 3)
-#res = groovesharkApi.getPopularSongsToday()
-res = groovesharkApi.getSongURLFromSongID('27425375')
+#res = groovesharkApi.getPopularSongsToday(3)
+#res = groovesharkApi.getSongURLFromSongID('26579347')
 #res = groovesharkApi.getAlbumSearchResults('london calling', 3)
+#res = groovesharkApi.getArtistAlbums('52283')
 #res = groovesharkApi.getArtistSearchResults('the clash', 3)
 #res = groovesharkApi.getUserFavoriteSongs()
 #res = groovesharkApi.getUserPlaylists()
@@ -550,8 +590,5 @@ res = groovesharkApi.getSongURLFromSongID('27425375')
 #res = groovesharkApi.getPlaylistSongs(40902662)
 #res = groovesharkApi.addUserFavoriteSong('27425375')
 #res = groovesharkApi.logout()
-
-pprint.pprint(res)
-
-
-
+#
+#pprint.pprint(res)
diff --git a/resources/lib/uuid/__init__.py b/resources/lib/uuid/__init__.py
new file mode 100644 (file)
index 0000000..75d189f
--- /dev/null
@@ -0,0 +1,477 @@
+r"""UUID objects (universally unique identifiers) according to RFC 4122.
+
+This module provides immutable UUID objects (class UUID) and the functions
+uuid1(), uuid3(), uuid4(), uuid5() for generating version 1, 3, 4, and 5
+UUIDs as specified in RFC 4122.
+
+If all you want is a unique ID, you should probably call uuid1() or uuid4().
+Note that uuid1() may compromise privacy since it creates a UUID containing
+the computer's network address.  uuid4() creates a random UUID.
+
+Typical usage:
+
+    >>> import uuid
+
+    # make a UUID based on the host ID and current time
+    >>> uuid.uuid1()
+    UUID('a8098c1a-f86e-11da-bd1a-00112444be1e')
+
+    # make a UUID using an MD5 hash of a namespace UUID and a name
+    >>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')
+    UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e')
+
+    # make a random UUID
+    >>> uuid.uuid4()
+    UUID('16fd2706-8baf-433b-82eb-8c7fada847da')
+
+    # make a UUID using a SHA-1 hash of a namespace UUID and a name
+    >>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
+    UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d')
+
+    # make a UUID from a string of hex digits (braces and hyphens ignored)
+    >>> x = uuid.UUID('{00010203-0405-0607-0809-0a0b0c0d0e0f}')
+
+    # convert a UUID to a string of hex digits in standard form
+    >>> str(x)
+    '00010203-0405-0607-0809-0a0b0c0d0e0f'
+
+    # get the raw 16 bytes of the UUID
+    >>> x.bytes
+    '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'
+
+    # make a UUID from a 16-byte string
+    >>> uuid.UUID(bytes=x.bytes)
+    UUID('00010203-0405-0607-0809-0a0b0c0d0e0f')
+
+This module works with Python 2.3 or higher."""
+
+__author__ = 'Ka-Ping Yee <ping@zesty.ca>'
+__date__ = '$Date: 2006/06/12 23:15:40 $'.split()[1].replace('/', '-')
+__version__ = '$Revision: 1.30 $'.split()[1]
+
+RESERVED_NCS, RFC_4122, RESERVED_MICROSOFT, RESERVED_FUTURE = [
+    'reserved for NCS compatibility', 'specified in RFC 4122',
+    'reserved for Microsoft compatibility', 'reserved for future definition']
+
+class UUID(object):
+    """Instances of the UUID class represent UUIDs as specified in RFC 4122.
+    UUID objects are immutable, hashable, and usable as dictionary keys.
+    Converting a UUID to a string with str() yields something in the form
+    '12345678-1234-1234-1234-123456789abc'.  The UUID constructor accepts
+    four possible forms: a similar string of hexadecimal digits, or a
+    string of 16 raw bytes as an argument named 'bytes', or a tuple of
+    six integer fields (with 32-bit, 16-bit, 16-bit, 8-bit, 8-bit, and
+    48-bit values respectively) as an argument named 'fields', or a single
+    128-bit integer as an argument named 'int'.
+    
+    UUIDs have these read-only attributes:
+
+        bytes       the UUID as a 16-byte string
+
+        fields      a tuple of the six integer fields of the UUID,
+                    which are also available as six individual attributes
+                    and two derived attributes:
+
+            time_low                the first 32 bits of the UUID
+            time_mid                the next 16 bits of the UUID
+            time_hi_version         the next 16 bits of the UUID
+            clock_seq_hi_variant    the next 8 bits of the UUID
+            clock_seq_low           the next 8 bits of the UUID
+            node                    the last 48 bits of the UUID
+
+            time                    the 60-bit timestamp
+            clock_seq               the 14-bit sequence number
+
+        hex         the UUID as a 32-character hexadecimal string
+
+        int         the UUID as a 128-bit integer
+
+        urn         the UUID as a URN as specified in RFC 4122
+
+        variant     the UUID variant (one of the constants RESERVED_NCS,
+                    RFC_4122, RESERVED_MICROSOFT, or RESERVED_FUTURE)
+
+        version     the UUID version number (1 through 5, meaningful only
+                    when the variant is RFC_4122)
+    """
+
+    def __init__(self, hex=None, bytes=None, fields=None, int=None,
+                       version=None):
+        r"""Create a UUID from either a string of 32 hexadecimal digits,
+        a string of 16 bytes as the 'bytes' argument, a tuple of six
+        integers (32-bit time_low, 16-bit time_mid, 16-bit time_hi_version,
+        8-bit clock_seq_hi_variant, 8-bit clock_seq_low, 48-bit node) as
+        the 'fields' argument, or a single 128-bit integer as the 'int'
+        argument.  When a string of hex digits is given, curly braces,
+        hyphens, and a URN prefix are all optional.  For example, these
+        expressions all yield the same UUID:
+
+        UUID('{12345678-1234-5678-1234-567812345678}')
+        UUID('12345678123456781234567812345678')
+        UUID('urn:uuid:12345678-1234-5678-1234-567812345678')
+        UUID(bytes='\x12\x34\x56\x78'*4)
+        UUID(fields=(0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678))
+        UUID(int=0x12345678123456781234567812345678)
+
+        Exactly one of 'hex', 'bytes', 'fields', or 'int' must be given.
+        The 'version' argument is optional; if given, the resulting UUID
+        will have its variant and version number set according to RFC 4122,
+        overriding bits in the given 'hex', 'bytes', 'fields', or 'int'.
+        """
+
+        if [hex, bytes, fields, int].count(None) != 3:
+            raise TypeError('need just one of hex, bytes, fields, or int')
+        if hex is not None:
+            hex = hex.replace('urn:', '').replace('uuid:', '')
+            hex = hex.strip('{}').replace('-', '')
+            if len(hex) != 32:
+                raise ValueError('badly formed hexadecimal UUID string')
+            int = long(hex, 16)
+        if bytes is not None:
+            if len(bytes) != 16:
+                raise ValueError('bytes is not a 16-char string')
+            int = long(('%02x'*16) % tuple(map(ord, bytes)), 16)
+        if fields is not None:
+            if len(fields) != 6:
+                raise ValueError('fields is not a 6-tuple')
+            (time_low, time_mid, time_hi_version,
+             clock_seq_hi_variant, clock_seq_low, node) = fields
+            if not 0 <= time_low < 1<<32L:
+                raise ValueError('field 1 out of range (need a 32-bit value)')
+            if not 0 <= time_mid < 1<<16L:
+                raise ValueError('field 2 out of range (need a 16-bit value)')
+            if not 0 <= time_hi_version < 1<<16L:
+                raise ValueError('field 3 out of range (need a 16-bit value)')
+            if not 0 <= clock_seq_hi_variant < 1<<8L:
+                raise ValueError('field 4 out of range (need an 8-bit value)')
+            if not 0 <= clock_seq_low < 1<<8L:
+                raise ValueError('field 5 out of range (need an 8-bit value)')
+            if not 0 <= node < 1<<48L:
+                raise ValueError('field 6 out of range (need a 48-bit value)')
+            clock_seq = (clock_seq_hi_variant << 8L) | clock_seq_low
+            int = ((time_low << 96L) | (time_mid << 80L) |
+                   (time_hi_version << 64L) | (clock_seq << 48L) | node)
+        if int is not None:
+            if not 0 <= int < 1<<128L:
+                raise ValueError('int is out of range (need a 128-bit value)')
+        if version is not None:
+            if not 1 <= version <= 5:
+                raise ValueError('illegal version number')
+            # Set the variant to RFC 4122.
+            int &= ~(0xc000 << 48L)
+            int |= 0x8000 << 48L
+            # Set the version number.
+            int &= ~(0xf000 << 64L)
+            int |= version << 76L
+        self.__dict__['int'] = int
+
+    def __cmp__(self, other):
+        if isinstance(other, UUID):
+            return cmp(self.int, other.int)
+        return NotImplemented
+
+    def __hash__(self):
+        return hash(self.int)
+
+    def __int__(self):
+        return self.int
+
+    def __repr__(self):
+        return 'UUID(%r)' % str(self)
+
+    def __setattr__(self, name, value):
+        raise TypeError('UUID objects are immutable')
+
+    def __str__(self):
+        hex = '%032x' % self.int
+        return '%s-%s-%s-%s-%s' % (
+            hex[:8], hex[8:12], hex[12:16], hex[16:20], hex[20:])
+
+    def get_bytes(self):
+        bytes = ''
+        for shift in range(0, 128, 8):
+            bytes = chr((self.int >> shift) & 0xff) + bytes
+        return bytes
+
+    bytes = property(get_bytes)
+
+    def get_fields(self):
+        return (self.time_low, self.time_mid, self.time_hi_version,
+                self.clock_seq_hi_variant, self.clock_seq_low, self.node)
+
+    fields = property(get_fields)
+
+    def get_time_low(self):
+        return self.int >> 96L
+   
+    time_low = property(get_time_low)
+
+    def get_time_mid(self):
+        return (self.int >> 80L) & 0xffff
+
+    time_mid = property(get_time_mid)
+
+    def get_time_hi_version(self):
+        return (self.int >> 64L) & 0xffff
+    
+    time_hi_version = property(get_time_hi_version)
+
+    def get_clock_seq_hi_variant(self):
+        return (self.int >> 56L) & 0xff
+
+    clock_seq_hi_variant = property(get_clock_seq_hi_variant)
+    
+    def get_clock_seq_low(self):
+        return (self.int >> 48L) & 0xff
+
+    clock_seq_low = property(get_clock_seq_low)
+
+    def get_time(self):
+        return (((self.time_hi_version & 0x0fffL) << 48L) |
+                (self.time_mid << 32L) | self.time_low)
+
+    time = property(get_time)
+
+    def get_clock_seq(self):
+        return (((self.clock_seq_hi_variant & 0x3fL) << 8L) |
+                self.clock_seq_low)
+
+    clock_seq = property(get_clock_seq)
+    
+    def get_node(self):
+        return self.int & 0xffffffffffff
+
+    node = property(get_node)
+
+    def get_hex(self):
+        return '%032x' % self.int
+
+    hex = property(get_hex)
+
+    def get_urn(self):
+        return 'urn:uuid:' + str(self)
+
+    urn = property(get_urn)
+
+    def get_variant(self):
+        if not self.int & (0x8000 << 48L):
+            return RESERVED_NCS
+        elif not self.int & (0x4000 << 48L):
+            return RFC_4122
+        elif not self.int & (0x2000 << 48L):
+            return RESERVED_MICROSOFT
+        else:
+            return RESERVED_FUTURE
+
+    variant = property(get_variant)
+
+    def get_version(self):
+        # The version bits are only meaningful for RFC 4122 UUIDs.
+        if self.variant == RFC_4122:
+            return int((self.int >> 76L) & 0xf)
+
+    version = property(get_version)
+
+def _ifconfig_getnode():
+    """Get the hardware address on Unix by running ifconfig."""
+    import os
+    for dir in ['', '/sbin/', '/usr/sbin']:
+        try:
+            pipe = os.popen(os.path.join(dir, 'ifconfig'))
+        except IOError:
+            continue
+        for line in pipe:
+            words = line.lower().split()
+            for i in range(len(words)):
+                if words[i] in ['hwaddr', 'ether']:
+                    return int(words[i + 1].replace(':', ''), 16)
+
+def _ipconfig_getnode():
+    """Get the hardware address on Windows by running ipconfig.exe."""
+    import os, re
+    dirs = ['', r'c:\windows\system32', r'c:\winnt\system32']
+    try:
+        import ctypes
+        buffer = ctypes.create_string_buffer(300)
+        ctypes.windll.kernel32.GetSystemDirectoryA(buffer, 300)
+        dirs.insert(0, buffer.value.decode('mbcs'))
+    except:
+        pass
+    for dir in dirs:
+        try:
+            pipe = os.popen(os.path.join(dir, 'ipconfig') + ' /all')
+        except IOError:
+            continue
+        for line in pipe:
+            value = line.split(':')[-1].strip().lower()
+            if re.match('([0-9a-f][0-9a-f]-){5}[0-9a-f][0-9a-f]', value):
+                return int(value.replace('-', ''), 16)
+
+def _netbios_getnode():
+    """Get the hardware address on Windows using NetBIOS calls.
+    See http://support.microsoft.com/kb/118623 for details."""
+    import win32wnet, netbios
+    ncb = netbios.NCB()
+    ncb.Command = netbios.NCBENUM
+    ncb.Buffer = adapters = netbios.LANA_ENUM()
+    adapters._pack()
+    if win32wnet.Netbios(ncb) != 0:
+        return
+    adapters._unpack()
+    for i in range(adapters.length):
+        ncb.Reset()
+        ncb.Command = netbios.NCBRESET
+        ncb.Lana_num = ord(adapters.lana[i])
+        if win32wnet.Netbios(ncb) != 0:
+            continue
+        ncb.Reset()
+        ncb.Command = netbios.NCBASTAT
+        ncb.Lana_num = ord(adapters.lana[i])
+        ncb.Callname = '*'.ljust(16)
+        ncb.Buffer = status = netbios.ADAPTER_STATUS()
+        if win32wnet.Netbios(ncb) != 0:
+            continue
+        status._unpack()
+        bytes = map(ord, status.adapter_address)
+        return ((bytes[0]<<40L) + (bytes[1]<<32L) + (bytes[2]<<24L) +
+                (bytes[3]<<16L) + (bytes[4]<<8L) + bytes[5])
+
+# Thanks to Thomas Heller for ctypes and for his help with its use here.
+
+# If ctypes is available, use it to find system routines for UUID generation.
+_uuid_generate_random = _uuid_generate_time = _UuidCreate = None
+try:
+    import ctypes, ctypes.util
+    _buffer = ctypes.create_string_buffer(16)
+
+    # The uuid_generate_* routines are provided by libuuid on at least
+    # Linux and FreeBSD, and provided by libc on Mac OS X.
+    for libname in ['uuid', 'c']:
+        try:
+            lib = ctypes.CDLL(ctypes.util.find_library(libname))
+        except:
+            continue
+        if hasattr(lib, 'uuid_generate_random'):
+            _uuid_generate_random = lib.uuid_generate_random
+        if hasattr(lib, 'uuid_generate_time'):
+            _uuid_generate_time = lib.uuid_generate_time
+
+    # On Windows prior to 2000, UuidCreate gives a UUID containing the
+    # hardware address.  On Windows 2000 and later, UuidCreate makes a
+    # random UUID and UuidCreateSequential gives a UUID containing the
+    # hardware address.  These routines are provided by the RPC runtime.
+    try:
+        lib = ctypes.windll.rpcrt4
+    except:
+        lib = None
+    _UuidCreate = getattr(lib, 'UuidCreateSequential',
+                          getattr(lib, 'UuidCreate', None))
+except:
+    pass
+
+def _unixdll_getnode():
+    """Get the hardware address on Unix using ctypes."""
+    _uuid_generate_time(_buffer)
+    return UUID(bytes=_buffer.raw).node
+
+def _windll_getnode():
+    """Get the hardware address on Windows using ctypes."""
+    if _UuidCreate(_buffer) == 0:
+        return UUID(bytes=_buffer.raw).node
+
+def _random_getnode():
+    """Get a random node ID, with eighth bit set as suggested by RFC 4122."""
+    import random
+    return random.randrange(0, 1<<48L) | 0x010000000000L
+
+_node = None
+
+def getnode():
+    """Get the hardware address as a 48-bit integer.  The first time this
+    runs, it may launch a separate program, which could be quite slow.  If
+    all attempts to obtain the hardware address fail, we choose a random
+    48-bit number with its eighth bit set to 1 as recommended in RFC 4122."""
+
+    global _node
+    if _node is not None:
+        return _node
+
+    import sys
+    if sys.platform == 'win32':
+        getters = [_windll_getnode, _netbios_getnode, _ipconfig_getnode]
+    else:
+        getters = [_unixdll_getnode, _ifconfig_getnode]
+
+    for getter in getters + [_random_getnode]:
+        try:
+            _node = getter()
+        except:
+            continue
+        if _node is not None:
+            return _node
+
+def uuid1(node=None, clock_seq=None):
+    """Generate a UUID from a host ID, sequence number, and the current time.
+    If 'node' is not given, getnode() is used to obtain the hardware
+    address.  If 'clock_seq' is given, it is used as the sequence number;
+    otherwise a random 14-bit sequence number is chosen."""
+
+    # When the system provides a version-1 UUID generator, use it (but don't
+    # use UuidCreate here because its UUIDs don't conform to RFC 4122).
+    if _uuid_generate_time and node is clock_seq is None:
+        _uuid_generate_time(_buffer)
+        return UUID(bytes=_buffer.raw)
+
+    import time
+    nanoseconds = int(time.time() * 1e9)
+    # 0x01b21dd213814000 is the number of 100-ns intervals between the
+    # UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00.
+    timestamp = int(nanoseconds/100) + 0x01b21dd213814000L
+    if clock_seq is None:
+        import random
+        clock_seq = random.randrange(1<<14L) # instead of stable storage
+    time_low = timestamp & 0xffffffffL
+    time_mid = (timestamp >> 32L) & 0xffffL
+    time_hi_version = (timestamp >> 48L) & 0x0fffL
+    clock_seq_low = clock_seq & 0xffL
+    clock_seq_hi_variant = (clock_seq >> 8L) & 0x3fL
+    if node is None:
+        node = getnode()
+    return UUID(fields=(time_low, time_mid, time_hi_version,
+                        clock_seq_hi_variant, clock_seq_low, node), version=1)
+
+def uuid3(namespace, name):
+    """Generate a UUID from the MD5 hash of a namespace UUID and a name."""
+    import md5
+    hash = md5.md5(namespace.bytes + name).digest()
+    return UUID(bytes=hash[:16], version=3)
+
+def uuid4():
+    """Generate a random UUID."""
+
+    # When the system provides a version-4 UUID generator, use it.
+    if _uuid_generate_random:
+        _uuid_generate_random(_buffer)
+        return UUID(bytes=_buffer.raw)
+
+    # Otherwise, get randomness from urandom or the 'random' module.
+    try:
+        import os
+        return UUID(bytes=os.urandom(16), version=4)
+    except:
+        import random
+        bytes = [chr(random.randrange(256)) for i in range(16)]
+        return UUID(bytes=bytes, version=4)
+
+def uuid5(namespace, name):
+    """Generate a UUID from the SHA-1 hash of a namespace UUID and a name."""
+    import sha
+    hash = sha.sha(namespace.bytes + name).digest()
+    return UUID(bytes=hash[:16], version=5)
+
+# The following standard UUIDs are for use with uuid3() or uuid5().
+
+NAMESPACE_DNS = UUID('6ba7b810-9dad-11d1-80b4-00c04fd430c8')
+NAMESPACE_URL = UUID('6ba7b811-9dad-11d1-80b4-00c04fd430c8')
+NAMESPACE_OID = UUID('6ba7b812-9dad-11d1-80b4-00c04fd430c8')
+NAMESPACE_X500 = UUID('6ba7b814-9dad-11d1-80b4-00c04fd430c8')