Fix directory creation bug.
[clinton/xbmc-groove.git] / default.py
CommitLineData
7ce01be6 1import urllib, sys, os, shutil, re, time, xbmcaddon, xbmcplugin, xbmcgui, xbmc
8817bb2e 2MODE_SEARCH_SONGS = 1
3MODE_SEARCH_ALBUMS = 2
4MODE_SEARCH_ARTISTS = 3
36cc00d7 5MODE_POPULAR_SONGS = 4
8817bb2e 6MODE_FAVORITES = 5
7MODE_PLAYLISTS = 6
8MODE_ALBUM = 7
9MODE_ARTIST = 8
10MODE_PLAYLIST = 9
406ab447 11MODE_SONG = 11
12MODE_FAVORITE = 12
7ea6f166 13
38df1fa5 14ACTION_MOVE_LEFT = 1
7ea6f166 15ACTION_MOVE_UP = 3
16ACTION_MOVE_DOWN = 4
17ACTION_PAGE_UP = 5
18ACTION_PAGE_DOWN = 6
19ACTION_SELECT_ITEM = 7
20ACTION_PREVIOUS_MENU = 10
8817bb2e 21
6ae708d0 22baseDir = os.getcwd()
23resDir = xbmc.translatePath(os.path.join(baseDir, 'resources'))
8817bb2e 24libDir = xbmc.translatePath(os.path.join(resDir, 'lib'))
25imgDir = xbmc.translatePath(os.path.join(resDir, 'img'))
7ce01be6 26cacheDir = os.path.join(xbmc.translatePath('special://masterprofile/addon_data/'), os.path.basename(os.getcwd()))
27thumbDirName = 'thumb'
28thumbDir = os.path.join('special://masterprofile/addon_data/', os.path.basename(os.getcwd()), thumbDirName)
4be42357 29
30baseModeUrl = 'plugin://plugin.audio.groove/'
e278f474 31playlistUrl = baseModeUrl + '?mode=' + str(MODE_PLAYLIST)
4be42357 32playlistsUrl = baseModeUrl + '?mode=' + str(MODE_PLAYLISTS)
33favoritesUrl = baseModeUrl + '?mode=' + str(MODE_FAVORITES)
34
7ce01be6 35thumbDef = os.path.join(imgDir, 'default.tbn')
8817bb2e 36
37sys.path.append (libDir)
7ce01be6 38from GroovesharkAPI import GrooveAPI
39
a3ad8f73 40try:
41 groovesharkApi = GrooveAPI()
7ce01be6 42 if groovesharkApi.pingService() != True:
43 raise StandardError('No Grooveshark service')
a3ad8f73 44except:
45 dialog = xbmcgui.Dialog()
46 dialog.ok('Grooveshark XBMC', 'Unable to connect with Grooveshark.', 'Please try again later')
47 sys.exit(-1)
48
8817bb2e 49
50class _Info:
51 def __init__( self, *args, **kwargs ):
52 self.__dict__.update( kwargs )
e278f474 53
7ce01be6 54
8817bb2e 55class Groveshark:
973b4c6c 56
7ea6f166 57 albumImg = xbmc.translatePath(os.path.join(imgDir, 'album.png'))
58 artistImg = xbmc.translatePath(os.path.join(imgDir, 'artist.png'))
59 favoritesImg = xbmc.translatePath(os.path.join(imgDir, 'favorites.png'))
60 playlistImg = xbmc.translatePath(os.path.join(imgDir, 'playlist.png'))
61 popularSongsImg = xbmc.translatePath(os.path.join(imgDir, 'popularSongs.png'))
62 songImg = xbmc.translatePath(os.path.join(imgDir, 'song.png'))
63 defImg = xbmc.translatePath(os.path.join(imgDir, 'default.tbn'))
2254a6b5 64 fanImg = xbmc.translatePath(os.path.join(baseDir, 'fanart.png'))
8817bb2e 65
2254a6b5 66 settings = xbmcaddon.Addon(id='plugin.audio.groove')
7ce01be6 67 songsearchlimit = int(settings.getSetting('songsearchlimit'))
68 albumsearchlimit = int(settings.getSetting('albumsearchlimit'))
69 artistsearchlimit = int(settings.getSetting('artistsearchlimit'))
2254a6b5 70 username = settings.getSetting('username')
71 password = settings.getSetting('password')
38df1fa5 72 userid = 0
4be42357 73
8817bb2e 74 def __init__( self ):
75 self._handle = int(sys.argv[1])
7ce01be6 76 if os.path.isdir(cacheDir) == False:
77 os.makedirs(cacheDir)
78 xbmc.log("Made " + cacheDir)
79 if os.path.isdir(thumbDir) == False:
3a794693 80 artDir = xbmc.translatePath(thumbDir)
81 os.makedirs(artDir)
82 xbmc.log("Made " + artDir)
b738088f 83
e278f474 84 # Top-level menu
8817bb2e 85 def categories(self):
2254a6b5 86
38df1fa5 87 self.userid = self._get_login()
b738088f 88
89 # Setup
6ae708d0 90 xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
6ae708d0 91
e278f474 92 self._add_dir('Search songs...', '', MODE_SEARCH_SONGS, self.songImg, 0)
93 self._add_dir('Search albums...', '', MODE_SEARCH_ALBUMS, self.albumImg, 0)
94 self._add_dir('Search artists...', '', MODE_SEARCH_ARTISTS, self.artistImg, 0)
36cc00d7 95 self._add_dir('Popular songs', '', MODE_POPULAR_SONGS, self.popularSongsImg, 0)
38df1fa5 96 if (self.userid != 0):
3fcef5ba 97 self._add_dir('Favorites', '', MODE_FAVORITES, self.favoritesImg, 0)
98 self._add_dir('Playlists', '', MODE_PLAYLISTS, self.playlistImg, 0)
e278f474 99
100 # Search for songs
8817bb2e 101 def searchSongs(self):
102 query = self._get_keyboard(default="", heading="Search songs")
7ea6f166 103 if (query != ''):
7ce01be6 104 songs = groovesharkApi.getSongSearchResults(query, limit = self.songsearchlimit)
8817bb2e 105 if (len(songs) > 0):
6ae708d0 106 self._add_songs_directory(songs)
8817bb2e 107 else:
108 dialog = xbmcgui.Dialog()
38df1fa5 109 dialog.ok('Grooveshark XBMC', 'No matching songs.')
8817bb2e 110 self.categories()
7ea6f166 111 else:
112 self.categories()
8817bb2e 113
e278f474 114 # Search for albums
8817bb2e 115 def searchAlbums(self):
116 query = self._get_keyboard(default="", heading="Search albums")
7ea6f166 117 if (query != ''):
7ce01be6 118 albums = groovesharkApi.getAlbumSearchResults(query, limit = self.albumsearchlimit)
8817bb2e 119 if (len(albums) > 0):
6ae708d0 120 self._add_albums_directory(albums)
8817bb2e 121 else:
122 dialog = xbmcgui.Dialog()
38df1fa5 123 dialog.ok('Grooveshark XBMC', 'No matching albums.')
8817bb2e 124 self.categories()
7ea6f166 125 else:
126 self.categories()
8817bb2e 127
e278f474 128 # Search for artists
8817bb2e 129 def searchArtists(self):
130 query = self._get_keyboard(default="", heading="Search artists")
7ea6f166 131 if (query != ''):
7ce01be6 132 artists = groovesharkApi.getArtistSearchResults(query, limit = self.artistsearchlimit)
8817bb2e 133 if (len(artists) > 0):
6ae708d0 134 self._add_artists_directory(artists)
8817bb2e 135 else:
136 dialog = xbmcgui.Dialog()
38df1fa5 137 dialog.ok('Grooveshark XBMC', 'No matching artists.')
8817bb2e 138 self.categories()
7ea6f166 139 else:
140 self.categories()
8817bb2e 141
e278f474 142 # Get my favorites
8817bb2e 143 def favorites(self):
36cc00d7 144 userid = self._get_login()
145 if (userid != 0):
7ce01be6 146 favorites = groovesharkApi.getUserFavoriteSongs()
36cc00d7 147 if (len(favorites) > 0):
7ce01be6 148 self._add_songs_directory(favorites)
36cc00d7 149 else:
150 dialog = xbmcgui.Dialog()
38df1fa5 151 dialog.ok('Grooveshark XBMC', 'You have no favorites.')
36cc00d7 152 self.categories()
8817bb2e 153
e278f474 154 # Get popular songs
36cc00d7 155 def popularSongs(self):
7ce01be6 156 popular = groovesharkApi.getPopularSongsToday(limit = self.songsearchlimit)
8817bb2e 157 if (len(popular) > 0):
6ae708d0 158 self._add_songs_directory(popular)
8817bb2e 159 else:
160 dialog = xbmcgui.Dialog()
38df1fa5 161 dialog.ok('Grooveshark XBMC', 'No popular songs.')
8817bb2e 162 self.categories()
36cc00d7 163
e278f474 164 # Get my playlists
8817bb2e 165 def playlists(self):
166 userid = self._get_login()
167 if (userid != 0):
7ce01be6 168 playlists = groovesharkApi.getUserPlaylists()
8817bb2e 169 if (len(playlists) > 0):
6ae708d0 170 self._add_playlists_directory(playlists)
8817bb2e 171 else:
172 dialog = xbmcgui.Dialog()
38df1fa5 173 dialog.ok('Grooveshark XBMC', 'You have no Grooveshark playlists.')
8817bb2e 174 self.categories()
7ea6f166 175 else:
176 dialog = xbmcgui.Dialog()
38df1fa5 177 dialog.ok('Grooveshark XBMC', 'You must be logged in ', ' to see your Grooveshark playlists.')
7ea6f166 178
e278f474 179 # Make songs a favorite
8817bb2e 180 def favorite(self, songid):
181 userid = self._get_login()
182 if (userid != 0):
406ab447 183 xbmc.log("Favorite song: " + str(songid))
7ce01be6 184 groovesharkApi.addUserFavoriteSong(songID = songid)
38df1fa5 185 xbmc.executebuiltin('XBMC.Notification(Grooveshark XBMC, Added to favorites, 1000, ' + thumbDef + ')')
8817bb2e 186 else:
187 dialog = xbmcgui.Dialog()
38df1fa5 188 dialog.ok('Grooveshark XBMC', 'You must be logged in', 'to add favorites.')
e278f474 189
190 # Show selected album
36cc00d7 191 def album(self, albumid):
7ce01be6 192 album = groovesharkApi.getAlbumSongs(albumid, limit = self.songsearchlimit)
6ae708d0 193 self._add_songs_directory(album)
e278f474 194
195 # Show selected artist
8817bb2e 196 def artist(self, artistid):
7ce01be6 197 albums = groovesharkApi.getArtistAlbums(artistid, limit = self.albumsearchlimit)
7fda21f0 198 self._add_albums_directory(albums)
8817bb2e 199
e278f474 200 # Show selected playlist
7ce01be6 201 def playlist(self, playlistid):
8817bb2e 202 userid = self._get_login()
203 if (userid != 0):
7ce01be6 204 songs = groovesharkApi.getPlaylistSongs(playlistid)
205 self._add_songs_directory(songs)
8817bb2e 206 else:
207 dialog = xbmcgui.Dialog()
38df1fa5 208 dialog.ok('Grooveshark XBMC', 'You must be logged in', 'to get Grooveshark playlists.')
8817bb2e 209
e278f474 210 # Play a song
6ae708d0 211 def playSong(self, item):
7ce01be6 212 songid = item.getProperty('songid')
213 song = groovesharkApi.getSongURLFromSongID(songid)
cbb0985e 214 if song != '':
7ce01be6 215 item.setPath(song)
216 xbmc.log("Playing: " + song)
217 xbmcplugin.setResolvedUrl(handle=int(sys.argv[1]), succeeded=True, listitem=item)
218 else:
cbb0985e 219 xbmc.executebuiltin('XBMC.Notification(Grooveshark XBMC, Unable to play song, 1000, ' + thumbDef + ')')
3fcef5ba 220
e278f474 221 # Make a song directory item
7ce01be6 222 def songItem(self, songid, name, album, artist, coverart):
223 songImg = self._get_icon(coverart, 'song-' + str(songid) + "-image")
224 item = xbmcgui.ListItem(label = artist + " - " + album + " - " + name, thumbnailImage=songImg, iconImage=songImg)
225 item.setInfo( type="music", infoLabels={ "title": name, "album": album, "artist": artist} )
2254a6b5 226 item.setProperty('mimetype', 'audio/mpeg')
227 item.setProperty("IsPlayable", "true")
7ce01be6 228 item.setProperty('songid', str(songid))
229 item.setProperty('coverart', songImg)
230 item.setProperty('title', name)
231 item.setProperty('album', album)
232 item.setProperty('artist', artist)
233
6ae708d0 234 return item
2254a6b5 235
e278f474 236 # Get keyboard input
8817bb2e 237 def _get_keyboard(self, default="", heading="", hidden=False):
3cfead3c 238 kb = xbmc.Keyboard(default, heading, hidden)
239 kb.doModal()
240 if (kb.isConfirmed()):
241 return unicode(kb.getText(), "utf-8")
242 return ''
8817bb2e 243
e278f474 244 # Login to grooveshark
8817bb2e 245 def _get_login(self):
2254a6b5 246 if (self.username == "" or self.password == ""):
8817bb2e 247 dialog = xbmcgui.Dialog()
38df1fa5 248 dialog.ok('Grooveshark XBMC', 'Unable to login.', 'Check username and password in settings.')
8817bb2e 249 return 0
250 else:
38df1fa5 251 if self.userid == 0:
7ce01be6 252 uid = groovesharkApi.login(self.username, self.password)
38df1fa5 253 if (uid != 0):
38df1fa5 254 return uid
8817bb2e 255 else:
256 dialog = xbmcgui.Dialog()
38df1fa5 257 dialog.ok('Grooveshark XBMC', 'Unable to login.', 'Check username and password in settings.')
8817bb2e 258 return 0
259
e278f474 260 # Get a song directory item
6ae708d0 261 def _get_song_item(self, song):
262 name = song[0]
7ce01be6 263 songid = song[1]
264 album = song[2]
265 artist = song[4]
266 coverart = song[6]
267 return self.songItem(songid, name, album, artist, coverart)
6ae708d0 268
269 # File download
7ce01be6 270 def _get_icon(self, url, songid):
271 if url != 'None':
272 localThumb = os.path.join(xbmc.translatePath(os.path.join(thumbDir, str(songid)))) + '.tbn'
273 try:
274 if os.path.isfile(localThumb) == False:
275 loc = urllib.URLopener()
276 loc.retrieve(url, localThumb)
277 except:
278 shutil.copy2(thumbDef, localThumb)
279 return os.path.join(os.path.join(thumbDir, str(songid))) + '.tbn'
280 else:
281 return thumbDef
e278f474 282
283 # Add songs to directory
7ce01be6 284 def _add_songs_directory(self, songs):
6ae708d0 285 n = len(songs)
286 xbmc.log("Found " + str(n) + " songs...")
8817bb2e 287 i = 0
6ae708d0 288 while i < n:
8817bb2e 289 song = songs[i]
6ae708d0 290 item = self._get_song_item(song)
7ce01be6 291 coverart = item.getProperty('coverart')
6ae708d0 292 songname = song[0]
293 songid = song[1]
7ce01be6 294 songalbum = song[2]
295 songartist = song[4]
e278f474 296 u=sys.argv[0]+"?mode="+str(MODE_SONG)+"&name="+urllib.quote_plus(songname)+"&id="+str(songid) \
6ae708d0 297 +"&album="+urllib.quote_plus(songalbum) \
298 +"&artist="+urllib.quote_plus(songartist) \
7ce01be6 299 +"&coverart="+urllib.quote_plus(coverart)
e278f474 300 fav=sys.argv[0]+"?mode="+str(MODE_FAVORITE)+"&name="+urllib.quote_plus(songname)+"&id="+str(songid)
6ae708d0 301 menuItems = []
7ce01be6 302 menuItems.append(("Grooveshark favorite", "XBMC.RunPlugin("+fav+")"))
6ae708d0 303 item.addContextMenuItems(menuItems, replaceItems=False)
e278f474 304 xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=item,isFolder=False, totalItems=n)
8817bb2e 305 i = i + 1
cb06c186 306
8817bb2e 307 xbmcplugin.setContent(self._handle, 'songs')
31731635 308 xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
e278f474 309
310 # Add albums to directory
7ce01be6 311 def _add_albums_directory(self, albums):
31731635 312 n = len(albums)
313 xbmc.log("Found " + str(n) + " albums...")
8817bb2e 314 i = 0
31731635 315 while i < n:
8817bb2e 316 album = albums[i]
317 albumArtistName = album[0]
318 albumName = album[2]
319 albumID = album[3]
2254a6b5 320 albumImage = self._get_icon(album[4], 'album-' + str(albumID))
31731635 321 self._add_dir(albumName + " - " + albumArtistName, '', MODE_ALBUM, albumImage, albumID, n)
8817bb2e 322 i = i + 1
323 xbmcplugin.setContent(self._handle, 'albums')
324 xbmcplugin.addSortMethod(self._handle, xbmcplugin.SORT_METHOD_ALBUM_IGNORE_THE)
31731635 325 xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
e278f474 326
327 # Add artists to directory
6ae708d0 328 def _add_artists_directory(self, artists):
31731635 329 n = len(artists)
330 xbmc.log("Found " + str(n) + " artists...")
8817bb2e 331 i = 0
31731635 332 while i < n:
8817bb2e 333 artist = artists[i]
334 artistName = artist[0]
335 artistID = artist[1]
31731635 336 self._add_dir(artistName, '', MODE_ARTIST, self.artistImg, artistID, n)
8817bb2e 337 i = i + 1
338 xbmcplugin.setContent(self._handle, 'artists')
339 xbmcplugin.addSortMethod(self._handle, xbmcplugin.SORT_METHOD_ARTIST_IGNORE_THE)
31731635 340 xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
e278f474 341
342 # Add playlists to directory
6ae708d0 343 def _add_playlists_directory(self, playlists):
31731635 344 n = len(playlists)
345 xbmc.log("Found " + str(n) + " playlists...")
8817bb2e 346 i = 0
31731635 347 while i < n:
8817bb2e 348 playlist = playlists[i]
349 playlistName = playlist[0]
350 playlistID = playlist[1]
31731635 351 self._add_dir(playlistName, '', MODE_PLAYLIST, self.playlistImg, playlistID, n)
8817bb2e 352 i = i + 1
353 xbmcplugin.setContent(self._handle, 'files')
354 xbmcplugin.addSortMethod(self._handle, xbmcplugin.SORT_METHOD_PLAYLIST_ORDER)
31731635 355 xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
3fcef5ba 356
e278f474 357 # Add whatever directory
31731635 358 def _add_dir(self, name, url, mode, iconimage, id, items=1):
e278f474 359
360 u=sys.argv[0]+"?mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&id="+str(id)
8817bb2e 361 dir=xbmcgui.ListItem(name, iconImage=iconimage, thumbnailImage=iconimage)
b738088f 362 dir.setInfo( type="Music", infoLabels={ "title": name } )
31731635 363 return xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=dir,isFolder=True, totalItems=items)
6ae708d0 364
e278f474 365
366# Parse URL parameters
8817bb2e 367def get_params():
368 param=[]
369 paramstring=sys.argv[2]
e278f474 370 xbmc.log(paramstring)
8817bb2e 371 if len(paramstring)>=2:
372 params=sys.argv[2]
373 cleanedparams=params.replace('?','')
374 if (params[len(params)-1]=='/'):
375 params=params[0:len(params)-2]
376 pairsofparams=cleanedparams.split('&')
377 param={}
378 for i in range(len(pairsofparams)):
379 splitparams={}
380 splitparams=pairsofparams[i].split('=')
381 if (len(splitparams))==2:
382 param[splitparams[0]]=splitparams[1]
8817bb2e 383 return param
384
e278f474 385# Main
8817bb2e 386grooveshark = Groveshark();
e278f474 387
8817bb2e 388params=get_params()
8817bb2e 389mode=None
8817bb2e 390try: mode=int(params["mode"])
391except: pass
7ce01be6 392id=0
393try: id=int(params["id"])
394except: pass
e278f474 395
396# Call function for URL
8817bb2e 397if mode==None:
398 grooveshark.categories()
399
400elif mode==MODE_SEARCH_SONGS:
401 grooveshark.searchSongs()
402
403elif mode==MODE_SEARCH_ALBUMS:
404 grooveshark.searchAlbums()
405
406elif mode==MODE_SEARCH_ARTISTS:
407 grooveshark.searchArtists()
408
36cc00d7 409elif mode==MODE_POPULAR_SONGS:
410 grooveshark.popularSongs()
8817bb2e 411
8817bb2e 412elif mode==MODE_FAVORITES:
413 grooveshark.favorites()
414
e278f474 415elif mode==MODE_PLAYLISTS:
416 grooveshark.playlists()
417
8817bb2e 418elif mode==MODE_SONG:
7ce01be6 419 try: name=urllib.unquote_plus(params["name"])
420 except: pass
8817bb2e 421 try: album=urllib.unquote_plus(params["album"])
422 except: pass
423 try: artist=urllib.unquote_plus(params["artist"])
424 except: pass
7ce01be6 425 try: coverart=urllib.unquote_plus(params["coverart"])
8817bb2e 426 except: pass
7ce01be6 427 song = grooveshark.songItem(id, name, album, artist, coverart)
3fcef5ba 428 grooveshark.playSong(song)
8817bb2e 429
430elif mode==MODE_ARTIST:
4be42357 431 grooveshark.artist(id)
8817bb2e 432
433elif mode==MODE_ALBUM:
4be42357 434 grooveshark.album(id)
8817bb2e 435
436elif mode==MODE_PLAYLIST:
7ce01be6 437 grooveshark.playlist(id)
8817bb2e 438
439elif mode==MODE_FAVORITE:
4be42357 440 grooveshark.favorite(id)
8817bb2e 441
e278f474 442if mode < MODE_SONG:
8817bb2e 443 xbmcplugin.endOfDirectory(int(sys.argv[1]))