Cleanup Plex notification

This commit is contained in:
Ruud
2013-09-24 22:37:40 +02:00
parent 3b1efb2c30
commit 9b5166826f
2 changed files with 49 additions and 33 deletions
@@ -17,14 +17,15 @@ config = [{
'type': 'enabler', 'type': 'enabler',
}, },
{ {
'name': 'media_server', 'name': 'host',
'label': 'Media Server',
'default': 'localhost', 'default': 'localhost',
'description': 'Media server hostname' 'description': 'Hostname/IP, default localhost'
}, },
{ {
'name': 'clients', 'name': 'clients',
'default': '', 'default': '',
'description': 'Comma separated list of client names\'s (computer names).' 'description': 'Comma separated list of client names\'s (computer names). Top right when you start Plex'
}, },
{ {
'name': 'on_snatch', 'name': 'on_snatch',
+45 -30
View File
@@ -1,14 +1,14 @@
from datetime import datetime
import json
from couchpotato.core.event import addEvent from couchpotato.core.event import addEvent
from couchpotato.core.helpers.encoding import tryUrlencode from couchpotato.core.helpers.encoding import tryUrlencode
from couchpotato.core.helpers.variable import cleanHost from couchpotato.core.helpers.variable import cleanHost
from couchpotato.core.logger import CPLog from couchpotato.core.logger import CPLog
from couchpotato.core.notifications.base import Notification from couchpotato.core.notifications.base import Notification
from urllib2 import URLError from datetime import datetime
from urlparse import urlparse
from xml.dom import minidom from xml.dom import minidom
import traceback import json
import requests import requests
import traceback
try: try:
import xml.etree.cElementTree as etree import xml.etree.cElementTree as etree
@@ -19,15 +19,19 @@ log = CPLog(__name__)
class Plex(Notification): class Plex(Notification):
client_update_time = 5 * 60 client_update_time = 5 * 60
http_time_between_calls = 0
def __init__(self): def __init__(self):
super(Plex, self).__init__() super(Plex, self).__init__()
self.clients = {} self.clients = {}
self.clients_updated = None self.clients_updated = None
addEvent('renamer.after', self.addToLibrary) addEvent('renamer.after', self.addToLibrary)
def updateClients(self, force=False): def updateClients(self, force = False):
if not self.conf('media_server'): if not self.conf('media_server'):
log.warning("Plex media server hostname is required") log.warning("Plex media server hostname is required")
return return
@@ -38,13 +42,14 @@ class Plex(Notification):
if force or self.clients_updated is None or since_update > self.client_update_time: if force or self.clients_updated is None or since_update > self.client_update_time:
self.clients = {} self.clients = {}
client_result = etree.fromstring(self.urlopen('http://%s:32400/clients' % self.conf('media_server'))) data = self.urlopen('%s/clients' % self.createHost(self.conf('media_server'), port = 32400))
client_result = etree.fromstring(data)
hosts = [x.strip().lower() for x in self.conf('clients').split(',')] clients = [x.strip().lower() for x in self.conf('clients').split(',')]
for server in client_result.findall('Server'): for server in client_result.findall('Server'):
if server.get('name').lower() in hosts: if server.get('name').lower() in clients:
hosts.remove(server.get('name').lower()) clients.remove(server.get('name').lower())
protocol = server.get('protocol', 'xbmchttp') protocol = server.get('protocol', 'xbmchttp')
if protocol in ['xbmcjson', 'xbmchttp']: if protocol in ['xbmcjson', 'xbmchttp']:
@@ -55,21 +60,21 @@ class Plex(Notification):
'protocol': protocol 'protocol': protocol
} }
if len(hosts) > 0: if len(clients) > 0:
log.warning('unable to find some plex hosts: %s', ', '.join(hosts)) log.info2('Unable to find plex clients: %s', ', '.join(clients))
log.info('found hosts: %s', ', '.join(self.clients.keys())) log.info2('Found hosts: %s', ', '.join(self.clients.keys()))
self.clients_updated = datetime.now() self.clients_updated = datetime.now()
def addToLibrary(self, message=None, group={}): def addToLibrary(self, message = None, group = {}):
if self.isDisabled(): return if self.isDisabled(): return
log.info('Sending notification to Plex') log.info('Sending notification to Plex')
source_type = ['movie'] source_type = ['movie']
base_url = 'http://%s:32400/library/sections' % self.conf('media_server') base_url = '%s/library/sections' % self.createHost(self.conf('media_server'), port = 32400)
refresh_url = '%s/%%s/refresh' % base_url refresh_url = '%s/%%s/refresh' % base_url
try: try:
@@ -89,7 +94,7 @@ class Plex(Notification):
return True return True
def send_http(self, command, client): def sendHTTP(self, command, client):
url = 'http://%s:%s/xbmcCmds/xbmcHttp/?%s' % ( url = 'http://%s:%s/xbmcCmds/xbmcHttp/?%s' % (
client['address'], client['address'],
client['port'], client['port'],
@@ -99,14 +104,14 @@ class Plex(Notification):
headers = {} headers = {}
try: try:
self.urlopen(url, headers=headers, timeout=3, show_error=False) self.urlopen(url, headers = headers, timeout = 3, show_error = False)
except Exception, err: except Exception, err:
log.error("Couldn't sent command to Plex: %s", err) log.error("Couldn't sent command to Plex: %s", err)
return False return False
return True return True
def notify_http(self, message='', data={}, listener=None): def notifyHTTP(self, message = '', data = {}, listener = None):
total = 0 total = 0
successful = 0 successful = 0
@@ -118,13 +123,13 @@ class Plex(Notification):
for name, client in self.clients.items(): for name, client in self.clients.items():
if client['protocol'] == 'xbmchttp': if client['protocol'] == 'xbmchttp':
total += 1 total += 1
if self.send_http(data, client): if self.sendHTTP(data, client):
successful += 1 successful += 1
return successful == total return successful == total
def send_json(self, method, params, client): def sendJSON(self, method, params, client):
log.debug('send_json("%s", %s, %s)', (method, params, client)) log.debug('sendJSON("%s", %s, %s)', (method, params, client))
url = 'http://%s:%s/jsonrpc' % ( url = 'http://%s:%s/jsonrpc' % (
client['address'], client['address'],
client['port'] client['port']
@@ -142,14 +147,14 @@ class Plex(Notification):
} }
try: try:
requests.post(url, headers=headers, timeout=3, data=json.dumps(request)) requests.post(url, headers = headers, timeout = 3, data = json.dumps(request))
except Exception, err: except Exception, err:
log.error("Couldn't sent command to Plex: %s", err) log.error("Couldn't sent command to Plex: %s", err)
return False return False
return True return True
def notify_json(self, message='', data={}, listener=None): def notifyJSON(self, message = '', data = {}, listener = None):
total = 0 total = 0
successful = 0 successful = 0
@@ -161,16 +166,16 @@ class Plex(Notification):
for name, client in self.clients.items(): for name, client in self.clients.items():
if client['protocol'] == 'xbmcjson': if client['protocol'] == 'xbmcjson':
total += 1 total += 1
if self.send_json('GUI.ShowNotification', params, client): if self.sendJSON('GUI.ShowNotification', params, client):
successful += 1 successful += 1
return successful == total return successful == total
def notify(self, message='', data={}, listener=None, force=False): def notify(self, message = '', data = {}, listener = None, force = False):
self.updateClients(force) self.updateClients(force)
http_result = self.notify_http(message, data, listener) http_result = self.notifyHTTP(message, data, listener)
json_result = self.notify_json(message, data, listener) json_result = self.notifyJSON(message, data, listener)
return http_result and json_result return http_result and json_result
@@ -181,13 +186,23 @@ class Plex(Notification):
log.info('Sending test to %s', test_type) log.info('Sending test to %s', test_type)
success = self.notify( success = self.notify(
message=self.test_message, message = self.test_message,
data={}, data = {},
listener='test', listener = 'test',
force=True force = True
) )
success2 = self.addToLibrary() success2 = self.addToLibrary()
return { return {
'success': success or success2 'success': success or success2
} }
def createHost(self, host, port = None):
h = cleanHost(host)
p = urlparse(h)
h = h.rstrip('/')
if port and not p.port:
h += ':%s' % port
return h