1 # Copyright 2011 Stephen Denham
3 # This file is part of xbmc-groove.
5 # xbmc-groove is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
10 # xbmc-groove is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with xbmc-groove. If not, see <http://www.gnu.org/licenses/>.
19 import urllib
, urllib2
, sys
, os
, shutil
, re
, pickle
, time
, traceback
, xbmcaddon
, xbmcplugin
, xbmcgui
, xbmc
21 __addon__
= xbmcaddon
.Addon('plugin.audio.groove')
22 __addonname__
= __addon__
.getAddonInfo('name')
23 __cwd__
= __addon__
.getAddonInfo('path')
24 __author__
= __addon__
.getAddonInfo('author')
25 __version__
= __addon__
.getAddonInfo('version')
26 __language__
= __addon__
.getLocalizedString
27 __debugging__
= __addon__
.getSetting('debug')
30 MODE_SEARCH_ALBUMS
= 2
31 MODE_SEARCH_ARTISTS
= 3
32 MODE_SEARCH_ARTISTS_ALBUMS
= 4
33 MODE_SEARCH_PLAYLISTS
= 5
34 MODE_ARTIST_POPULAR
= 6
35 MODE_POPULAR_SONGS
= 7
42 MODE_SIMILAR_ARTISTS
= 14
46 MODE_MAKE_PLAYLIST
= 18
47 MODE_REMOVE_PLAYLIST
= 19
48 MODE_RENAME_PLAYLIST
= 20
49 MODE_REMOVE_PLAYLIST_SONG
= 21
50 MODE_ADD_PLAYLIST_SONG
= 22
57 ACTION_SELECT_ITEM
= 7
58 ACTION_PREVIOUS_MENU
= 10
60 # Formats for track labels
61 ARTIST_ALBUM_NAME_LABEL
= 0
62 NAME_ALBUM_ARTIST_LABEL
= 1
64 # Stream marking time (seconds)
65 STREAM_MARKING_TIME
= 30
71 player
= xbmc
.Player()
75 resDir
= xbmc
.translatePath(os
.path
.join(baseDir
, 'resources'))
76 libDir
= xbmc
.translatePath(os
.path
.join(resDir
, 'lib'))
77 imgDir
= xbmc
.translatePath(os
.path
.join(resDir
, 'img'))
78 cacheDir
= os
.path
.join(xbmc
.translatePath('special://masterprofile/addon_data/'), os
.path
.basename(baseDir
))
79 tempDir
= xbmc
.translatePath('special://temp')
80 thumbDirName
= 'thumb'
81 thumbDir
= os
.path
.join(xbmc
.translatePath('special://masterprofile/addon_data/'), os
.path
.basename(baseDir
), thumbDirName
)
83 baseModeUrl
= 'plugin://plugin.audio.groove/'
84 playlistUrl
= baseModeUrl
+ '?mode=' + str(MODE_PLAYLIST
)
85 playlistsUrl
= baseModeUrl
+ '?mode=' + str(MODE_PLAYLISTS
)
86 favoritesUrl
= baseModeUrl
+ '?mode=' + str(MODE_FAVORITES
)
88 searchArtistsAlbumsName
= __language__(30006)
90 thumbDef
= os
.path
.join(imgDir
, 'default.tbn')
91 listBackground
= os
.path
.join(imgDir
, 'listbackground.png')
93 sys
.path
.append (libDir
)
94 from GroovesharkAPI
import GrooveAPI
95 from threading
import Event
, Thread
97 if __debugging__
== 'true':
100 __debugging__
= False
103 groovesharkApi
= GrooveAPI(__debugging__
, tempDir
)
104 if groovesharkApi
.pingService() != True:
105 raise StandardError(__language__(30007))
107 print "Exception on initialisation"
109 traceback
.print_exc()
111 dialog
= xbmcgui
.Dialog(__language__(30008),__language__(30009),__language__(30010))
112 dialog
.ok(__language__(30008),__language__(30009))
115 # Mark song as playing or played
116 def markSong(songid
, duration
, streamKey
, streamServerID
):
120 if player
.isPlayingAudio():
121 tNow
= player
.getTime()
122 if tNow
>= STREAM_MARKING_TIME
and songMarkTime
== 0:
123 groovesharkApi
.markStreamKeyOver30Secs(streamKey
, streamServerID
)
125 elif duration
> tNow
and duration
- tNow
< 2 and songMarkTime
>= STREAM_MARKING_TIME
:
128 groovesharkApi
.markSongComplete(songid
, streamKey
, streamServerID
)
134 def __init__( self
, *args
, **kwargs
):
135 self
.__dict
__.update( kwargs
)
137 # Window dialog to select a grooveshark playlist
138 class GroovesharkPlaylistSelect(xbmcgui
.WindowDialog
):
140 def __init__(self
, items
=[]):
141 gap
= int(self
.getHeight()/100)
142 w
= int(self
.getWidth()*0.5)
143 h
= self
.getHeight()-30*gap
145 rh
= self
.getHeight()
149 self
.imgBg
= xbmcgui
.ControlImage(x
+gap
, 5*gap
+y
, w
-2*gap
, h
-5*gap
, listBackground
)
150 self
.addControl(self
.imgBg
)
152 self
.playlistControl
= xbmcgui
.ControlList(2*gap
+x
, y
+3*gap
+30, w
-4*gap
, h
-10*gap
, textColor
='0xFFFFFFFF', selectedColor
='0xFFFF4242')
153 self
.playlistControl
.setItemHeight(50)
154 self
.addControl(self
.playlistControl
)
157 self
.isSelecting
= False
160 for playlist
in items
:
161 listitems
.append(xbmcgui
.ListItem(playlist
[0]))
162 listitems
.append(xbmcgui
.ListItem(__language__(30011)))
163 self
.playlistControl
.addItems(listitems
)
164 self
.setFocus(self
.playlistControl
)
165 self
.playlistControl
.selectItem(0)
166 item
= self
.playlistControl
.getListItem(self
.lastPos
)
169 # Highlight selected item
170 def setHighlight(self
):
174 self
.isSelecting
= True
176 pos
= self
.playlistControl
.getSelectedPosition()
178 item
= self
.playlistControl
.getListItem(self
.lastPos
)
180 item
= self
.playlistControl
.getListItem(pos
)
183 self
.isSelecting
= False
186 def onControl(self
, control
):
187 if control
== self
.playlistControl
:
188 self
.selected
= self
.playlistControl
.getSelectedPosition()
191 # Action - close or up/down
192 def onAction(self
, action
):
193 if action
== ACTION_PREVIOUS_MENU
:
196 elif action
== ACTION_MOVE_UP
or action
== ACTION_MOVE_DOWN
or action
== ACTION_PAGE_UP
or action
== ACTION_PAGE_DOWN
== 6:
197 self
.setFocus(self
.playlistControl
)
201 class PlayTimer(Thread
):
202 # interval -- floating point number specifying the number of seconds to wait before executing function
203 # function -- the function (or callable object) to be executed
205 # iterations -- integer specifying the number of iterations to perform
206 # args -- list of positional arguments passed to function
207 # kwargs -- dictionary of keyword arguments passed to function
209 def __init__(self
, interval
, function
, iterations
=0, args
=[], kwargs
={}):
210 Thread
.__init
__(self
)
211 self
.interval
= interval
212 self
.function
= function
213 self
.iterations
= iterations
216 self
.finished
= Event()
220 while not self
.finished
.isSet() and (self
.iterations
<= 0 or count
< self
.iterations
):
221 self
.finished
.wait(self
.interval
)
222 if not self
.finished
.isSet():
223 self
.function(*self
.args
, **self
.kwargs
)
229 def setIterations(self
, iterations
):
230 self
.iterations
= iterations
234 return self
.iterations
* self
.interval
239 albumImg
= xbmc
.translatePath(os
.path
.join(imgDir
, 'album.png'))
240 artistImg
= xbmc
.translatePath(os
.path
.join(imgDir
, 'artist.png'))
241 artistsAlbumsImg
= xbmc
.translatePath(os
.path
.join(imgDir
, 'artistsalbums.png'))
242 favoritesImg
= xbmc
.translatePath(os
.path
.join(imgDir
, 'favorites.png'))
243 playlistImg
= xbmc
.translatePath(os
.path
.join(imgDir
, 'playlist.png'))
244 usersplaylistsImg
= xbmc
.translatePath(os
.path
.join(imgDir
, 'usersplaylists.png'))
245 popularSongsImg
= xbmc
.translatePath(os
.path
.join(imgDir
, 'popularSongs.png'))
246 popularSongsArtistImg
= xbmc
.translatePath(os
.path
.join(imgDir
, 'popularSongsArtist.png'))
247 songImg
= xbmc
.translatePath(os
.path
.join(imgDir
, 'song.png'))
248 defImg
= xbmc
.translatePath(os
.path
.join(imgDir
, 'default.tbn'))
249 fanImg
= xbmc
.translatePath(os
.path
.join(baseDir
, 'fanart.jpg'))
251 settings
= xbmcaddon
.Addon(id='plugin.audio.groove')
252 songsearchlimit
= int(settings
.getSetting('songsearchlimit'))
253 albumsearchlimit
= int(settings
.getSetting('albumsearchlimit'))
254 artistsearchlimit
= int(settings
.getSetting('artistsearchlimit'))
255 songspagelimit
= int(settings
.getSetting('songspagelimit'))
256 username
= settings
.getSetting('username')
257 password
= settings
.getSetting('password')
261 def __init__( self
):
262 self
._handle
= int(sys
.argv
[1])
263 if os
.path
.isdir(cacheDir
) == False:
264 os
.makedirs(cacheDir
)
266 xbmc
.log(__language__(30012) + " " + cacheDir
)
267 artDir
= xbmc
.translatePath(thumbDir
)
268 if os
.path
.isdir(artDir
) == False:
271 xbmc
.log(__language__(30012) + " " + artDir
)
274 def categories(self
):
276 self
.userid
= self
._get
_login
()
279 xbmcplugin
.setPluginFanart(int(sys
.argv
[1]), self
.fanImg
)
281 self
._add
_dir
(__language__(30013), '', MODE_SEARCH_SONGS
, self
.songImg
, 0)
282 self
._add
_dir
(__language__(30014), '', MODE_SEARCH_ALBUMS
, self
.albumImg
, 0)
283 self
._add
_dir
(__language__(30015), '', MODE_SEARCH_ARTISTS
, self
.artistImg
, 0)
284 self
._add
_dir
(searchArtistsAlbumsName
, '', MODE_SEARCH_ARTISTS_ALBUMS
, self
.artistsAlbumsImg
, 0)
285 # Not supported by key
286 #self._add_dir("Search for user's playlists...", '', MODE_SEARCH_PLAYLISTS, self.usersplaylistsImg, 0)
287 self
._add
_dir
(__language__(30016), '', MODE_ARTIST_POPULAR
, self
.popularSongsArtistImg
, 0)
288 self
._add
_dir
(__language__(30017), '', MODE_POPULAR_SONGS
, self
.popularSongsImg
, 0)
289 if (self
.userid
!= 0):
290 self
._add
_dir
(__language__(30018), '', MODE_FAVORITES
, self
.favoritesImg
, 0)
291 self
._add
_dir
(__language__(30019), '', MODE_PLAYLISTS
, self
.playlistImg
, 0)
294 def searchSongs(self
):
295 query
= self
._get
_keyboard
(default
="", heading
=__language__(30020))
297 songs
= groovesharkApi
.getSongSearchResults(query
, limit
= self
.songsearchlimit
)
299 self
._add
_songs
_directory
(songs
)
301 dialog
= xbmcgui
.Dialog()
302 dialog
.ok(__language__(30008), __language__(30021))
308 def searchAlbums(self
):
309 query
= self
._get
_keyboard
(default
="", heading
=__language__(30022))
311 albums
= groovesharkApi
.getAlbumSearchResults(query
, limit
= self
.albumsearchlimit
)
312 if (len(albums
) > 0):
313 self
._add
_albums
_directory
(albums
)
315 dialog
= xbmcgui
.Dialog()
316 dialog
.ok(__language__(30008), __language__(30023))
322 def searchArtists(self
):
323 query
= self
._get
_keyboard
(default
="", heading
=__language__(30024))
325 artists
= groovesharkApi
.getArtistSearchResults(query
, limit
= self
.artistsearchlimit
)
326 if (len(artists
) > 0):
327 self
._add
_artists
_directory
(artists
)
329 dialog
= xbmcgui
.Dialog()
330 dialog
.ok(__language__(30008), __language__(30025))
335 # Search for playlists
336 def searchPlaylists(self
):
337 query
= self
._get
_keyboard
(default
="", heading
=__language__(30026))
339 playlists
= groovesharkApi
.getUserPlaylistsByUsername(query
)
340 if (len(playlists
) > 0):
341 self
._add
_playlists
_directory
(playlists
)
343 dialog
= xbmcgui
.Dialog()
344 dialog
.ok(__language__(30008), __language__(30027))
349 # Search for artists albums
350 def searchArtistsAlbums(self
, artistName
= None):
351 if artistName
== None or artistName
== searchArtistsAlbumsName
:
352 query
= self
._get
_keyboard
(default
="", heading
=__language__(30028))
356 artists
= groovesharkApi
.getArtistSearchResults(query
, limit
= self
.artistsearchlimit
)
357 if (len(artists
) > 0):
358 # check for artist name match, first result is sometimes not the closest lexical match
359 artist
= next ((a
for a
in artists
if a
[0].lower() == query
.lower()), artists
[0])
362 xbmc
.log("Found " + artist
[0] + "...")
363 albums
= groovesharkApi
.getArtistAlbums(artistID
, self
.albumsearchlimit
)
364 if (len(albums
) > 0):
365 self
._add
_albums
_directory
(albums
, artistID
)
367 dialog
= xbmcgui
.Dialog()
368 dialog
.ok(__language__(30008), __language__(30029))
371 dialog
= xbmcgui
.Dialog()
372 dialog
.ok(__language__(30008), __language__(30030))
379 userid
= self
._get
_login
()
381 favorites
= groovesharkApi
.getUserFavoriteSongs()
382 if (len(favorites
) > 0):
383 self
._add
_songs
_directory
(favorites
, isFavorites
=True)
385 dialog
= xbmcgui
.Dialog()
386 dialog
.ok(__language__(30008), __language__(30031))
390 def popularSongs(self
):
391 popular
= groovesharkApi
.getPopularSongsToday(limit
= self
.songsearchlimit
)
392 if (len(popular
) > 0):
393 self
._add
_songs
_directory
(popular
)
395 dialog
= xbmcgui
.Dialog()
396 dialog
.ok(__language__(30008), __language__(30032))
401 userid
= self
._get
_login
()
403 playlists
= groovesharkApi
.getUserPlaylists()
404 if (len(playlists
) > 0):
405 self
._add
_playlists
_directory
(playlists
)
407 dialog
= xbmcgui
.Dialog()
408 dialog
.ok(__language__(30008), __language__(30033))
411 dialog
= xbmcgui
.Dialog()
412 dialog
.ok(__language__(30008), __language__(30034), __language__(30035))
414 # Make songs a favorite
415 def favorite(self
, songid
):
416 userid
= self
._get
_login
()
419 xbmc
.log("Favorite song: " + str(songid
))
420 groovesharkApi
.addUserFavoriteSong(songID
= songid
)
421 xbmc
.executebuiltin('XBMC.Notification(' + __language__(30008) + ', ' + __language__(30036) + ', 1000, ' + thumbDef
+ ')')
423 dialog
= xbmcgui
.Dialog()
424 dialog
.ok(__language__(30008), __language__(30034), __language__(30037))
426 # Remove song from favorites
427 def unfavorite(self
, songid
, prevMode
=0):
428 userid
= self
._get
_login
()
431 xbmc
.log("Unfavorite song: " + str(songid
) + ', previous mode was ' + str(prevMode
))
432 groovesharkApi
.removeUserFavoriteSongs(songIDs
= songid
)
433 xbmc
.executebuiltin('XBMC.Notification(' + __language__(30008) + ', ' + __language__(30038) + ', 1000, ' + thumbDef
+ ')')
434 # Refresh to remove item from directory
435 if (int(prevMode
) == MODE_FAVORITES
):
436 xbmc
.executebuiltin("Container.Refresh(" + favoritesUrl
+ ")")
438 dialog
= xbmcgui
.Dialog()
439 dialog
.ok(__language__(30008), __language__(30034), __language__(30039))
442 # Show selected album
443 def album(self
, albumid
):
444 album
= groovesharkApi
.getAlbumSongs(albumid
, limit
= self
.songsearchlimit
)
445 self
._add
_songs
_directory
(album
, trackLabelFormat
=NAME_ALBUM_ARTIST_LABEL
)
447 # Show selected artist
448 def artist(self
, artistid
):
449 albums
= groovesharkApi
.getArtistAlbums(artistid
, limit
= self
.albumsearchlimit
)
450 self
._add
_albums
_directory
(albums
, artistid
, True)
452 # Show selected playlist
453 def playlist(self
, playlistid
, playlistname
):
454 userid
= self
._get
_login
()
456 songs
= groovesharkApi
.getPlaylistSongs(playlistid
)
457 self
._add
_songs
_directory
(songs
, trackLabelFormat
=NAME_ALBUM_ARTIST_LABEL
, playlistid
=playlistid
, playlistname
=playlistname
)
459 dialog
= xbmcgui
.Dialog()
460 dialog
.ok(__language__(30008), __language__(30034), __language__(30040))
462 # Show popular songs of the artist
463 def artistPopularSongs(self
):
464 query
= self
._get
_keyboard
(default
="", heading
=__language__(30041))
466 artists
= groovesharkApi
.getArtistSearchResults(query
, limit
= self
.artistsearchlimit
)
467 if (len(artists
) > 0):
468 # check for exact artist name match, sometimes a more
469 # popular artist is returned first (e.g. 'Angel Dust'
470 # gets you 'Faith No More' because of their popular
471 # album 'Angel Dust')
472 artist
= next ((a
for a
in artists
if a
[0].lower() == query
.lower()), artists
[0])
475 xbmc
.log("Found " + artist
[0] + "...")
476 songs
= groovesharkApi
.getArtistPopularSongs(artistID
, limit
= self
.songsearchlimit
)
478 self
._add
_songs
_directory
(songs
, trackLabelFormat
=NAME_ALBUM_ARTIST_LABEL
)
480 dialog
= xbmcgui
.Dialog()
481 dialog
.ok(__language__(30008), __language__(30042))
484 dialog
= xbmcgui
.Dialog()
485 dialog
.ok(__language__(30008), __language__(30043))
491 def playSong(self
, item
):
495 # Get stream as it could have expired
498 songid
= item
.getProperty('songid')
499 stream
= groovesharkApi
.getSubscriberStreamKey(songid
)
502 key
= stream
['StreamKey']
503 server
= stream
['StreamServerID']
504 duration
= int(self
._setDuration
(stream
['uSecs']))
505 stream
= [songid
, duration
, url
, key
, server
]
506 self
._setSongStream
(stream
)
509 xbmcplugin
.setResolvedUrl(handle
=int(sys
.argv
[1]), succeeded
=True, listitem
=item
)
511 xbmc
.log("Grooveshark playing: " + url
)
512 # Wait for play then start timer
514 while seconds
< STREAM_TIMEOUT
:
516 if player
.isPlayingAudio() == True:
517 if playTimer
!= None:
520 playTimer
= PlayTimer(1, markSong
, self
._setDuration
(duration
), [songid
, duration
, key
, server
])
525 seconds
= seconds
+ 1
527 xbmc
.log("No song URL")
529 xbmc
.log("No song stream")
531 xbmc
.executebuiltin('XBMC.Notification(' + __language__(30008) + ', ' + __language__(30044) + ', 1000, ' + thumbDef
+ ')')
533 # Make a song directory item
534 def songItem(self
, songid
, name
, album
, artist
, coverart
, trackLabelFormat
=ARTIST_ALBUM_NAME_LABEL
, tracknumber
=1):
536 stream
= self
._getSongStream
(songid
)
542 songImg
= self
._get
_icon
(coverart
, 'song-' + str(songid
) + "-image")
543 if int(trackLabelFormat
) == NAME_ALBUM_ARTIST_LABEL
:
544 trackLabel
= name
+ " - " + album
+ " - " + artist
546 trackLabel
= artist
+ " - " + album
+ " - " + name
547 item
= xbmcgui
.ListItem(label
= trackLabel
, thumbnailImage
=songImg
, iconImage
=songImg
)
549 item
.setInfo( type="music", infoLabels
={ "title": name
, "album": album
, "artist": artist
, "duration": duration
, "tracknumber" : tracknumber
} )
550 item
.setProperty('mimetype', 'audio/mpeg')
551 item
.setProperty("IsPlayable", "true")
552 item
.setProperty('songid', str(songid
))
553 item
.setProperty('coverart', songImg
)
554 item
.setProperty('title', name
)
555 item
.setProperty('album', album
)
556 item
.setProperty('artist', artist
)
557 item
.setProperty('duration', str(duration
))
558 item
.setProperty('key', str(key
))
559 item
.setProperty('server', str(server
))
560 item
.setProperty('fanart_image', self
.fanImg
)
563 xbmc
.log("No access to song URL")
567 def songPage(self
, offset
, trackLabelFormat
, playlistid
= 0, playlistname
= ''):
568 self
._add
_songs
_directory
([], trackLabelFormat
, offset
, playlistid
= playlistid
, playlistname
= playlistname
)
570 # Make a playlist from an album
571 def makePlaylist(self
, albumid
, name
):
572 userid
= self
._get
_login
()
574 re
.split(' - ',name
,1)
575 nameTokens
= re
.split(' - ',name
,1) # suggested name
576 name
= self
._get
_keyboard
(default
=nameTokens
[0], heading
=__language__(30045))
578 album
= groovesharkApi
.getAlbumSongs(albumid
, limit
= self
.songsearchlimit
)
581 songids
.append(song
[1])
582 if groovesharkApi
.createPlaylist(name
, songids
) == 0:
583 dialog
= xbmcgui
.Dialog()
584 dialog
.ok(__language__(30008), __language__(30046), name
)
586 xbmc
.executebuiltin('XBMC.Notification(' + __language__(30008) + ',' + __language__(30047)+ ', 1000, ' + thumbDef
+ ')')
588 dialog
= xbmcgui
.Dialog()
589 dialog
.ok(__language__(30008), __language__(30034), __language__(30048))
592 def renamePlaylist(self
, playlistid
, name
):
593 userid
= self
._get
_login
()
595 newname
= self
._get
_keyboard
(default
=name
, heading
=__language__(30049))
598 elif groovesharkApi
.playlistRename(playlistid
, newname
) == 0:
599 dialog
= xbmcgui
.Dialog()
600 dialog
.ok(__language__(30008), __language__(30050), name
)
602 # Refresh to show new item name
603 xbmc
.executebuiltin("Container.Refresh")
605 dialog
= xbmcgui
.Dialog()
606 dialog
.ok(__language__(30008), __language__(30034), __language__(30051))
609 def removePlaylist(self
, playlistid
, name
):
610 dialog
= xbmcgui
.Dialog()
611 if dialog
.yesno(__language__(30008), name
, __language__(30052)) == True:
612 userid
= self
._get
_login
()
614 if groovesharkApi
.playlistDelete(playlistid
) == 0:
615 dialog
= xbmcgui
.Dialog()
616 dialog
.ok(__language__(30008), __language__(30053), name
)
618 # Refresh to remove item from directory
619 xbmc
.executebuiltin("Container.Refresh(" + playlistsUrl
+ ")")
621 dialog
= xbmcgui
.Dialog()
622 dialog
.ok(__language__(30008), __language__(30034), __language__(30054))
624 # Add song to playlist
625 def addPlaylistSong(self
, songid
):
626 userid
= self
._get
_login
()
628 playlists
= groovesharkApi
.getUserPlaylists()
629 if (len(playlists
) > 0):
631 # Select the playlist
632 playlistSelect
= GroovesharkPlaylistSelect(items
=playlists
)
633 playlistSelect
.setFocus(playlistSelect
.playlistControl
)
634 playlistSelect
.doModal()
635 i
= playlistSelect
.selected
639 if i
>= len(playlists
):
640 name
= self
._get
_keyboard
(default
='', heading
=__language__(30055))
643 songIds
.append(songid
)
644 if groovesharkApi
.createPlaylist(name
, songIds
) == 0:
645 dialog
= xbmcgui
.Dialog()
646 dialog
.ok(__language__(30008), __language__(30056), name
)
648 xbmc
.executebuiltin('XBMC.Notification(' + __language__(30008) + ',' + __language__(30057) + ', 1000, ' + thumbDef
+ ')')
651 playlist
= playlists
[i
]
652 playlistid
= playlist
[1]
654 xbmc
.log("Add song " + str(songid
) + " to playlist " + str(playlistid
))
656 songs
= groovesharkApi
.getPlaylistSongs(playlistid
)
658 songIDs
.append(song
[1])
659 songIDs
.append(songid
)
660 ret
= groovesharkApi
.setPlaylistSongs(playlistid
, songIDs
)
662 dialog
= xbmcgui
.Dialog()
663 dialog
.ok(__language__(30008), __language__(30058))
665 xbmc
.executebuiltin('XBMC.Notification(' + __language__(30008) + ',' + __language__(30059) + ', 1000, ' + thumbDef
+ ')')
667 dialog
= xbmcgui
.Dialog()
668 dialog
.ok(__language__(30008), __language__(30060))
671 dialog
= xbmcgui
.Dialog()
672 dialog
.ok(__language__(30008), __language__(30034), __language__(30061))
674 # Remove song from playlist
675 def removePlaylistSong(self
, playlistid
, playlistname
, songid
):
676 dialog
= xbmcgui
.Dialog()
677 if dialog
.yesno(__language__(30008), __language__(30062), __language__(30063)) == True:
678 userid
= self
._get
_login
()
680 songs
= groovesharkApi
.getPlaylistSongs(playlistID
)
683 if (song
[1] != songid
):
684 songIDs
.append(song
[1])
685 ret
= groovesharkApi
.setPlaylistSongs(playlistID
, songIDs
)
687 dialog
= xbmcgui
.Dialog()
688 dialog
.ok(__language__(30008), __language__(30064), __language__(30065))
690 # Refresh to remove item from directory
691 xbmc
.executebuiltin('XBMC.Notification(' + __language__(30008) + ',' + __language__(30066)+ ', 1000, ' + thumbDef
+ ')')
692 xbmc
.executebuiltin("Container.Update(" + playlistUrl
+ "&id="+str(playlistid
) + "&name=" + str(playlistname
) + ")")
694 dialog
= xbmcgui
.Dialog()
695 dialog
.ok(__language__(30008), __language__(30034), __language__(30067))
697 # Find similar artists to searched artist
698 def similarArtists(self
, artistId
):
699 similar
= groovesharkApi
.getSimilarArtists(artistId
, limit
= self
.artistsearchlimit
)
700 if (len(similar
) > 0):
701 self
._add
_artists
_directory
(similar
)
703 dialog
= xbmcgui
.Dialog()
704 dialog
.ok(__language__(30008), __language__(30068))
708 def _get_keyboard(self
, default
="", heading
="", hidden
=False):
709 kb
= xbmc
.Keyboard(default
, heading
, hidden
)
711 if (kb
.isConfirmed()):
712 return unicode(kb
.getText(), "utf-8")
715 # Login to grooveshark
716 def _get_login(self
):
717 if (self
.username
== "" or self
.password
== ""):
718 dialog
= xbmcgui
.Dialog()
719 dialog
.ok(__language__(30008), __language__(30069), __language__(30070), __language__(30082))
722 uid
= groovesharkApi
.login(self
.username
, self
.password
)
726 dialog
= xbmcgui
.Dialog()
727 dialog
.ok(__language__(30008), __language__(30069), __language__(30070), __language__(30082))
731 def _get_icon(self
, url
, songid
):
733 localThumb
= os
.path
.join(xbmc
.translatePath(os
.path
.join(thumbDir
, str(songid
)))) + '.tbn'
735 if os
.path
.isfile(localThumb
) == False:
736 headers
= { 'User-Agent' : 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.102 Chrome/32.0.1700.102 Safari/537.36' }
737 req
= urllib2
.Request(url
, None, headers
)
738 loc
= urllib2
.urlopen(req
)
739 output
= open(localThumb
,'wb')
740 output
.write(loc
.read())
743 shutil
.copy2(thumbDef
, localThumb
)
744 return os
.path
.join(os
.path
.join(thumbDir
, str(songid
))) + '.tbn'
748 # Add songs to directory
749 def _add_songs_directory(self
, songs
, trackLabelFormat
=ARTIST_ALBUM_NAME_LABEL
, offset
=0, playlistid
=0, playlistname
='', isFavorites
=False):
751 totalSongs
= len(songs
)
757 if offset
== 0 and totalSongs
<= self
.songspagelimit
:
759 xbmc
.log("Found " + str(totalSongs
) + " songs...")
762 # Cache all next pages songs
764 self
._setSavedSongs
(songs
)
766 songs
= self
._getSavedSongs
()
767 totalSongs
= len(songs
)
771 end
= min(start
+ self
.songspagelimit
,totalSongs
)
782 item
= self
.songItem(songid
, name
, album
, artist
, coverart
, trackLabelFormat
, (n
+1))
784 coverart
= item
.getProperty('coverart')
788 u
=sys
.argv
[0]+"?mode="+str(MODE_SONG
)+"&name="+urllib
.quote_plus(songname
)+"&id="+str(songid
) \
789 +"&album="+urllib
.quote_plus(songalbum
) \
790 +"&artist="+urllib
.quote_plus(songartist
) \
791 +"&coverart="+urllib
.quote_plus(coverart
)
792 fav
=sys
.argv
[0]+"?mode="+str(MODE_FAVORITE
)+"&name="+urllib
.quote_plus(songname
)+"&id="+str(songid
)
793 unfav
=sys
.argv
[0]+"?mode="+str(MODE_UNFAVORITE
)+"&name="+urllib
.quote_plus(songname
)+"&id="+str(songid
)+"&prevmode="
795 if isFavorites
== True:
796 unfav
= unfav
+str(MODE_FAVORITES
)
798 menuItems
.append((__language__(30071), "XBMC.RunPlugin("+fav
+")"))
799 menuItems
.append((__language__(30072), "XBMC.RunPlugin("+unfav
+")"))
801 rmplaylstsong
=sys
.argv
[0]+"?playlistid="+str(playlistid
)+"&id="+str(songid
)+"&mode="+str(MODE_REMOVE_PLAYLIST_SONG
)+"&name="+str(playlistname
)
802 menuItems
.append((__language__(30073), "XBMC.RunPlugin("+rmplaylstsong
+")"))
804 addplaylstsong
=sys
.argv
[0]+"?id="+str(songid
)+"&mode="+str(MODE_ADD_PLAYLIST_SONG
)
805 menuItems
.append((__language__(30074), "XBMC.RunPlugin("+addplaylstsong
+")"))
806 item
.addContextMenuItems(menuItems
, replaceItems
=False)
807 xbmcplugin
.addDirectoryItem(handle
=int(sys
.argv
[1]),url
=u
,listitem
=item
,isFolder
=False, totalItems
=items
)
809 end
= min(end
+ 1,totalSongs
)
811 xbmc
.log(song
[0] + " does not exist.")
815 u
=sys
.argv
[0]+"?mode="+str(MODE_SONG_PAGE
)+"&id=playlistid"+"&offset="+str(end
)+"&label="+str(trackLabelFormat
)+"&name="+str(playlistname
)
816 self
._add
_dir
(__language__(30075) + '...', u
, MODE_SONG_PAGE
, self
.songImg
, 0, totalSongs
- end
)
818 xbmcplugin
.setContent(self
._handle
, 'songs')
819 xbmcplugin
.setPluginFanart(int(sys
.argv
[1]), self
.fanImg
)
821 # Add albums to directory
822 def _add_albums_directory(self
, albums
, artistid
=0, isverified
=False):
826 xbmc
.log("Found " + str(n
) + " albums...")
832 albumArtistName
= album
[0]
834 albumImage
= self
._get
_icon
(album
[4], 'album-' + str(albumID
))
835 self
._add
_dir
(albumName
+ " - " + albumArtistName
, '', MODE_ALBUM
, albumImage
, albumID
, itemsExisting
)
837 itemsExisting
= itemsExisting
- 1
839 # Not supported by key
841 # self._add_dir('Similar artists...', '', MODE_SIMILAR_ARTISTS, self.artistImg, artistid)
842 xbmcplugin
.setContent(self
._handle
, 'albums')
843 xbmcplugin
.addSortMethod(self
._handle
, xbmcplugin
.SORT_METHOD_ALBUM_IGNORE_THE
)
844 xbmcplugin
.setPluginFanart(int(sys
.argv
[1]), self
.fanImg
)
846 # Add artists to directory
847 def _add_artists_directory(self
, artists
):
851 xbmc
.log("Found " + str(n
) + " artists...")
856 artistName
= artist
[0]
857 self
._add
_dir
(artistName
, '', MODE_ARTIST
, self
.artistImg
, artistID
, itemsExisting
)
859 xbmcplugin
.setContent(self
._handle
, 'artists')
860 xbmcplugin
.addSortMethod(self
._handle
, xbmcplugin
.SORT_METHOD_ARTIST_IGNORE_THE
)
861 xbmcplugin
.setPluginFanart(int(sys
.argv
[1]), self
.fanImg
)
863 # Add playlists to directory
864 def _add_playlists_directory(self
, playlists
):
867 xbmc
.log("Found " + str(n
) + " playlists...")
870 playlist
= playlists
[i
]
871 playlistName
= playlist
[0]
872 playlistID
= playlist
[1]
873 self
._add
_dir
(playlistName
, '', MODE_PLAYLIST
, self
.playlistImg
, playlistID
, n
)
875 xbmcplugin
.setContent(self
._handle
, 'files')
876 xbmcplugin
.addSortMethod(self
._handle
, xbmcplugin
.SORT_METHOD_LABEL
)
877 xbmcplugin
.setPluginFanart(int(sys
.argv
[1]), self
.fanImg
)
879 # Add whatever directory
880 def _add_dir(self
, name
, url
, mode
, iconimage
, itemId
, items
=1):
883 u
=sys
.argv
[0]+"?mode="+str(mode
)+"&name="+urllib
.quote_plus(name
)+"&id="+str(itemId
)
886 directory
=xbmcgui
.ListItem(name
, iconImage
=iconimage
, thumbnailImage
=iconimage
)
887 directory
.setInfo( type="Music", infoLabels
={ "title": name
} )
888 directory
.setProperty('fanart_image', self
.fanImg
)
892 if mode
== MODE_ALBUM
:
893 mkplaylst
=sys
.argv
[0]+"?mode="+str(MODE_MAKE_PLAYLIST
)+"&name="+name
+"&id="+str(itemId
)
894 menuItems
.append((__language__(30076), "XBMC.RunPlugin("+mkplaylst
+")"))
895 if mode
== MODE_PLAYLIST
:
896 rmplaylst
=sys
.argv
[0]+"?mode="+str(MODE_REMOVE_PLAYLIST
)+"&name="+urllib
.quote_plus(name
)+"&id="+str(itemId
)
897 menuItems
.append((__language__(30077), "XBMC.RunPlugin("+rmplaylst
+")"))
898 mvplaylst
=sys
.argv
[0]+"?mode="+str(MODE_RENAME_PLAYLIST
)+"&name="+urllib
.quote_plus(name
)+"&id="+str(itemId
)
899 menuItems
.append((__language__(30078), "XBMC.RunPlugin("+mvplaylst
+")"))
901 directory
.addContextMenuItems(menuItems
, replaceItems
=False)
903 return xbmcplugin
.addDirectoryItem(handle
=int(sys
.argv
[1]),url
=u
,listitem
=directory
,isFolder
=True, totalItems
=items
)
905 def _getSavedSongs(self
):
906 path
= os
.path
.join(cacheDir
, 'songs.dmp')
909 songs
= pickle
.load(f
)
916 def _setSavedSongs(self
, songs
):
918 # Create the 'data' directory if it doesn't exist.
919 if not os
.path
.exists(cacheDir
):
920 os
.makedirs(cacheDir
)
921 path
= os
.path
.join(cacheDir
, 'songs.dmp')
923 pickle
.dump(songs
, f
, protocol
=pickle
.HIGHEST_PROTOCOL
)
926 xbmc
.log("An error occurred saving songs")
929 # Duration to seconds
930 def _setDuration(self
, usecs
):
932 usecs
= usecs
* 10 # Some durations are 10x to small
933 return int(usecs
/ 1000000)
935 def _getSongStream(self
, songid
):
939 path
= os
.path
.join(cacheDir
, 'streams.dmp')
942 streams
= pickle
.load(f
)
943 song
= streams
[songid
]
949 stream
= [idSong
, duration
, url
, key
, server
]
952 xbmc
.log("Found " + str(idSong
) + " in stream cache")
960 stream
= groovesharkApi
.getSubscriberStreamKey(songid
)
961 if stream
!= False and stream
['url'] != '':
962 duration
= self
._setDuration
(stream
['uSecs'])
964 key
= stream
['StreamKey']
965 server
= stream
['StreamServerID']
966 stream
= [idSong
, duration
, url
, key
, server
]
967 self
._addSongStream
(stream
)
971 def _addSongStream(self
, stream
):
972 streams
= self
._getStreams
()
973 streams
[int(stream
[0])] = stream
974 path
= os
.path
.join(cacheDir
, 'streams.dmp')
977 pickle
.dump(streams
, f
, protocol
=pickle
.HIGHEST_PROTOCOL
)
980 xbmc
.log("Added " + str(stream
[0]) + " to stream cache")
982 xbmc
.log("An error occurred adding to stream")
984 def _setSongStream(self
, stream
):
985 idStream
= int(stream
[0])
986 stream
[1] = self
._setDuration
(stream
[1])
987 streams
= self
._getStreams
()
988 path
= os
.path
.join(cacheDir
, 'streams.dmp')
991 streams
[idStream
] = stream
993 pickle
.dump(streams
, f
, protocol
=pickle
.HIGHEST_PROTOCOL
)
996 xbmc
.log("Updated " + str(idStream
) + " in stream cache")
999 xbmc
.log("An error occurred setting stream")
1001 def _getStreams(self
):
1002 path
= os
.path
.join(cacheDir
, 'streams.dmp')
1004 f
= open(path
, 'rb')
1005 streams
= pickle
.load(f
)
1013 # Parse URL parameters
1016 paramstring
=sys
.argv
[2]
1018 xbmc
.log(paramstring
)
1019 if len(paramstring
)>=2:
1021 cleanedparams
=params
.replace('?','')
1022 if (params
[len(params
)-1]=='/'):
1023 params
=params
[0:len(params
)-2]
1024 pairsofparams
=cleanedparams
.split('&')
1026 for i
in range(len(pairsofparams
)):
1028 splitparams
=pairsofparams
[i
].split('=')
1029 if (len(splitparams
))==2:
1030 param
[splitparams
[0]]=splitparams
[1]
1034 grooveshark
= Grooveshark();
1038 try: mode
=int(params
["mode"])
1041 try: itemId
=int(params
["id"])
1044 try: name
=urllib
.unquote_plus(params
["name"])
1047 # Call function for URL
1049 grooveshark
.categories()
1051 elif mode
==MODE_SEARCH_SONGS
:
1052 grooveshark
.searchSongs()
1054 elif mode
==MODE_SEARCH_ALBUMS
:
1055 grooveshark
.searchAlbums()
1057 elif mode
==MODE_SEARCH_ARTISTS
:
1058 grooveshark
.searchArtists()
1060 elif mode
==MODE_SEARCH_ARTISTS_ALBUMS
:
1061 grooveshark
.searchArtistsAlbums(name
)
1063 elif mode
==MODE_SEARCH_PLAYLISTS
:
1064 grooveshark
.searchPlaylists()
1066 elif mode
==MODE_POPULAR_SONGS
:
1067 grooveshark
.popularSongs()
1069 elif mode
==MODE_ARTIST_POPULAR
:
1070 grooveshark
.artistPopularSongs()
1072 elif mode
==MODE_FAVORITES
:
1073 grooveshark
.favorites()
1075 elif mode
==MODE_PLAYLISTS
:
1076 grooveshark
.playlists()
1078 elif mode
==MODE_SONG_PAGE
:
1079 try: offset
=urllib
.unquote_plus(params
["offset"])
1081 try: label
=urllib
.unquote_plus(params
["label"])
1083 grooveshark
.songPage(offset
, label
, itemId
, name
)
1085 elif mode
==MODE_SONG
:
1086 try: album
=urllib
.unquote_plus(params
["album"])
1088 try: artist
=urllib
.unquote_plus(params
["artist"])
1090 try: coverart
=urllib
.unquote_plus(params
["coverart"])
1092 song
= grooveshark
.songItem(itemId
, name
, album
, artist
, coverart
)
1093 grooveshark
.playSong(song
)
1095 elif mode
==MODE_ARTIST
:
1096 grooveshark
.artist(itemId
)
1098 elif mode
==MODE_ALBUM
:
1099 grooveshark
.album(itemId
)
1101 elif mode
==MODE_PLAYLIST
:
1102 grooveshark
.playlist(itemId
, name
)
1104 elif mode
==MODE_FAVORITE
:
1105 grooveshark
.favorite(itemId
)
1107 elif mode
==MODE_UNFAVORITE
:
1108 try: prevMode
=int(urllib
.unquote_plus(params
["prevmode"]))
1111 grooveshark
.unfavorite(itemId
, prevMode
)
1113 elif mode
==MODE_SIMILAR_ARTISTS
:
1114 grooveshark
.similarArtists(itemId
)
1116 elif mode
==MODE_MAKE_PLAYLIST
:
1117 grooveshark
.makePlaylist(itemId
, name
)
1119 elif mode
==MODE_REMOVE_PLAYLIST
:
1120 grooveshark
.removePlaylist(itemId
, name
)
1122 elif mode
==MODE_RENAME_PLAYLIST
:
1123 grooveshark
.renamePlaylist(itemId
, name
)
1125 elif mode
==MODE_REMOVE_PLAYLIST_SONG
:
1126 try: playlistID
=urllib
.unquote_plus(params
["playlistid"])
1128 grooveshark
.removePlaylistSong(playlistID
, name
, itemId
)
1130 elif mode
==MODE_ADD_PLAYLIST_SONG
:
1131 grooveshark
.addPlaylistSong(itemId
)
1133 if mode
< MODE_SONG
:
1134 xbmcplugin
.endOfDirectory(int(sys
.argv
[1]))