Cleanup websocket_client.py

This commit is contained in:
tomkat83 2016-09-04 16:41:05 +02:00
parent 5615bad026
commit 9d704a844f

View file

@ -1,7 +1,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
############################################################################### ###############################################################################
import logging
import json import json
import threading import threading
import Queue import Queue
@ -10,15 +10,18 @@ import ssl
import xbmc import xbmc
import utils from utils import window, settings, ThreadMethodsAdditionalSuspend, \
ThreadMethods
###############################################################################
log = logging.getLogger("PLEX."+__name__)
############################################################################### ###############################################################################
@utils.logging @ThreadMethodsAdditionalSuspend('suspend_LibraryThread')
@utils.ThreadMethodsAdditionalSuspend('suspend_LibraryThread') @ThreadMethods
@utils.ThreadMethods
class WebSocket(threading.Thread): class WebSocket(threading.Thread):
opcode_data = (websocket.ABNF.OPCODE_TEXT, websocket.ABNF.OPCODE_BINARY) opcode_data = (websocket.ABNF.OPCODE_TEXT, websocket.ABNF.OPCODE_BINARY)
@ -35,16 +38,16 @@ class WebSocket(threading.Thread):
try: try:
message = json.loads(message) message = json.loads(message)
except Exception as ex: except Exception as ex:
self.logMsg('Error decoding message from websocket: %s' % ex, -1) log.error('Error decoding message from websocket: %s' % ex)
self.logMsg(message, -1) log.error(message)
return False return False
# Triage # Triage
typus = message.get('type') typus = message.get('type')
if typus is None: if typus is None:
self.logMsg('No message type, dropping message: %s' % message, -1) log.error('No message type, dropping message: %s' % message)
return False return False
self.logMsg('Received message from PMS server: %s' % message, 2) log.debug('Received message from PMS server: %s' % message)
# Drop everything we're not interested in # Drop everything we're not interested in
if typus not in ('playing', 'timeline'): if typus not in ('playing', 'timeline'):
return True return True
@ -55,7 +58,7 @@ class WebSocket(threading.Thread):
return True return True
except Queue.Full: except Queue.Full:
# Queue only takes 200 messages. No worries if we miss one or two # Queue only takes 200 messages. No worries if we miss one or two
self.logMsg('Queue is full, dropping PMS message %s' % message, 0) log.info('Queue is full, dropping PMS message %s' % message)
return False return False
def receive(self, ws): def receive(self, ws):
@ -77,9 +80,9 @@ class WebSocket(threading.Thread):
return None, None return None, None
def getUri(self): def getUri(self):
server = utils.window('pms_server') server = window('pms_server')
# Need to use plex.tv token, if any. NOT user token # Need to use plex.tv token, if any. NOT user token
token = utils.window('plex_token') token = window('plex_token')
# Get the appropriate prefix for the websocket # Get the appropriate prefix for the websocket
if "https" in server: if "https" in server:
server = server.replace('https', "wss") server = server.replace('https', "wss")
@ -89,13 +92,12 @@ class WebSocket(threading.Thread):
if token: if token:
uri += '?X-Plex-Token=%s' % token uri += '?X-Plex-Token=%s' % token
sslopt = {} sslopt = {}
if utils.settings('sslverify') == "false": if settings('sslverify') == "false":
sslopt["cert_reqs"] = ssl.CERT_NONE sslopt["cert_reqs"] = ssl.CERT_NONE
return uri, sslopt return uri, sslopt
def run(self): def run(self):
log = self.logMsg log.info("----===## Starting WebSocketClient ##===----")
log("----===## Starting WebSocketClient ##===----", 0)
counter = 0 counter = 0
threadStopped = self.threadStopped threadStopped = self.threadStopped
@ -112,7 +114,7 @@ class WebSocket(threading.Thread):
self.ws = None self.ws = None
if threadStopped(): if threadStopped():
# Abort was requested while waiting. We should exit # Abort was requested while waiting. We should exit
log("##===---- WebSocketClient Stopped ----===##", 0) log.info("##===---- WebSocketClient Stopped ----===##")
return return
xbmc.sleep(1000) xbmc.sleep(1000)
try: try:
@ -121,7 +123,7 @@ class WebSocket(threading.Thread):
# No worries if read timed out # No worries if read timed out
pass pass
except websocket.WebSocketConnectionClosedException: except websocket.WebSocketConnectionClosedException:
log("Connection closed, (re)connecting", 0) log.info("Connection closed, (re)connecting")
uri, sslopt = self.getUri() uri, sslopt = self.getUri()
try: try:
# Low timeout - let's us shut this thread down! # Low timeout - let's us shut this thread down!
@ -132,40 +134,41 @@ class WebSocket(threading.Thread):
enable_multithread=True) enable_multithread=True)
except IOError: except IOError:
# Server is probably offline # Server is probably offline
log("Error connecting", 0) log.info("Error connecting")
self.ws = None self.ws = None
counter += 1 counter += 1
if counter > 10: if counter > 10:
log("Repeatedly could not connect to PMS, declaring " log.warn("Repeatedly could not connect to PMS, "
"the connection dead", -1) "declaring the connection dead")
utils.window('plex_online', value='false') window('plex_online', value='false')
counter = 0 counter = 0
xbmc.sleep(1000) xbmc.sleep(1000)
except websocket.WebSocketTimeoutException: except websocket.WebSocketTimeoutException:
log("timeout while connecting, trying again", 0) log.info("timeout while connecting, trying again")
self.ws = None self.ws = None
xbmc.sleep(1000) xbmc.sleep(1000)
except Exception as e: except Exception as e:
log("Unknown exception encountered in connecting: %s" % e) log.error("Unknown exception encountered in connecting: %s"
% e)
self.ws = None self.ws = None
xbmc.sleep(1000) xbmc.sleep(1000)
else: else:
counter = 0 counter = 0
except Exception as e: except Exception as e:
log("Unknown exception encountered: %s" % e) log.error("Unknown exception encountered: %s" % e)
try: try:
self.ws.shutdown() self.ws.shutdown()
except: except:
pass pass
self.ws = None self.ws = None
log("##===---- WebSocketClient Stopped ----===##", 0) log.info("##===---- WebSocketClient Stopped ----===##")
def stopThread(self): def stopThread(self):
""" """
Overwrite this method from ThreadMethods to close websockets Overwrite this method from ThreadMethods to close websockets
""" """
self.logMsg("Stopping websocket client thread.", 1) log.info("Stopping websocket client thread.")
self._threadStopped = True self._threadStopped = True
try: try:
self.ws.shutdown() self.ws.shutdown()