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