jellyfin-kodi/resources/lib/websocket_client.py

362 lines
12 KiB
Python
Raw Normal View History

2016-03-31 19:48:52 +00:00
# -*- coding: utf-8 -*-
#################################################################################################
import json
import logging
2016-03-31 19:48:52 +00:00
import threading
import websocket
import xbmc
import clientinfo
import downloadutils
import librarysync
import playlist
import userclient
import playbackutils
2016-09-07 07:14:02 +00:00
from utils import window, settings, dialog, language as lang, JSONRPC
2018-05-13 03:56:53 +00:00
#from ga_client import log_error
2016-03-31 19:48:52 +00:00
##################################################################################################
log = logging.getLogger("EMBY."+__name__)
##################################################################################################
2016-03-31 19:48:52 +00:00
2016-09-09 03:13:25 +00:00
class WebSocketClient(threading.Thread):
2016-03-31 19:48:52 +00:00
_shared_state = {}
2016-09-07 07:14:02 +00:00
_client = None
_stop_websocket = False
2016-03-31 19:48:52 +00:00
def __init__(self):
self.__dict__ = self._shared_state
self.monitor = xbmc.Monitor()
2016-09-09 03:13:25 +00:00
2016-09-07 07:14:02 +00:00
self.doutils = downloadutils.DownloadUtils()
self.client_info = clientinfo.ClientInfo()
self.device_id = self.client_info.get_device_id()
self.library_sync = librarysync.LibrarySync()
2016-09-09 03:13:25 +00:00
2016-03-31 19:48:52 +00:00
threading.Thread.__init__(self)
2018-05-13 03:56:53 +00:00
#@log_error()
2016-03-31 19:48:52 +00:00
def on_message(self, ws, message):
result = json.loads(message)
2016-09-07 07:14:02 +00:00
message_type = result['MessageType']
2016-03-31 19:48:52 +00:00
if message_type not in ('NotificationAdded', 'SessionEnded', 'RestartRequired',
'PackageInstalling'):
2016-03-31 19:48:52 +00:00
# Mute certain events
2016-09-09 03:13:25 +00:00
log.info("Message: %s", message)
2016-03-31 19:48:52 +00:00
2016-09-09 03:13:25 +00:00
if message_type == 'Play':
2016-03-31 19:48:52 +00:00
# A remote control play command has been sent from the server.
2017-01-03 05:39:29 +00:00
data = result['Data']
2016-10-18 10:20:10 +00:00
self._play(data)
2016-03-31 19:48:52 +00:00
2016-09-09 03:13:25 +00:00
elif message_type == 'Playstate':
2016-09-07 07:14:02 +00:00
# A remote control update playstate command has been sent from the server.
2017-01-03 05:39:29 +00:00
data = result['Data']
2016-10-18 10:20:10 +00:00
self._playstate(data)
2016-03-31 19:48:52 +00:00
2016-09-07 07:14:02 +00:00
elif message_type == "UserDataChanged":
2016-03-31 19:48:52 +00:00
# A user changed their personal rating for an item, or their playstate was updated
2017-01-03 05:39:29 +00:00
data = result['Data']
2016-03-31 19:48:52 +00:00
userdata_list = data['UserDataList']
2016-09-07 07:14:02 +00:00
self.library_sync.triage_items("userdata", userdata_list)
2016-03-31 19:48:52 +00:00
2016-09-07 07:14:02 +00:00
elif message_type == "LibraryChanged":
2017-01-03 05:39:29 +00:00
data = result['Data']
2016-09-09 03:13:25 +00:00
self._library_changed(data)
2016-03-31 19:48:52 +00:00
2016-09-07 07:14:02 +00:00
elif message_type == "GeneralCommand":
2017-01-03 05:39:29 +00:00
data = result['Data']
2016-09-07 07:14:02 +00:00
self._general_commands(data)
elif message_type == "ServerRestarting":
self._server_restarting()
elif message_type == "UserConfigurationUpdated":
2016-03-31 19:48:52 +00:00
# Update user data set in userclient
2017-01-03 05:39:29 +00:00
data = result['Data']
userclient.UserClient().get_user(data)
2016-09-07 07:14:02 +00:00
self.library_sync.refresh_views = True
2016-03-31 19:48:52 +00:00
2016-09-07 07:14:02 +00:00
elif message_type == "ServerShuttingDown":
# Server went offline
window('emby_online', value="false")
2016-09-07 07:14:02 +00:00
@classmethod
2016-10-18 10:20:10 +00:00
def _play(cls, data):
2016-09-07 07:14:02 +00:00
''' {"Id":"e2c106a953bfc0d9c191a49cda6561de",
"ItemIds":["52f0c57e2133e1c11d36c59edcd835fc"],
"PlayCommand":"PlayNow","ControllingUserId":"d40000000000000000000000000000000",
"SubtitleStreamIndex":3,"AudioStreamIndex":1,
"MediaSourceId":"ba83c549ac5c0e4180ae33ebdf813c51"}}
'''
2016-09-07 07:14:02 +00:00
item_ids = data['ItemIds']
kwargs = {
'SubtitleStreamIndex': data.get('SubtitleStreamIndex'),
'AudioStreamIndex': data.get('AudioStreamIndex'),
'MediaSourceId': data.get('MediaSourceId')
}
2016-09-07 07:14:02 +00:00
command = data['PlayCommand']
playlist_ = playlist.Playlist()
2016-09-09 03:13:25 +00:00
if command == 'PlayNow':
if playbackutils.PlaybackUtils(None, item_ids[0]).play_all(item_ids, data.get('StartPositionTicks', 0), **kwargs):
dialog(type_="notification",
heading="{emby}",
message="%s %s" % (len(item_ids), lang(33004)),
icon="{emby}",
sound=False)
2016-09-07 07:14:02 +00:00
2016-09-09 03:13:25 +00:00
elif command == 'PlayNext':
new_playlist = playlist_.modify_playlist(item_ids)
2016-09-07 07:14:02 +00:00
dialog(type_="notification",
2016-09-09 03:13:25 +00:00
heading="{emby}",
2016-09-07 07:14:02 +00:00
message="%s %s" % (len(item_ids), lang(33005)),
icon="{emby}",
sound=False)
player = xbmc.Player()
if not player.isPlaying():
# Only start the playlist if nothing is playing
2016-09-09 03:13:25 +00:00
player.play(new_playlist)
2016-09-07 07:14:02 +00:00
@classmethod
2016-10-18 10:20:10 +00:00
def _playstate(cls, data):
2016-09-07 07:14:02 +00:00
command = data['Command']
player = xbmc.Player()
actions = {
'Stop': player.stop,
'Unpause': player.pause,
'Pause': player.pause,
2017-09-03 19:08:52 +00:00
'PlayPause': player.pause,
2016-09-07 07:14:02 +00:00
'NextTrack': player.playnext,
2016-09-09 03:13:25 +00:00
'PreviousTrack': player.playprevious
2016-09-07 07:14:02 +00:00
}
2016-09-09 03:13:25 +00:00
if command == 'Seek':
2017-01-03 05:39:29 +00:00
if player.isPlaying():
seek_to = data['SeekPositionTicks']
seek_time = seek_to / 10000000.0
player.seekTime(seek_time)
log.info("Seek to %s", seek_time)
2016-09-09 03:13:25 +00:00
elif command in actions:
actions[command]()
2016-09-07 07:14:02 +00:00
log.info("Command: %s completed", command)
2016-09-09 03:13:25 +00:00
else:
log.info("Unknown command: %s", command)
return
2016-09-07 07:14:02 +00:00
window('emby_command', value="true")
2016-09-09 03:13:25 +00:00
def _library_changed(self, data):
process_list = {
'added': data['ItemsAdded'],
'update': data['ItemsUpdated'],
'remove': data['ItemsRemoved']
}
for action in process_list:
self.library_sync.triage_items(action, process_list[action])
2016-09-07 07:14:02 +00:00
@classmethod
def _general_commands(cls, data):
command = data['Name']
arguments = data['Arguments']
if command in ('Mute', 'Unmute', 'SetVolume',
2017-08-25 07:22:12 +00:00
'SetSubtitleStreamIndex', 'SetAudioStreamIndex', 'SetRepeatMode'):
2016-09-07 07:14:02 +00:00
player = xbmc.Player()
# These commands need to be reported back
2016-09-09 03:13:25 +00:00
if command == 'Mute':
2016-09-07 07:14:02 +00:00
xbmc.executebuiltin('Mute')
2016-09-09 03:13:25 +00:00
elif command == 'Unmute':
2016-09-07 07:14:02 +00:00
xbmc.executebuiltin('Mute')
2016-09-09 03:13:25 +00:00
elif command == 'SetVolume':
2016-09-07 07:14:02 +00:00
volume = arguments['Volume']
xbmc.executebuiltin('SetVolume(%s[,showvolumebar])' % volume)
2016-09-09 03:13:25 +00:00
elif command == 'SetAudioStreamIndex':
2016-09-07 07:14:02 +00:00
index = int(arguments['Index'])
player.setAudioStream(index - 1)
2017-08-25 07:22:12 +00:00
elif command == 'SetRepeatMode':
mode = arguments['RepeatMode']
xbmc.executebuiltin('xbmc.PlayerControl(%s)' % mode)
2016-09-09 03:13:25 +00:00
elif command == 'SetSubtitleStreamIndex':
emby_index = int(arguments['Index'])
current_file = player.getPlayingFile()
mapping = window('emby_%s.indexMapping.json' % current_file)
2016-10-09 04:06:46 +00:00
if emby_index == -1:
player.showSubtitles(False)
elif mapping:
2016-09-09 03:13:25 +00:00
external_index = json.loads(mapping)
2016-09-07 07:14:02 +00:00
# If there's external subtitles added via playbackutils
2016-09-09 03:13:25 +00:00
for index in external_index:
if external_index[index] == emby_index:
2016-09-07 07:14:02 +00:00
player.setSubtitleStream(int(index))
break
else:
# User selected internal subtitles
2016-09-09 03:13:25 +00:00
external = len(external_index)
audio_tracks = len(player.getAvailableAudioStreams())
player.setSubtitleStream(external + emby_index - audio_tracks - 1)
2016-09-07 07:14:02 +00:00
else:
# Emby merges audio and subtitle index together
2016-09-09 03:13:25 +00:00
audio_tracks = len(player.getAvailableAudioStreams())
2016-10-09 02:05:00 +00:00
player.setSubtitleStream(emby_index - audio_tracks - 1)
2016-09-07 07:14:02 +00:00
# Let service know
window('emby_command', value="true")
2016-09-09 03:13:25 +00:00
elif command == 'DisplayMessage':
2016-09-07 07:14:02 +00:00
header = arguments['Header']
text = arguments['Text']
dialog(type_="notification",
heading=header,
message=text,
icon="{emby}",
time=int(settings('displayMessage'))*1000)
2016-09-07 07:14:02 +00:00
2016-09-09 03:13:25 +00:00
elif command == 'SendString':
2016-09-07 07:14:02 +00:00
params = {
2016-09-09 03:13:25 +00:00
2016-09-07 07:14:02 +00:00
'text': arguments['String'],
'done': False
}
2016-09-09 03:13:25 +00:00
JSONRPC('Input.SendText').execute(params)
2016-09-07 07:14:02 +00:00
2016-09-09 03:13:25 +00:00
elif command in ('MoveUp', 'MoveDown', 'MoveRight', 'MoveLeft'):
2016-09-07 07:14:02 +00:00
# Commands that should wake up display
actions = {
2016-09-09 03:13:25 +00:00
2016-09-07 07:14:02 +00:00
'MoveUp': "Input.Up",
'MoveDown': "Input.Down",
'MoveRight': "Input.Right",
'MoveLeft': "Input.Left"
}
2016-09-09 03:13:25 +00:00
JSONRPC(actions[command]).execute()
2016-09-07 07:14:02 +00:00
2016-09-09 03:13:25 +00:00
elif command == 'GoHome':
JSONRPC('GUI.ActivateWindow').execute({'window': "home"})
2016-09-07 07:14:02 +00:00
2017-05-09 07:58:59 +00:00
elif command == "Guide":
JSONRPC('GUI.ActivateWindow').execute({'window': "tvguide"})
2016-09-07 07:14:02 +00:00
else:
builtin = {
'ToggleFullscreen': 'Action(FullScreen)',
'ToggleOsdMenu': 'Action(OSD)',
'ToggleContextMenu': 'Action(ContextMenu)',
'Select': 'Action(Select)',
'Back': 'Action(back)',
'PageUp': 'Action(PageUp)',
'NextLetter': 'Action(NextLetter)',
'GoToSearch': 'VideoLibrary.Search',
'GoToSettings': 'ActivateWindow(Settings)',
'PageDown': 'Action(PageDown)',
'PreviousLetter': 'Action(PrevLetter)',
'TakeScreenshot': 'TakeScreenshot',
'ToggleMute': 'Mute',
'VolumeUp': 'Action(VolumeUp)',
'VolumeDown': 'Action(VolumeDown)',
}
2016-09-09 03:13:25 +00:00
if command in builtin:
xbmc.executebuiltin(builtin[command])
2016-09-07 07:14:02 +00:00
@classmethod
def _server_restarting(cls):
if settings('supressRestartMsg') == "true":
dialog(type_="notification",
2016-09-09 03:13:25 +00:00
heading="{emby}",
2016-09-07 07:14:02 +00:00
message=lang(33006),
icon="{emby}")
window('emby_online', value="false")
2016-09-07 07:14:02 +00:00
2016-03-31 19:48:52 +00:00
def on_close(self, ws):
2016-09-07 07:14:02 +00:00
log.debug("closed")
2016-03-31 19:48:52 +00:00
def on_open(self, ws):
log.debug("open")
2016-03-31 19:48:52 +00:00
def on_error(self, ws, error):
2016-09-09 03:13:25 +00:00
2016-03-31 19:48:52 +00:00
if "10061" in str(error):
# Server is offline
pass
else:
2016-09-07 07:14:02 +00:00
log.debug("Error: %s", error)
2016-03-31 19:48:52 +00:00
def run(self):
# websocket.enableTrace(True)
2016-09-07 07:14:02 +00:00
user_id = window('emby_currUser')
server = window('emby_server%s' % user_id)
token = window('emby_accessToken%s' % user_id)
2016-03-31 19:48:52 +00:00
# Get the appropriate prefix for the websocket
if "https" in server:
server = server.replace('https', "wss")
else:
server = server.replace('http', "ws")
2017-07-27 23:41:56 +00:00
websocket_url = "%s/embywebsocket?api_key=%s&deviceId=%s" % (server, token, self.device_id)
2016-09-07 07:14:02 +00:00
log.info("websocket url: %s", websocket_url)
2016-03-31 19:48:52 +00:00
2016-09-07 07:14:02 +00:00
self._client = websocket.WebSocketApp(websocket_url,
2016-09-09 03:13:25 +00:00
on_message=self.on_message,
on_error=self.on_error,
on_close=self.on_close)
2016-09-07 07:14:02 +00:00
self._client.on_open = self.on_open
log.warn("----===## Starting WebSocketClient ##===----")
2016-03-31 19:48:52 +00:00
2016-03-31 19:52:09 +00:00
while not self.monitor.abortRequested():
2016-03-31 19:48:52 +00:00
if window('emby_online') == "true":
self._client.run_forever(ping_interval=10)
2016-09-27 06:33:09 +00:00
2016-09-07 07:14:02 +00:00
if self._stop_websocket:
2016-03-31 19:48:52 +00:00
break
2018-05-09 21:53:10 +00:00
if self.monitor.waitForAbort(120):
2016-03-31 19:48:52 +00:00
# Abort was requested, exit
break
log.warn("##===---- WebSocketClient Stopped ----===##")
2016-03-31 19:48:52 +00:00
2016-09-07 07:14:02 +00:00
def stop_client(self):
2016-03-31 19:48:52 +00:00
2016-09-07 07:14:02 +00:00
self._stop_websocket = True
if self._client is not None:
self._client.close()
2016-09-07 07:14:02 +00:00
log.info("Stopping thread")