2017-02-11 04:08:36 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
import json, threading
|
|
|
|
from plexapi import log
|
2017-02-11 04:26:09 +00:00
|
|
|
from plexapi.exceptions import Unsupported
|
2017-02-11 04:08:36 +00:00
|
|
|
|
|
|
|
|
|
|
|
class PlexNotifier(threading.Thread):
|
|
|
|
""" Creates a websocket connection to the Plex Server to optionally recieve
|
|
|
|
notifications. These often include messages from Plex about media scans
|
|
|
|
as well as updates to currently running Transcode Sessions.
|
2017-02-11 04:26:09 +00:00
|
|
|
|
2017-02-13 02:55:55 +00:00
|
|
|
Parameters:
|
|
|
|
server (:class:`~plexapi.server.PlexServer`): PlexServer this notifier is connected to.
|
|
|
|
callback (func): Callback function to call on recieved messages.
|
|
|
|
|
2017-02-11 04:26:09 +00:00
|
|
|
NOTE: You need websocket-client installed in order to use this feature.
|
2017-02-13 19:38:40 +00:00
|
|
|
>> pip install websocket-client
|
2017-02-11 04:08:36 +00:00
|
|
|
"""
|
|
|
|
key = '/:/websockets/notifications'
|
|
|
|
|
|
|
|
def __init__(self, server, callback=None):
|
|
|
|
self._server = server
|
|
|
|
self._callback = callback
|
|
|
|
self._ws = None
|
|
|
|
super(PlexNotifier, self).__init__()
|
|
|
|
|
|
|
|
def run(self):
|
2017-02-13 02:55:55 +00:00
|
|
|
""" Starts the PlexNotifier thread. This function should not be called
|
|
|
|
directly, instead use :func:`~plexapi.server.PlexServer.startNotifier`.
|
|
|
|
"""
|
2017-02-11 04:26:09 +00:00
|
|
|
# try importing websocket-client package
|
|
|
|
try:
|
2017-02-13 02:55:55 +00:00
|
|
|
import websocket
|
2017-02-11 04:26:09 +00:00
|
|
|
except:
|
|
|
|
raise Unsupported('Websocket-client package is required to use this feature.')
|
|
|
|
# create the websocket connection
|
2017-02-11 04:08:36 +00:00
|
|
|
url = self._server.url(self.key).replace('http', 'ws')
|
|
|
|
log.info('Starting PlexNotifier: %s', url)
|
|
|
|
self._ws = websocket.WebSocketApp(url,
|
|
|
|
on_message=self._onMessage,
|
|
|
|
on_error=self._onError)
|
|
|
|
self._ws.run_forever()
|
|
|
|
|
|
|
|
def stop(self):
|
2017-02-13 02:55:55 +00:00
|
|
|
""" Stop the PlexNotifier thread. """
|
2017-02-11 04:08:36 +00:00
|
|
|
log.info('Stopping PlexNotifier.')
|
|
|
|
self._ws.close()
|
|
|
|
|
|
|
|
def _onMessage(self, ws, message):
|
2017-02-13 19:38:40 +00:00
|
|
|
""" Called when websocket message is recieved. """
|
2017-02-11 04:08:36 +00:00
|
|
|
try:
|
|
|
|
data = json.loads(message)['NotificationContainer']
|
|
|
|
log.debug('Notify: %s', data)
|
|
|
|
if self._callback:
|
|
|
|
self._callback(data)
|
|
|
|
except Exception as err:
|
|
|
|
log.error('PlexNotifier Msg Error: %s', err)
|
|
|
|
|
|
|
|
def _onError(self, ws, err):
|
2017-02-13 19:38:40 +00:00
|
|
|
""" Called when websocket error is recieved. """
|
2017-02-11 04:08:36 +00:00
|
|
|
log.error('PlexNotifier Error: %s' % err)
|