Skip to content

Commit

Permalink
Working version, still some minor events not handled correctly
Browse files Browse the repository at this point in the history
  • Loading branch information
jbkaiser committed Mar 15, 2020
1 parent 9dfc6a4 commit 1fab167
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 74 deletions.
32 changes: 11 additions & 21 deletions resources/lib/httpproxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,15 @@

class Root:
spotty = None
connect_player = None

spotty_bin = None
spotty_trackid = None
spotty_range_l = None

def __init__(self, spotty):
def __init__(self, spotty, connect_player):
self.__spotty = spotty
self.__connect_player = connect_player

def _check_request(self):
method = cherrypy.request.method.upper()
Expand Down Expand Up @@ -60,13 +62,13 @@ def lms(self, filename, **kwargs):
xbmc.executebuiltin("SetProperty(spotify-cmd,__LOGOUT__,Home)")
if "start" in event:
log_msg("playback start requested by connect")
xbmc.executebuiltin("RunPlugin(plugin://plugin.audio.spotify-headless/?action=play_connect)")
self.__connect_player.handle_lms_event()
elif "change" in event:
log_msg("playback change requested by connect")
xbmc.executebuiltin("RunPlugin(plugin://plugin.audio.spotify-headless/?action=play_connect)")
self.__connect_player.handle_lms_event()
elif "stop" in event:
log_msg("playback stop requested by connect")
xbmc.executebuiltin("PlayerControl(Stop)")
self.__connect_player.handle_lms_event()
elif "volume" in event:
vol_level = event[2]
log_msg("volume change detected on connect player: %s" % vol_level)
Expand Down Expand Up @@ -142,6 +144,9 @@ def send_audio_stream(self, track_id, filesize, wave_header, range_l):
log_msg("start transfer for track %s - range: %s" % (track_id, range_l), \
xbmc.LOGDEBUG)
try:
self.spotty_trackid = track_id
self.spotty_range_l = range_l

# Initialize some loop vars
max_buffer_size = 524288
bytes_written = 0
Expand All @@ -155,8 +160,6 @@ def send_audio_stream(self, track_id, filesize, wave_header, range_l):
# get pcm data from spotty stdout and append to our buffer
args = ["-n", "temp", "--single-track", track_id]
self.spotty_bin = self.__spotty.run_spotty(args, use_creds=True)
self.spotty_trackid = track_id
self.spotty_range_l = range_l

# ignore the first x bytes to match the range request
if range_l:
Expand Down Expand Up @@ -212,26 +215,13 @@ def callback(self, **kwargs):
xbmc.executebuiltin("SetProperty(spotify-token-info,%s,Home)" % url)
log_msg("authkey sent")
return html

@cherrypy.expose
def playercmd(self, cmd, **kwargs):
if cmd == "start":
cherrypy.response.headers['Content-Type'] = 'text'
log_msg("playback start requested by connect")
xbmc.executebuiltin("RunPlugin(plugin://plugin.audio.spotify-headless/?action=play_connect)")
return "OK"
elif cmd == "stop":
cherrypy.response.headers['Content-Type'] = 'text'
log_msg("playback stop requested by connect")
xbmc.executebuiltin("PlayerControl(Stop)")
return "OK"

class ProxyRunner(threading.Thread):
__server = None
__root = None

def __init__(self, spotty):
self.__root = Root(spotty)
def __init__(self, spotty, connect_player):
self.__root = Root(spotty, connect_player)
log = cherrypy.log
log.access_file = ''
log.error_file = ''
Expand Down
12 changes: 4 additions & 8 deletions resources/lib/main_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def __init__(self):
self.sp = spotipy.Spotify()
self.connect_player = ConnectPlayer.getInstance(sp=self.sp)

self.proxy_runner = ProxyRunner(self.spotty)
self.proxy_runner = ProxyRunner(self.spotty, self.connect_player)
self.proxy_runner.start()
webport = self.proxy_runner.get_port()
log_msg('started webproxy at port {0}'.format(webport))
Expand Down Expand Up @@ -84,13 +84,9 @@ def main_loop(self):
# token needs refreshing !
log_msg("token needs to be refreshed")
self.renew_token()
elif self.connect_player.connect_playing or cmd == "__RECONNECT__":
# monitor for remote track changes
loop_timer = 2
reconnect = cmd == "__RECONNECT__"
if reconnect:
self.win.clearProperty("spotify-cmd")
self.connect_player.update_info(reconnect)
elif cmd == "__RECONNECT__":
self.win.clearProperty("spotify-cmd")
self.connect_player.update_info()
else:
loop_timer = 5

Expand Down
44 changes: 27 additions & 17 deletions resources/lib/player_monitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ class ConnectPlayer(xbmc.Player):
__ignore_seek = False
__sp = None
__skip_events = False
__is_loading_next_track = False

