diff --git a/plexpy/__init__.py b/plexpy/__init__.py index ef5fa871..202687c2 100644 --- a/plexpy/__init__.py +++ b/plexpy/__init__.py @@ -71,6 +71,7 @@ COMMITS_BEHIND = None UMASK = None +POLLING_FAILOVER = False def initialize(config_file): with INIT_LOCK: @@ -80,6 +81,7 @@ def initialize(config_file): global CURRENT_VERSION global LATEST_VERSION global UMASK + global POLLING_FAILOVER CONFIG = plexpy.config.Config(config_file) @@ -281,7 +283,7 @@ def initialize_scheduler(): schedule_job(plextv.get_real_pms_url, 'Refresh Plex Server URLs', hours=12, minutes=0, seconds=0) # If we're not using websockets then fall back to polling - if not CONFIG.MONITORING_USE_WEBSOCKET: + if not CONFIG.MONITORING_USE_WEBSOCKET or POLLING_FAILOVER: schedule_job(monitor.check_active_sessions, 'Check for active sessions', hours=0, minutes=0, seconds=seconds) diff --git a/plexpy/web_socket.py b/plexpy/web_socket.py index b696a4fa..f8ee16bd 100644 --- a/plexpy/web_socket.py +++ b/plexpy/web_socket.py @@ -43,12 +43,23 @@ def run(): if plexpy.CONFIG.PMS_TOKEN: uri += '?X-Plex-Token=' + plexpy.CONFIG.PMS_TOKEN - ws = create_connection(uri) - + ws_connected = False reconnects = 0 - logger.debug(u'PlexPy WebSocket :: Ready') - while True: + # Try an open the websocket connection - if it fails after 5 retries fallback to polling + while not ws_connected and reconnects < 5: + try: + logger.info(u'PlexPy WebSocket :: Opening websocket, connection attempt %s.' % str(reconnects + 1)) + ws = create_connection(uri) + reconnects = 0 + ws_connected = True + logger.debug(u'PlexPy WebSocket :: Ready') + except IOError, e: + logger.info(u'PlexPy WebSocket :: %s.' % e) + reconnects += 1 + time.sleep(5) + + while ws_connected: try: process(*receive(ws)) @@ -63,11 +74,20 @@ def run(): time.sleep(2 * (reconnects - 1)) logger.info(u'PlexPy WebSocket :: Connection has closed, reconnecting...') - ws = create_connection(uri) + try: + ws = create_connection(uri) + except IOError, e: + logger.info(u'PlexPy WebSocket :: %s.' % e) + else: - logger.error(u'PlexPy WebSocket :: Connection unavailable, activity monitoring not available') + ws_connected = False break + if not ws_connected: + logger.error(u'PlexPy WebSocket :: Connection unavailable, falling back to polling.') + plexpy.POLLING_FAILOVER = True + plexpy.initialize_scheduler() + logger.debug(u'Leaving thread.')