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
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
68 player
= xbmc
.Player()
72 resDir
= xbmc
.translatePath(os
.path
.join(baseDir
, 'resources'))
73 libDir
= xbmc
.translatePath(os
.path
.join(resDir
, 'lib'))
74 imgDir
= xbmc
.translatePath(os
.path
.join(resDir
, 'img'))
75 cacheDir
= os
.path
.join(xbmc
.translatePath('special://masterprofile/addon_data/'), os
.path
.basename(baseDir
))
76 thumbDirName
= 'thumb'
77 thumbDir
= os
.path
.join('special://masterprofile/addon_data/', os
.path
.basename(baseDir
), thumbDirName
)
79 baseModeUrl
= 'plugin://plugin.audio.groove/'
80 playlistUrl
= baseModeUrl
+ '?mode=' + str(MODE_PLAYLIST
)
81 playlistsUrl
= baseModeUrl
+ '?mode=' + str(MODE_PLAYLISTS
)
82 favoritesUrl
= baseModeUrl
+ '?mode=' + str(MODE_FAVORITES
)
84 searchArtistsAlbumsName
= __language__(30006)
86 thumbDef
= os
.path
.join(imgDir
, 'default.tbn')
87 listBackground
= os
.path
.join(imgDir
, 'listbackground.png')
89 sys
.path
.append (libDir
)
90 from GroovesharkAPI
import GrooveAPI
91 from threading
import Event
, Thread
94 groovesharkApi
= GrooveAPI()
95 if groovesharkApi
.pingService() != True:
96 raise StandardError(__language__(30007))
98 dialog
= xbmcgui
.Dialog(__language__(30008),__language__(30009),__language__(30010))
102 # Mark song as playing or played
103 def markSong(songid
, duration
):
107 if player
.isPlayingAudio():
108 tNow
= player
.getTime()
109 if tNow
>= STREAM_MARKING_TIME
and songMarkTime
== 0:
110 groovesharkApi
.markStreamKeyOver30Secs()
112 elif duration
> tNow
and duration
- tNow
< 2 and songMarkTime
>= STREAM_MARKING_TIME
:
115 groovesharkApi
.markSongComplete(songid
)
121 def __init__( self
, *args
, **kwargs
):
122 self
.__dict
__.update( kwargs
)
124 # Window dialog to select a grooveshark playlist
125 class GroovesharkPlaylistSelect(xbmcgui
.WindowDialog
):
127 def __init__(self
, items
=[]):
128 gap
= int(self
.getHeight()/100)
129 w
= int(self
.getWidth()*0.5)
130 h
= self
.getHeight()-30*gap
132 rh
= self
.getHeight()
136 self
.imgBg
= xbmcgui
.ControlImage(x
+gap
, 5*gap
+y
, w
-2*gap
, h
-5*gap
, listBackground
)
137 self
.addControl(self
.imgBg
)
139 self
.playlistControl
= xbmcgui
.ControlList(2*gap
+x
, y
+3*gap
+30, w
-4*gap
, h
-10*gap
, textColor
='0xFFFFFFFF', selectedColor
='0xFFFF4242', itemTextYOffset
=0, itemHeight
=50, alignmentY
= 0)
140 self
.addControl(self
.playlistControl
)
143 self
.isSelecting
= False
146 for playlist
in items
:
147 listitems
.append(xbmcgui
.ListItem(playlist
[0]))
148 listitems
.append(xbmcgui
.ListItem(__language__(30011)))
149 self
.playlistControl
.addItems(listitems
)
150 self
.setFocus(self
.playlistControl
)
151 self
.playlistControl
.selectItem(0)
152 item
= self
.playlistControl
.getListItem(self
.lastPos
)
155 # Highlight selected item
156 def setHighlight(self
):
160 self
.isSelecting
= True
162 pos
= self
.playlistControl
.getSelectedPosition()
164 item
= self
.playlistControl
.getListItem(self
.lastPos
)
166 item
= self
.playlistControl
.getListItem(pos
)
169 self
.isSelecting
= False
172 def onControl(self
, control
):
173 if control
== self
.playlistControl
:
174 self
.selected
= self
.playlistControl
.getSelectedPosition()
177 # Action - close or up/down
178 def onAction(self
, action
):
179 if action
== ACTION_PREVIOUS_MENU
:
182 elif action
== ACTION_MOVE_UP
or action
== ACTION_MOVE_DOWN
or action
== ACTION_PAGE_UP
or action
== ACTION_PAGE_DOWN
== 6:
183 self
.setFocus(self
.playlistControl
)
187 class PlayTimer(Thread
):
188 # interval -- floating point number specifying the number of seconds to wait before executing function
189 # function -- the function (or callable object) to be executed
191 # iterations -- integer specifying the number of iterations to perform
192 # args -- list of positional arguments passed to function
193 # kwargs -- dictionary of keyword arguments passed to function
195 def __init__(self
, interval
, function
, iterations
=0, args
=[], kwargs
={}):
196 Thread
.__init
__(self
)
197 self
.interval
= interval
198 self
.function
= function
199 self
.iterations
= iterations
202 self
.finished
= Event()
206 while not self
.finished
.isSet() and (self
.iterations
<= 0 or count
< self
.iterations
):
207 self
.finished
.wait(self
.interval
)
208 if not self
.finished
.isSet():
209 self
.function(*self
.args
, **self
.kwargs
)
215 def setIterations(self
, iterations
):
216 self
.iterations
= iterations
220 return self
.iterations
* self
.interval
225 albumImg
= xbmc
.translatePath(os
.path
.join(imgDir
, 'album.png'))
226 artistImg
= xbmc
.translatePath(os
.path
.join(imgDir
, 'artist.png'))
227 artistsAlbumsImg
= xbmc
.translatePath(os
.path
.join(imgDir
, 'artistsalbums.png'))
228 favoritesImg
= xbmc
.translatePath(os
.path
.join(imgDir
, 'favorites.png'))
229 playlistImg
= xbmc
.translatePath(os
.path
.join(imgDir
, 'playlist.png'))
230 usersplaylistsImg
= xbmc
.translatePath(os
.path
.join(imgDir
, 'usersplaylists.png'))
231 popularSongsImg
= xbmc
.translatePath(os
.path
.join(imgDir
, 'popularSongs.png'))
232 popularSongsArtistImg
= xbmc
.translatePath(os
.path
.join(imgDir
, 'popularSongsArtist.png'))
233 songImg
= xbmc
.translatePath(os
.path
.join(imgDir
, 'song.png'))
234 defImg
= xbmc
.translatePath(os
.path
.join(imgDir
, 'default.tbn'))
235 fanImg
= xbmc
.translatePath(os
.path
.join(baseDir
, 'fanart.png'))
237 settings
= xbmcaddon
.Addon(id='plugin.audio.groove')
238 songsearchlimit
= int(settings
.getSetting('songsearchlimit'))
239 albumsearchlimit
= int(settings
.getSetting('albumsearchlimit'))
240 artistsearchlimit
= int(settings
.getSetting('artistsearchlimit'))
241 songspagelimit
= int(settings
.getSetting('songspagelimit'))
242 username
= settings
.getSetting('username')
243 password
= settings
.getSetting('password')
247 def __init__( self
):
248 self
._handle
= int(sys
.argv
[1])
250 if os
.path
.isdir(cacheDir
) == False:
251 os
.makedirs(cacheDir
)
253 xbmc
.log(__language__(30012) + " " + cacheDir
)
254 artDir
= xbmc
.translatePath(thumbDir
)
255 if os
.path
.isdir(artDir
) == False:
258 xbmc
.log(__language__(30012) + " " + artDir
)
261 def categories(self
):
263 self
.userid
= self
._get
_login
()
266 xbmcplugin
.setPluginFanart(int(sys
.argv
[1]), self
.fanImg
)
268 self
._add
_dir
(__language__(30013), '', MODE_SEARCH_SONGS
, self
.songImg
, 0)
269 self
._add
_dir
(__language__(30014), '', MODE_SEARCH_ALBUMS
, self
.albumImg
, 0)
270 self
._add
_dir
(__language__(30015), '', MODE_SEARCH_ARTISTS
, self
.artistImg
, 0)
271 self
._add
_dir
(searchArtistsAlbumsName
, '', MODE_SEARCH_ARTISTS_ALBUMS
, self
.artistsAlbumsImg
, 0)
272 # Not supported by key
273 #self._add_dir("Search for user's playlists...", '', MODE_SEARCH_PLAYLISTS, self.usersplaylistsImg, 0)
274 self
._add
_dir
(__language__(30016), '', MODE_ARTIST_POPULAR
, self
.popularSongsArtistImg
, 0)
275 self
._add
_dir
(__language__(30017), '', MODE_POPULAR_SONGS
, self
.popularSongsImg
, 0)
276 if (self
.userid
!= 0):
277 self
._add
_dir
(__language__(30018), '', MODE_FAVORITES
, self
.favoritesImg
, 0)
278 self
._add
_dir
(__language__(30019), '', MODE_PLAYLISTS
, self
.playlistImg
, 0)
281 def searchSongs(self
):
282 query
= self
._get
_keyboard
(default
="", heading
=__language__(30020))
284 songs
= groovesharkApi
.getSongSearchResults(query
, limit
= self
.songsearchlimit
)
286 self
._add
_songs
_directory
(songs
)
288 dialog
= xbmcgui
.Dialog()
289 dialog
.ok(__language__(30008), __language__(30021))
295 def searchAlbums(self
):
296 query
= self
._get
_keyboard
(default
="", heading
=__language__(30022))
298 albums
= groovesharkApi
.getAlbumSearchResults(query
, limit
= self
.albumsearchlimit
)
299 if (len(albums
) > 0):
300 self
._add
_albums
_directory
(albums
)
302 dialog
= xbmcgui
.Dialog()
303 dialog
.ok(__language__(30008), __language__(30023))
309 def searchArtists(self
):
310 query
= self
._get
_keyboard
(default
="", heading
=__language__(30024))
312 artists
= groovesharkApi
.getArtistSearchResults(query
, limit
= self
.artistsearchlimit
)
313 if (len(artists
) > 0):
314 self
._add
_artists
_directory
(artists
)
316 dialog
= xbmcgui
.Dialog()
317 dialog
.ok(__language__(30008), __language__(30025))
322 # Search for playlists
323 def searchPlaylists(self
):
324 query
= self
._get
_keyboard
(default
="", heading
=__language__(30026))
326 playlists
= groovesharkApi
.getUserPlaylistsByUsername(query
)
327 if (len(playlists
) > 0):
328 self
._add
_playlists
_directory
(playlists
)
330 dialog
= xbmcgui
.Dialog()
331 dialog
.ok(__language__(30008), __language__(30027))
336 # Search for artists albums
337 def searchArtistsAlbums(self
, artistName
= None):
338 if artistName
== None or artistName
== searchArtistsAlbumsName
:
339 query
= self
._get
_keyboard
(default
="", heading
=__language__(30028))
343 artists
= groovesharkApi
.getArtistSearchResults(query
, limit
= self
.artistsearchlimit
)
344 if (len(artists
) > 0):
348 xbmc
.log("Found " + artist
[0] + "...")
349 albums
= groovesharkApi
.getArtistAlbums(artistID
, limit
= self
.albumsearchlimit
)
350 if (len(albums
) > 0):
351 self
._add
_albums
_directory
(albums
, artistID
)
353 dialog
= xbmcgui
.Dialog()
354 dialog
.ok(__language__(30008), __language__(30029))
357 dialog
= xbmcgui
.Dialog()
358 dialog
.ok(__language__(30008), __language__(30030))
365 userid
= self
._get
_login
()
367 favorites
= groovesharkApi
.getUserFavoriteSongs()
368 if (len(favorites
) > 0):
369 self
._add
_songs
_directory
(favorites
, isFavorites
=True)
371 dialog
= xbmcgui
.Dialog()
372 dialog
.ok(__language__(30008), __language__(30031))
376 def popularSongs(self
):
377 popular
= groovesharkApi
.getPopularSongsToday(limit
= self
.songsearchlimit
)
378 if (len(popular
) > 0):
379 self
._add
_songs
_directory
(popular
)
381 dialog
= xbmcgui
.Dialog()
382 dialog
.ok(__language__(30008), __language__(30032))
387 userid
= self
._get
_login
()
389 playlists
= groovesharkApi
.getUserPlaylists()
390 if (len(playlists
) > 0):
391 self
._add
_playlists
_directory
(playlists
)
393 dialog
= xbmcgui
.Dialog()
394 dialog
.ok(__language__(30008), __language__(30033))
397 dialog
= xbmcgui
.Dialog()
398 dialog
.ok(__language__(30008), __language__(30034), __language__(30035))
400 # Make songs a favorite
401 def favorite(self
, songid
):
402 userid
= self
._get
_login
()
405 xbmc
.log("Favorite song: " + str(songid
))
406 groovesharkApi
.addUserFavoriteSong(songID
= songid
)
407 xbmc
.executebuiltin('XBMC.Notification(' + __language__(30008) + ', ' + __language__(30036) + ', 1000, ' + thumbDef
+ ')')
409 dialog
= xbmcgui
.Dialog()
410 dialog
.ok(__language__(30008), __language__(30034), __language__(30037))
412 # Remove song from favorites
413 def unfavorite(self
, songid
, prevMode
=0):
414 userid
= self
._get
_login
()
417 xbmc
.log("Unfavorite song: " + str(songid
) + ', previous mode was ' + str(prevMode
))
418 groovesharkApi
.removeUserFavoriteSongs(songIDs
= songid
)
419 xbmc
.executebuiltin('XBMC.Notification(' + __language__(30008) + ', ' + __language__(30038) + ', 1000, ' + thumbDef
+ ')')
420 # Refresh to remove item from directory
421 if (int(prevMode
) == MODE_FAVORITES
):
422 xbmc
.executebuiltin("Container.Refresh(" + favoritesUrl
+ ")")
424 dialog
= xbmcgui
.Dialog()
425 dialog
.ok(__language__(30008), __language__(30034), __language__(30039))
428 # Show selected album
429 def album(self
, albumid
):
430 album
= groovesharkApi
.getAlbumSongs(albumid
, limit
= self
.songsearchlimit
)
431 self
._add
_songs
_directory
(album
, trackLabelFormat
=NAME_ALBUM_ARTIST_LABEL
)
433 # Show selected artist
434 def artist(self
, artistid
):
435 albums
= groovesharkApi
.getArtistAlbums(artistid
, limit
= self
.albumsearchlimit
)
436 self
._add
_albums
_directory
(albums
, artistid
)
438 # Show selected playlist
439 def playlist(self
, playlistid
, playlistname
):
440 userid
= self
._get
_login
()
442 songs
= groovesharkApi
.getPlaylistSongs(playlistid
)
443 self
._add
_songs
_directory
(songs
, trackLabelFormat
=NAME_ALBUM_ARTIST_LABEL
, playlistid
=playlistid
, playlistname
=playlistname
)
445 dialog
= xbmcgui
.Dialog()
446 dialog
.ok(__language__(30008), __language__(30034), __language__(30040))
448 # Show popular songs of the artist
449 def artistPopularSongs(self
):
450 query
= self
._get
_keyboard
(default
="", heading
=__language__(30041))
452 artists
= groovesharkApi
.getArtistSearchResults(query
, limit
= self
.artistsearchlimit
)
453 if (len(artists
) > 0):
457 xbmc
.log("Found " + artist
[0] + "...")
458 songs
= groovesharkApi
.getArtistPopularSongs(artistID
, limit
= self
.songsearchlimit
)
460 self
._add
_songs
_directory
(songs
, trackLabelFormat
=NAME_ALBUM_ARTIST_LABEL
)
462 dialog
= xbmcgui
.Dialog()
463 dialog
.ok(__language__(30008), __language__(30042))
466 dialog
= xbmcgui
.Dialog()
467 dialog
.ok(__language__(30008), __language__(30043))
473 def playSong(self
, item
):
477 songid
= item
.getProperty('songid')
478 url
= item
.getProperty('url')
480 stream
= groovesharkApi
.getSubscriberStreamKey(songid
)
484 xbmc
.log("Grooveshark playing: " + url
)
485 xbmcplugin
.setResolvedUrl(handle
=int(sys
.argv
[1]), succeeded
=True, listitem
=item
)
486 # Wait for play then start time
488 while seconds
< STREAM_MARKING_TIME
:
490 if player
.isPlayingAudio() == True:
491 if playTimer
!= None:
494 duration
= int(item
.getProperty('duration'))
495 playTimer
= PlayTimer(1, markSong
, duration
, [songid
, duration
])
500 seconds
= seconds
+ 1
502 xbmc
.executebuiltin('XBMC.Notification(' + __language__(30008) + ', ' + __language__(30044) + ', 1000, ' + thumbDef
+ ')')
504 # Make a song directory item
505 def songItem(self
, songid
, name
, album
, artist
, coverart
, trackLabelFormat
=ARTIST_ALBUM_NAME_LABEL
):
506 songImg
= self
._get
_icon
(coverart
, 'song-' + str(songid
) + "-image")
507 if int(trackLabelFormat
) == NAME_ALBUM_ARTIST_LABEL
:
508 trackLabel
= name
+ " - " + album
+ " - " + artist
510 trackLabel
= artist
+ " - " + album
+ " - " + name
511 stream
= self
._getSongStream
(songid
)
512 duration
= stream
['duration']
514 item
= xbmcgui
.ListItem(label
= trackLabel
, thumbnailImage
=songImg
, iconImage
=songImg
)
515 item
.setInfo( type="music", infoLabels
={ "title": name
, "album": album
, "artist": artist
, "duration": duration
} )
516 item
.setProperty('mimetype', 'audio/mpeg')
517 item
.setProperty("IsPlayable", "true")
518 item
.setProperty('songid', str(songid
))
519 item
.setProperty('coverart', songImg
)
520 item
.setProperty('title', name
)
521 item
.setProperty('album', album
)
522 item
.setProperty('artist', artist
)
523 item
.setProperty('duration', str(duration
))
524 item
.setProperty('url', str(url
))
529 def songPage(self
, offset
, trackLabelFormat
, playlistid
= 0, playlistname
= ''):
530 self
._add
_songs
_directory
([], trackLabelFormat
, offset
, playlistid
= playlistid
, playlistname
= playlistname
)
532 # Make a playlist from an album
533 def makePlaylist(self
, albumid
, name
):
534 userid
= self
._get
_login
()
536 re
.split(' - ',name
,1)
537 nameTokens
= re
.split(' - ',name
,1) # suggested name
538 name
= self
._get
_keyboard
(default
=nameTokens
[0], heading
=__language__(30045))
540 album
= groovesharkApi
.getAlbumSongs(albumid
, limit
= self
.songsearchlimit
)
543 songids
.append(song
[1])
544 if groovesharkApi
.createPlaylist(name
, songids
) == 0:
545 dialog
= xbmcgui
.Dialog()
546 dialog
.ok(__language__(30008), __language__(30046), name
)
548 xbmc
.executebuiltin('XBMC.Notification(' + __language__(30008) + ',' + __language__(30047)+ ', 1000, ' + thumbDef
+ ')')
550 dialog
= xbmcgui
.Dialog()
551 dialog
.ok(__language__(30008), __language__(30034), __language__(30048))
554 def renamePlaylist(self
, playlistid
, name
):
555 userid
= self
._get
_login
()
557 newname
= self
._get
_keyboard
(default
=name
, heading
=__language__(30049))
560 elif groovesharkApi
.playlistRename(playlistid
, newname
) == 0:
561 dialog
= xbmcgui
.Dialog()
562 dialog
.ok(__language__(30008), __language__(30050), name
)
564 # Refresh to show new item name
565 xbmc
.executebuiltin("Container.Refresh")
567 dialog
= xbmcgui
.Dialog()
568 dialog
.ok(__language__(30008), __language__(30034), __language__(30051))
571 def removePlaylist(self
, playlistid
, name
):
572 dialog
= xbmcgui
.Dialog()
573 if dialog
.yesno(__language__(30008), name
, __language__(30052)) == True:
574 userid
= self
._get
_login
()
576 if groovesharkApi
.playlistDelete(playlistid
) == 0:
577 dialog
= xbmcgui
.Dialog()
578 dialog
.ok(__language__(30008), __language__(30053), name
)
580 # Refresh to remove item from directory
581 xbmc
.executebuiltin("Container.Refresh(" + playlistsUrl
+ ")")
583 dialog
= xbmcgui
.Dialog()
584 dialog
.ok(__language__(30008), __language__(30034), __language__(30054))
586 # Add song to playlist
587 def addPlaylistSong(self
, songid
):
588 userid
= self
._get
_login
()
590 playlists
= groovesharkApi
.getUserPlaylists()
591 if (len(playlists
) > 0):
593 # Select the playlist
594 playlistSelect
= GroovesharkPlaylistSelect(items
=playlists
)
595 playlistSelect
.setFocus(playlistSelect
.playlistControl
)
596 playlistSelect
.doModal()
597 i
= playlistSelect
.selected
601 if i
>= len(playlists
):
602 name
= self
._get
_keyboard
(default
='', heading
=__language__(30055))
605 songIds
.append(songid
)
606 if groovesharkApi
.createPlaylist(name
, songIds
) == 0:
607 dialog
= xbmcgui
.Dialog()
608 dialog
.ok(__language__(30008), __language__(30056), name
)
610 xbmc
.executebuiltin('XBMC.Notification(' + __language__(30008) + ',' + __language__(30057) + ', 1000, ' + thumbDef
+ ')')
613 playlist
= playlists
[i
]
614 playlistid
= playlist
[1]
616 xbmc
.log("Add song " + str(songid
) + " to playlist " + str(playlistid
))
618 songs
= groovesharkApi
.getPlaylistSongs(playlistid
)
620 songIDs
.append(song
[1])
621 songIDs
.append(songid
)
622 ret
= groovesharkApi
.setPlaylistSongs(playlistid
, songIDs
)
624 dialog
= xbmcgui
.Dialog()
625 dialog
.ok(__language__(30008), __language__(30058))
627 xbmc
.executebuiltin('XBMC.Notification(' + __language__(30008) + ',' + __language__(30059) + ', 1000, ' + thumbDef
+ ')')
629 dialog
= xbmcgui
.Dialog()
630 dialog
.ok(__language__(30008), __language__(30060))
633 dialog
= xbmcgui
.Dialog()
634 dialog
.ok(__language__(30008), __language__(30034), __language__(30061))
636 # Remove song from playlist
637 def removePlaylistSong(self
, playlistid
, playlistname
, songid
):
638 dialog
= xbmcgui
.Dialog()
639 if dialog
.yesno(__language__(30008), __language__(30062), __language__(30063)) == True:
640 userid
= self
._get
_login
()
642 songs
= groovesharkApi
.getPlaylistSongs(playlistID
)
645 if (song
[1] != songid
):
646 songIDs
.append(song
[1])
647 ret
= groovesharkApi
.setPlaylistSongs(playlistID
, songIDs
)
649 dialog
= xbmcgui
.Dialog()
650 dialog
.ok(__language__(30008), __language__(30064), __language__(30065))
652 # Refresh to remove item from directory
653 xbmc
.executebuiltin('XBMC.Notification(' + __language__(30008) + ',' + __language__(30066)+ ', 1000, ' + thumbDef
+ ')')
654 xbmc
.executebuiltin("Container.Update(" + playlistUrl
+ "&id="+str(playlistid
) + "&name=" + playlistname
+ ")")
656 dialog
= xbmcgui
.Dialog()
657 dialog
.ok(__language__(30008), __language__(30034), __language__(30067))
659 # Find similar artists to searched artist
660 def similarArtists(self
, artistId
):
661 similar
= groovesharkApi
.getSimilarArtists(artistId
, limit
= self
.artistsearchlimit
)
662 if (len(similar
) > 0):
663 self
._add
_artists
_directory
(similar
)
665 dialog
= xbmcgui
.Dialog()
666 dialog
.ok(__language__(30008), __language__(30068))
671 self
.debug
= self
.settings
.getSetting('debug')
673 xbmc
.log("Debug is on")
680 def _get_keyboard(self
, default
="", heading
="", hidden
=False):
681 kb
= xbmc
.Keyboard(default
, heading
, hidden
)
683 if (kb
.isConfirmed()):
684 return unicode(kb
.getText(), "utf-8")
687 # Login to grooveshark
688 def _get_login(self
):
689 if (self
.username
== "" or self
.password
== ""):
690 dialog
= xbmcgui
.Dialog()
691 dialog
.ok(__language__(30008), __language__(30069), __language__(30070))
695 uid
= groovesharkApi
.login(self
.username
, self
.password
)
699 dialog
= xbmcgui
.Dialog()
700 dialog
.ok(__language__(30008), __language__(30069), __language__(30070))
703 # Get a song directory item
704 def _get_song_item(self
, song
, trackLabelFormat
):
710 return self
.songItem(songid
, name
, album
, artist
, coverart
, trackLabelFormat
)
713 def _get_icon(self
, url
, songid
):
715 localThumb
= os
.path
.join(xbmc
.translatePath(os
.path
.join(thumbDir
, str(songid
)))) + '.tbn'
717 if os
.path
.isfile(localThumb
) == False:
718 loc
= urllib
.URLopener()
719 loc
.retrieve(url
, localThumb
)
721 shutil
.copy2(thumbDef
, localThumb
)
722 return os
.path
.join(os
.path
.join(thumbDir
, str(songid
))) + '.tbn'
726 # Add songs to directory
727 def _add_songs_directory(self
, songs
, trackLabelFormat
=ARTIST_ALBUM_NAME_LABEL
, offset
=0, playlistid
=0, playlistname
='', isFavorites
=False):
729 totalSongs
= len(songs
)
735 if offset
== 0 and totalSongs
<= self
.songspagelimit
:
737 xbmc
.log("Found " + str(totalSongs
) + " songs...")
740 # Cache all next pages songs
742 self
._setSavedSongs
(songs
)
744 songs
= self
._getSavedSongs
()
745 totalSongs
= len(songs
)
749 end
= min(start
+ self
.songspagelimit
,totalSongs
)
757 stream
= self
._getSongStream
(songid
)
758 if stream
['url'] != '':
759 item
= self
._get
_song
_item
(song
, trackLabelFormat
)
760 coverart
= item
.getProperty('coverart')
764 u
=sys
.argv
[0]+"?mode="+str(MODE_SONG
)+"&name="+urllib
.quote_plus(songname
)+"&id="+str(songid
) \
765 +"&album="+urllib
.quote_plus(songalbum
) \
766 +"&artist="+urllib
.quote_plus(songartist
) \
767 +"&coverart="+urllib
.quote_plus(coverart
)
768 fav
=sys
.argv
[0]+"?mode="+str(MODE_FAVORITE
)+"&name="+urllib
.quote_plus(songname
)+"&id="+str(songid
)
769 unfav
=sys
.argv
[0]+"?mode="+str(MODE_UNFAVORITE
)+"&name="+urllib
.quote_plus(songname
)+"&id="+str(songid
)+"&prevmode="
771 if isFavorites
== True:
772 unfav
= unfav
+str(MODE_FAVORITES
)
774 menuItems
.append((__language__(30071), "XBMC.RunPlugin("+fav
+")"))
775 menuItems
.append((__language__(30072), "XBMC.RunPlugin("+unfav
+")"))
777 rmplaylstsong
=sys
.argv
[0]+"?playlistid="+str(playlistid
)+"&id="+str(songid
)+"&mode="+str(MODE_REMOVE_PLAYLIST_SONG
)+"&name="+playlistname
778 menuItems
.append((__language__(30073), "XBMC.RunPlugin("+rmplaylstsong
+")"))
780 addplaylstsong
=sys
.argv
[0]+"?id="+str(songid
)+"&mode="+str(MODE_ADD_PLAYLIST_SONG
)
781 menuItems
.append((__language__(30074), "XBMC.RunPlugin("+addplaylstsong
+")"))
782 item
.addContextMenuItems(menuItems
, replaceItems
=False)
783 xbmcplugin
.addDirectoryItem(handle
=int(sys
.argv
[1]),url
=u
,listitem
=item
,isFolder
=False, totalItems
=items
)
786 end
= min(end
+ 1,totalSongs
)
788 xbmc
.log(song
[0] + " does not exist.")
792 u
=sys
.argv
[0]+"?mode="+str(MODE_SONG_PAGE
)+"&id=playlistid"+"&offset="+str(end
)+"&label="+str(trackLabelFormat
)+"&name="+playlistname
793 self
._add
_dir
(__language__(30075) + '...', u
, MODE_SONG_PAGE
, self
.songImg
, 0, totalSongs
- end
)
795 xbmcplugin
.setContent(self
._handle
, 'songs')
796 xbmcplugin
.setPluginFanart(int(sys
.argv
[1]), self
.fanImg
)
798 # Add albums to directory
799 def _add_albums_directory(self
, albums
, artistid
=0):
803 xbmc
.log("Found " + str(n
) + " albums...")
808 if groovesharkApi
.getDoesAlbumExist(albumID
):
809 albumArtistName
= album
[0]
811 albumImage
= self
._get
_icon
(album
[4], 'album-' + str(albumID
))
812 self
._add
_dir
(albumName
+ " - " + albumArtistName
, '', MODE_ALBUM
, albumImage
, albumID
, itemsExisting
)
814 itemsExisting
= itemsExisting
- 1
816 # Not supported by key
818 # self._add_dir('Similar artists...', '', MODE_SIMILAR_ARTISTS, self.artistImg, artistid)
819 xbmcplugin
.setContent(self
._handle
, 'albums')
820 xbmcplugin
.addSortMethod(self
._handle
, xbmcplugin
.SORT_METHOD_ALBUM_IGNORE_THE
)
821 xbmcplugin
.setPluginFanart(int(sys
.argv
[1]), self
.fanImg
)
823 # Add artists to directory
824 def _add_artists_directory(self
, artists
):
828 xbmc
.log("Found " + str(n
) + " artists...")
833 if groovesharkApi
.getDoesArtistExist(artistID
):
834 artistName
= artist
[0]
835 self
._add
_dir
(artistName
, '', MODE_ARTIST
, self
.artistImg
, artistID
, itemsExisting
)
837 itemsExisting
= itemsExisting
- 1
839 xbmcplugin
.setContent(self
._handle
, 'artists')
840 xbmcplugin
.addSortMethod(self
._handle
, xbmcplugin
.SORT_METHOD_ARTIST_IGNORE_THE
)
841 xbmcplugin
.setPluginFanart(int(sys
.argv
[1]), self
.fanImg
)
843 # Add playlists to directory
844 def _add_playlists_directory(self
, playlists
):
847 xbmc
.log("Found " + str(n
) + " playlists...")
850 playlist
= playlists
[i
]
851 playlistName
= playlist
[0]
852 playlistID
= playlist
[1]
853 dir = self
._add
_dir
(playlistName
, '', MODE_PLAYLIST
, self
.playlistImg
, playlistID
, n
)
855 xbmcplugin
.setContent(self
._handle
, 'files')
856 xbmcplugin
.addSortMethod(self
._handle
, xbmcplugin
.SORT_METHOD_LABEL
)
857 xbmcplugin
.setPluginFanart(int(sys
.argv
[1]), self
.fanImg
)
859 # Add whatever directory
860 def _add_dir(self
, name
, url
, mode
, iconimage
, id, items
=1):
863 u
=sys
.argv
[0]+"?mode="+str(mode
)+"&name="+urllib
.quote_plus(name
)+"&id="+str(id)
866 dir=xbmcgui
.ListItem(name
, iconImage
=iconimage
, thumbnailImage
=iconimage
)
867 dir.setInfo( type="Music", infoLabels
={ "title": name
} )
871 if mode
== MODE_ALBUM
:
872 mkplaylst
=sys
.argv
[0]+"?mode="+str(MODE_MAKE_PLAYLIST
)+"&name="+name
+"&id="+str(id)
873 menuItems
.append((__language__(30076), "XBMC.RunPlugin("+mkplaylst
+")"))
874 if mode
== MODE_PLAYLIST
:
875 rmplaylst
=sys
.argv
[0]+"?mode="+str(MODE_REMOVE_PLAYLIST
)+"&name="+urllib
.quote_plus(name
)+"&id="+str(id)
876 menuItems
.append((__language__(30077), "XBMC.RunPlugin("+rmplaylst
+")"))
877 mvplaylst
=sys
.argv
[0]+"?mode="+str(MODE_RENAME_PLAYLIST
)+"&name="+urllib
.quote_plus(name
)+"&id="+str(id)
878 menuItems
.append((__language__(30078), "XBMC.RunPlugin("+mvplaylst
+")"))
880 dir.addContextMenuItems(menuItems
, replaceItems
=False)
882 return xbmcplugin
.addDirectoryItem(handle
=int(sys
.argv
[1]),url
=u
,listitem
=dir,isFolder
=True, totalItems
=items
)
884 def _getSavedSongs(self
):
885 path
= os
.path
.join(cacheDir
, 'songs.dmp')
888 songs
= pickle
.load(f
)
895 def _setSavedSongs(self
, songs
):
897 # Create the 'data' directory if it doesn't exist.
898 if not os
.path
.exists(cacheDir
):
899 os
.makedirs(cacheDir
)
900 path
= os
.path
.join(cacheDir
, 'songs.dmp')
902 pickle
.dump(songs
, f
, protocol
=pickle
.HIGHEST_PROTOCOL
)
905 xbmc
.log("An error occurred saving songs")
908 def _getSongStream(self
, songid
):
913 path
= os
.path
.join(cacheDir
, 'streams.dmp')
916 streams
= pickle
.load(f
)
926 if duration
< 0 and groovesharkApi
.getDoesSongExist(songid
):
927 stream
= groovesharkApi
.getSubscriberStreamKey(songid
)
929 usecs
= stream
['uSecs']
931 usecs
= usecs
* 10 # Some durations are 10x to small
932 duration
= usecs
/ 1000000
933 song
= [id, duration
, url
]
935 self
._setSongStream
(streams
)
937 return {'duration':duration
, 'url':url
}
939 def _setSongStream(self
, streams
):
941 # Create the 'data' directory if it doesn't exist.
942 if not os
.path
.exists(cacheDir
):
943 os
.makedirs(cacheDir
)
944 path
= os
.path
.join(cacheDir
, 'streams.dmp')
946 pickle
.dump(streams
, f
, protocol
=pickle
.HIGHEST_PROTOCOL
)
949 xbmc
.log("An error occurred saving streams")
953 # Parse URL parameters
956 paramstring
=sys
.argv
[2]
957 if grooveshark
.getDebug():
958 xbmc
.log(paramstring
)
959 if len(paramstring
)>=2:
961 cleanedparams
=params
.replace('?','')
962 if (params
[len(params
)-1]=='/'):
963 params
=params
[0:len(params
)-2]
964 pairsofparams
=cleanedparams
.split('&')
966 for i
in range(len(pairsofparams
)):
968 splitparams
=pairsofparams
[i
].split('=')
969 if (len(splitparams
))==2:
970 param
[splitparams
[0]]=splitparams
[1]
974 grooveshark
= Grooveshark();
975 grooveshark
.setDebug()
976 groovesharkApi
.setDebug(grooveshark
.getDebug())
980 try: mode
=int(params
["mode"])
983 try: id=int(params
["id"])
986 try: name
=urllib
.unquote_plus(params
["name"])
989 # Call function for URL
991 grooveshark
.categories()
993 elif mode
==MODE_SEARCH_SONGS
:
994 grooveshark
.searchSongs()
996 elif mode
==MODE_SEARCH_ALBUMS
:
997 grooveshark
.searchAlbums()
999 elif mode
==MODE_SEARCH_ARTISTS
:
1000 grooveshark
.searchArtists()
1002 elif mode
==MODE_SEARCH_ARTISTS_ALBUMS
:
1003 grooveshark
.searchArtistsAlbums(name
)
1005 elif mode
==MODE_SEARCH_PLAYLISTS
:
1006 grooveshark
.searchPlaylists()
1008 elif mode
==MODE_POPULAR_SONGS
:
1009 grooveshark
.popularSongs()
1011 elif mode
==MODE_ARTIST_POPULAR
:
1012 grooveshark
.artistPopularSongs()
1014 elif mode
==MODE_FAVORITES
:
1015 grooveshark
.favorites()
1017 elif mode
==MODE_PLAYLISTS
:
1018 grooveshark
.playlists()
1020 elif mode
==MODE_SONG_PAGE
:
1021 try: offset
=urllib
.unquote_plus(params
["offset"])
1023 try: label
=urllib
.unquote_plus(params
["label"])
1025 grooveshark
.songPage(offset
, label
, id, name
)
1027 elif mode
==MODE_SONG
:
1028 try: album
=urllib
.unquote_plus(params
["album"])
1030 try: artist
=urllib
.unquote_plus(params
["artist"])
1032 try: coverart
=urllib
.unquote_plus(params
["coverart"])
1034 song
= grooveshark
.songItem(id, name
, album
, artist
, coverart
)
1035 grooveshark
.playSong(song
)
1037 elif mode
==MODE_ARTIST
:
1038 grooveshark
.artist(id)
1040 elif mode
==MODE_ALBUM
:
1041 grooveshark
.album(id)
1043 elif mode
==MODE_PLAYLIST
:
1044 grooveshark
.playlist(id, name
)
1046 elif mode
==MODE_FAVORITE
:
1047 grooveshark
.favorite(id)
1049 elif mode
==MODE_UNFAVORITE
:
1050 try: prevMode
=int(urllib
.unquote_plus(params
["prevmode"]))
1053 grooveshark
.unfavorite(id, prevMode
)
1055 elif mode
==MODE_SIMILAR_ARTISTS
:
1056 grooveshark
.similarArtists(id)
1058 elif mode
==MODE_MAKE_PLAYLIST
:
1059 grooveshark
.makePlaylist(id, name
)
1061 elif mode
==MODE_REMOVE_PLAYLIST
:
1062 grooveshark
.removePlaylist(id, name
)
1064 elif mode
==MODE_RENAME_PLAYLIST
:
1065 grooveshark
.renamePlaylist(id, name
)
1067 elif mode
==MODE_REMOVE_PLAYLIST_SONG
:
1068 try: playlistID
=urllib
.unquote_plus(params
["playlistid"])
1070 grooveshark
.removePlaylistSong(playlistID
, name
, id)
1072 elif mode
==MODE_ADD_PLAYLIST_SONG
:
1073 grooveshark
.addPlaylistSong(id)
1075 if mode
< MODE_SONG
:
1076 xbmcplugin
.endOfDirectory(int(sys
.argv
[1]))