def __init__(self, **kwargs):
if ConnectPlayer.__instance != None:
Expand Down Expand Up @@ -73,10 +74,13 @@ def onPlayBackStarted(self):
# we started playback with (remote) connect player
log_msg("Playback started of Spotify Connect stream")
self.connect_playing = True
self.__is_loading_next_track = False
if "nexttrack" in filename:
# next track requested for kodi player
self.__skip_events = True
self.__sp.next_track()
if not self.__is_loading_next_track:
self.__skip_events = True
self.__is_loading_next_track = True
self.__sp.next_track()
else:
self.__skip_events = False

Expand Down Expand Up @@ -108,46 +112,52 @@ def add_nexttrack_to_playlist(self):
url = "http://localhost:%s/nexttrack" % PROXY_PORT
li = xbmcgui.ListItem('...', path=url)
self.__playlist.add(url, li)
## self.__playlist.add(url, li)

def start_playback(self, track_id):
self.__skip_events = True
self.connect_playing = True
self.__is_loading_next_track = False
self.__playlist.clear()
trackdetails = self.__sp.track(track_id)
url, li = parse_spotify_track(trackdetails, silenced=False, is_connect=True)
self.__playlist.add(url, li)
self.add_nexttrack_to_playlist()
self.__ignore_seek = True
self.__sp.seek_track(0) # for now we always start a track at the beginning
## self.__sp.seek_track(0) # for now we always start a track at the beginning
self.play(self.__playlist)

def update_info(self, force):
cur_playback = None
count = 0
while not cur_playback and count < 10:
try:
cur_playback = self.__sp.current_playback()
except:
count += 1
xbmc.sleep(500)
def update_info(self):
log_msg("Called update_info()!")

def handle_lms_event(self):

cur_playback = self.__sp.current_playback()

if not cur_playback:
log_msg("Could not retrieve trackdetails from api, stopping playback")
self.__skip_events = True
self.connect_playing = False
self.stop()
else:
if cur_playback["is_playing"] and (not xbmc.getCondVisibility("Player.Paused") or force):

if cur_playback["is_playing"] and not xbmc.getCondVisibility("Player.Paused"):
player_title = None
if self.isPlaying():
player_title = self.getMusicInfoTag().getTitle().decode("utf-8")
trackdetails = cur_playback["item"]
if trackdetails is not None and (not player_title or player_title == "nexttrack" or player_title != trackdetails["name"]):
log_msg("Next track requested by Spotify Connect player")
self.start_playback(trackdetails["id"])
if trackdetails is not None:
if not player_title or player_title != trackdetails["name"]:
log_msg("Next track requested by Spotify Connect player")
self.start_playback(trackdetails["id"])
if not self.connect_playing:
log_msg("Playback start or resume requested by Spotify Connect player")
self.start_playback(trackdetails["id"])

elif cur_playback["is_playing"] and xbmc.getCondVisibility("Player.Paused"):
log_msg("Playback resumed from pause requested by Spotify Connect")
self.__skip_events = True
self.play()

elif not xbmc.getCondVisibility("Player.Paused"):
log_msg("Pause requested by Spotify Connect")
self.__skip_events = True
Expand Down
29 changes: 1 addition & 28 deletions resources/lib/plugin_content.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ class PluginContent():

action = ""
sp = None
connect_player = None
userid = ""
usercountry = ""
offset = 0
Expand Down Expand Up @@ -49,7 +48,6 @@ def __init__(self):
if auth_token:
self.parse_params()
self.sp = spotipy.Spotify(auth=auth_token)
self.connect_player = ConnectPlayer.getInstance(sp=self.sp)
self.userid = self.win.getProperty("spotify-username").decode("utf-8")
self.usercountry = self.win.getProperty("spotify-country").decode("utf-8")
self.local_playback, self.playername, self.connect_id = self.active_playback_device()
Expand Down Expand Up @@ -105,10 +103,7 @@ def refresh_connected_device(self):

def switch_user(self):
'''switch or logout user'''
if self.addon.getSetting("multi_account") == "true":
return self.switch_user_multi()
else:
return self.logoff_user()
return self.logoff_user()

def logoff_user(self):
''' logoff user '''
Expand All @@ -125,28 +120,6 @@ def logoff_user(self):
xbmc.executebuiltin("Container.Refresh")
del dialog

def next_track(self):
'''special entry which tells the remote connect player to move to the next track'''

cur_playlist_position = xbmc.PlayList(xbmc.PLAYLIST_MUSIC).getposition()
# prevent unintentional skipping when Kodi track ends before connect player
# playlist position will increse only when play next button is pressed
if cur_playlist_position > self.last_playlist_position:
# move to next track
self.sp.next_track()
# give time for connect player to update info
xbmc.sleep(300)

self.last_playlist_position = cur_playlist_position
cur_playback = self.sp.current_playback()
trackdetails = cur_playback["item"]
url, li = parse_spotify_track(trackdetails, silenced=True)
xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, li)

def play_connect(self):
'''start local connect playback - called from webservice when local connect player starts playback'''
self.connect_player.update_info(True)

def browse_main(self):
# main listing
xbmcplugin.setContent(self.addon_handle, "files")
Expand Down

0 comments on commit 1fab167

Please sign in to comment.