PlexKodiConnect/resources/lib/websocket_client.py

192 lines
6.7 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 json
import threading
2016-03-25 04:52:02 +11:00
import Queue
2016-03-20 03:57:57 +11:00
import websocket
2016-03-22 03:15:22 +11:00
import ssl
2016-03-20 03:57:57 +11:00
import xbmc
2016-09-05 00:41:05 +10:00
from utils import window, settings, ThreadMethodsAdditionalSuspend, \
ThreadMethods
###############################################################################
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-09-05 00:41:05 +10:00
@ThreadMethodsAdditionalSuspend('suspend_LibraryThread')
@ThreadMethods
2016-03-30 03:44:13 +11:00
class WebSocket(threading.Thread):
opcode_data = (websocket.ABNF.OPCODE_TEXT, websocket.ABNF.OPCODE_BINARY)
2016-03-20 03:57:57 +11:00
2016-03-25 04:52:02 +11:00
def __init__(self, queue):
2016-03-30 03:44:13 +11:00
self.ws = None
2016-03-25 04:52:02 +11:00
# Communication with librarysync
self.queue = queue
2016-03-22 03:15:22 +11:00
threading.Thread.__init__(self)
2016-03-20 03:57:57 +11:00
2016-03-30 03:44:13 +11:00
def process(self, opcode, message):
if opcode not in self.opcode_data:
return False
2016-03-20 03:57:57 +11:00
2016-03-22 03:15:22 +11:00
try:
message = json.loads(message)
2016-03-30 03:44:13 +11:00
except Exception as ex:
2016-09-05 00:41:05 +10:00
log.error('Error decoding message from websocket: %s' % ex)
log.error(message)
2016-03-22 03:15:22 +11:00
return False
2016-03-28 04:06:36 +11:00
# Triage
typus = message.get('type')
if typus is None:
2016-12-17 22:09:21 +11:00
log.debug('No message type, dropping message: %s' % message)
2016-03-28 04:06:36 +11:00
return False
2016-09-05 00:41:05 +10:00
log.debug('Received message from PMS server: %s' % message)
2016-03-28 04:06:36 +11:00
# Drop everything we're not interested in
if typus not in ('playing', 'timeline'):
2016-03-30 03:44:13 +11:00
return True
2016-03-25 04:52:02 +11:00
# Put PMS message on queue and let libsync take care of it
try:
self.queue.put(message)
2016-03-22 03:15:22 +11:00
return True
2016-03-25 04:52:02 +11:00
except Queue.Full:
2016-03-30 03:44:13 +11:00
# Queue only takes 200 messages. No worries if we miss one or two
2016-09-05 00:41:05 +10:00
log.info('Queue is full, dropping PMS message %s' % message)
2016-03-25 04:52:02 +11:00
return False
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):
2016-09-05 00:41:05 +10:00
server = window('pms_server')
2016-03-28 04:06:36 +11:00
# Need to use plex.tv token, if any. NOT user token
2016-09-05 00:41:05 +10:00
token = window('plex_token')
2016-03-20 03:57:57 +11:00
# Get the appropriate prefix for the websocket
2016-11-13 03:45:37 +11:00
if server.startswith('https'):
server = "wss%s" % server[5:]
2016-03-20 03:57:57 +11:00
else:
2016-11-13 03:45:37 +11:00
server = "ws%s" % server[4:]
2016-03-30 03:44:13 +11:00
uri = "%s/:/websockets/notifications" % server
2016-03-22 03:15:22 +11:00
if token:
2016-03-30 03:44:13 +11:00
uri += '?X-Plex-Token=%s' % token
2016-03-22 03:15:22 +11:00
sslopt = {}
2016-09-05 00:41:05 +10:00
if settings('sslverify') == "false":
2016-03-22 03:15:22 +11:00
sslopt["cert_reqs"] = ssl.CERT_NONE
2016-11-13 03:45:37 +11:00
log.debug("Uri: %s, sslopt: %s" % (uri, sslopt))
return uri, sslopt
2016-03-20 03:57:57 +11:00
def run(self):
2016-09-05 00:41:05 +10:00
log.info("----===## Starting WebSocketClient ##===----")
2016-03-20 03:57:57 +11:00
counter = 0
handshake_counter = 0
2016-03-30 03:44:13 +11:00
threadStopped = self.threadStopped
threadSuspended = self.threadSuspended
while not threadStopped():
# In the event the server goes offline
while threadSuspended():
# Set in service.py
if self.ws is not None:
try:
self.ws.shutdown()
except:
pass
self.ws = None
2016-03-30 03:44:13 +11:00
if threadStopped():
# Abort was requested while waiting. We should exit
2016-09-05 00:41:05 +10:00
log.info("##===---- WebSocketClient Stopped ----===##")
2016-03-30 03:44:13 +11:00
return
xbmc.sleep(1000)
try:
self.process(*self.receive(self.ws))
except websocket.WebSocketTimeoutException:
# No worries if read timed out
pass
except websocket.WebSocketConnectionClosedException:
2016-09-05 00:41:05 +10:00
log.info("Connection closed, (re)connecting")
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
2016-09-05 00:41:05 +10:00
log.info("Error connecting")
self.ws = None
counter += 1
if counter > 10:
2016-09-05 00:41:05 +10:00
log.warn("Repeatedly could not connect to PMS, "
"declaring the connection dead")
window('plex_online', value='false')
counter = 0
xbmc.sleep(1000)
except websocket.WebSocketTimeoutException:
2016-09-05 00:41:05 +10:00
log.info("timeout while connecting, trying again")
self.ws = None
xbmc.sleep(1000)
except websocket.WebSocketException as e:
log.info('WebSocketException: %s' % e)
if 'Handshake Status 401' in e.args:
handshake_counter += 1
if handshake_counter >= 5:
log.info('Error in handshake detected. Stopping '
'WebSocketClient now')
break
self.ws = None
xbmc.sleep(1000)
except Exception as e:
2016-09-05 00:41:05 +10:00
log.error("Unknown exception encountered in connecting: %s"
% e)
import traceback
log.error("Traceback:\n%s" % traceback.format_exc())
self.ws = None
2016-03-30 03:44:13 +11:00
xbmc.sleep(1000)
else:
counter = 0
handshake_counter = 0
2016-03-30 03:44:13 +11:00
except Exception as e:
2016-09-05 00:41:05 +10:00
log.error("Unknown exception encountered: %s" % e)
2016-03-30 04:16:08 +11:00
try:
self.ws.shutdown()
except:
pass
self.ws = None
2016-03-20 03:57:57 +11:00
2016-09-05 00:41:05 +10:00
log.info("##===---- WebSocketClient Stopped ----===##")
2016-03-20 03:57:57 +11:00
2016-03-22 03:15:22 +11:00
def stopThread(self):
"""
2016-03-30 03:44:13 +11:00
Overwrite this method from ThreadMethods to close websockets
2016-03-22 03:15:22 +11:00
"""
2016-09-05 00:41:05 +10:00
log.info("Stopping websocket client thread.")
2016-03-22 03:15:22 +11:00
self._threadStopped = True
2016-03-30 03:44:13 +11:00
try:
self.ws.shutdown()
except:
pass