PlexKodiConnect/resources/lib/websocket_client.py

272 lines
9.8 KiB
Python
Raw Permalink 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
2018-09-06 01:36:38 +10:00
import defusedxml.ElementTree as etree # etree parse unsafe
2016-12-21 02:30:22 +11:00
from threading import Thread
from ssl import CERT_NONE
from xbmc import sleep
2016-03-20 03:57:57 +11:00
from . import websocket, utils, companion, state, 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
2016-12-21 02:30:22 +11:00
class WebSocket(Thread):
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
super(WebSocket, self).__init__()
2016-03-20 03:57:57 +11:00
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 run(self):
2018-02-10 01:10:20 +11:00
LOG.info("----===## Starting %s ##===----", self.__class__.__name__)
2016-03-20 03:57:57 +11:00
counter = 0
2018-02-12 00:57:39 +11:00
stopped = self.stopped
suspended = self.suspended
while not stopped():
2016-03-30 03:44:13 +11:00
# In the event the server goes offline
2018-02-12 00:57:39 +11:00
while suspended():
2016-03-30 03:44:13 +11:00
# Set in service.py
if self.ws is not None:
2018-02-10 01:10:20 +11:00
self.ws.close()
self.ws = None
2018-02-12 00:57:39 +11:00
if stopped():
2016-03-30 03:44:13 +11:00
# Abort was requested while waiting. We should exit
2018-02-10 01:10:20 +11:00
LOG.info("##===---- %s Stopped ----===##",
self.__class__.__name__)
2016-03-30 03:44:13 +11:00
return
2016-12-21 02:30:22 +11:00
sleep(1000)
2016-03-30 03:44:13 +11:00
try:
self.process(*self.receive(self.ws))
except websocket.WebSocketTimeoutException:
# No worries if read timed out
pass
except websocket.WebSocketConnectionClosedException:
2018-02-10 01:10:20 +11:00
LOG.info("%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
2018-02-10 01:10:20 +11:00
LOG.info("%s: Error connecting", self.__class__.__name__)
self.ws = None
counter += 1
if counter >= 10:
LOG.info('%s: Repeated IOError detected. Stopping now',
self.__class__.__name__)
break
2016-12-21 02:30:22 +11:00
sleep(1000)
except websocket.WebSocketTimeoutException:
2018-02-10 01:10:20 +11:00
LOG.info("%s: Timeout while connecting, trying again",
self.__class__.__name__)
self.ws = None
2016-12-21 02:30:22 +11:00
sleep(1000)
except websocket.WebSocketException as e:
2018-02-10 01:10:20 +11:00
LOG.info('%s: WebSocketException: %s',
self.__class__.__name__, e)
if ('Handshake Status 401' in e.args or
'Handshake Status 403' in e.args):
counter += 1
if counter >= 5:
2018-02-10 01:10:20 +11:00
LOG.info('%s: Error in handshake detected. '
'Stopping now', self.__class__.__name__)
break
self.ws = None
2016-12-21 02:30:22 +11:00
sleep(1000)
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
2016-12-21 02:30:22 +11:00
sleep(1000)
else:
counter = 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())
if self.ws is not None:
self.ws.close()
2016-03-30 04:16:08 +11:00
self.ws = None
2018-02-10 01:10:20 +11:00
# Close websocket connection on shutdown
if self.ws is not None:
self.ws.close()
LOG.info("##===---- %s Stopped ----===##", self.__class__.__name__)
2017-03-05 03:54:24 +11:00
2018-06-22 03:24:37 +10:00
@utils.thread_methods(add_suspends=['SUSPEND_LIBRARY_THREAD',
'BACKGROUND_SYNC_DISABLED'])
2017-03-05 03:54:24 +11:00
class PMS_Websocket(WebSocket):
"""
Websocket connection with the PMS for Plex Companion
"""
def getUri(self):
2018-06-22 03:24:37 +10:00
server = utils.window('pms_server')
2017-03-05 03:54:24 +11:00
# 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
# Need to use plex.tv token, if any. NOT user token
if state.PLEX_TOKEN:
uri += '?X-Plex-Token=%s' % state.PLEX_TOKEN
2017-03-05 03:54:24 +11:00
sslopt = {}
2018-06-22 03:24:37 +10:00
if utils.settings('sslverify') == "false":
2017-03-05 03:54:24 +11:00
sslopt["cert_reqs"] = CERT_NONE
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)
2017-09-07 03:26:48 +10:00
except ValueError:
2018-02-10 01:10:20 +11:00
LOG.error('%s: Error decoding message from websocket',
self.__class__.__name__)
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
elif typus == 'activity' and state.DB_SCAN is True:
# Only add to processing if PKC is NOT doing a lib scan (and thus
# possibly causing these reprocessing messages en mass)
2018-02-10 01:10:20 +11:00
LOG.debug('%s: Dropping message as PKC is currently synching',
self.__class__.__name__)
else:
# Put PMS message on queue and let libsync take care of it
state.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.
2018-06-22 03:24:37 +10:00
Can't use utils.thread_methods!
2017-03-05 03:54:24 +11:00
"""
2018-02-11 23:24:00 +11:00
thread_stopped = False
thread_suspended = False
2017-05-17 22:34:52 +10:00
2017-03-05 03:54:24 +11:00
def getUri(self):
uri = ('wss://pubsub.plex.tv/sub/websockets/%s/%s?X-Plex-Token=%s'
2017-05-18 00:15:16 +10:00
% (state.PLEX_USER_ID,
2018-02-10 01:10:20 +11:00
v.PKC_MACHINE_IDENTIFIER,
state.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 = etree.fromstring(message)
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
2017-03-05 03:54:24 +11:00
except:
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)
2017-03-05 03:54:24 +11:00
2018-06-22 03:24:37 +10:00
# Path in utils.thread_methods
2018-02-12 00:57:39 +11:00
def stop(self):
2018-02-11 23:24:00 +11:00
self.thread_stopped = True
2017-05-17 22:34:52 +10:00
2018-02-12 00:57:39 +11:00
def suspend(self):
2018-02-11 23:24:00 +11:00
self.thread_suspended = True
2017-05-17 22:34:52 +10:00
2018-02-12 00:57:39 +11:00
def resume(self):
2018-02-11 23:24:00 +11:00
self.thread_suspended = False
2017-05-17 22:34:52 +10:00
2018-02-12 00:57:39 +11:00
def stopped(self):
2018-02-11 23:24:00 +11:00
if self.thread_stopped is True:
2017-05-17 22:34:52 +10:00
return True
if state.STOP_PKC:
return True
return False
# The culprit
2018-02-12 00:57:39 +11:00
def suspended(self):
2017-05-17 22:20:43 +10:00
"""
Overwrite method since we need to check for plex token
"""
2018-02-11 23:24:00 +11:00
if self.thread_suspended is True:
2017-05-17 22:20:43 +10:00
return True
if not state.PLEX_TOKEN:
return True
if state.RESTRICTED_USER:
return True
return False