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
, sys
, os
, shutil
, re
, pickle
, time
, tempfile
, 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 thumbDirName
= 'thumb'
80 thumbDir
= os
.path
.join(xbmc
.translatePath('special://masterprofile/addon_data/'), os
.path
.basename(baseDir
), thumbDirName
)
82 baseModeUrl
= 'plugin://plugin.audio.groove/'
83 playlistUrl
= baseModeUrl
+ '?mode=' + str(MODE_PLAYLIST
)
84 playlistsUrl
= baseModeUrl
+ '?mode=' + str(MODE_PLAYLISTS
)
85 favoritesUrl
= baseModeUrl
+ '?mode=' + str(MODE_FAVORITES
)
87 searchArtistsAlbumsName
= __language__(30006)
89 thumbDef
= os
.path
.join(imgDir
, 'default.tbn')
90 listBackground
= os
.path
.join(imgDir
, 'listbackground.png')
92 sys
.path
.append (libDir
)
93 from GroovesharkAPI
import GrooveAPI
94 from threading
import Event
, Thread
96 if __debugging__
== 'true':
102 groovesharkApi
= GrooveAPI(__debugging__
)
103 if groovesharkApi
.pingService() != True:
104 raise StandardError(__language__(30007))
106 dialog
= xbmcgui
.Dialog(__language__(30008),__language__(30009),__language__(30010))
107 dialog
.ok(__language__(30008),__language__(30009))
110 # Mark song as playing or played
111 def markSong(songid
, duration
, streamKey
, streamServerID
):
115 if player
.isPlayingAudio():
116 tNow
= player
.getTime()
117 if tNow
>= STREAM_MARKING_TIME
and songMarkTime
== 0:
118 groovesharkApi
.markStreamKeyOver30Secs(streamKey
, streamServerID
)
120 elif duration
> tNow
and duration
- tNow
< 2 and songMarkTime
>= STREAM_MARKING_TIME
:
123 groovesharkApi
.markSongComplete(songid
, streamKey
, streamServerID
)
129 def __init__( self
, *args
, **kwargs
):
130 self
.__dict
__.update( kwargs
)
132 # Window dialog to select a grooveshark playlist
133 class GroovesharkPlaylistSelect(xbmcgui
.WindowDialog
):
135 def __init__(self
, items
=[]):
136 gap
= int(self
.getHeight()/100)
137 w
= int(self
.getWidth()*0.5)
138 h
= self
.getHeight()-30*gap
140 rh
= self
.getHeight()
144 self
.imgBg
= xbmcgui
.ControlImage(x
+gap
, 5*gap
+y
, w
-2*gap
, h
-5*gap
, listBackground
)
145 self
.addControl(self
.imgBg
)
147 self
.playlistControl
= xbmcgui
.ControlList(2*gap
+x
, y
+3*gap
+30, w
-4*gap
, h
-10*gap
, textColor
='0xFFFFFFFF', selectedColor
='0xFFFF4242')
148 self
.playlistControl
.setItemHeight(50)
149 self
.addControl(self
.playlistControl
)
152 self
.isSelecting
= False
155 for playlist
in items
:
156 listitems
.append(xbmcgui
.ListItem(playlist
[0]))
157 listitems
.append(xbmcgui
.ListItem(__language__(30011)))
158 self
.playlistControl
.addItems(listitems
)
159 self
.setFocus(self
.playlistControl
)
160 self
.playlistControl
.selectItem(0)
161 item
= self
.playlistControl
.getListItem(self
.lastPos
)
164 # Highlight selected item
165 def setHighlight(self
):
169 self
.isSelecting
= True
171 pos
= self
.playlistControl
.getSelectedPosition()
173 item
= self
.playlistControl
.getListItem(self
.lastPos
)
175 item
= self
.playlistControl
.getListItem(pos
)
178 self
.isSelecting
= False
181 def onControl(self
, control
):
182 if control
== self
.playlistControl
:
183 self
.selected
= self
.playlistControl
.getSelectedPosition()
186 # Action - close or up/down
187 def onAction(self
, action
):
188 if action
== ACTION_PREVIOUS_MENU
:
191 elif action
== ACTION_MOVE_UP
or action
== ACTION_MOVE_DOWN
or action
== ACTION_PAGE_UP
or action
== ACTION_PAGE_DOWN
== 6:
192 self
.setFocus(self
.playlistControl
)
196 class PlayTimer(Thread
):
197 # interval -- floating point number specifying the number of seconds to wait before executing function
198 # function -- the function (or callable object) to be executed
200 # iterations -- integer specifying the number of iterations to perform
201 # args -- list of positional arguments passed to function
202 # kwargs -- dictionary of keyword arguments passed to function
204 def __init__(self
, interval
, function
, iterations
=0, args
=[], kwargs
={}):
205 Thread
.__init
__(self
)
206 self
.interval
= interval
207 self
.function
= function
208 self
.iterations
= iterations
211 self
.finished
= Event()
215 while not self
.finished
.isSet() and (self
.iterations
<= 0 or count
< self
.iterations
):
216 self
.finished
.wait(self
.interval
)
217 if not self
.finished
.isSet():
218 self
.function(*self
.args
, **self
.kwargs
)
224 def setIterations(self
, iterations
):
225 self
.iterations
= iterations
229 return self
.iterations
* self
.interval
234 albumImg
= xbmc
.translatePath(os
.path
.join(imgDir
, 'album.png'))
235 artistImg
= xbmc
.translatePath(os
.path
.join(imgDir
, 'artist.png'))
236 artistsAlbumsImg
= xbmc
.translatePath(os
.path
.join(imgDir
, 'artistsalbums.png'))
237 favoritesImg
= xbmc
.translatePath(os
.path
.join(imgDir
, 'favorites.png'))
238 playlistImg
= xbmc
.translatePath(os
.path
.join(imgDir
, 'playlist.png'))
239 usersplaylistsImg
= xbmc
.translatePath(os
.path
.join(imgDir
, 'usersplaylists.png'))
240 popularSongsImg
= xbmc
.translatePath(os
.path
.join(imgDir
, 'popularSongs.png'))
241 popularSongsArtistImg
= xbmc
.translatePath(os
.path
.join(imgDir
, 'popularSongsArtist.png'))
242 songImg
= xbmc
.translatePath(os
.path
.join(imgDir
, 'song.png'))
243 defImg
= xbmc
.translatePath(os
.path
.join(imgDir
, 'default.tbn'))
244 fanImg
= xbmc
.translatePath(os
.path
.join(baseDir
, 'fanart.jpg'))
246 settings
= xbmcaddon
.Addon(id='plugin.audio.groove')
247 songsearchlimit
= int(settings
.getSetting('songsearchlimit'))
248 albumsearchlimit
= int(settings
.getSetting('albumsearchlimit'))
249 artistsearchlimit
= int(settings
.getSetting('artistsearchlimit'))
250 songspagelimit
= int(settings
.getSetting('songspagelimit'))
251 username
= settings
.getSetting('username')
252 password
= settings
.getSetting('password')
256 def __init__( self
):
257 self
._handle
= int(sys
.argv
[1])
258 if os
.path
.isdir(cacheDir
) == False:
259 os
.makedirs(cacheDir
)
261 xbmc
.log(__language__(30012) + " " + cacheDir
)
262 artDir
= xbmc
.translatePath(thumbDir
)
263 if os
.path
.isdir(artDir
) == False:
266 xbmc
.log(__language__(30012) + " " + artDir
)
269 def categories(self
):
271 self
.userid
= self
._get
_login
()
274 xbmcplugin
.setPluginFanart(int(sys
.argv
[1]), self
.fanImg
)
276 self
._add
_dir
(__language__(30013), '', MODE_SEARCH_SONGS
, self
.songImg
, 0)
277 self
._add
_dir
(__language__(30014), '', MODE_SEARCH_ALBUMS
, self
.albumImg
, 0)
278 self
._add
_dir
(__language__(30015), '', MODE_SEARCH_ARTISTS
, self
.artistImg
, 0)
279 self
._add
_dir
(searchArtistsAlbumsName
, '', MODE_SEARCH_ARTISTS_ALBUMS
, self
.artistsAlbumsImg
, 0)
280 # Not supported by key
281 #self._add_dir("Search for user's playlists...", '', MODE_SEARCH_PLAYLISTS, self.usersplaylistsImg, 0)
282 self
._add
_dir
(__language__(30016), '', MODE_ARTIST_POPULAR
, self
.popularSongsArtistImg
, 0)
283 self
._add
_dir
(__language__(30017), '', MODE_POPULAR_SONGS
, self
.popularSongsImg
, 0)
284 if (self
.userid
!= 0):
285 self
._add
_dir
(__language__(30018), '', MODE_FAVORITES
, self
.favoritesImg
, 0)
286 self
._add
_dir
(__language__(30019), '', MODE_PLAYLISTS
, self
.playlistImg
, 0)
289 def searchSongs(self
):
290 query
= self
._get
_keyboard
(default
="", heading
=__language__(30020))
292 songs
= groovesharkApi
.getSongSearchResults(query
, limit
= self
.songsearchlimit
)
294 self
._add
_songs
_directory
(songs
)
296 dialog
= xbmcgui
.Dialog()
297 dialog
.ok(__language__(30008), __language__(30021))
303 def searchAlbums(self
):
304 query
= self
._get
_keyboard
(default
="", heading
=__language__(30022))
306 albums
= groovesharkApi
.getAlbumSearchResults(query
, limit
= self
.albumsearchlimit
)
307 if (len(albums
) > 0):
308 self
._add
_albums
_directory
(albums
)
310 dialog
= xbmcgui
.Dialog()
311 dialog
.ok(__language__(30008), __language__(30023))
317 def searchArtists(self
):
318 query
= self
._get
_keyboard
(default
="", heading
=__language__(30024))
320 artists
= groovesharkApi
.getArtistSearchResults(query
, limit
= self
.artistsearchlimit
)
321 if (len(artists
) > 0):
322 self
._add
_artists
_directory
(artists
)
324 dialog
= xbmcgui
.Dialog()
325 dialog
.ok(__language__(30008), __language__(30025))
330 # Search for playlists
331 def searchPlaylists(self
):
332 query
= self
._get
_keyboard
(default
="", heading
=__language__(30026))
334 playlists
= groovesharkApi
.getUserPlaylistsByUsername(query
)
335 if (len(playlists
) > 0):
336 self
._add
_playlists
_directory
(playlists
)
338 dialog
= xbmcgui
.Dialog()
339 dialog
.ok(__language__(30008), __language__(30027))
344 # Search for artists albums
345 def searchArtistsAlbums(self
, artistName
= None):
346 if artistName
== None or artistName
== searchArtistsAlbumsName
:
347 query
= self
._get
_keyboard
(default
="", heading
=__language__(30028))
351 artists
= groovesharkApi
.getArtistSearchResults(query
, limit
= self
.artistsearchlimit
)
352 if (len(artists
) > 0):
356 xbmc
.log("Found " + artist
[0] + "...")
357 albums
= groovesharkApi
.getArtistAlbums(artistID
, self
.albumsearchlimit
)
358 if (len(albums
) > 0):
359 self
._add
_albums
_directory
(albums
, artistID
)
361 dialog
= xbmcgui
.Dialog()
362 dialog
.ok(__language__(30008), __language__(30029))
365 dialog
= xbmcgui
.Dialog()
366 dialog
.ok(__language__(30008), __language__(30030))
373 userid
= self
._get
_login
()
375 favorites
= groovesharkApi
.getUserFavoriteSongs()
376 if (len(favorites
) > 0):
377 self
._add
_songs
_directory
(favorites
, isFavorites
=True)
379 dialog
= xbmcgui
.Dialog()
380 dialog
.ok(__language__(30008), __language__(30031))
384 def popularSongs(self
):
385 popular
= groovesharkApi
.getPopularSongsToday(limit
= self
.songsearchlimit
)
386 if (len(popular
) > 0):
387 self
._add
_songs
_directory
(popular
)
389 dialog
= xbmcgui
.Dialog()
390 dialog
.ok(__language__(30008), __language__(30032))
395 userid
= self
._get
_login
()
397 playlists
= groovesharkApi
.getUserPlaylists()
398 if (len(playlists
) > 0):
399 self
._add
_playlists
_directory
(playlists
)
401 dialog
= xbmcgui
.Dialog()
402 dialog
.ok(__language__(30008), __language__(30033))
405 dialog
= xbmcgui
.Dialog()
406 dialog
.ok(__language__(30008), __language__(30034), __language__(30035))
408 # Make songs a favorite
409 def favorite(self
, songid
):
410 userid
= self
._get
_login
()
413 xbmc
.log("Favorite song: " + str(songid
))
414 groovesharkApi
.addUserFavoriteSong(songID
= songid
)
415 xbmc
.executebuiltin('XBMC.Notification(' + __language__(30008) + ', ' + __language__(30036) + ', 1000, ' + thumbDef
+ ')')
417 dialog
= xbmcgui
.Dialog()
418 dialog
.ok(__language__(30008), __language__(30034), __language__(30037))
420 # Remove song from favorites
421 def unfavorite(self
, songid
, prevMode
=0):
422 userid
= self
._get
_login
()
425 xbmc
.log("Unfavorite song: " + str(songid
) + ', previous mode was ' + str(prevMode
))
426 groovesharkApi
.removeUserFavoriteSongs(songIDs
= songid
)
427 xbmc
.executebuiltin('XBMC.Notification(' + __language__(30008) + ', ' + __language__(30038) + ', 1000, ' + thumbDef
+ ')')
428 # Refresh to remove item from directory
429 if (int(prevMode
) == MODE_FAVORITES
):
430 xbmc
.executebuiltin("Container.Refresh(" + favoritesUrl
+ ")")
432 dialog
= xbmcgui
.Dialog()
433 dialog
.ok(__language__(30008), __language__(30034), __language__(30039))
436 # Show selected album
437 def album(self
, albumid
):
438 album
= groovesharkApi
.getAlbumSongs(albumid
, limit
= self
.songsearchlimit
)
439 self
._add
_songs
_directory
(album
, trackLabelFormat
=NAME_ALBUM_ARTIST_LABEL
)
441 # Show selected artist
442 def artist(self
, artistid
):
443 albums
= groovesharkApi
.getArtistAlbums(artistid
, limit
= self
.albumsearchlimit
)
444 self
._add
_albums
_directory
(albums
, artistid
, True)
446 # Show selected playlist
447 def playlist(self
, playlistid
, playlistname
):
448 userid
= self
._get
_login
()
450 songs
= groovesharkApi
.getPlaylistSongs(playlistid
)
451 self
._add
_songs
_directory
(songs
, trackLabelFormat
=NAME_ALBUM_ARTIST_LABEL
, playlistid
=playlistid
, playlistname
=playlistname
)
453 dialog
= xbmcgui
.Dialog()
454 dialog
.ok(__language__(30008), __language__(30034), __language__(30040))
456 # Show popular songs of the artist
457 def artistPopularSongs(self
):
458 query
= self
._get
_keyboard
(default
="", heading
=__language__(30041))
460 artists
= groovesharkApi
.getArtistSearchResults(query
, limit
= self
.artistsearchlimit
)
461 if (len(artists
) > 0):
465 xbmc
.log("Found " + artist
[0] + "...")
466 songs
= groovesharkApi
.getArtistPopularSongs(artistID
, limit
= self
.songsearchlimit
)
468 self
._add
_songs
_directory
(songs
, trackLabelFormat
=NAME_ALBUM_ARTIST_LABEL
)
470 dialog
= xbmcgui
.Dialog()
471 dialog
.ok(__language__(30008), __language__(30042))
474 dialog
= xbmcgui
.Dialog()
475 dialog
.ok(__language__(30008), __language__(30043))
481 def playSong(self
, item
):
485 # Get stream as it could have expired
488 songid
= item
.getProperty('songid')
489 stream
= groovesharkApi
.getSubscriberStreamKey(songid
)
492 key
= stream
['StreamKey']
493 server
= stream
['StreamServerID']
494 duration
= int(self
._setDuration
(stream
['uSecs']))
495 stream
= [songid
, duration
, url
, key
, server
]
496 self
._setSongStream
(stream
)
499 xbmcplugin
.setResolvedUrl(handle
=int(sys
.argv
[1]), succeeded
=True, listitem
=item
)
501 xbmc
.log("Grooveshark playing: " + url
)
502 # Wait for play then start timer
504 while seconds
< STREAM_TIMEOUT
:
506 if player
.isPlayingAudio() == True:
507 if playTimer
!= None:
510 playTimer
= PlayTimer(1, markSong
, self
._setDuration
(duration
), [songid
, duration
, key
, server
])
515 seconds
= seconds
+ 1
517 xbmc
.log("No song URL")
519 xbmc
.log("No song stream")
521 xbmc
.executebuiltin('XBMC.Notification(' + __language__(30008) + ', ' + __language__(30044) + ', 1000, ' + thumbDef
+ ')')
523 # Make a song directory item
524 def songItem(self
, songid
, name
, album
, artist
, coverart
, trackLabelFormat
=ARTIST_ALBUM_NAME_LABEL
, tracknumber
=1):
526 stream
= self
._getSongStream
(songid
)
532 songImg
= self
._get
_icon
(coverart
, 'song-' + str(songid
) + "-image")
533 if int(trackLabelFormat
) == NAME_ALBUM_ARTIST_LABEL
:
534 trackLabel
= name
+ " - " + album
+ " - " + artist
536 trackLabel
= artist
+ " - " + album
+ " - " + name
537 item
= xbmcgui
.ListItem(label
= trackLabel
, thumbnailImage
=songImg
, iconImage
=songImg
)
539 item
.setInfo( type="music", infoLabels
={ "title": name
, "album": album
, "artist": artist
, "duration": duration
, "tracknumber" : tracknumber
} )
540 item
.setProperty('mimetype', 'audio/mpeg')
541 item
.setProperty("IsPlayable", "true")
542 item
.setProperty('songid', str(songid
))
543 item
.setProperty('coverart', songImg
)
544 item
.setProperty('title', name
)
545 item
.setProperty('album', album
)
546 item
.setProperty('artist', artist
)
547 item
.setProperty('duration', str(duration
))
548 item
.setProperty('key', str(key
))
549 item
.setProperty('server', str(server
))
550 item
.setProperty('fanart_image', self
.fanImg
)
553 xbmc
.log("No song URL")
557 def songPage(self
, offset
, trackLabelFormat
, playlistid
= 0, playlistname
= ''):
558 self
._add
_songs
_directory
([], trackLabelFormat
, offset
, playlistid
= playlistid
, playlistname
= playlistname
)
560 # Make a playlist from an album
561 def makePlaylist(self
, albumid
, name
):
562 userid
= self
._get
_login
()
564 re
.split(' - ',name
,1)
565 nameTokens
= re
.split(' - ',name
,1) # suggested name
566 name
= self
._get
_keyboard
(default
=nameTokens
[0], heading
=__language__(30045))
568 album
= groovesharkApi
.getAlbumSongs(albumid
, limit
= self
.songsearchlimit
)
571 songids
.append(song
[1])
572 if groovesharkApi
.createPlaylist(name
, songids
) == 0:
573 dialog
= xbmcgui
.Dialog()
574 dialog
.ok(__language__(30008), __language__(30046), name
)
576 xbmc
.executebuiltin('XBMC.Notification(' + __language__(30008) + ',' + __language__(30047)+ ', 1000, ' + thumbDef
+ ')')
578 dialog
= xbmcgui
.Dialog()
579 dialog
.ok(__language__(30008), __language__(30034), __language__(30048))
582 def renamePlaylist(self
, playlistid
, name
):
583 userid
= self
._get
_login
()
585 newname
= self
._get
_keyboard
(default
=name
, heading
=__language__(30049))
588 elif groovesharkApi
.playlistRename(playlistid
, newname
) == 0:
589 dialog
= xbmcgui
.Dialog()
590 dialog
.ok(__language__(30008), __language__(30050), name
)
592 # Refresh to show new item name
593 xbmc
.executebuiltin("Container.Refresh")
595 dialog
= xbmcgui
.Dialog()
596 dialog
.ok(__language__(30008), __language__(30034), __language__(30051))
599 def removePlaylist(self
, playlistid
, name
):
600 dialog
= xbmcgui
.Dialog()
601 if dialog
.yesno(__language__(30008), name
, __language__(30052)) == True:
602 userid
= self
._get
_login
()
604 if groovesharkApi
.playlistDelete(playlistid
) == 0:
605 dialog
= xbmcgui
.Dialog()
606 dialog
.ok(__language__(30008), __language__(30053), name
)
608 # Refresh to remove item from directory
609 xbmc
.executebuiltin("Container.Refresh(" + playlistsUrl
+ ")")
611 dialog
= xbmcgui
.Dialog()
612 dialog
.ok(__language__(30008), __language__(30034), __language__(30054))
614 # Add song to playlist
615 def addPlaylistSong(self
, songid
):
616 userid
= self
._get
_login
()
618 playlists
= groovesharkApi
.getUserPlaylists()
619 if (len(playlists
) > 0):
621 # Select the playlist
622 playlistSelect
= GroovesharkPlaylistSelect(items
=playlists
)
623 playlistSelect
.setFocus(playlistSelect
.playlistControl
)
624 playlistSelect
.doModal()
625 i
= playlistSelect
.selected
629 if i
>= len(playlists
):
630 name
= self
._get
_keyboard
(default
='', heading
=__language__(30055))
633 songIds
.append(songid
)
634 if groovesharkApi
.createPlaylist(name
, songIds
) == 0:
635 dialog
= xbmcgui
.Dialog()
636 dialog
.ok(__language__(30008), __language__(30056), name
)
638 xbmc
.executebuiltin('XBMC.Notification(' + __language__(30008) + ',' + __language__(30057) + ', 1000, ' + thumbDef
+ ')')
641 playlist
= playlists
[i
]
642 playlistid
= playlist
[1]
644 xbmc
.log("Add song " + str(songid
) + " to playlist " + str(playlistid
))
646 songs
= groovesharkApi
.getPlaylistSongs(playlistid
)
648 songIDs
.append(song
[1])
649 songIDs
.append(songid
)
650 ret
= groovesharkApi
.setPlaylistSongs(playlistid
, songIDs
)
652 dialog
= xbmcgui
.Dialog()
653 dialog
.ok(__language__(30008), __language__(30058))
655 xbmc
.executebuiltin('XBMC.Notification(' + __language__(30008) + ',' + __language__(30059) + ', 1000, ' + thumbDef
+ ')')
657 dialog
= xbmcgui
.Dialog()
658 dialog
.ok(__language__(30008), __language__(30060))
661 dialog
= xbmcgui
.Dialog()
662 dialog
.ok(__language__(30008), __language__(30034), __language__(30061))
664 # Remove song from playlist
665 def removePlaylistSong(self
, playlistid
, playlistname
, songid
):
666 dialog
= xbmcgui
.Dialog()
667 if dialog
.yesno(__language__(30008), __language__(30062), __language__(30063)) == True:
668 userid
= self
._get
_login
()
670 songs
= groovesharkApi
.getPlaylistSongs(playlistID
)
673 if (song
[1] != songid
):
674 songIDs
.append(song
[1])
675 ret
= groovesharkApi
.setPlaylistSongs(playlistID
, songIDs
)
677 dialog
= xbmcgui
.Dialog()
678 dialog
.ok(__language__(30008), __language__(30064), __language__(30065))
680 # Refresh to remove item from directory
681 xbmc
.executebuiltin('XBMC.Notification(' + __language__(30008) + ',' + __language__(30066)+ ', 1000, ' + thumbDef
+ ')')
682 xbmc
.executebuiltin("Container.Update(" + playlistUrl
+ "&id="+str(playlistid
) + "&name=" + str(playlistname
) + ")")
684 dialog
= xbmcgui
.Dialog()
685 dialog
.ok(__language__(30008), __language__(30034), __language__(30067))
687 # Find similar artists to searched artist
688 def similarArtists(self
, artistId
):
689 similar
= groovesharkApi
.getSimilarArtists(artistId
, limit
= self
.artistsearchlimit
)
690 if (len(similar
) > 0):
691 self
._add
_artists
_directory
(similar
)
693 dialog
= xbmcgui
.Dialog()
694 dialog
.ok(__language__(30008), __language__(30068))
698 def _get_keyboard(self
, default
="", heading
="", hidden
=False):
699 kb
= xbmc
.Keyboard(default
, heading
, hidden
)
701 if (kb
.isConfirmed()):
702 return unicode(kb
.getText(), "utf-8")
705 # Login to grooveshark
706 def _get_login(self
):
707 if (self
.username
== "" or self
.password
== ""):
708 dialog
= xbmcgui
.Dialog()
709 dialog
.ok(__language__(30008), __language__(30069), __language__(30070), __language__(30082))
713 uid
= groovesharkApi
.login(self
.username
, self
.password
)
717 dialog
= xbmcgui
.Dialog()
718 dialog
.ok(__language__(30008), __language__(30069), __language__(30070), __language__(30082))
722 def _get_icon(self
, url
, songid
):
724 localThumb
= os
.path
.join(xbmc
.translatePath(os
.path
.join(thumbDir
, str(songid
)))) + '.tbn'
726 if os
.path
.isfile(localThumb
) == False:
727 loc
= urllib
.URLopener()
728 loc
.retrieve(url
, localThumb
)
730 shutil
.copy2(thumbDef
, localThumb
)
731 return os
.path
.join(os
.path
.join(thumbDir
, str(songid
))) + '.tbn'
735 # Add songs to directory
736 def _add_songs_directory(self
, songs
, trackLabelFormat
=ARTIST_ALBUM_NAME_LABEL
, offset
=0, playlistid
=0, playlistname
='', isFavorites
=False):
738 totalSongs
= len(songs
)
744 if offset
== 0 and totalSongs
<= self
.songspagelimit
:
746 xbmc
.log("Found " + str(totalSongs
) + " songs...")
749 # Cache all next pages songs
751 self
._setSavedSongs
(songs
)
753 songs
= self
._getSavedSongs
()
754 totalSongs
= len(songs
)
758 end
= min(start
+ self
.songspagelimit
,totalSongs
)
769 item
= self
.songItem(songid
, name
, album
, artist
, coverart
, trackLabelFormat
, (n
+1))
771 coverart
= item
.getProperty('coverart')
775 u
=sys
.argv
[0]+"?mode="+str(MODE_SONG
)+"&name="+urllib
.quote_plus(songname
)+"&id="+str(songid
) \
776 +"&album="+urllib
.quote_plus(songalbum
) \
777 +"&artist="+urllib
.quote_plus(songartist
) \
778 +"&coverart="+urllib
.quote_plus(coverart
)
779 fav
=sys
.argv
[0]+"?mode="+str(MODE_FAVORITE
)+"&name="+urllib
.quote_plus(songname
)+"&id="+str(songid
)
780 unfav
=sys
.argv
[0]+"?mode="+str(MODE_UNFAVORITE
)+"&name="+urllib
.quote_plus(songname
)+"&id="+str(songid
)+"&prevmode="
782 if isFavorites
== True:
783 unfav
= unfav
+str(MODE_FAVORITES
)
785 menuItems
.append((__language__(30071), "XBMC.RunPlugin("+fav
+")"))
786 menuItems
.append((__language__(30072), "XBMC.RunPlugin("+unfav
+")"))
788 rmplaylstsong
=sys
.argv
[0]+"?playlistid="+str(playlistid
)+"&id="+str(songid
)+"&mode="+str(MODE_REMOVE_PLAYLIST_SONG
)+"&name="+str(playlistname
)
789 menuItems
.append((__language__(30073), "XBMC.RunPlugin("+rmplaylstsong
+")"))
791 addplaylstsong
=sys
.argv
[0]+"?id="+str(songid
)+"&mode="+str(MODE_ADD_PLAYLIST_SONG
)
792 menuItems
.append((__language__(30074), "XBMC.RunPlugin("+addplaylstsong
+")"))
793 item
.addContextMenuItems(menuItems
, replaceItems
=False)
794 xbmcplugin
.addDirectoryItem(handle
=int(sys
.argv
[1]),url
=u
,listitem
=item
,isFolder
=False, totalItems
=items
)
796 end
= min(end
+ 1,totalSongs
)
798 xbmc
.log(song
[0] + " does not exist.")
802 u
=sys
.argv
[0]+"?mode="+str(MODE_SONG_PAGE
)+"&id=playlistid"+"&offset="+str(end
)+"&label="+str(trackLabelFormat
)+"&name="+str(playlistname
)
803 self
._add
_dir
(__language__(30075) + '...', u
, MODE_SONG_PAGE
, self
.songImg
, 0, totalSongs
- end
)
805 xbmcplugin
.setContent(self
._handle
, 'songs')
806 xbmcplugin
.setPluginFanart(int(sys
.argv
[1]), self
.fanImg
)
808 # Add albums to directory
809 def _add_albums_directory(self
, albums
, artistid
=0, isverified
=False):
813 xbmc
.log("Found " + str(n
) + " albums...")
818 if isverified
or groovesharkApi
.getDoesAlbumExist(albumID
):
819 albumArtistName
= album
[0]
821 albumImage
= self
._get
_icon
(album
[4], 'album-' + str(albumID
))
822 self
._add
_dir
(albumName
+ " - " + albumArtistName
, '', MODE_ALBUM
, albumImage
, albumID
, itemsExisting
)
824 itemsExisting
= itemsExisting
- 1
826 # Not supported by key
828 # self._add_dir('Similar artists...', '', MODE_SIMILAR_ARTISTS, self.artistImg, artistid)
829 xbmcplugin
.setContent(self
._handle
, 'albums')
830 xbmcplugin
.addSortMethod(self
._handle
, xbmcplugin
.SORT_METHOD_ALBUM_IGNORE_THE
)
831 xbmcplugin
.setPluginFanart(int(sys
.argv
[1]), self
.fanImg
)
833 # Add artists to directory
834 def _add_artists_directory(self
, artists
):
838 xbmc
.log("Found " + str(n
) + " artists...")
843 if groovesharkApi
.getDoesArtistExist(artistID
):
844 artistName
= artist
[0]
845 self
._add
_dir
(artistName
, '', MODE_ARTIST
, self
.artistImg
, artistID
, itemsExisting
)
847 itemsExisting
= itemsExisting
- 1
849 xbmcplugin
.setContent(self
._handle
, 'artists')
850 xbmcplugin
.addSortMethod(self
._handle
, xbmcplugin
.SORT_METHOD_ARTIST_IGNORE_THE
)
851 xbmcplugin
.setPluginFanart(int(sys
.argv
[1]), self
.fanImg
)
853 # Add playlists to directory
854 def _add_playlists_directory(self
, playlists
):
857 xbmc
.log("Found " + str(n
) + " playlists...")
860 playlist
= playlists
[i
]
861 playlistName
= playlist
[0]
862 playlistID
= playlist
[1]
863 self
._add
_dir
(playlistName
, '', MODE_PLAYLIST
, self
.playlistImg
, playlistID
, n
)
865 xbmcplugin
.setContent(self
._handle
, 'files')
866 xbmcplugin
.addSortMethod(self
._handle
, xbmcplugin
.SORT_METHOD_LABEL
)
867 xbmcplugin
.setPluginFanart(int(sys
.argv
[1]), self
.fanImg
)
869 # Add whatever directory
870 def _add_dir(self
, name
, url
, mode
, iconimage
, itemId
, items
=1):
873 u
=sys
.argv
[0]+"?mode="+str(mode
)+"&name="+urllib
.quote_plus(name
)+"&id="+str(itemId
)
876 directory
=xbmcgui
.ListItem(name
, iconImage
=iconimage
, thumbnailImage
=iconimage
)
877 directory
.setInfo( type="Music", infoLabels
={ "title": name
} )
878 directory
.setProperty('fanart_image', self
.fanImg
)
882 if mode
== MODE_ALBUM
:
883 mkplaylst
=sys
.argv
[0]+"?mode="+str(MODE_MAKE_PLAYLIST
)+"&name="+name
+"&id="+str(itemId
)
884 menuItems
.append((__language__(30076), "XBMC.RunPlugin("+mkplaylst
+")"))
885 if mode
== MODE_PLAYLIST
:
886 rmplaylst
=sys
.argv
[0]+"?mode="+str(MODE_REMOVE_PLAYLIST
)+"&name="+urllib
.quote_plus(name
)+"&id="+str(itemId
)
887 menuItems
.append((__language__(30077), "XBMC.RunPlugin("+rmplaylst
+")"))
888 mvplaylst
=sys
.argv
[0]+"?mode="+str(MODE_RENAME_PLAYLIST
)+"&name="+urllib
.quote_plus(name
)+"&id="+str(itemId
)
889 menuItems
.append((__language__(30078), "XBMC.RunPlugin("+mvplaylst
+")"))
891 directory
.addContextMenuItems(menuItems
, replaceItems
=False)
893 return xbmcplugin
.addDirectoryItem(handle
=int(sys
.argv
[1]),url
=u
,listitem
=directory
,isFolder
=True, totalItems
=items
)
895 def _getSavedSongs(self
):
896 path
= os
.path
.join(cacheDir
, 'songs.dmp')
899 songs
= pickle
.load(f
)
906 def _setSavedSongs(self
, songs
):
908 # Create the 'data' directory if it doesn't exist.
909 if not os
.path
.exists(cacheDir
):
910 os
.makedirs(cacheDir
)
911 path
= os
.path
.join(cacheDir
, 'songs.dmp')
913 pickle
.dump(songs
, f
, protocol
=pickle
.HIGHEST_PROTOCOL
)
916 xbmc
.log("An error occurred saving songs")
919 # Duration to seconds
920 def _setDuration(self
, usecs
):
922 usecs
= usecs
* 10 # Some durations are 10x to small
923 return int(usecs
/ 1000000)
925 def _getSongStream(self
, songid
):
929 path
= os
.path
.join(cacheDir
, 'streams.dmp')
932 streams
= pickle
.load(f
)
934 if song
[0] == idSong
:
939 stream
= [idSong
, duration
, url
, key
, server
]
941 xbmc
.log("Found " + str(idSong
) + " in stream cache")
949 stream
= groovesharkApi
.getSubscriberStreamKey(songid
)
950 if stream
!= False and stream
['url'] != '':
951 duration
= self
._setDuration
(stream
['uSecs'])
953 key
= stream
['StreamKey']
954 server
= stream
['StreamServerID']
955 stream
= [idSong
, duration
, url
, key
, server
]
956 self
._addSongStream
(stream
)
960 def _addSongStream(self
, stream
):
961 streams
= self
._getStreams
()
962 streams
.append(stream
)
963 path
= os
.path
.join(cacheDir
, 'streams.dmp')
966 pickle
.dump(streams
, f
, protocol
=pickle
.HIGHEST_PROTOCOL
)
969 xbmc
.log("Added " + str(stream
[0]) + " to stream cache")
971 xbmc
.log("An error occurred adding to stream")
973 def _setSongStream(self
, stream
):
974 idStream
= int(stream
[0])
975 stream
[1] = self
._setDuration
(stream
[1])
976 streams
= self
._getStreams
()
977 path
= os
.path
.join(cacheDir
, 'streams.dmp')
981 if song
[0] == idStream
:
985 pickle
.dump(streams
, f
, protocol
=pickle
.HIGHEST_PROTOCOL
)
988 xbmc
.log("Updated " + str(idStream
) + " in stream cache")
991 xbmc
.log("An error occurred setting stream")
994 def _getStreams(self
):
995 path
= os
.path
.join(cacheDir
, 'streams.dmp')
998 streams
= pickle
.load(f
)
1006 # Parse URL parameters
1009 paramstring
=sys
.argv
[2]
1011 xbmc
.log(paramstring
)
1012 if len(paramstring
)>=2:
1014 cleanedparams
=params
.replace('?','')
1015 if (params
[len(params
)-1]=='/'):
1016 params
=params
[0:len(params
)-2]
1017 pairsofparams
=cleanedparams
.split('&')
1019 for i
in range(len(pairsofparams
)):
1021 splitparams
=pairsofparams
[i
].split('=')
1022 if (len(splitparams
))==2:
1023 param
[splitparams
[0]]=splitparams
[1]
1027 grooveshark
= Grooveshark();
1031 try: mode
=int(params
["mode"])
1034 try: itemId
=int(params
["id"])
1037 try: name
=urllib
.unquote_plus(params
["name"])
1040 # Call function for URL
1042 grooveshark
.categories()
1044 elif mode
==MODE_SEARCH_SONGS
:
1045 grooveshark
.searchSongs()
1047 elif mode
==MODE_SEARCH_ALBUMS
:
1048 grooveshark
.searchAlbums()
1050 elif mode
==MODE_SEARCH_ARTISTS
:
1051 grooveshark
.searchArtists()
1053 elif mode
==MODE_SEARCH_ARTISTS_ALBUMS
:
1054 grooveshark
.searchArtistsAlbums(name
)
1056 elif mode
==MODE_SEARCH_PLAYLISTS
:
1057 grooveshark
.searchPlaylists()
1059 elif mode
==MODE_POPULAR_SONGS
:
1060 grooveshark
.popularSongs()
1062 elif mode
==MODE_ARTIST_POPULAR
:
1063 grooveshark
.artistPopularSongs()
1065 elif mode
==MODE_FAVORITES
:
1066 grooveshark
.favorites()
1068 elif mode
==MODE_PLAYLISTS
:
1069 grooveshark
.playlists()
1071 elif mode
==MODE_SONG_PAGE
:
1072 try: offset
=urllib
.unquote_plus(params
["offset"])
1074 try: label
=urllib
.unquote_plus(params
["label"])
1076 grooveshark
.songPage(offset
, label
, itemId
, name
)
1078 elif mode
==MODE_SONG
:
1079 try: album
=urllib
.unquote_plus(params
["album"])
1081 try: artist
=urllib
.unquote_plus(params
["artist"])
1083 try: coverart
=urllib
.unquote_plus(params
["coverart"])
1085 song
= grooveshark
.songItem(itemId
, name
, album
, artist
, coverart
)
1086 grooveshark
.playSong(song
)
1088 elif mode
==MODE_ARTIST
:
1089 grooveshark
.artist(itemId
)
1091 elif mode
==MODE_ALBUM
:
1092 grooveshark
.album(itemId
)
1094 elif mode
==MODE_PLAYLIST
:
1095 grooveshark
.playlist(itemId
, name
)
1097 elif mode
==MODE_FAVORITE
:
1098 grooveshark
.favorite(itemId
)
1100 elif mode
==MODE_UNFAVORITE
:
1101 try: prevMode
=int(urllib
.unquote_plus(params
["prevmode"]))
1104 grooveshark
.unfavorite(itemId
, prevMode
)
1106 elif mode
==MODE_SIMILAR_ARTISTS
:
1107 grooveshark
.similarArtists(itemId
)
1109 elif mode
==MODE_MAKE_PLAYLIST
:
1110 grooveshark
.makePlaylist(itemId
, name
)
1112 elif mode
==MODE_REMOVE_PLAYLIST
:
1113 grooveshark
.removePlaylist(itemId
, name
)
1115 elif mode
==MODE_RENAME_PLAYLIST
:
1116 grooveshark
.renamePlaylist(itemId
, name
)
1118 elif mode
==MODE_REMOVE_PLAYLIST_SONG
:
1119 try: playlistID
=urllib
.unquote_plus(params
["playlistid"])
1121 grooveshark
.removePlaylistSong(playlistID
, name
, itemId
)
1123 elif mode
==MODE_ADD_PLAYLIST_SONG
:
1124 grooveshark
.addPlaylistSong(itemId
)
1126 if mode
< MODE_SONG
:
1127 xbmcplugin
.endOfDirectory(int(sys
.argv
[1]))