PlexKodiConnect/resources/lib/websocket_client.py

259 lines
9.4 KiB
Python
Raw Normal View History

#!/usr/bin/env python
2016-03-20 03:57:57 +11:00
# -*- coding: utf-8 -*-
2017-12-10 00:35:08 +11:00
from logging import getLogger
2016-12-21 02:30:22 +11:00
from json import loads
2016-03-20 03:57:57 +11:00
2018-11-19 00:59:17 +11:00
from . import backgroundthread, websocket, utils, companion, app, variables as v
2016-09-05 00:41:05 +10:00
###############################################################################
2016-03-20 03:57:57 +11:00
2018-06-22 03:24:37 +10:00
LOG = getLogger('PLEX.websocket_client')
2016-03-20 03:57:57 +11:00
2016-03-22 03:15:22 +11:00
###############################################################################
2016-03-20 03:57:57 +11:00
2018-11-19 00:59:17 +11:00
class WebSocket(backgroundthread.KillableThread):
2016-03-30 03:44:13 +11:00
opcode_data = (websocket.ABNF.OPCODE_TEXT, websocket.ABNF.OPCODE_BINARY)
2018-02-10 01:10:20 +11:00
def __init__(self):
self.ws = None
2019-02-05 22:37:01 +11:00
self.redirect_uri = None
self.sleeptime = 0.0
2018-02-10 01:10:20 +11:00
super(WebSocket, self).__init__()
2016-03-20 03:57:57 +11:00
2020-05-07 15:48:50 +10:00
def close_websocket(self):
if self.ws is not None:
self.ws.close()
self.ws = None
2016-03-30 03:44:13 +11:00
def process(self, opcode, message):
2017-03-05 03:54:24 +11:00
raise NotImplementedError
2016-03-22 03:15:22 +11:00
2016-03-30 03:44:13 +11:00
def receive(self, ws):
# Not connected yet
if ws is None:
raise websocket.WebSocketConnectionClosedException
2016-03-20 03:57:57 +11:00
2016-03-30 03:44:13 +11:00
frame = ws.recv_frame()
2016-03-20 03:57:57 +11:00
2016-03-30 03:44:13 +11:00
if not frame:
raise websocket.WebSocketException("Not a valid frame %s" % frame)
elif frame.opcode in self.opcode_data:
return frame.opcode, frame.data
elif frame.opcode == websocket.ABNF.OPCODE_CLOSE:
ws.send_close()
return frame.opcode, None
elif frame.opcode == websocket.ABNF.OPCODE_PING:
ws.pong("Hi!")
return None, None
2016-03-20 03:57:57 +11:00
2016-03-30 03:44:13 +11:00
def getUri(self):
2017-03-05 03:54:24 +11:00
raise NotImplementedError
2016-03-20 03:57:57 +11:00
def _sleep_cycle(self):
"""
Sleeps for 2^self.sleeptime where sleeping period will be doubled with
each unsuccessful connection attempt.
Will sleep at most 64 seconds
"""
self.sleep(2 ** self.sleeptime)
if self.sleeptime < 6:
self.sleeptime += 1.0
def run(self):
LOG.info("----===## Starting %s ##===----", self.__class__.__name__)
app.APP.register_thread(self)
try:
self._run()
finally:
2020-05-07 15:48:50 +10:00
self.close_websocket()
app.APP.deregister_thread(self)
LOG.info("##===---- %s Stopped ----===##", self.__class__.__name__)
def _run(self):
while not self.should_cancel():
2016-03-30 03:44:13 +11:00
# In the event the server goes offline
if self.should_suspend():
# Set in service.py
2020-05-07 15:48:50 +10:00
self.close_websocket()
if self.wait_while_suspended():
2016-03-30 03:44:13 +11:00
# Abort was requested while waiting. We should exit
return
try:
self.process(*self.receive(self.ws))
except websocket.WebSocketTimeoutException:
# No worries if read timed out
pass
except websocket.WebSocketConnectionClosedException:
LOG.debug("%s: connection closed, (re)connecting",
self.__class__.__name__)
uri, sslopt = self.getUri()
2016-03-30 03:44:13 +11:00
try:
# Low timeout - let's us shut this thread down!
self.ws = websocket.create_connection(
uri,
timeout=1,
sslopt=sslopt,
enable_multithread=True)
except IOError:
# Server is probably offline
LOG.debug("%s: IOError connecting", self.__class__.__name__)
self.ws = None
self._sleep_cycle()
except websocket.WebSocketTimeoutException:
LOG.debug("%s: WebSocketTimeoutException", self.__class__.__name__)
self.ws = None
self._sleep_cycle()
2019-02-05 22:37:01 +11:00
except websocket.WebsocketRedirect as e:
LOG.debug('301 redirect detected: %s', e)
self.redirect_uri = e.headers.get('location',
e.headers.get('Location'))
2019-02-05 22:37:01 +11:00
if self.redirect_uri:
self.redirect_uri = self.redirect_uri.decode('utf-8')
self.ws = None
self._sleep_cycle()
except websocket.WebSocketException as e:
LOG.debug('%s: WebSocketException: %s', self.__class__.__name__, e)
self.ws = None
self._sleep_cycle()
except Exception as e:
2018-02-10 01:10:20 +11:00
LOG.error('%s: Unknown exception encountered when '
'connecting: %s', self.__class__.__name__, e)
import traceback
2018-02-10 01:10:20 +11:00
LOG.error("%s: Traceback:\n%s",
self.__class__.__name__, traceback.format_exc())
self.ws = None
self._sleep_cycle()
else:
self.sleeptime = 0.0
2016-03-30 03:44:13 +11:00
except Exception as e:
2018-02-10 01:10:20 +11:00
LOG.error("%s: Unknown exception encountered: %s",
self.__class__.__name__, e)
2017-03-05 03:54:24 +11:00
import traceback
2018-02-10 01:10:20 +11:00
LOG.error("%s: Traceback:\n%s",
self.__class__.__name__, traceback.format_exc())
2020-05-07 15:48:50 +10:00
self.close_websocket()
2017-03-05 03:54:24 +11:00
class PMS_Websocket(WebSocket):
"""
Websocket connection with the PMS for Plex Companion
"""
def should_suspend(self):
"""
Returns True if the thread is suspended.
"""
suspend = self._suspended or app.SYNC.background_sync_disabled
if suspend:
# This thread needs to clear the Event() _is_not_suspended itself!
self.suspend()
return suspend
2018-11-19 00:59:17 +11:00
2017-03-05 03:54:24 +11:00
def getUri(self):
2019-02-05 22:37:01 +11:00
if self.redirect_uri:
uri = self.redirect_uri
self.redirect_uri = None
2017-03-05 03:54:24 +11:00
else:
2019-02-05 22:37:01 +11:00
server = app.CONN.server
# Get the appropriate prefix for the websocket
if server.startswith('https'):
server = "wss%s" % server[5:]
else:
server = "ws%s" % server[4:]
uri = "%s/:/websockets/notifications" % server
if app.ACCOUNT.pms_token:
uri += '?X-Plex-Token=%s' % app.ACCOUNT.pms_token
2017-03-05 03:54:24 +11:00
sslopt = {}
2018-02-10 01:10:20 +11:00
LOG.debug("%s: Uri: %s, sslopt: %s",
self.__class__.__name__, uri, sslopt)
2017-03-05 03:54:24 +11:00
return uri, sslopt
def process(self, opcode, message):
if opcode not in self.opcode_data:
return
2017-03-05 03:54:24 +11:00
try:
message = loads(message)
except ValueError as err:
LOG.error('%s: Error decoding message from websocket: %s',
self.__class__.__name__, err)
2018-02-10 01:10:20 +11:00
LOG.error(message)
return
2017-03-05 03:54:24 +11:00
try:
message = message['NotificationContainer']
except KeyError:
2018-02-10 01:10:20 +11:00
LOG.error('%s: Could not parse PMS message: %s',
self.__class__.__name__, message)
return
2017-03-05 03:54:24 +11:00
# Triage
typus = message.get('type')
if typus is None:
2018-02-10 01:10:20 +11:00
LOG.error('%s: No message type, dropping message: %s',
self.__class__.__name__, message)
return
2018-02-10 01:10:20 +11:00
LOG.debug('%s: Received message from PMS server: %s',
self.__class__.__name__, message)
2017-03-05 03:54:24 +11:00
# Drop everything we're not interested in
if typus not in ('playing', 'timeline', 'activity'):
return
else:
# Put PMS message on queue and let libsync take care of it
2018-11-19 00:59:17 +11:00
app.APP.websocket_queue.put(message)
2017-03-05 03:54:24 +11:00
2017-03-06 01:48:08 +11:00
class Alexa_Websocket(WebSocket):
2017-03-05 03:54:24 +11:00
"""
2017-05-17 22:34:52 +10:00
Websocket connection to talk to Amazon Alexa.
2017-03-05 03:54:24 +11:00
"""
def should_suspend(self):
"""
Overwrite method since we need to check for plex token
"""
suspend = self._suspended or \
not app.SYNC.enable_alexa or \
app.ACCOUNT.restricted_user or \
not app.ACCOUNT.plex_token
if suspend:
# This thread needs to clear the Event() _is_not_suspended itself!
self.suspend()
return suspend
2017-05-17 22:34:52 +10:00
2017-03-05 03:54:24 +11:00
def getUri(self):
2019-02-05 22:37:01 +11:00
if self.redirect_uri:
uri = self.redirect_uri
self.redirect_uri = None
else:
uri = ('wss://pubsub.plex.tv/sub/websockets/%s/%s?X-Plex-Token=%s'
% (app.ACCOUNT.plex_user_id,
v.PKC_MACHINE_IDENTIFIER,
app.ACCOUNT.plex_token))
2017-03-05 03:54:24 +11:00
sslopt = {}
2018-02-10 01:10:20 +11:00
LOG.debug("%s: Uri: %s, sslopt: %s",
self.__class__.__name__, uri, sslopt)
2017-03-05 03:54:24 +11:00
return uri, sslopt
def process(self, opcode, message):
if opcode not in self.opcode_data:
return
2018-02-10 01:10:20 +11:00
LOG.debug('%s: Received the following message from Alexa:',
self.__class__.__name__)
LOG.debug('%s: %s', self.__class__.__name__, message)
2017-03-05 03:54:24 +11:00
try:
message = utils.etree.fromstring(message)
2017-03-05 03:54:24 +11:00
except Exception as ex:
2018-02-10 01:10:20 +11:00
LOG.error('%s: Error decoding message from Alexa: %s',
self.__class__.__name__, ex)
return
2017-03-05 03:54:24 +11:00
try:
if message.attrib['command'] == 'processRemoteControlCommand':
message = message[0]
else:
2018-02-10 01:10:20 +11:00
LOG.error('%s: Unknown Alexa message received',
self.__class__.__name__)
return
2019-02-03 06:22:06 +11:00
except Exception:
2018-02-10 01:10:20 +11:00
LOG.error('%s: Could not parse Alexa message',
self.__class__.__name__)
return
2018-06-22 03:24:37 +10:00
companion.process_command(message.attrib['path'][1:], message.attrib)