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
70 player
= xbmc
.Player()
74 resDir
= xbmc
.translatePath(os
.path
.join(baseDir
, 'resources'))
75 libDir
= xbmc
.translatePath(os
.path
.join(resDir
, 'lib'))
76 imgDir
= xbmc
.translatePath(os
.path
.join(resDir
, 'img'))
77 cacheDir
= os
.path
.join(xbmc
.translatePath('special://masterprofile/addon_data/'), os
.path
.basename(baseDir
))
78 thumbDirName
= 'thumb'
79 thumbDir
= os
.path
.join('special://masterprofile/addon_data/', os
.path
.basename(baseDir
), thumbDirName
)
81 baseModeUrl
= 'plugin://plugin.audio.groove/'
82 playlistUrl
= baseModeUrl
+ '?mode=' + str(MODE_PLAYLIST
)
83 playlistsUrl
= baseModeUrl
+ '?mode=' + str(MODE_PLAYLISTS
)
84 favoritesUrl
= baseModeUrl
+ '?mode=' + str(MODE_FAVORITES
)
86 searchArtistsAlbumsName
= __language__(30006)
88 thumbDef
= os
.path
.join(imgDir
, 'default.tbn')
89 listBackground
= os
.path
.join(imgDir
, 'listbackground.png')
91 sys
.path
.append (libDir
)
92 from GroovesharkAPI
import GrooveAPI
93 from threading
import Event
, Thread
96 groovesharkApi
= GrooveAPI()
97 if groovesharkApi
.pingService() != True:
98 raise StandardError(__language__(30007))
100 dialog
= xbmcgui
.Dialog(__language__(30008),__language__(30009),__language__(30010))
104 # Mark song as playing or played
105 def markSong(songid
, duration
):
109 if player
.isPlayingAudio():
110 tNow
= player
.getTime()
111 if tNow
>= STREAM_MARKING_TIME
and songMarkTime
== 0:
112 groovesharkApi
.markStreamKeyOver30Secs()
114 elif duration
> tNow
and duration
- tNow
< 2 and songMarkTime
>= STREAM_MARKING_TIME
:
117 groovesharkApi
.markSongComplete(songid
)
123 def __init__( self
, *args
, **kwargs
):
124 self
.__dict
__.update( kwargs
)
126 # Window dialog to select a grooveshark playlist
127 class GroovesharkPlaylistSelect(xbmcgui
.WindowDialog
):
129 def __init__(self
, items
=[]):
130 gap
= int(self
.getHeight()/100)
131 w
= int(self
.getWidth()*0.5)
132 h
= self
.getHeight()-30*gap
134 rh
= self
.getHeight()
138 self
.imgBg
= xbmcgui
.ControlImage(x
+gap
, 5*gap
+y
, w
-2*gap
, h
-5*gap
, listBackground
)
139 self
.addControl(self
.imgBg
)
141 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)
142 self
.addControl(self
.playlistControl
)
145 self
.isSelecting
= False
148 for playlist
in items
:
149 listitems
.append(xbmcgui
.ListItem(playlist
[0]))
150 listitems
.append(xbmcgui
.ListItem(__language__(30011)))
151 self
.playlistControl
.addItems(listitems
)
152 self
.setFocus(self
.playlistControl
)
153 self
.playlistControl
.selectItem(0)
154 item
= self
.playlistControl
.getListItem(self
.lastPos
)
157 # Highlight selected item
158 def setHighlight(self
):
162 self
.isSelecting
= True
164 pos
= self
.playlistControl
.getSelectedPosition()
166 item
= self
.playlistControl
.getListItem(self
.lastPos
)
168 item
= self
.playlistControl
.getListItem(pos
)
171 self
.isSelecting
= False
174 def onControl(self
, control
):
175 if control
== self
.playlistControl
:
176 self
.selected
= self
.playlistControl
.getSelectedPosition()
179 # Action - close or up/down
180 def onAction(self
, action
):
181 if action
== ACTION_PREVIOUS_MENU
:
184 elif action
== ACTION_MOVE_UP
or action
== ACTION_MOVE_DOWN
or action
== ACTION_PAGE_UP
or action
== ACTION_PAGE_DOWN
== 6:
185 self
.setFocus(self
.playlistControl
)
189 class PlayTimer(Thread
):
190 # interval -- floating point number specifying the number of seconds to wait before executing function
191 # function -- the function (or callable object) to be executed
193 # iterations -- integer specifying the number of iterations to perform
194 # args -- list of positional arguments passed to function
195 # kwargs -- dictionary of keyword arguments passed to function
197 def __init__(self
, interval
, function
, iterations
=0, args
=[], kwargs
={}):
198 Thread
.__init
__(self
)
199 self
.interval
= interval
200 self
.function
= function
201 self
.iterations
= iterations
204 self
.finished
= Event()
208 while not self
.finished
.isSet() and (self
.iterations
<= 0 or count
< self
.iterations
):
209 self
.finished
.wait(self
.interval
)
210 if not self
.finished
.isSet():
211 self
.function(*self
.args
, **self
.kwargs
)
217 def setIterations(self
, iterations
):
218 self
.iterations
= iterations
222 return self
.iterations
* self
.interval
227 albumImg
= xbmc
.translatePath(os
.path
.join(imgDir
, 'album.png'))
228 artistImg
= xbmc
.translatePath(os
.path
.join(imgDir
, 'artist.png'))
229 artistsAlbumsImg
= xbmc
.translatePath(os
.path
.join(imgDir
, 'artistsalbums.png'))
230 favoritesImg
= xbmc
.translatePath(os
.path
.join(imgDir
, 'favorites.png'))
231 playlistImg
= xbmc
.translatePath(os
.path
.join(imgDir
, 'playlist.png'))
232 usersplaylistsImg
= xbmc
.translatePath(os
.path
.join(imgDir
, 'usersplaylists.png'))
233 popularSongsImg
= xbmc
.translatePath(os
.path
.join(imgDir
, 'popularSongs.png'))
234 popularSongsArtistImg
= xbmc
.translatePath(os
.path
.join(imgDir
, 'popularSongsArtist.png'))
235 songImg
= xbmc
.translatePath(os
.path
.join(imgDir
, 'song.png'))
236 defImg
= xbmc
.translatePath(os
.path
.join(imgDir
, 'default.tbn'))
237 fanImg
= xbmc
.translatePath(os
.path
.join(baseDir
, 'fanart.png'))
239 settings
= xbmcaddon
.Addon(id='plugin.audio.groove')
240 songsearchlimit
= int(settings
.getSetting('songsearchlimit'))
241 albumsearchlimit
= int(settings
.getSetting('albumsearchlimit'))
242 artistsearchlimit
= int(settings
.getSetting('artistsearchlimit'))
243 songspagelimit
= int(settings
.getSetting('songspagelimit'))
244 username
= settings
.getSetting('username')
245 password
= settings
.getSetting('password')
249 def __init__( self
):
250 self
._handle
= int(sys
.argv
[1])
252 if os
.path
.isdir(cacheDir
) == False:
253 os
.makedirs(cacheDir
)
255 xbmc
.log(__language__(30012) + " " + cacheDir
)
256 artDir
= xbmc
.translatePath(thumbDir
)
257 if os
.path
.isdir(artDir
) == False:
260 xbmc
.log(__language__(30012) + " " + artDir
)
263 def categories(self
):
265 self
.userid
= self
._get
_login
()
268 xbmcplugin
.setPluginFanart(int(sys
.argv
[1]), self
.fanImg
)
270 self
._add
_dir
(__language__(30013), '', MODE_SEARCH_SONGS
, self
.songImg
, 0)
271 self
._add
_dir
(__language__(30014), '', MODE_SEARCH_ALBUMS
, self
.albumImg
, 0)
272 self
._add
_dir
(__language__(30015), '', MODE_SEARCH_ARTISTS
, self
.artistImg
, 0)
273 self
._add
_dir
(searchArtistsAlbumsName
, '', MODE_SEARCH_ARTISTS_ALBUMS
, self
.artistsAlbumsImg
, 0)
274 # Not supported by key
275 #self._add_dir("Search for user's playlists...", '', MODE_SEARCH_PLAYLISTS, self.usersplaylistsImg, 0)
276 self
._add
_dir
(__language__(30016), '', MODE_ARTIST_POPULAR
, self
.popularSongsArtistImg
, 0)
277 self
._add
_dir
(__language__(30017), '', MODE_POPULAR_SONGS
, self
.popularSongsImg
, 0)
278 if (self
.userid
!= 0):
279 self
._add
_dir
(__language__(30018), '', MODE_FAVORITES
, self
.favoritesImg
, 0)
280 self
._add
_dir
(__language__(30019), '', MODE_PLAYLISTS
, self
.playlistImg
, 0)
283 def searchSongs(self
):
284 query
= self
._get
_keyboard
(default
="", heading
=__language__(30020))
286 songs
= groovesharkApi
.getSongSearchResults(query
, limit
= self
.songsearchlimit
)
288 self
._add
_songs
_directory
(songs
)
290 dialog
= xbmcgui
.Dialog()
291 dialog
.ok(__language__(30008), __language__(30021))
297 def searchAlbums(self
):
298 query
= self
._get
_keyboard
(default
="", heading
=__language__(30022))
300 albums
= groovesharkApi
.getAlbumSearchResults(query
, limit
= self
.albumsearchlimit
)
301 if (len(albums
) > 0):
302 self
._add
_albums
_directory
(albums
)
304 dialog
= xbmcgui
.Dialog()
305 dialog
.ok(__language__(30008), __language__(30023))
311 def searchArtists(self
):
312 query
= self
._get
_keyboard
(default
="", heading
=__language__(30024))
314 artists
= groovesharkApi
.getArtistSearchResults(query
, limit
= self
.artistsearchlimit
)
315 if (len(artists
) > 0):
316 self
._add
_artists
_directory
(artists
)
318 dialog
= xbmcgui
.Dialog()
319 dialog
.ok(__language__(30008), __language__(30025))
324 # Search for playlists
325 def searchPlaylists(self
):
326 query
= self
._get
_keyboard
(default
="", heading
=__language__(30026))
328 playlists
= groovesharkApi
.getUserPlaylistsByUsername(query
)
329 if (len(playlists
) > 0):
330 self
._add
_playlists
_directory
(playlists
)
332 dialog
= xbmcgui
.Dialog()
333 dialog
.ok(__language__(30008), __language__(30027))
338 # Search for artists albums
339 def searchArtistsAlbums(self
, artistName
= None):
340 if artistName
== None or artistName
== searchArtistsAlbumsName
:
341 query
= self
._get
_keyboard
(default
="", heading
=__language__(30028))
345 artists
= groovesharkApi
.getArtistSearchResults(query
, limit
= self
.artistsearchlimit
)
346 if (len(artists
) > 0):
350 xbmc
.log("Found " + artist
[0] + "...")
351 albums
= groovesharkApi
.getArtistAlbums(artistID
, limit
= self
.albumsearchlimit
)
352 if (len(albums
) > 0):
353 self
._add
_albums
_directory
(albums
, artistID
)
355 dialog
= xbmcgui
.Dialog()
356 dialog
.ok(__language__(30008), __language__(30029))
359 dialog
= xbmcgui
.Dialog()
360 dialog
.ok(__language__(30008), __language__(30030))
367 userid
= self
._get
_login
()
369 favorites
= groovesharkApi
.getUserFavoriteSongs()
370 if (len(favorites
) > 0):
371 self
._add
_songs
_directory
(favorites
, isFavorites
=True)
373 dialog
= xbmcgui
.Dialog()
374 dialog
.ok(__language__(30008), __language__(30031))
378 def popularSongs(self
):
379 popular
= groovesharkApi
.getPopularSongsToday(limit
= self
.songsearchlimit
)
380 if (len(popular
) > 0):
381 self
._add
_songs
_directory
(popular
)
383 dialog
= xbmcgui
.Dialog()
384 dialog
.ok(__language__(30008), __language__(30032))
389 userid
= self
._get
_login
()
391 playlists
= groovesharkApi
.getUserPlaylists()
392 if (len(playlists
) > 0):
393 self
._add
_playlists
_directory
(playlists
)
395 dialog
= xbmcgui
.Dialog()
396 dialog
.ok(__language__(30008), __language__(30033))
399 dialog
= xbmcgui
.Dialog()
400 dialog
.ok(__language__(30008), __language__(30034), __language__(30035))
402 # Make songs a favorite
403 def favorite(self
, songid
):
404 userid
= self
._get
_login
()
407 xbmc
.log("Favorite song: " + str(songid
))
408 groovesharkApi
.addUserFavoriteSong(songID
= songid
)
409 xbmc
.executebuiltin('XBMC.Notification(' + __language__(30008) + ', ' + __language__(30036) + ', 1000, ' + thumbDef
+ ')')
411 dialog
= xbmcgui
.Dialog()
412 dialog
.ok(__language__(30008), __language__(30034), __language__(30037))
414 # Remove song from favorites
415 def unfavorite(self
, songid
, prevMode
=0):
416 userid
= self
._get
_login
()
419 xbmc
.log("Unfavorite song: " + str(songid
) + ', previous mode was ' + str(prevMode
))
420 groovesharkApi
.removeUserFavoriteSongs(songIDs
= songid
)
421 xbmc
.executebuiltin('XBMC.Notification(' + __language__(30008) + ', ' + __language__(30038) + ', 1000, ' + thumbDef
+ ')')
422 # Refresh to remove item from directory
423 if (int(prevMode
) == MODE_FAVORITES
):
424 xbmc
.executebuiltin("Container.Refresh(" + favoritesUrl
+ ")")
426 dialog
= xbmcgui
.Dialog()
427 dialog
.ok(__language__(30008), __language__(30034), __language__(30039))
430 # Show selected album
431 def album(self
, albumid
):
432 album
= groovesharkApi
.getAlbumSongs(albumid
, limit
= self
.songsearchlimit
)
433 self
._add
_songs
_directory
(album
, trackLabelFormat
=NAME_ALBUM_ARTIST_LABEL
)
435 # Show selected artist
436 def artist(self
, artistid
):
437 albums
= groovesharkApi
.getArtistAlbums(artistid
, limit
= self
.albumsearchlimit
)
438 self
._add
_albums
_directory
(albums
, artistid
)
440 # Show selected playlist
441 def playlist(self
, playlistid
, playlistname
):
442 userid
= self
._get
_login
()
444 songs
= groovesharkApi
.getPlaylistSongs(playlistid
)
445 self
._add
_songs
_directory
(songs
, trackLabelFormat
=NAME_ALBUM_ARTIST_LABEL
, playlistid
=playlistid
, playlistname
=playlistname
)
447 dialog
= xbmcgui
.Dialog()
448 dialog
.ok(__language__(30008), __language__(30034), __language__(30040))
450 # Show popular songs of the artist
451 def artistPopularSongs(self
):
452 query
= self
._get
_keyboard
(default
="", heading
=__language__(30041))
454 artists
= groovesharkApi
.getArtistSearchResults(query
, limit
= self
.artistsearchlimit
)
455 if (len(artists
) > 0):
459 xbmc
.log("Found " + artist
[0] + "...")
460 songs
= groovesharkApi
.getArtistPopularSongs(artistID
, limit
= self
.songsearchlimit
)
462 self
._add
_songs
_directory
(songs
, trackLabelFormat
=NAME_ALBUM_ARTIST_LABEL
)
464 dialog
= xbmcgui
.Dialog()
465 dialog
.ok(__language__(30008), __language__(30042))
468 dialog
= xbmcgui
.Dialog()
469 dialog
.ok(__language__(30008), __language__(30043))
475 def playSong(self
, item
):
479 songid
= item
.getProperty('songid')
480 url
= item
.getProperty('url')
482 stream
= groovesharkApi
.getSubscriberStreamKey(songid
)
486 xbmc
.log("Grooveshark playing: " + url
)
487 xbmcplugin
.setResolvedUrl(handle
=int(sys
.argv
[1]), succeeded
=True, listitem
=item
)
488 # Wait for play then start time
490 while seconds
< STREAM_MARKING_TIME
:
492 if player
.isPlayingAudio() == True:
493 if playTimer
!= None:
496 duration
= int(item
.getProperty('duration'))
497 playTimer
= PlayTimer(1, markSong
, duration
, [songid
, duration
])
502 seconds
= seconds
+ 1
503 if (seconds
== STREAM_RETRY
):
504 stream
= groovesharkApi
.getSubscriberStreamKey(songid
)
507 xbmcplugin
.setResolvedUrl(handle
=int(sys
.argv
[1]), succeeded
=True, listitem
=item
)
509 xbmc
.executebuiltin('XBMC.Notification(' + __language__(30008) + ', ' + __language__(30044) + ', 1000, ' + thumbDef
+ ')')
511 # Make a song directory item
512 def songItem(self
, songid
, name
, album
, artist
, coverart
, trackLabelFormat
=ARTIST_ALBUM_NAME_LABEL
):
513 songImg
= self
._get
_icon
(coverart
, 'song-' + str(songid
) + "-image")
514 if int(trackLabelFormat
) == NAME_ALBUM_ARTIST_LABEL
:
515 trackLabel
= name
+ " - " + album
+ " - " + artist
517 trackLabel
= artist
+ " - " + album
+ " - " + name
518 stream
= self
._getSongStream
(songid
)
519 duration
= stream
['duration']
521 item
= xbmcgui
.ListItem(label
= trackLabel
, thumbnailImage
=songImg
, iconImage
=songImg
)
522 item
.setInfo( type="music", infoLabels
={ "title": name
, "album": album
, "artist": artist
, "duration": duration
} )
523 item
.setProperty('mimetype', 'audio/mpeg')
524 item
.setProperty("IsPlayable", "true")
525 item
.setProperty('songid', str(songid
))
526 item
.setProperty('coverart', songImg
)
527 item
.setProperty('title', name
)
528 item
.setProperty('album', album
)
529 item
.setProperty('artist', artist
)
530 item
.setProperty('duration', str(duration
))
531 item
.setProperty('url', str(url
))
536 def songPage(self
, offset
, trackLabelFormat
, playlistid
= 0, playlistname
= ''):
537 self
._add
_songs
_directory
([], trackLabelFormat
, offset
, playlistid
= playlistid
, playlistname
= playlistname
)
539 # Make a playlist from an album
540 def makePlaylist(self
, albumid
, name
):
541 userid
= self
._get
_login
()
543 re
.split(' - ',name
,1)
544 nameTokens
= re
.split(' - ',name
,1) # suggested name
545 name
= self
._get
_keyboard
(default
=nameTokens
[0], heading
=__language__(30045))
547 album
= groovesharkApi
.getAlbumSongs(albumid
, limit
= self
.songsearchlimit
)
550 songids
.append(song
[1])
551 if groovesharkApi
.createPlaylist(name
, songids
) == 0:
552 dialog
= xbmcgui
.Dialog()
553 dialog
.ok(__language__(30008), __language__(30046), name
)
555 xbmc
.executebuiltin('XBMC.Notification(' + __language__(30008) + ',' + __language__(30047)+ ', 1000, ' + thumbDef
+ ')')
557 dialog
= xbmcgui
.Dialog()
558 dialog
.ok(__language__(30008), __language__(30034), __language__(30048))
561 def renamePlaylist(self
, playlistid
, name
):
562 userid
= self
._get
_login
()
564 newname
= self
._get
_keyboard
(default
=name
, heading
=__language__(30049))
567 elif groovesharkApi
.playlistRename(playlistid
, newname
) == 0:
568 dialog
= xbmcgui
.Dialog()
569 dialog
.ok(__language__(30008), __language__(30050), name
)
571 # Refresh to show new item name
572 xbmc
.executebuiltin("Container.Refresh")
574 dialog
= xbmcgui
.Dialog()
575 dialog
.ok(__language__(30008), __language__(30034), __language__(30051))
578 def removePlaylist(self
, playlistid
, name
):
579 dialog
= xbmcgui
.Dialog()
580 if dialog
.yesno(__language__(30008), name
, __language__(30052)) == True:
581 userid
= self
._get
_login
()
583 if groovesharkApi
.playlistDelete(playlistid
) == 0:
584 dialog
= xbmcgui
.Dialog()
585 dialog
.ok(__language__(30008), __language__(30053), name
)
587 # Refresh to remove item from directory
588 xbmc
.executebuiltin("Container.Refresh(" + playlistsUrl
+ ")")
590 dialog
= xbmcgui
.Dialog()
591 dialog
.ok(__language__(30008), __language__(30034), __language__(30054))
593 # Add song to playlist
594 def addPlaylistSong(self
, songid
):
595 userid
= self
._get
_login
()
597 playlists
= groovesharkApi
.getUserPlaylists()
598 if (len(playlists
) > 0):
600 # Select the playlist
601 playlistSelect
= GroovesharkPlaylistSelect(items
=playlists
)
602 playlistSelect
.setFocus(playlistSelect
.playlistControl
)
603 playlistSelect
.doModal()
604 i
= playlistSelect
.selected
608 if i
>= len(playlists
):
609 name
= self
._get
_keyboard
(default
='', heading
=__language__(30055))
612 songIds
.append(songid
)
613 if groovesharkApi
.createPlaylist(name
, songIds
) == 0:
614 dialog
= xbmcgui
.Dialog()
615 dialog
.ok(__language__(30008), __language__(30056), name
)
617 xbmc
.executebuiltin('XBMC.Notification(' + __language__(30008) + ',' + __language__(30057) + ', 1000, ' + thumbDef
+ ')')
620 playlist
= playlists
[i
]
621 playlistid
= playlist
[1]
623 xbmc
.log("Add song " + str(songid
) + " to playlist " + str(playlistid
))
625 songs
= groovesharkApi
.getPlaylistSongs(playlistid
)
627 songIDs
.append(song
[1])
628 songIDs
.append(songid
)
629 ret
= groovesharkApi
.setPlaylistSongs(playlistid
, songIDs
)
631 dialog
= xbmcgui
.Dialog()
632 dialog
.ok(__language__(30008), __language__(30058))
634 xbmc
.executebuiltin('XBMC.Notification(' + __language__(30008) + ',' + __language__(30059) + ', 1000, ' + thumbDef
+ ')')
636 dialog
= xbmcgui
.Dialog()
637 dialog
.ok(__language__(30008), __language__(30060))
640 dialog
= xbmcgui
.Dialog()
641 dialog
.ok(__language__(30008), __language__(30034), __language__(30061))
643 # Remove song from playlist
644 def removePlaylistSong(self
, playlistid
, playlistname
, songid
):
645 dialog
= xbmcgui
.Dialog()
646 if dialog
.yesno(__language__(30008), __language__(30062), __language__(30063)) == True:
647 userid
= self
._get
_login
()
649 songs
= groovesharkApi
.getPlaylistSongs(playlistID
)
652 if (song
[1] != songid
):
653 songIDs
.append(song
[1])
654 ret
= groovesharkApi
.setPlaylistSongs(playlistID
, songIDs
)
656 dialog
= xbmcgui
.Dialog()
657 dialog
.ok(__language__(30008), __language__(30064), __language__(30065))
659 # Refresh to remove item from directory
660 xbmc
.executebuiltin('XBMC.Notification(' + __language__(30008) + ',' + __language__(30066)+ ', 1000, ' + thumbDef
+ ')')
661 xbmc
.executebuiltin("Container.Update(" + playlistUrl
+ "&id="+str(playlistid
) + "&name=" + playlistname
+ ")")
663 dialog
= xbmcgui
.Dialog()
664 dialog
.ok(__language__(30008), __language__(30034), __language__(30067))
666 # Find similar artists to searched artist
667 def similarArtists(self
, artistId
):
668 similar
= groovesharkApi
.getSimilarArtists(artistId
, limit
= self
.artistsearchlimit
)
669 if (len(similar
) > 0):
670 self
._add
_artists
_directory
(similar
)
672 dialog
= xbmcgui
.Dialog()
673 dialog
.ok(__language__(30008), __language__(30068))
678 self
.debug
= self
.settings
.getSetting('debug')
680 xbmc
.log("Debug is on")
687 def _get_keyboard(self
, default
="", heading
="", hidden
=False):
688 kb
= xbmc
.Keyboard(default
, heading
, hidden
)
690 if (kb
.isConfirmed()):
691 return unicode(kb
.getText(), "utf-8")
694 # Login to grooveshark
695 def _get_login(self
):
696 if (self
.username
== "" or self
.password
== ""):
697 dialog
= xbmcgui
.Dialog()
698 dialog
.ok(__language__(30008), __language__(30069), __language__(30070))
702 uid
= groovesharkApi
.login(self
.username
, self
.password
)
706 dialog
= xbmcgui
.Dialog()
707 dialog
.ok(__language__(30008), __language__(30069), __language__(30070))
710 # Get a song directory item
711 def _get_song_item(self
, song
, trackLabelFormat
):
717 return self
.songItem(songid
, name
, album
, artist
, coverart
, trackLabelFormat
)
720 def _get_icon(self
, url
, songid
):
722 localThumb
= os
.path
.join(xbmc
.translatePath(os
.path
.join(thumbDir
, str(songid
)))) + '.tbn'
724 if os
.path
.isfile(localThumb
) == False:
725 loc
= urllib
.URLopener()
726 loc
.retrieve(url
, localThumb
)
728 shutil
.copy2(thumbDef
, localThumb
)
729 return os
.path
.join(os
.path
.join(thumbDir
, str(songid
))) + '.tbn'
733 # Add songs to directory
734 def _add_songs_directory(self
, songs
, trackLabelFormat
=ARTIST_ALBUM_NAME_LABEL
, offset
=0, playlistid
=0, playlistname
='', isFavorites
=False):
736 totalSongs
= len(songs
)
742 if offset
== 0 and totalSongs
<= self
.songspagelimit
:
744 xbmc
.log("Found " + str(totalSongs
) + " songs...")
747 # Cache all next pages songs
749 self
._setSavedSongs
(songs
)
751 songs
= self
._getSavedSongs
()
752 totalSongs
= len(songs
)
756 end
= min(start
+ self
.songspagelimit
,totalSongs
)
764 stream
= self
._getSongStream
(songid
)
765 if stream
['url'] != '':
766 item
= self
._get
_song
_item
(song
, trackLabelFormat
)
767 coverart
= item
.getProperty('coverart')
771 u
=sys
.argv
[0]+"?mode="+str(MODE_SONG
)+"&name="+urllib
.quote_plus(songname
)+"&id="+str(songid
) \
772 +"&album="+urllib
.quote_plus(songalbum
) \
773 +"&artist="+urllib
.quote_plus(songartist
) \
774 +"&coverart="+urllib
.quote_plus(coverart
)
775 fav
=sys
.argv
[0]+"?mode="+str(MODE_FAVORITE
)+"&name="+urllib
.quote_plus(songname
)+"&id="+str(songid
)
776 unfav
=sys
.argv
[0]+"?mode="+str(MODE_UNFAVORITE
)+"&name="+urllib
.quote_plus(songname
)+"&id="+str(songid
)+"&prevmode="
778 if isFavorites
== True:
779 unfav
= unfav
+str(MODE_FAVORITES
)
781 menuItems
.append((__language__(30071), "XBMC.RunPlugin("+fav
+")"))
782 menuItems
.append((__language__(30072), "XBMC.RunPlugin("+unfav
+")"))
784 rmplaylstsong
=sys
.argv
[0]+"?playlistid="+str(playlistid
)+"&id="+str(songid
)+"&mode="+str(MODE_REMOVE_PLAYLIST_SONG
)+"&name="+playlistname
785 menuItems
.append((__language__(30073), "XBMC.RunPlugin("+rmplaylstsong
+")"))
787 addplaylstsong
=sys
.argv
[0]+"?id="+str(songid
)+"&mode="+str(MODE_ADD_PLAYLIST_SONG
)
788 menuItems
.append((__language__(30074), "XBMC.RunPlugin("+addplaylstsong
+")"))
789 item
.addContextMenuItems(menuItems
, replaceItems
=False)
790 xbmcplugin
.addDirectoryItem(handle
=int(sys
.argv
[1]),url
=u
,listitem
=item
,isFolder
=False, totalItems
=items
)
793 end
= min(end
+ 1,totalSongs
)
795 xbmc
.log(song
[0] + " does not exist.")
799 u
=sys
.argv
[0]+"?mode="+str(MODE_SONG_PAGE
)+"&id=playlistid"+"&offset="+str(end
)+"&label="+str(trackLabelFormat
)+"&name="+playlistname
800 self
._add
_dir
(__language__(30075) + '...', u
, MODE_SONG_PAGE
, self
.songImg
, 0, totalSongs
- end
)
802 xbmcplugin
.setContent(self
._handle
, 'songs')
803 xbmcplugin
.setPluginFanart(int(sys
.argv
[1]), self
.fanImg
)
805 # Add albums to directory
806 def _add_albums_directory(self
, albums
, artistid
=0):
810 xbmc
.log("Found " + str(n
) + " albums...")
815 if groovesharkApi
.getDoesAlbumExist(albumID
):
816 albumArtistName
= album
[0]
818 albumImage
= self
._get
_icon
(album
[4], 'album-' + str(albumID
))
819 self
._add
_dir
(albumName
+ " - " + albumArtistName
, '', MODE_ALBUM
, albumImage
, albumID
, itemsExisting
)
821 itemsExisting
= itemsExisting
- 1
823 # Not supported by key
825 # self._add_dir('Similar artists...', '', MODE_SIMILAR_ARTISTS, self.artistImg, artistid)
826 xbmcplugin
.setContent(self
._handle
, 'albums')
827 xbmcplugin
.addSortMethod(self
._handle
, xbmcplugin
.SORT_METHOD_ALBUM_IGNORE_THE
)
828 xbmcplugin
.setPluginFanart(int(sys
.argv
[1]), self
.fanImg
)
830 # Add artists to directory
831 def _add_artists_directory(self
, artists
):
835 xbmc
.log("Found " + str(n
) + " artists...")
840 if groovesharkApi
.getDoesArtistExist(artistID
):
841 artistName
= artist
[0]
842 self
._add
_dir
(artistName
, '', MODE_ARTIST
, self
.artistImg
, artistID
, itemsExisting
)
844 itemsExisting
= itemsExisting
- 1
846 xbmcplugin
.setContent(self
._handle
, 'artists')
847 xbmcplugin
.addSortMethod(self
._handle
, xbmcplugin
.SORT_METHOD_ARTIST_IGNORE_THE
)
848 xbmcplugin
.setPluginFanart(int(sys
.argv
[1]), self
.fanImg
)
850 # Add playlists to directory
851 def _add_playlists_directory(self
, playlists
):
854 xbmc
.log("Found " + str(n
) + " playlists...")
857 playlist
= playlists
[i
]
858 playlistName
= playlist
[0]
859 playlistID
= playlist
[1]
860 dir = self
._add
_dir
(playlistName
, '', MODE_PLAYLIST
, self
.playlistImg
, playlistID
, n
)
862 xbmcplugin
.setContent(self
._handle
, 'files')
863 xbmcplugin
.addSortMethod(self
._handle
, xbmcplugin
.SORT_METHOD_LABEL
)
864 xbmcplugin
.setPluginFanart(int(sys
.argv
[1]), self
.fanImg
)
866 # Add whatever directory
867 def _add_dir(self
, name
, url
, mode
, iconimage
, id, items
=1):
870 u
=sys
.argv
[0]+"?mode="+str(mode
)+"&name="+urllib
.quote_plus(name
)+"&id="+str(id)
873 dir=xbmcgui
.ListItem(name
, iconImage
=iconimage
, thumbnailImage
=iconimage
)
874 dir.setInfo( type="Music", infoLabels
={ "title": name
} )
878 if mode
== MODE_ALBUM
:
879 mkplaylst
=sys
.argv
[0]+"?mode="+str(MODE_MAKE_PLAYLIST
)+"&name="+name
+"&id="+str(id)
880 menuItems
.append((__language__(30076), "XBMC.RunPlugin("+mkplaylst
+")"))
881 if mode
== MODE_PLAYLIST
:
882 rmplaylst
=sys
.argv
[0]+"?mode="+str(MODE_REMOVE_PLAYLIST
)+"&name="+urllib
.quote_plus(name
)+"&id="+str(id)
883 menuItems
.append((__language__(30077), "XBMC.RunPlugin("+rmplaylst
+")"))
884 mvplaylst
=sys
.argv
[0]+"?mode="+str(MODE_RENAME_PLAYLIST
)+"&name="+urllib
.quote_plus(name
)+"&id="+str(id)
885 menuItems
.append((__language__(30078), "XBMC.RunPlugin("+mvplaylst
+")"))
887 dir.addContextMenuItems(menuItems
, replaceItems
=False)
889 return xbmcplugin
.addDirectoryItem(handle
=int(sys
.argv
[1]),url
=u
,listitem
=dir,isFolder
=True, totalItems
=items
)
891 def _getSavedSongs(self
):
892 path
= os
.path
.join(cacheDir
, 'songs.dmp')
895 songs
= pickle
.load(f
)
902 def _setSavedSongs(self
, songs
):
904 # Create the 'data' directory if it doesn't exist.
905 if not os
.path
.exists(cacheDir
):
906 os
.makedirs(cacheDir
)
907 path
= os
.path
.join(cacheDir
, 'songs.dmp')
909 pickle
.dump(songs
, f
, protocol
=pickle
.HIGHEST_PROTOCOL
)
912 xbmc
.log("An error occurred saving songs")
915 def _getSongStream(self
, songid
):
920 path
= os
.path
.join(cacheDir
, 'streams.dmp')
923 streams
= pickle
.load(f
)
933 if duration
< 0 and groovesharkApi
.getDoesSongExist(songid
):
934 stream
= groovesharkApi
.getSubscriberStreamKey(songid
)
936 usecs
= stream
['uSecs']
938 usecs
= usecs
* 10 # Some durations are 10x to small
939 duration
= usecs
/ 1000000
940 song
= [id, duration
, url
]
942 self
._setSongStream
(streams
)
944 return {'duration':duration
, 'url':url
}
946 def _setSongStream(self
, streams
):
948 # Create the 'data' directory if it doesn't exist.
949 if not os
.path
.exists(cacheDir
):
950 os
.makedirs(cacheDir
)
951 path
= os
.path
.join(cacheDir
, 'streams.dmp')
953 pickle
.dump(streams
, f
, protocol
=pickle
.HIGHEST_PROTOCOL
)
956 xbmc
.log("An error occurred saving streams")
960 # Parse URL parameters
963 paramstring
=sys
.argv
[2]
964 if grooveshark
.getDebug():
965 xbmc
.log(paramstring
)
966 if len(paramstring
)>=2:
968 cleanedparams
=params
.replace('?','')
969 if (params
[len(params
)-1]=='/'):
970 params
=params
[0:len(params
)-2]
971 pairsofparams
=cleanedparams
.split('&')
973 for i
in range(len(pairsofparams
)):
975 splitparams
=pairsofparams
[i
].split('=')
976 if (len(splitparams
))==2:
977 param
[splitparams
[0]]=splitparams
[1]
981 grooveshark
= Grooveshark();
982 grooveshark
.setDebug()
983 groovesharkApi
.setDebug(grooveshark
.getDebug())
987 try: mode
=int(params
["mode"])
990 try: id=int(params
["id"])
993 try: name
=urllib
.unquote_plus(params
["name"])
996 # Call function for URL
998 grooveshark
.categories()
1000 elif mode
==MODE_SEARCH_SONGS
:
1001 grooveshark
.searchSongs()
1003 elif mode
==MODE_SEARCH_ALBUMS
:
1004 grooveshark
.searchAlbums()
1006 elif mode
==MODE_SEARCH_ARTISTS
:
1007 grooveshark
.searchArtists()
1009 elif mode
==MODE_SEARCH_ARTISTS_ALBUMS
:
1010 grooveshark
.searchArtistsAlbums(name
)
1012 elif mode
==MODE_SEARCH_PLAYLISTS
:
1013 grooveshark
.searchPlaylists()
1015 elif mode
==MODE_POPULAR_SONGS
:
1016 grooveshark
.popularSongs()
1018 elif mode
==MODE_ARTIST_POPULAR
:
1019 grooveshark
.artistPopularSongs()
1021 elif mode
==MODE_FAVORITES
:
1022 grooveshark
.favorites()
1024 elif mode
==MODE_PLAYLISTS
:
1025 grooveshark
.playlists()
1027 elif mode
==MODE_SONG_PAGE
:
1028 try: offset
=urllib
.unquote_plus(params
["offset"])
1030 try: label
=urllib
.unquote_plus(params
["label"])
1032 grooveshark
.songPage(offset
, label
, id, name
)
1034 elif mode
==MODE_SONG
:
1035 try: album
=urllib
.unquote_plus(params
["album"])
1037 try: artist
=urllib
.unquote_plus(params
["artist"])
1039 try: coverart
=urllib
.unquote_plus(params
["coverart"])
1041 song
= grooveshark
.songItem(id, name
, album
, artist
, coverart
)
1042 grooveshark
.playSong(song
)
1044 elif mode
==MODE_ARTIST
:
1045 grooveshark
.artist(id)
1047 elif mode
==MODE_ALBUM
:
1048 grooveshark
.album(id)
1050 elif mode
==MODE_PLAYLIST
:
1051 grooveshark
.playlist(id, name
)
1053 elif mode
==MODE_FAVORITE
:
1054 grooveshark
.favorite(id)
1056 elif mode
==MODE_UNFAVORITE
:
1057 try: prevMode
=int(urllib
.unquote_plus(params
["prevmode"]))
1060 grooveshark
.unfavorite(id, prevMode
)
1062 elif mode
==MODE_SIMILAR_ARTISTS
:
1063 grooveshark
.similarArtists(id)
1065 elif mode
==MODE_MAKE_PLAYLIST
:
1066 grooveshark
.makePlaylist(id, name
)
1068 elif mode
==MODE_REMOVE_PLAYLIST
:
1069 grooveshark
.removePlaylist(id, name
)
1071 elif mode
==MODE_RENAME_PLAYLIST
:
1072 grooveshark
.renamePlaylist(id, name
)
1074 elif mode
==MODE_REMOVE_PLAYLIST_SONG
:
1075 try: playlistID
=urllib
.unquote_plus(params
["playlistid"])
1077 grooveshark
.removePlaylistSong(playlistID
, name
, id)
1079 elif mode
==MODE_ADD_PLAYLIST_SONG
:
1080 grooveshark
.addPlaylistSong(id)
1082 if mode
< MODE_SONG
:
1083 xbmcplugin
.endOfDirectory(int(sys
.argv
[1]))