PlexKodiConnect/resources/lib/websocket_client.py

308 lines
11 KiB
Python
Raw Normal View History

2016-03-20 03:57:57 +11:00
# -*- coding: utf-8 -*-
2016-03-22 03:15:22 +11:00
###############################################################################
2016-09-05 00:41:05 +10:00
import logging
2016-03-20 03:57:57 +11:00
import websocket
2016-12-21 02:30:22 +11:00
from json import loads
2017-03-05 03:54:24 +11:00
import xml.etree.ElementTree as etree
2016-12-21 02:30:22 +11:00
from threading import Thread
2016-12-28 03:33:52 +11:00
from Queue import Queue
2016-12-21 02:30:22 +11:00
from ssl import CERT_NONE
2016-03-20 03:57:57 +11:00
2016-12-21 02:30:22 +11:00
from xbmc import sleep
2016-03-20 03:57:57 +11:00
2017-05-17 21:55:24 +10:00
from utils import window, settings, thread_methods
2017-03-05 03:54:24 +11:00
from companion import process_command
import state
2016-09-05 00:41:05 +10:00
###############################################################################
2016-03-20 03:57:57 +11:00
2016-09-05 00:41:05 +10:00
log = logging.getLogger("PLEX."+__name__)
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)
2016-03-20 03:57:57 +11:00
2016-12-28 03:33:52 +11:00
def __init__(self, callback=None):
if callback is not None:
self.mgr = callback
2016-03-30 03:44:13 +11:00
self.ws = None
2016-12-21 02:30:22 +11:00
Thread.__init__(self)
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):
2017-03-05 03:54:24 +11:00
log.info("----===## Starting %s ##===----" % self.__class__.__name__)
2016-03-20 03:57:57 +11:00
counter = 0
handshake_counter = 0
thread_stopped = self.thread_stopped
thread_suspended = self.thread_suspended
while not thread_stopped():
2016-03-30 03:44:13 +11:00
# In the event the server goes offline
while thread_suspended():
2016-03-30 03:44:13 +11:00
# Set in service.py
if self.ws is not None:
try:
self.ws.shutdown()
except:
pass
self.ws = None
if thread_stopped():
2016-03-30 03:44:13 +11:00
# Abort was requested while waiting. We should exit
2017-03-05 03:54:24 +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:
2017-09-06 22:14:42 +10: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
2017-09-06 22:14:42 +10:00
log.info("%s: Error connecting" % self.__class__.__name__)
self.ws = None
counter += 1
2016-12-21 02:13:19 +11:00
if counter > 3:
counter = 0
2017-03-05 03:54:24 +11:00
self.IOError_response()
2016-12-21 02:30:22 +11:00
sleep(1000)
except websocket.WebSocketTimeoutException:
2017-09-06 22:14:42 +10: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:
2017-09-06 22:14:42 +10:00
log.info('%s: WebSocketException: %s'
% (self.__class__.__name__, e))
if 'Handshake Status 401' in e.args:
handshake_counter += 1
if handshake_counter >= 5:
2017-09-06 22:14:42 +10: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:
2017-09-06 22:14:42 +10:00
log.error('%s: Unknown exception encountered when '
'connecting: %s' % (self.__class__.__name__, e))
import traceback
2017-09-06 22:14:42 +10: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
handshake_counter = 0
2016-03-30 03:44:13 +11:00
except Exception as e:
2017-09-06 22:14:42 +10:00
log.error("%s: Unknown exception encountered: %s"
% (self.__class__.__name__, e))
2017-03-05 03:54:24 +11:00
import traceback
2017-09-06 22:14:42 +10:00
log.error("%s: Traceback:\n%s"
% (self.__class__.__name__,
traceback.format_exc()))
2016-03-30 04:16:08 +11:00
try:
self.ws.shutdown()
except:
pass
self.ws = None
2017-03-05 03:54:24 +11:00
log.info("##===---- %s Stopped ----===##" % self.__class__.__name__)
2016-03-20 03:57:57 +11:00
2016-03-22 03:15:22 +11:00
def stopThread(self):
"""
2017-05-17 21:55:24 +10:00
Overwrite this method from thread_methods to close websockets
2016-03-22 03:15:22 +11:00
"""
2017-03-05 03:54:24 +11:00
log.info("Stopping %s thread." % self.__class__.__name__)
2017-05-17 21:55:24 +10:00
self.__threadStopped = True
2016-03-30 03:44:13 +11:00
try:
self.ws.shutdown()
except:
pass
2017-03-05 03:54:24 +11:00
2017-05-17 22:34:52 +10:00
@thread_methods(add_suspends=['SUSPEND_LIBRARY_THREAD'])
2017-03-05 03:54:24 +11:00
class PMS_Websocket(WebSocket):
"""
Websocket connection with the PMS for Plex Companion
"""
# Communication with librarysync
queue = Queue()
def getUri(self):
server = window('pms_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
# 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 = {}
if settings('sslverify') == "false":
sslopt["cert_reqs"] = CERT_NONE
2017-09-06 22:14:42 +10: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:
log.error('%s: Error decoding message from websocket'
% self.__class__.__name__)
2017-03-05 03:54:24 +11:00
log.error(message)
return
2017-03-05 03:54:24 +11:00
try:
message = message['NotificationContainer']
except KeyError:
2017-09-06 22:14:42 +10: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:
2017-09-06 22:14:42 +10:00
log.error('%s: No message type, dropping message: %s'
% (self.__class__.__name__, message))
return
2017-09-06 22:14:42 +10: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)
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
self.queue.put(message)
2017-03-05 03:54:24 +11:00
def IOError_response(self):
log.warn("Repeatedly could not connect to PMS, "
"declaring the connection dead")
window('plex_online', value='false')
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.
Can't use thread_methods!
2017-03-05 03:54:24 +11:00
"""
2017-05-17 22:34:52 +10:00
__thread_stopped = False
__thread_suspended = False
2017-03-05 03:54:24 +11:00
def getUri(self):
self.plex_client_Id = window('plex_client_Id')
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,
2017-05-17 23:57:30 +10:00
self.plex_client_Id, state.PLEX_TOKEN))
2017-03-05 03:54:24 +11:00
sslopt = {}
2017-09-06 22:14:42 +10: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-09-06 22:14:42 +10: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:
2017-09-06 22:14:42 +10: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:
2017-09-06 22:14:42 +10:00
log.error('%s: Unknown Alexa message received'
% self.__class__.__name__)
return
2017-03-05 03:54:24 +11:00
except:
2017-09-06 22:14:42 +10:00
log.error('%s: Could not parse Alexa message'
% self.__class__.__name__)
return
2017-03-05 03:54:24 +11:00
process_command(message.attrib['path'][1:],
message.attrib,
queue=self.mgr.plexCompanion.queue)
def IOError_response(self):
pass
2017-05-17 22:20:43 +10:00
2017-05-17 22:34:52 +10:00
# Path in thread_methods
def stop_thread(self):
self.__thread_stopped = True
def suspend_thread(self):
self.__thread_suspended = True
def resume_thread(self):
self.__thread_suspended = False
def thread_stopped(self):
if self.__thread_stopped is True:
return True
if state.STOP_PKC:
return True
return False
# The culprit
2017-05-17 22:20:43 +10:00
def thread_suspended(self):
"""
Overwrite method since we need to check for plex token
"""
if self.__thread_suspended is True:
return True
if not state.PLEX_TOKEN:
return True
if state.RESTRICTED_USER:
return True
return False