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
, 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):
361 xbmc
.log("Found " + artist
[0] + "...")
362 albums
= groovesharkApi
.getArtistAlbums(artistID
, self
.albumsearchlimit
)
363 if (len(albums
) > 0):
364 self
._add
_albums
_directory
(albums
, artistID
)
366 dialog
= xbmcgui
.Dialog()
367 dialog
.ok(__language__(30008), __language__(30029))
370 dialog
= xbmcgui
.Dialog()
371 dialog
.ok(__language__(30008), __language__(30030))
378 userid
= self
._get
_login
()
380 favorites
= groovesharkApi
.getUserFavoriteSongs()
381 if (len(favorites
) > 0):
382 self
._add
_songs
_directory
(favorites
, isFavorites
=True)
384 dialog
= xbmcgui
.Dialog()
385 dialog
.ok(__language__(30008), __language__(30031))
389 def popularSongs(self
):
390 popular
= groovesharkApi
.getPopularSongsToday(limit
= self
.songsearchlimit
)
391 if (len(popular
) > 0):
392 self
._add
_songs
_directory
(popular
)
394 dialog
= xbmcgui
.Dialog()
395 dialog
.ok(__language__(30008), __language__(30032))
400 userid
= self
._get
_login
()
402 playlists
= groovesharkApi
.getUserPlaylists()
403 if (len(playlists
) > 0):
404 self
._add
_playlists
_directory
(playlists
)
406 dialog
= xbmcgui
.Dialog()
407 dialog
.ok(__language__(30008), __language__(30033))
410 dialog
= xbmcgui
.Dialog()
411 dialog
.ok(__language__(30008), __language__(30034), __language__(30035))
413 # Make songs a favorite
414 def favorite(self
, songid
):
415 userid
= self
._get
_login
()
418 xbmc
.log("Favorite song: " + str(songid
))
419 groovesharkApi
.addUserFavoriteSong(songID
= songid
)
420 xbmc
.executebuiltin('XBMC.Notification(' + __language__(30008) + ', ' + __language__(30036) + ', 1000, ' + thumbDef
+ ')')
422 dialog
= xbmcgui
.Dialog()
423 dialog
.ok(__language__(30008), __language__(30034), __language__(30037))
425 # Remove song from favorites
426 def unfavorite(self
, songid
, prevMode
=0):
427 userid
= self
._get
_login
()
430 xbmc
.log("Unfavorite song: " + str(songid
) + ', previous mode was ' + str(prevMode
))
431 groovesharkApi
.removeUserFavoriteSongs(songIDs
= songid
)
432 xbmc
.executebuiltin('XBMC.Notification(' + __language__(30008) + ', ' + __language__(30038) + ', 1000, ' + thumbDef
+ ')')
433 # Refresh to remove item from directory
434 if (int(prevMode
) == MODE_FAVORITES
):
435 xbmc
.executebuiltin("Container.Refresh(" + favoritesUrl
+ ")")
437 dialog
= xbmcgui
.Dialog()
438 dialog
.ok(__language__(30008), __language__(30034), __language__(30039))
441 # Show selected album
442 def album(self
, albumid
):
443 album
= groovesharkApi
.getAlbumSongs(albumid
, limit
= self
.songsearchlimit
)
444 self
._add
_songs
_directory
(album
, trackLabelFormat
=NAME_ALBUM_ARTIST_LABEL
)
446 # Show selected artist
447 def artist(self
, artistid
):
448 albums
= groovesharkApi
.getArtistAlbums(artistid
, limit
= self
.albumsearchlimit
)
449 self
._add
_albums
_directory
(albums
, artistid
, True)
451 # Show selected playlist
452 def playlist(self
, playlistid
, playlistname
):
453 userid
= self
._get
_login
()
455 songs
= groovesharkApi
.getPlaylistSongs(playlistid
)
456 self
._add
_songs
_directory
(songs
, trackLabelFormat
=NAME_ALBUM_ARTIST_LABEL
, playlistid
=playlistid
, playlistname
=playlistname
)
458 dialog
= xbmcgui
.Dialog()
459 dialog
.ok(__language__(30008), __language__(30034), __language__(30040))
461 # Show popular songs of the artist
462 def artistPopularSongs(self
):
463 query
= self
._get
_keyboard
(default
="", heading
=__language__(30041))
465 artists
= groovesharkApi
.getArtistSearchResults(query
, limit
= self
.artistsearchlimit
)
466 if (len(artists
) > 0):
470 xbmc
.log("Found " + artist
[0] + "...")
471 songs
= groovesharkApi
.getArtistPopularSongs(artistID
, limit
= self
.songsearchlimit
)
473 self
._add
_songs
_directory
(songs
, trackLabelFormat
=NAME_ALBUM_ARTIST_LABEL
)
475 dialog
= xbmcgui
.Dialog()
476 dialog
.ok(__language__(30008), __language__(30042))
479 dialog
= xbmcgui
.Dialog()
480 dialog
.ok(__language__(30008), __language__(30043))
486 def playSong(self
, item
):
490 # Get stream as it could have expired
493 songid
= item
.getProperty('songid')
494 stream
= groovesharkApi
.getSubscriberStreamKey(songid
)
497 key
= stream
['StreamKey']
498 server
= stream
['StreamServerID']
499 duration
= int(self
._setDuration
(stream
['uSecs']))
500 stream
= [songid
, duration
, url
, key
, server
]
501 self
._setSongStream
(stream
)
504 xbmcplugin
.setResolvedUrl(handle
=int(sys
.argv
[1]), succeeded
=True, listitem
=item
)
506 xbmc
.log("Grooveshark playing: " + url
)
507 # Wait for play then start timer
509 while seconds
< STREAM_TIMEOUT
:
511 if player
.isPlayingAudio() == True:
512 if playTimer
!= None:
515 playTimer
= PlayTimer(1, markSong
, self
._setDuration
(duration
), [songid
, duration
, key
, server
])
520 seconds
= seconds
+ 1
522 xbmc
.log("No song URL")
524 xbmc
.log("No song stream")
526 xbmc
.executebuiltin('XBMC.Notification(' + __language__(30008) + ', ' + __language__(30044) + ', 1000, ' + thumbDef
+ ')')
528 # Make a song directory item
529 def songItem(self
, songid
, name
, album
, artist
, coverart
, trackLabelFormat
=ARTIST_ALBUM_NAME_LABEL
, tracknumber
=1):
531 stream
= self
._getSongStream
(songid
)
537 songImg
= self
._get
_icon
(coverart
, 'song-' + str(songid
) + "-image")
538 if int(trackLabelFormat
) == NAME_ALBUM_ARTIST_LABEL
:
539 trackLabel
= name
+ " - " + album
+ " - " + artist
541 trackLabel
= artist
+ " - " + album
+ " - " + name
542 item
= xbmcgui
.ListItem(label
= trackLabel
, thumbnailImage
=songImg
, iconImage
=songImg
)
544 item
.setInfo( type="music", infoLabels
={ "title": name
, "album": album
, "artist": artist
, "duration": duration
, "tracknumber" : tracknumber
} )
545 item
.setProperty('mimetype', 'audio/mpeg')
546 item
.setProperty("IsPlayable", "true")
547 item
.setProperty('songid', str(songid
))
548 item
.setProperty('coverart', songImg
)
549 item
.setProperty('title', name
)
550 item
.setProperty('album', album
)
551 item
.setProperty('artist', artist
)
552 item
.setProperty('duration', str(duration
))
553 item
.setProperty('key', str(key
))
554 item
.setProperty('server', str(server
))
555 item
.setProperty('fanart_image', self
.fanImg
)
558 xbmc
.log("No access to song URL")
562 def songPage(self
, offset
, trackLabelFormat
, playlistid
= 0, playlistname
= ''):
563 self
._add
_songs
_directory
([], trackLabelFormat
, offset
, playlistid
= playlistid
, playlistname
= playlistname
)
565 # Make a playlist from an album
566 def makePlaylist(self
, albumid
, name
):
567 userid
= self
._get
_login
()
569 re
.split(' - ',name
,1)
570 nameTokens
= re
.split(' - ',name
,1) # suggested name
571 name
= self
._get
_keyboard
(default
=nameTokens
[0], heading
=__language__(30045))
573 album
= groovesharkApi
.getAlbumSongs(albumid
, limit
= self
.songsearchlimit
)
576 songids
.append(song
[1])
577 if groovesharkApi
.createPlaylist(name
, songids
) == 0:
578 dialog
= xbmcgui
.Dialog()
579 dialog
.ok(__language__(30008), __language__(30046), name
)
581 xbmc
.executebuiltin('XBMC.Notification(' + __language__(30008) + ',' + __language__(30047)+ ', 1000, ' + thumbDef
+ ')')
583 dialog
= xbmcgui
.Dialog()
584 dialog
.ok(__language__(30008), __language__(30034), __language__(30048))
587 def renamePlaylist(self
, playlistid
, name
):
588 userid
= self
._get
_login
()
590 newname
= self
._get
_keyboard
(default
=name
, heading
=__language__(30049))
593 elif groovesharkApi
.playlistRename(playlistid
, newname
) == 0:
594 dialog
= xbmcgui
.Dialog()
595 dialog
.ok(__language__(30008), __language__(30050), name
)
597 # Refresh to show new item name
598 xbmc
.executebuiltin("Container.Refresh")
600 dialog
= xbmcgui
.Dialog()
601 dialog
.ok(__language__(30008), __language__(30034), __language__(30051))
604 def removePlaylist(self
, playlistid
, name
):
605 dialog
= xbmcgui
.Dialog()
606 if dialog
.yesno(__language__(30008), name
, __language__(30052)) == True:
607 userid
= self
._get
_login
()
609 if groovesharkApi
.playlistDelete(playlistid
) == 0:
610 dialog
= xbmcgui
.Dialog()
611 dialog
.ok(__language__(30008), __language__(30053), name
)
613 # Refresh to remove item from directory
614 xbmc
.executebuiltin("Container.Refresh(" + playlistsUrl
+ ")")
616 dialog
= xbmcgui
.Dialog()
617 dialog
.ok(__language__(30008), __language__(30034), __language__(30054))
619 # Add song to playlist
620 def addPlaylistSong(self
, songid
):
621 userid
= self
._get
_login
()
623 playlists
= groovesharkApi
.getUserPlaylists()
624 if (len(playlists
) > 0):
626 # Select the playlist
627 playlistSelect
= GroovesharkPlaylistSelect(items
=playlists
)
628 playlistSelect
.setFocus(playlistSelect
.playlistControl
)
629 playlistSelect
.doModal()
630 i
= playlistSelect
.selected
634 if i
>= len(playlists
):
635 name
= self
._get
_keyboard
(default
='', heading
=__language__(30055))
638 songIds
.append(songid
)
639 if groovesharkApi
.createPlaylist(name
, songIds
) == 0:
640 dialog
= xbmcgui
.Dialog()
641 dialog
.ok(__language__(30008), __language__(30056), name
)
643 xbmc
.executebuiltin('XBMC.Notification(' + __language__(30008) + ',' + __language__(30057) + ', 1000, ' + thumbDef
+ ')')
646 playlist
= playlists
[i
]
647 playlistid
= playlist
[1]
649 xbmc
.log("Add song " + str(songid
) + " to playlist " + str(playlistid
))
651 songs
= groovesharkApi
.getPlaylistSongs(playlistid
)
653 songIDs
.append(song
[1])
654 songIDs
.append(songid
)
655 ret
= groovesharkApi
.setPlaylistSongs(playlistid
, songIDs
)
657 dialog
= xbmcgui
.Dialog()
658 dialog
.ok(__language__(30008), __language__(30058))
660 xbmc
.executebuiltin('XBMC.Notification(' + __language__(30008) + ',' + __language__(30059) + ', 1000, ' + thumbDef
+ ')')
662 dialog
= xbmcgui
.Dialog()
663 dialog
.ok(__language__(30008), __language__(30060))
666 dialog
= xbmcgui
.Dialog()
667 dialog
.ok(__language__(30008), __language__(30034), __language__(30061))
669 # Remove song from playlist
670 def removePlaylistSong(self
, playlistid
, playlistname
, songid
):
671 dialog
= xbmcgui
.Dialog()
672 if dialog
.yesno(__language__(30008), __language__(30062), __language__(30063)) == True:
673 userid
= self
._get
_login
()
675 songs
= groovesharkApi
.getPlaylistSongs(playlistID
)
678 if (song
[1] != songid
):
679 songIDs
.append(song
[1])
680 ret
= groovesharkApi
.setPlaylistSongs(playlistID
, songIDs
)
682 dialog
= xbmcgui
.Dialog()
683 dialog
.ok(__language__(30008), __language__(30064), __language__(30065))
685 # Refresh to remove item from directory
686 xbmc
.executebuiltin('XBMC.Notification(' + __language__(30008) + ',' + __language__(30066)+ ', 1000, ' + thumbDef
+ ')')
687 xbmc
.executebuiltin("Container.Update(" + playlistUrl
+ "&id="+str(playlistid
) + "&name=" + str(playlistname
) + ")")
689 dialog
= xbmcgui
.Dialog()
690 dialog
.ok(__language__(30008), __language__(30034), __language__(30067))
692 # Find similar artists to searched artist
693 def similarArtists(self
, artistId
):
694 similar
= groovesharkApi
.getSimilarArtists(artistId
, limit
= self
.artistsearchlimit
)
695 if (len(similar
) > 0):
696 self
._add
_artists
_directory
(similar
)
698 dialog
= xbmcgui
.Dialog()
699 dialog
.ok(__language__(30008), __language__(30068))
703 def _get_keyboard(self
, default
="", heading
="", hidden
=False):
704 kb
= xbmc
.Keyboard(default
, heading
, hidden
)
706 if (kb
.isConfirmed()):
707 return unicode(kb
.getText(), "utf-8")
710 # Login to grooveshark
711 def _get_login(self
):
712 if (self
.username
== "" or self
.password
== ""):
713 dialog
= xbmcgui
.Dialog()
714 dialog
.ok(__language__(30008), __language__(30069), __language__(30070), __language__(30082))
718 uid
= groovesharkApi
.login(self
.username
, self
.password
)
722 dialog
= xbmcgui
.Dialog()
723 dialog
.ok(__language__(30008), __language__(30069), __language__(30070), __language__(30082))
727 def _get_icon(self
, url
, songid
):
729 localThumb
= os
.path
.join(xbmc
.translatePath(os
.path
.join(thumbDir
, str(songid
)))) + '.tbn'
731 if os
.path
.isfile(localThumb
) == False:
732 loc
= urllib
.URLopener()
733 loc
.retrieve(url
, localThumb
)
735 shutil
.copy2(thumbDef
, localThumb
)
736 return os
.path
.join(os
.path
.join(thumbDir
, str(songid
))) + '.tbn'
740 # Add songs to directory
741 def _add_songs_directory(self
, songs
, trackLabelFormat
=ARTIST_ALBUM_NAME_LABEL
, offset
=0, playlistid
=0, playlistname
='', isFavorites
=False):
743 totalSongs
= len(songs
)
749 if offset
== 0 and totalSongs
<= self
.songspagelimit
:
751 xbmc
.log("Found " + str(totalSongs
) + " songs...")
754 # Cache all next pages songs
756 self
._setSavedSongs
(songs
)
758 songs
= self
._getSavedSongs
()
759 totalSongs
= len(songs
)
763 end
= min(start
+ self
.songspagelimit
,totalSongs
)
774 item
= self
.songItem(songid
, name
, album
, artist
, coverart
, trackLabelFormat
, (n
+1))
776 coverart
= item
.getProperty('coverart')
780 u
=sys
.argv
[0]+"?mode="+str(MODE_SONG
)+"&name="+urllib
.quote_plus(songname
)+"&id="+str(songid
) \
781 +"&album="+urllib
.quote_plus(songalbum
) \
782 +"&artist="+urllib
.quote_plus(songartist
) \
783 +"&coverart="+urllib
.quote_plus(coverart
)
784 fav
=sys
.argv
[0]+"?mode="+str(MODE_FAVORITE
)+"&name="+urllib
.quote_plus(songname
)+"&id="+str(songid
)
785 unfav
=sys
.argv
[0]+"?mode="+str(MODE_UNFAVORITE
)+"&name="+urllib
.quote_plus(songname
)+"&id="+str(songid
)+"&prevmode="
787 if isFavorites
== True:
788 unfav
= unfav
+str(MODE_FAVORITES
)
790 menuItems
.append((__language__(30071), "XBMC.RunPlugin("+fav
+")"))
791 menuItems
.append((__language__(30072), "XBMC.RunPlugin("+unfav
+")"))
793 rmplaylstsong
=sys
.argv
[0]+"?playlistid="+str(playlistid
)+"&id="+str(songid
)+"&mode="+str(MODE_REMOVE_PLAYLIST_SONG
)+"&name="+str(playlistname
)
794 menuItems
.append((__language__(30073), "XBMC.RunPlugin("+rmplaylstsong
+")"))
796 addplaylstsong
=sys
.argv
[0]+"?id="+str(songid
)+"&mode="+str(MODE_ADD_PLAYLIST_SONG
)
797 menuItems
.append((__language__(30074), "XBMC.RunPlugin("+addplaylstsong
+")"))
798 item
.addContextMenuItems(menuItems
, replaceItems
=False)
799 xbmcplugin
.addDirectoryItem(handle
=int(sys
.argv
[1]),url
=u
,listitem
=item
,isFolder
=False, totalItems
=items
)
801 end
= min(end
+ 1,totalSongs
)
803 xbmc
.log(song
[0] + " does not exist.")
807 u
=sys
.argv
[0]+"?mode="+str(MODE_SONG_PAGE
)+"&id=playlistid"+"&offset="+str(end
)+"&label="+str(trackLabelFormat
)+"&name="+str(playlistname
)
808 self
._add
_dir
(__language__(30075) + '...', u
, MODE_SONG_PAGE
, self
.songImg
, 0, totalSongs
- end
)
810 xbmcplugin
.setContent(self
._handle
, 'songs')
811 xbmcplugin
.setPluginFanart(int(sys
.argv
[1]), self
.fanImg
)
813 # Add albums to directory
814 def _add_albums_directory(self
, albums
, artistid
=0, isverified
=False):
818 xbmc
.log("Found " + str(n
) + " albums...")
823 if isverified
or groovesharkApi
.getDoesAlbumExist(albumID
):
824 albumArtistName
= album
[0]
826 albumImage
= self
._get
_icon
(album
[4], 'album-' + str(albumID
))
827 self
._add
_dir
(albumName
+ " - " + albumArtistName
, '', MODE_ALBUM
, albumImage
, albumID
, itemsExisting
)
829 itemsExisting
= itemsExisting
- 1
831 # Not supported by key
833 # self._add_dir('Similar artists...', '', MODE_SIMILAR_ARTISTS, self.artistImg, artistid)
834 xbmcplugin
.setContent(self
._handle
, 'albums')
835 xbmcplugin
.addSortMethod(self
._handle
, xbmcplugin
.SORT_METHOD_ALBUM_IGNORE_THE
)
836 xbmcplugin
.setPluginFanart(int(sys
.argv
[1]), self
.fanImg
)
838 # Add artists to directory
839 def _add_artists_directory(self
, artists
):
843 xbmc
.log("Found " + str(n
) + " artists...")
848 if groovesharkApi
.getDoesArtistExist(artistID
):
849 artistName
= artist
[0]
850 self
._add
_dir
(artistName
, '', MODE_ARTIST
, self
.artistImg
, artistID
, itemsExisting
)
852 itemsExisting
= itemsExisting
- 1
854 xbmcplugin
.setContent(self
._handle
, 'artists')
855 xbmcplugin
.addSortMethod(self
._handle
, xbmcplugin
.SORT_METHOD_ARTIST_IGNORE_THE
)
856 xbmcplugin
.setPluginFanart(int(sys
.argv
[1]), self
.fanImg
)
858 # Add playlists to directory
859 def _add_playlists_directory(self
, playlists
):
862 xbmc
.log("Found " + str(n
) + " playlists...")
865 playlist
= playlists
[i
]
866 playlistName
= playlist
[0]
867 playlistID
= playlist
[1]
868 self
._add
_dir
(playlistName
, '', MODE_PLAYLIST
, self
.playlistImg
, playlistID
, n
)
870 xbmcplugin
.setContent(self
._handle
, 'files')
871 xbmcplugin
.addSortMethod(self
._handle
, xbmcplugin
.SORT_METHOD_LABEL
)
872 xbmcplugin
.setPluginFanart(int(sys
.argv
[1]), self
.fanImg
)
874 # Add whatever directory
875 def _add_dir(self
, name
, url
, mode
, iconimage
, itemId
, items
=1):
878 u
=sys
.argv
[0]+"?mode="+str(mode
)+"&name="+urllib
.quote_plus(name
)+"&id="+str(itemId
)
881 directory
=xbmcgui
.ListItem(name
, iconImage
=iconimage
, thumbnailImage
=iconimage
)
882 directory
.setInfo( type="Music", infoLabels
={ "title": name
} )
883 directory
.setProperty('fanart_image', self
.fanImg
)
887 if mode
== MODE_ALBUM
:
888 mkplaylst
=sys
.argv
[0]+"?mode="+str(MODE_MAKE_PLAYLIST
)+"&name="+name
+"&id="+str(itemId
)
889 menuItems
.append((__language__(30076), "XBMC.RunPlugin("+mkplaylst
+")"))
890 if mode
== MODE_PLAYLIST
:
891 rmplaylst
=sys
.argv
[0]+"?mode="+str(MODE_REMOVE_PLAYLIST
)+"&name="+urllib
.quote_plus(name
)+"&id="+str(itemId
)
892 menuItems
.append((__language__(30077), "XBMC.RunPlugin("+rmplaylst
+")"))
893 mvplaylst
=sys
.argv
[0]+"?mode="+str(MODE_RENAME_PLAYLIST
)+"&name="+urllib
.quote_plus(name
)+"&id="+str(itemId
)
894 menuItems
.append((__language__(30078), "XBMC.RunPlugin("+mvplaylst
+")"))
896 directory
.addContextMenuItems(menuItems
, replaceItems
=False)
898 return xbmcplugin
.addDirectoryItem(handle
=int(sys
.argv
[1]),url
=u
,listitem
=directory
,isFolder
=True, totalItems
=items
)
900 def _getSavedSongs(self
):
901 path
= os
.path
.join(cacheDir
, 'songs.dmp')
904 songs
= pickle
.load(f
)
911 def _setSavedSongs(self
, songs
):
913 # Create the 'data' directory if it doesn't exist.
914 if not os
.path
.exists(cacheDir
):
915 os
.makedirs(cacheDir
)
916 path
= os
.path
.join(cacheDir
, 'songs.dmp')
918 pickle
.dump(songs
, f
, protocol
=pickle
.HIGHEST_PROTOCOL
)
921 xbmc
.log("An error occurred saving songs")
924 # Duration to seconds
925 def _setDuration(self
, usecs
):
927 usecs
= usecs
* 10 # Some durations are 10x to small
928 return int(usecs
/ 1000000)
930 def _getSongStream(self
, songid
):
934 path
= os
.path
.join(cacheDir
, 'streams.dmp')
937 streams
= pickle
.load(f
)
939 if song
[0] == idSong
:
944 stream
= [idSong
, duration
, url
, key
, server
]
946 xbmc
.log("Found " + str(idSong
) + " in stream cache")
954 stream
= groovesharkApi
.getSubscriberStreamKey(songid
)
955 if stream
!= False and stream
['url'] != '':
956 duration
= self
._setDuration
(stream
['uSecs'])
958 key
= stream
['StreamKey']
959 server
= stream
['StreamServerID']
960 stream
= [idSong
, duration
, url
, key
, server
]
961 self
._addSongStream
(stream
)
965 def _addSongStream(self
, stream
):
966 streams
= self
._getStreams
()
967 streams
.append(stream
)
968 path
= os
.path
.join(cacheDir
, 'streams.dmp')
971 pickle
.dump(streams
, f
, protocol
=pickle
.HIGHEST_PROTOCOL
)
974 xbmc
.log("Added " + str(stream
[0]) + " to stream cache")
976 xbmc
.log("An error occurred adding to stream")
978 def _setSongStream(self
, stream
):
979 idStream
= int(stream
[0])
980 stream
[1] = self
._setDuration
(stream
[1])
981 streams
= self
._getStreams
()
982 path
= os
.path
.join(cacheDir
, 'streams.dmp')
986 if song
[0] == idStream
:
990 pickle
.dump(streams
, f
, protocol
=pickle
.HIGHEST_PROTOCOL
)
993 xbmc
.log("Updated " + str(idStream
) + " in stream cache")
996 xbmc
.log("An error occurred setting stream")
999 def _getStreams(self
):
1000 path
= os
.path
.join(cacheDir
, 'streams.dmp')
1002 f
= open(path
, 'rb')
1003 streams
= pickle
.load(f
)
1011 # Parse URL parameters
1014 paramstring
=sys
.argv
[2]
1016 xbmc
.log(paramstring
)
1017 if len(paramstring
)>=2:
1019 cleanedparams
=params
.replace('?','')
1020 if (params
[len(params
)-1]=='/'):
1021 params
=params
[0:len(params
)-2]
1022 pairsofparams
=cleanedparams
.split('&')
1024 for i
in range(len(pairsofparams
)):
1026 splitparams
=pairsofparams
[i
].split('=')
1027 if (len(splitparams
))==2:
1028 param
[splitparams
[0]]=splitparams
[1]
1032 grooveshark
= Grooveshark();
1036 try: mode
=int(params
["mode"])
1039 try: itemId
=int(params
["id"])
1042 try: name
=urllib
.unquote_plus(params
["name"])
1045 # Call function for URL
1047 grooveshark
.categories()
1049 elif mode
==MODE_SEARCH_SONGS
:
1050 grooveshark
.searchSongs()
1052 elif mode
==MODE_SEARCH_ALBUMS
:
1053 grooveshark
.searchAlbums()
1055 elif mode
==MODE_SEARCH_ARTISTS
:
1056 grooveshark
.searchArtists()
1058 elif mode
==MODE_SEARCH_ARTISTS_ALBUMS
:
1059 grooveshark
.searchArtistsAlbums(name
)
1061 elif mode
==MODE_SEARCH_PLAYLISTS
:
1062 grooveshark
.searchPlaylists()
1064 elif mode
==MODE_POPULAR_SONGS
:
1065 grooveshark
.popularSongs()
1067 elif mode
==MODE_ARTIST_POPULAR
:
1068 grooveshark
.artistPopularSongs()
1070 elif mode
==MODE_FAVORITES
:
1071 grooveshark
.favorites()
1073 elif mode
==MODE_PLAYLISTS
:
1074 grooveshark
.playlists()
1076 elif mode
==MODE_SONG_PAGE
:
1077 try: offset
=urllib
.unquote_plus(params
["offset"])
1079 try: label
=urllib
.unquote_plus(params
["label"])
1081 grooveshark
.songPage(offset
, label
, itemId
, name
)
1083 elif mode
==MODE_SONG
:
1084 try: album
=urllib
.unquote_plus(params
["album"])
1086 try: artist
=urllib
.unquote_plus(params
["artist"])
1088 try: coverart
=urllib
.unquote_plus(params
["coverart"])
1090 song
= grooveshark
.songItem(itemId
, name
, album
, artist
, coverart
)
1091 grooveshark
.playSong(song
)
1093 elif mode
==MODE_ARTIST
:
1094 grooveshark
.artist(itemId
)
1096 elif mode
==MODE_ALBUM
:
1097 grooveshark
.album(itemId
)
1099 elif mode
==MODE_PLAYLIST
:
1100 grooveshark
.playlist(itemId
, name
)
1102 elif mode
==MODE_FAVORITE
:
1103 grooveshark
.favorite(itemId
)
1105 elif mode
==MODE_UNFAVORITE
:
1106 try: prevMode
=int(urllib
.unquote_plus(params
["prevmode"]))
1109 grooveshark
.unfavorite(itemId
, prevMode
)
1111 elif mode
==MODE_SIMILAR_ARTISTS
:
1112 grooveshark
.similarArtists(itemId
)
1114 elif mode
==MODE_MAKE_PLAYLIST
:
1115 grooveshark
.makePlaylist(itemId
, name
)
1117 elif mode
==MODE_REMOVE_PLAYLIST
:
1118 grooveshark
.removePlaylist(itemId
, name
)
1120 elif mode
==MODE_RENAME_PLAYLIST
:
1121 grooveshark
.renamePlaylist(itemId
, name
)
1123 elif mode
==MODE_REMOVE_PLAYLIST_SONG
:
1124 try: playlistID
=urllib
.unquote_plus(params
["playlistid"])
1126 grooveshark
.removePlaylistSong(playlistID
, name
, itemId
)
1128 elif mode
==MODE_ADD_PLAYLIST_SONG
:
1129 grooveshark
.addPlaylistSong(itemId
)
1131 if mode
< MODE_SONG
:
1132 xbmcplugin
.endOfDirectory(int(sys
.argv
[1]))