Change notifier code to follow quotation standards

This commit is contained in:
Adam 2015-08-16 11:23:56 +08:00
parent 03defe0219
commit 5cc1855b73
15 changed files with 232 additions and 232 deletions

View file

@ -103,6 +103,6 @@ def notify_snatch(ep_name):
n.notify_snatch(ep_name) n.notify_snatch(ep_name)
def notify_git_update(new_version=""): def notify_git_update(new_version=''):
for n in notifiers: for n in notifiers:
n.notify_git_update(new_version) n.notify_git_update(new_version)

View file

@ -43,7 +43,7 @@ class EmailNotifier:
msg['To'] = to msg['To'] = to
return self._sendmail(host, port, smtp_from, use_tls, user, pwd, [to], msg, True) return self._sendmail(host, port, smtp_from, use_tls, user, pwd, [to], msg, True)
def notify_snatch(self, ep_name, title="Snatched:"): def notify_snatch(self, ep_name, title='Snatched:'):
""" """
Send a notification that an episode was snatched Send a notification that an episode was snatched
@ -62,8 +62,8 @@ class EmailNotifier:
msg = MIMEMultipart('alternative') msg = MIMEMultipart('alternative')
msg.attach(MIMEText( msg.attach(MIMEText(
"<body style='font-family:Helvetica, Arial, sans-serif;'><h3>SickGear Notification - Snatched</h3>\n<p>Show: <b>" + re.search( "<body style='font-family:Helvetica, Arial, sans-serif;'><h3>SickGear Notification - Snatched</h3>\n<p>Show: <b>" + re.search(
"(.+?) -.+", ep_name).group(1) + "</b></p>\n<p>Episode: <b>" + re.search( '(.+?) -.+', ep_name).group(1) + '</b></p>\n<p>Episode: <b>' + re.search(
".+ - (.+?-.+) -.+", ep_name).group( '.+ - (.+?-.+) -.+', ep_name).group(
1) + "</b></p>\n\n<footer style='margin-top: 2.5em; padding: .7em 0; color: #777; border-top: #BBB solid 1px;'>Powered by SickGear.</footer></body>", 1) + "</b></p>\n\n<footer style='margin-top: 2.5em; padding: .7em 0; color: #777; border-top: #BBB solid 1px;'>Powered by SickGear.</footer></body>",
'html')) 'html'))
except: except:
@ -74,11 +74,11 @@ class EmailNotifier:
msg['To'] = ','.join(to) msg['To'] = ','.join(to)
if self._sendmail(sickbeard.EMAIL_HOST, sickbeard.EMAIL_PORT, sickbeard.EMAIL_FROM, sickbeard.EMAIL_TLS, if self._sendmail(sickbeard.EMAIL_HOST, sickbeard.EMAIL_PORT, sickbeard.EMAIL_FROM, sickbeard.EMAIL_TLS,
sickbeard.EMAIL_USER, sickbeard.EMAIL_PASSWORD, to, msg): sickbeard.EMAIL_USER, sickbeard.EMAIL_PASSWORD, to, msg):
logger.log("Snatch notification sent to [%s] for '%s'" % (to, ep_name), logger.DEBUG) logger.log('Snatch notification sent to [%s] for "%s"' % (to, ep_name), logger.DEBUG)
else: else:
logger.log("Snatch notification ERROR: %s" % self.last_err, logger.ERROR) logger.log('Snatch notification ERROR: %s' % self.last_err, logger.ERROR)
def notify_download(self, ep_name, title="Completed:"): def notify_download(self, ep_name, title='Completed:'):
""" """
Send a notification that an episode was downloaded Send a notification that an episode was downloaded
@ -97,8 +97,8 @@ class EmailNotifier:
msg = MIMEMultipart('alternative') msg = MIMEMultipart('alternative')
msg.attach(MIMEText( msg.attach(MIMEText(
"<body style='font-family:Helvetica, Arial, sans-serif;'><h3>SickGear Notification - Downloaded</h3>\n<p>Show: <b>" + re.search( "<body style='font-family:Helvetica, Arial, sans-serif;'><h3>SickGear Notification - Downloaded</h3>\n<p>Show: <b>" + re.search(
"(.+?) -.+", ep_name).group(1) + "</b></p>\n<p>Episode: <b>" + re.search( '(.+?) -.+', ep_name).group(1) + '</b></p>\n<p>Episode: <b>' + re.search(
".+ - (.+?-.+) -.+", ep_name).group( '.+ - (.+?-.+) -.+', ep_name).group(
1) + "</b></p>\n\n<footer style='margin-top: 2.5em; padding: .7em 0; color: #777; border-top: #BBB solid 1px;'>Powered by SickGear.</footer></body>", 1) + "</b></p>\n\n<footer style='margin-top: 2.5em; padding: .7em 0; color: #777; border-top: #BBB solid 1px;'>Powered by SickGear.</footer></body>",
'html')) 'html'))
except: except:
@ -109,11 +109,11 @@ class EmailNotifier:
msg['To'] = ','.join(to) msg['To'] = ','.join(to)
if self._sendmail(sickbeard.EMAIL_HOST, sickbeard.EMAIL_PORT, sickbeard.EMAIL_FROM, sickbeard.EMAIL_TLS, if self._sendmail(sickbeard.EMAIL_HOST, sickbeard.EMAIL_PORT, sickbeard.EMAIL_FROM, sickbeard.EMAIL_TLS,
sickbeard.EMAIL_USER, sickbeard.EMAIL_PASSWORD, to, msg): sickbeard.EMAIL_USER, sickbeard.EMAIL_PASSWORD, to, msg):
logger.log("Download notification sent to [%s] for '%s'" % (to, ep_name), logger.DEBUG) logger.log('Download notification sent to [%s] for "%s"' % (to, ep_name), logger.DEBUG)
else: else:
logger.log("Download notification ERROR: %s" % self.last_err, logger.ERROR) logger.log('Download notification ERROR: %s' % self.last_err, logger.ERROR)
def notify_subtitle_download(self, ep_name, lang, title="Downloaded subtitle:"): def notify_subtitle_download(self, ep_name, lang, title='Downloaded subtitle:'):
""" """
Send a notification that an subtitle was downloaded Send a notification that an subtitle was downloaded
@ -132,24 +132,24 @@ class EmailNotifier:
msg = MIMEMultipart('alternative') msg = MIMEMultipart('alternative')
msg.attach(MIMEText( msg.attach(MIMEText(
"<body style='font-family:Helvetica, Arial, sans-serif;'><h3>SickGear Notification - Subtitle Downloaded</h3>\n<p>Show: <b>" + re.search( "<body style='font-family:Helvetica, Arial, sans-serif;'><h3>SickGear Notification - Subtitle Downloaded</h3>\n<p>Show: <b>" + re.search(
"(.+?) -.+", ep_name).group(1) + "</b></p>\n<p>Episode: <b>" + re.search( '(.+?) -.+', ep_name).group(1) + '</b></p>\n<p>Episode: <b>' + re.search(
".+ - (.+?-.+) -.+", ep_name).group( '.+ - (.+?-.+) -.+', ep_name).group(
1) + "</b></p>\n<p>Language: <b>" + lang + "</b></p>\n\n<footer style='margin-top: 2.5em; padding: .7em 0; color: #777; border-top: #BBB solid 1px;'>Powered by SickGear.</footer></body>", 1) + '</b></p>\n<p>Language: <b>' + lang + "</b></p>\n\n<footer style='margin-top: 2.5em; padding: .7em 0; color: #777; border-top: #BBB solid 1px;'>Powered by SickGear.</footer></body>",
'html')) 'html'))
except: except:
msg = MIMEText(ep_name + ": " + lang) msg = MIMEText(ep_name + ': ' + lang)
msg['Subject'] = lang + ' Subtitle Downloaded: ' + ep_name msg['Subject'] = lang + ' Subtitle Downloaded: ' + ep_name
msg['From'] = sickbeard.EMAIL_FROM msg['From'] = sickbeard.EMAIL_FROM
msg['To'] = ','.join(to) msg['To'] = ','.join(to)
if self._sendmail(sickbeard.EMAIL_HOST, sickbeard.EMAIL_PORT, sickbeard.EMAIL_FROM, sickbeard.EMAIL_TLS, if self._sendmail(sickbeard.EMAIL_HOST, sickbeard.EMAIL_PORT, sickbeard.EMAIL_FROM, sickbeard.EMAIL_TLS,
sickbeard.EMAIL_USER, sickbeard.EMAIL_PASSWORD, to, msg): sickbeard.EMAIL_USER, sickbeard.EMAIL_PASSWORD, to, msg):
logger.log("Download notification sent to [%s] for '%s'" % (to, ep_name), logger.DEBUG) logger.log('Download notification sent to [%s] for "%s"' % (to, ep_name), logger.DEBUG)
else: else:
logger.log("Download notification ERROR: %s" % self.last_err, logger.ERROR) logger.log('Download notification ERROR: %s' % self.last_err, logger.ERROR)
def notify_git_update(self, new_version="??"): def notify_git_update(self, new_version='??'):
pass pass
def _generate_recepients(self, show): def _generate_recepients(self, show):
@ -163,7 +163,7 @@ class EmailNotifier:
# Grab the recipients for the show # Grab the recipients for the show
myDB = db.DBConnection() myDB = db.DBConnection()
for s in show: for s in show:
for subs in myDB.select("SELECT notify_list FROM tv_shows WHERE show_name = ?", (s,)): for subs in myDB.select('SELECT notify_list FROM tv_shows WHERE show_name = ?', (s,)):
if subs['notify_list']: if subs['notify_list']:
for addr in subs['notify_list'].split(','): for addr in subs['notify_list'].split(','):
if (len(addr.strip()) > 0): if (len(addr.strip()) > 0):
@ -199,10 +199,10 @@ class EmailNotifier:
def _parseEp(self, ep_name): def _parseEp(self, ep_name):
ep_name = ep_name.encode('utf-8', 'replace') ep_name = ep_name.encode('utf-8', 'replace')
sep = " - " sep = ' - '
titles = ep_name.split(sep) titles = ep_name.split(sep)
titles.sort(key=len, reverse=True) titles.sort(key=len, reverse=True)
logger.log("TITLES: %s" % titles, logger.DEBUG) logger.log('TITLES: %s' % titles, logger.DEBUG)
return titles return titles

View file

@ -30,7 +30,7 @@ from lib.growl import gntp
class GrowlNotifier: class GrowlNotifier:
def test_notify(self, host, password): def test_notify(self, host, password):
self._sendRegistration(host, password, 'Test') self._sendRegistration(host, password, 'Test')
return self._sendGrowl("Test Growl", "Testing Growl settings from SickGear", "Test", host, password, return self._sendGrowl('Test Growl', 'Testing Growl settings from SickGear', 'Test', host, password,
force=True) force=True)
def notify_snatch(self, ep_name): def notify_snatch(self, ep_name):
@ -43,9 +43,9 @@ class GrowlNotifier:
def notify_subtitle_download(self, ep_name, lang): def notify_subtitle_download(self, ep_name, lang):
if sickbeard.GROWL_NOTIFY_ONSUBTITLEDOWNLOAD: if sickbeard.GROWL_NOTIFY_ONSUBTITLEDOWNLOAD:
self._sendGrowl(common.notifyStrings[common.NOTIFY_SUBTITLE_DOWNLOAD], ep_name + ": " + lang) self._sendGrowl(common.notifyStrings[common.NOTIFY_SUBTITLE_DOWNLOAD], ep_name + ': ' + lang)
def notify_git_update(self, new_version = "??"): def notify_git_update(self, new_version = '??'):
if sickbeard.USE_GROWL: if sickbeard.USE_GROWL:
update_text=common.notifyStrings[common.NOTIFY_GIT_UPDATE_TEXT] update_text=common.notifyStrings[common.NOTIFY_GIT_UPDATE_TEXT]
title=common.notifyStrings[common.NOTIFY_GIT_UPDATE] title=common.notifyStrings[common.NOTIFY_GIT_UPDATE]
@ -93,7 +93,7 @@ class GrowlNotifier:
return response return response
def _sendGrowl(self, title="SickGear Notification", message=None, name=None, host=None, password=None, def _sendGrowl(self, title='SickGear Notification', message=None, name=None, host=None, password=None,
force=False): force=False):
if not sickbeard.USE_GROWL and not force: if not sickbeard.USE_GROWL and not force:
return False return False
@ -134,7 +134,7 @@ class GrowlNotifier:
for pc in growlHosts: for pc in growlHosts:
opts['host'] = pc[0] opts['host'] = pc[0]
opts['port'] = pc[1] opts['port'] = pc[1]
logger.log(u"GROWL: Sending message '" + message + "' to " + opts['host'] + ":" + str(opts['port']), logger.DEBUG) logger.log(u'GROWL: Sending message "' + message + '" to ' + opts['host'] + ':' + str(opts['port']), logger.DEBUG)
try: try:
if self._send_growl(opts, message): if self._send_growl(opts, message):
return True return True
@ -144,7 +144,7 @@ class GrowlNotifier:
else: else:
return False return False
except Exception as e: except Exception as e:
logger.log(u"GROWL: Unable to send growl to " + opts['host'] + ":" + str(opts['port']) + " - " + ex(e), logger.WARNING) logger.log(u'GROWL: Unable to send growl to ' + opts['host'] + ':' + str(opts['port']) + ' - ' + ex(e), logger.WARNING)
return False return False
def _sendRegistration(self, host=None, password=None, name='SickGear Notification'): def _sendRegistration(self, host=None, password=None, name='SickGear Notification'):
@ -188,7 +188,7 @@ class GrowlNotifier:
try: try:
return self._send(opts['host'], opts['port'], register.encode(), opts['debug']) return self._send(opts['host'], opts['port'], register.encode(), opts['debug'])
except Exception as e: except Exception as e:
logger.log(u"GROWL: Unable to send growl to " + opts['host'] + ":" + str(opts['port']) + " - " + ex(e), logger.WARNING) logger.log(u'GROWL: Unable to send growl to ' + opts['host'] + ':' + str(opts['port']) + ' - ' + ex(e), logger.WARNING)
return False return False

View file

@ -6,7 +6,7 @@ from lib.pynma import pynma
class NMA_Notifier: class NMA_Notifier:
def test_notify(self, nma_api, nma_priority): def test_notify(self, nma_api, nma_priority):
return self._sendNMA(nma_api, nma_priority, event="Test", message="Testing NMA settings from SickGear", return self._sendNMA(nma_api, nma_priority, event='Test', message='Testing NMA settings from SickGear',
force=True) force=True)
def notify_snatch(self, ep_name): def notify_snatch(self, ep_name):
@ -22,9 +22,9 @@ class NMA_Notifier:
def notify_subtitle_download(self, ep_name, lang): def notify_subtitle_download(self, ep_name, lang):
if sickbeard.NMA_NOTIFY_ONSUBTITLEDOWNLOAD: if sickbeard.NMA_NOTIFY_ONSUBTITLEDOWNLOAD:
self._sendNMA(nma_api=None, nma_priority=None, event=common.notifyStrings[common.NOTIFY_SUBTITLE_DOWNLOAD], self._sendNMA(nma_api=None, nma_priority=None, event=common.notifyStrings[common.NOTIFY_SUBTITLE_DOWNLOAD],
message=ep_name + ": " + lang) message=ep_name + ': ' + lang)
def notify_git_update(self, new_version = "??"): def notify_git_update(self, new_version = '??'):
if sickbeard.USE_NMA: if sickbeard.USE_NMA:
update_text=common.notifyStrings[common.NOTIFY_GIT_UPDATE_TEXT] update_text=common.notifyStrings[common.NOTIFY_GIT_UPDATE_TEXT]
title=common.notifyStrings[common.NOTIFY_GIT_UPDATE] title=common.notifyStrings[common.NOTIFY_GIT_UPDATE]
@ -51,14 +51,14 @@ class NMA_Notifier:
if len(keys) > 1: batch = True if len(keys) > 1: batch = True
logger.log("NMA: Sending notice with details: event=\"%s\", message=\"%s\", priority=%s, batch=%s" % (event, message, nma_priority, batch), logger.DEBUG) logger.log('NMA: Sending notice with details: event="%s", message="%s", priority=%s, batch=%s' % (event, message, nma_priority, batch), logger.DEBUG)
response = p.push(title, event, message, priority=nma_priority, batch_mode=batch) response = p.push(title, event, message, priority=nma_priority, batch_mode=batch)
if not response[nma_api][u'code'] == u'200': if not response[nma_api][u'code'] == u'200':
logger.log(u'Could not send notification to NotifyMyAndroid', logger.ERROR) logger.log(u'Could not send notification to NotifyMyAndroid', logger.ERROR)
return False return False
else: else:
logger.log(u"NMA: Notification sent to NotifyMyAndroid", logger.MESSAGE) logger.log(u'NMA: Notification sent to NotifyMyAndroid', logger.MESSAGE)
return True return True

View file

@ -45,41 +45,41 @@ class NMJNotifier:
try: try:
terminal = telnetlib.Telnet(host) terminal = telnetlib.Telnet(host)
except Exception: except Exception:
logger.log(u"Warning: unable to get a telnet session to %s" % (host), logger.WARNING) logger.log(u'Warning: unable to get a telnet session to %s' % (host), logger.WARNING)
return False return False
# tell the terminal to output the necessary info to the screen so we can search it later # tell the terminal to output the necessary info to the screen so we can search it later
logger.log(u"Connected to %s via telnet" % (host), logger.DEBUG) logger.log(u'Connected to %s via telnet' % (host), logger.DEBUG)
terminal.read_until("sh-3.00# ") terminal.read_until('sh-3.00# ')
terminal.write("cat /tmp/source\n") terminal.write('cat /tmp/source\n')
terminal.write("cat /tmp/netshare\n") terminal.write('cat /tmp/netshare\n')
terminal.write("exit\n") terminal.write('exit\n')
tnoutput = terminal.read_all() tnoutput = terminal.read_all()
database = "" database = ''
device = "" device = ''
match = re.search(r"(.+\.db)\r\n?(.+)(?=sh-3.00# cat /tmp/netshare)", tnoutput) match = re.search(r'(.+\.db)\r\n?(.+)(?=sh-3.00# cat /tmp/netshare)', tnoutput)
# if we found the database in the terminal output then save that database to the config # if we found the database in the terminal output then save that database to the config
if match: if match:
database = match.group(1) database = match.group(1)
device = match.group(2) device = match.group(2)
logger.log(u"Found NMJ database %s on device %s" % (database, device), logger.DEBUG) logger.log(u'Found NMJ database %s on device %s' % (database, device), logger.DEBUG)
sickbeard.NMJ_DATABASE = database sickbeard.NMJ_DATABASE = database
else: else:
logger.log(u"Could not get current NMJ database on %s, NMJ is probably not running!" % (host), logger.WARNING) logger.log(u'Could not get current NMJ database on %s, NMJ is probably not running!' % (host), logger.WARNING)
return False return False
# if the device is a remote host then try to parse the mounting URL and save it to the config # if the device is a remote host then try to parse the mounting URL and save it to the config
if device.startswith("NETWORK_SHARE/"): if device.startswith('NETWORK_SHARE/'):
match = re.search(".*(?=\r\n?%s)" % (re.escape(device[14:])), tnoutput) match = re.search('.*(?=\r\n?%s)' % (re.escape(device[14:])), tnoutput)
if match: if match:
mount = match.group().replace("127.0.0.1", host) mount = match.group().replace('127.0.0.1', host)
logger.log(u"Found mounting url on the Popcorn Hour in configuration: %s" % (mount), logger.DEBUG) logger.log(u'Found mounting url on the Popcorn Hour in configuration: %s' % (mount), logger.DEBUG)
sickbeard.NMJ_MOUNT = mount sickbeard.NMJ_MOUNT = mount
else: else:
logger.log(u"Detected a network share on the Popcorn Hour, but could not get the mounting url", logger.log(u'Detected a network share on the Popcorn Hour, but could not get the mounting url',
logger.WARNING) logger.WARNING)
return False return False
@ -119,59 +119,59 @@ class NMJNotifier:
if mount: if mount:
try: try:
req = urllib2.Request(mount) req = urllib2.Request(mount)
logger.log(u"Try to mount network drive via url: %s" % (mount), logger.DEBUG) logger.log(u'Try to mount network drive via url: %s' % (mount), logger.DEBUG)
handle = urllib2.urlopen(req) handle = urllib2.urlopen(req)
except IOError as e: except IOError as e:
if hasattr(e, 'reason'): if hasattr(e, 'reason'):
logger.log(u"NMJ: Could not contact Popcorn Hour on host %s: %s" % (host, e.reason), logger.WARNING) logger.log(u'NMJ: Could not contact Popcorn Hour on host %s: %s' % (host, e.reason), logger.WARNING)
elif hasattr(e, 'code'): elif hasattr(e, 'code'):
logger.log(u"NMJ: Problem with Popcorn Hour on host %s: %s" % (host, e.code), logger.WARNING) logger.log(u'NMJ: Problem with Popcorn Hour on host %s: %s' % (host, e.code), logger.WARNING)
return False return False
except Exception as e: except Exception as e:
logger.log(u"NMJ: Unknown exception: " + ex(e), logger.ERROR) logger.log(u'NMJ: Unknown exception: ' + ex(e), logger.ERROR)
return False return False
# build up the request URL and parameters # build up the request URL and parameters
UPDATE_URL = "http://%(host)s:8008/metadata_database?%(params)s" UPDATE_URL = 'http://%(host)s:8008/metadata_database?%(params)s'
params = { params = {
"arg0": "scanner_start", 'arg0': 'scanner_start',
"arg1": database, 'arg1': database,
"arg2": "background", 'arg2': 'background',
"arg3": "" 'arg3': ''
} }
params = urllib.urlencode(params) params = urllib.urlencode(params)
updateUrl = UPDATE_URL % {"host": host, "params": params} updateUrl = UPDATE_URL % {'host': host, 'params': params}
# send the request to the server # send the request to the server
try: try:
req = urllib2.Request(updateUrl) req = urllib2.Request(updateUrl)
logger.log(u"Sending NMJ scan update command via url: %s" % (updateUrl), logger.DEBUG) logger.log(u'Sending NMJ scan update command via url: %s' % (updateUrl), logger.DEBUG)
handle = urllib2.urlopen(req) handle = urllib2.urlopen(req)
response = handle.read() response = handle.read()
except IOError as e: except IOError as e:
if hasattr(e, 'reason'): if hasattr(e, 'reason'):
logger.log(u"NMJ: Could not contact Popcorn Hour on host %s: %s" % (host, e.reason), logger.WARNING) logger.log(u'NMJ: Could not contact Popcorn Hour on host %s: %s' % (host, e.reason), logger.WARNING)
elif hasattr(e, 'code'): elif hasattr(e, 'code'):
logger.log(u"NMJ: Problem with Popcorn Hour on host %s: %s" % (host, e.code), logger.WARNING) logger.log(u'NMJ: Problem with Popcorn Hour on host %s: %s' % (host, e.code), logger.WARNING)
return False return False
except Exception as e: except Exception as e:
logger.log(u"NMJ: Unknown exception: " + ex(e), logger.ERROR) logger.log(u'NMJ: Unknown exception: ' + ex(e), logger.ERROR)
return False return False
# try to parse the resulting XML # try to parse the resulting XML
try: try:
et = etree.fromstring(response) et = etree.fromstring(response)
result = et.findtext("returnValue") result = et.findtext('returnValue')
except SyntaxError as e: except SyntaxError as e:
logger.log(u"Unable to parse XML returned from the Popcorn Hour: %s" % (e), logger.ERROR) logger.log(u'Unable to parse XML returned from the Popcorn Hour: %s' % (e), logger.ERROR)
return False return False
# if the result was a number then consider that an error # if the result was a number then consider that an error
if int(result) > 0: if int(result) > 0:
logger.log(u"Popcorn Hour returned an errorcode: %s" % (result), logger.ERROR) logger.log(u'Popcorn Hour returned an errorcode: %s' % (result), logger.ERROR)
return False return False
else: else:
logger.log(u"NMJ started background scan", logger.MESSAGE) logger.log(u'NMJ started background scan', logger.MESSAGE)
return True return True
def _notifyNMJ(self, host=None, database=None, mount=None, force=False): def _notifyNMJ(self, host=None, database=None, mount=None, force=False):
@ -184,7 +184,7 @@ class NMJNotifier:
force: If True then the notification will be sent even if NMJ is disabled in the config force: If True then the notification will be sent even if NMJ is disabled in the config
""" """
if not sickbeard.USE_NMJ and not force: if not sickbeard.USE_NMJ and not force:
logger.log("Notification for NMJ scan update not enabled, skipping this notification", logger.DEBUG) logger.log('Notification for NMJ scan update not enabled, skipping this notification', logger.DEBUG)
return False return False
# fill in omitted parameters # fill in omitted parameters
@ -195,7 +195,7 @@ class NMJNotifier:
if not mount: if not mount:
mount = sickbeard.NMJ_MOUNT mount = sickbeard.NMJ_MOUNT
logger.log(u"Sending scan command for NMJ ", logger.DEBUG) logger.log(u'Sending scan command for NMJ ', logger.DEBUG)
return self._sendNMJ(host, database, mount) return self._sendNMJ(host, database, mount)

View file

@ -61,7 +61,7 @@ class NMJv2Notifier:
Returns: True if the settings were retrieved successfully, False otherwise Returns: True if the settings were retrieved successfully, False otherwise
""" """
try: try:
url_loc = "http://" + host + ":8008/file_operation?arg0=list_user_storage_file&arg1=&arg2=" + instance + "&arg3=20&arg4=true&arg5=true&arg6=true&arg7=all&arg8=name_asc&arg9=false&arg10=false" url_loc = 'http://' + host + ':8008/file_operation?arg0=list_user_storage_file&arg1=&arg2=' + instance + '&arg3=20&arg4=true&arg5=true&arg6=true&arg7=all&arg8=name_asc&arg9=false&arg10=false'
req = urllib2.Request(url_loc) req = urllib2.Request(url_loc)
handle1 = urllib2.urlopen(req) handle1 = urllib2.urlopen(req)
response1 = handle1.read() response1 = handle1.read()
@ -70,22 +70,22 @@ class NMJv2Notifier:
for node in xml.getElementsByTagName('path'): for node in xml.getElementsByTagName('path'):
xmlTag = node.toxml(); xmlTag = node.toxml();
xmlData = xmlTag.replace('<path>', '').replace('</path>', '').replace('[=]', '') xmlData = xmlTag.replace('<path>', '').replace('</path>', '').replace('[=]', '')
url_db = "http://" + host + ":8008/metadata_database?arg0=check_database&arg1=" + xmlData url_db = 'http://' + host + ':8008/metadata_database?arg0=check_database&arg1=' + xmlData
reqdb = urllib2.Request(url_db) reqdb = urllib2.Request(url_db)
handledb = urllib2.urlopen(reqdb) handledb = urllib2.urlopen(reqdb)
responsedb = handledb.read() responsedb = handledb.read()
xmldb = parseString(responsedb) xmldb = parseString(responsedb)
returnvalue = xmldb.getElementsByTagName('returnValue')[0].toxml().replace('<returnValue>', '').replace( returnvalue = xmldb.getElementsByTagName('returnValue')[0].toxml().replace('<returnValue>', '').replace(
'</returnValue>', '') '</returnValue>', '')
if returnvalue == "0": if returnvalue == '0':
DB_path = xmldb.getElementsByTagName('database_path')[0].toxml().replace('<database_path>', DB_path = xmldb.getElementsByTagName('database_path')[0].toxml().replace('<database_path>',
'').replace( '').replace(
'</database_path>', '').replace('[=]', '') '</database_path>', '').replace('[=]', '')
if dbloc == "local" and DB_path.find("localhost") > -1: if dbloc == 'local' and DB_path.find('localhost') > -1:
sickbeard.NMJv2_HOST = host sickbeard.NMJv2_HOST = host
sickbeard.NMJv2_DATABASE = DB_path sickbeard.NMJv2_DATABASE = DB_path
return True return True
if dbloc == "network" and DB_path.find("://") > -1: if dbloc == 'network' and DB_path.find('://') > -1:
sickbeard.NMJv2_HOST = host sickbeard.NMJv2_HOST = host
sickbeard.NMJv2_DATABASE = DB_path sickbeard.NMJv2_DATABASE = DB_path
return True return True
@ -108,10 +108,10 @@ class NMJv2Notifier:
#if a host is provided then attempt to open a handle to that URL #if a host is provided then attempt to open a handle to that URL
try: try:
url_scandir = "http://" + host + ":8008/metadata_database?arg0=update_scandir&arg1=" + sickbeard.NMJv2_DATABASE + "&arg2=&arg3=update_all" url_scandir = 'http://' + host + ':8008/metadata_database?arg0=update_scandir&arg1=' + sickbeard.NMJv2_DATABASE + '&arg2=&arg3=update_all'
logger.log(u"NMJ scan update command sent to host: %s" % (host), logger.DEBUG) logger.log(u'NMJ scan update command sent to host: %s' % (host), logger.DEBUG)
url_updatedb = "http://" + host + ":8008/metadata_database?arg0=scanner_start&arg1=" + sickbeard.NMJv2_DATABASE + "&arg2=background&arg3=" url_updatedb = 'http://' + host + ':8008/metadata_database?arg0=scanner_start&arg1=' + sickbeard.NMJv2_DATABASE + '&arg2=background&arg3='
logger.log(u"Try to mount network drive via url: %s" % (host), logger.DEBUG) logger.log(u'Try to mount network drive via url: %s' % (host), logger.DEBUG)
prereq = urllib2.Request(url_scandir) prereq = urllib2.Request(url_scandir)
req = urllib2.Request(url_updatedb) req = urllib2.Request(url_updatedb)
handle1 = urllib2.urlopen(prereq) handle1 = urllib2.urlopen(prereq)
@ -124,37 +124,37 @@ class NMJv2Notifier:
return False return False
try: try:
et = etree.fromstring(response1) et = etree.fromstring(response1)
result1 = et.findtext("returnValue") result1 = et.findtext('returnValue')
except SyntaxError as e: except SyntaxError as e:
logger.log(u"Unable to parse XML returned from the Popcorn Hour: update_scandir, %s" % (e), logger.ERROR) logger.log(u'Unable to parse XML returned from the Popcorn Hour: update_scandir, %s' % (e), logger.ERROR)
return False return False
try: try:
et = etree.fromstring(response2) et = etree.fromstring(response2)
result2 = et.findtext("returnValue") result2 = et.findtext('returnValue')
except SyntaxError as e: except SyntaxError as e:
logger.log(u"Unable to parse XML returned from the Popcorn Hour: scanner_start, %s" % (e), logger.ERROR) logger.log(u'Unable to parse XML returned from the Popcorn Hour: scanner_start, %s' % (e), logger.ERROR)
return False return False
# if the result was a number then consider that an error # if the result was a number then consider that an error
error_codes = ["8", "11", "22", "49", "50", "51", "60"] error_codes = ['8', '11', '22', '49', '50', '51', '60']
error_messages = ["Invalid parameter(s)/argument(s)", error_messages = ['Invalid parameter(s)/argument(s)',
"Invalid database path", 'Invalid database path',
"Insufficient size", 'Insufficient size',
"Database write error", 'Database write error',
"Database read error", 'Database read error',
"Open fifo pipe failed", 'Open fifo pipe failed',
"Read only file system"] 'Read only file system']
if int(result1) > 0: if int(result1) > 0:
index = error_codes.index(result1) index = error_codes.index(result1)
logger.log(u"Popcorn Hour returned an error: %s" % (error_messages[index]), logger.ERROR) logger.log(u'Popcorn Hour returned an error: %s' % (error_messages[index]), logger.ERROR)
return False return False
else: else:
if int(result2) > 0: if int(result2) > 0:
index = error_codes.index(result2) index = error_codes.index(result2)
logger.log(u"Popcorn Hour returned an error: %s" % (error_messages[index]), logger.ERROR) logger.log(u'Popcorn Hour returned an error: %s' % (error_messages[index]), logger.ERROR)
return False return False
else: else:
logger.log(u"NMJv2 started background scan", logger.MESSAGE) logger.log(u'NMJv2 started background scan', logger.MESSAGE)
return True return True
def _notifyNMJ(self, host=None, force=False): def _notifyNMJ(self, host=None, force=False):
@ -167,14 +167,14 @@ class NMJv2Notifier:
force: If True then the notification will be sent even if NMJ is disabled in the config force: If True then the notification will be sent even if NMJ is disabled in the config
""" """
if not sickbeard.USE_NMJv2 and not force: if not sickbeard.USE_NMJv2 and not force:
logger.log("Notification for NMJ scan update not enabled, skipping this notification", logger.DEBUG) logger.log('Notification for NMJ scan update not enabled, skipping this notification', logger.DEBUG)
return False return False
# fill in omitted parameters # fill in omitted parameters
if not host: if not host:
host = sickbeard.NMJv2_HOST host = sickbeard.NMJv2_HOST
logger.log(u"Sending scan command for NMJ ", logger.DEBUG) logger.log(u'Sending scan command for NMJ ', logger.DEBUG)
return self._sendNMJ(host) return self._sendNMJ(host)

View file

@ -36,8 +36,8 @@ from sickbeard import logger, common
class ProwlNotifier: class ProwlNotifier:
def test_notify(self, prowl_api, prowl_priority): def test_notify(self, prowl_api, prowl_priority):
return self._sendProwl(prowl_api, prowl_priority, event="Test", return self._sendProwl(prowl_api, prowl_priority, event='Test',
message="Testing Prowl settings from SickGear", force=True) message='Testing Prowl settings from SickGear', force=True)
def notify_snatch(self, ep_name): def notify_snatch(self, ep_name):
if sickbeard.PROWL_NOTIFY_ONSNATCH: if sickbeard.PROWL_NOTIFY_ONSNATCH:
@ -52,9 +52,9 @@ class ProwlNotifier:
def notify_subtitle_download(self, ep_name, lang): def notify_subtitle_download(self, ep_name, lang):
if sickbeard.PROWL_NOTIFY_ONSUBTITLEDOWNLOAD: if sickbeard.PROWL_NOTIFY_ONSUBTITLEDOWNLOAD:
self._sendProwl(prowl_api=None, prowl_priority=None, self._sendProwl(prowl_api=None, prowl_priority=None,
event=common.notifyStrings[common.NOTIFY_SUBTITLE_DOWNLOAD], message=ep_name + ": " + lang) event=common.notifyStrings[common.NOTIFY_SUBTITLE_DOWNLOAD], message=ep_name + ': ' + lang)
def notify_git_update(self, new_version = "??"): def notify_git_update(self, new_version = '??'):
if sickbeard.USE_PROWL: if sickbeard.USE_PROWL:
update_text=common.notifyStrings[common.NOTIFY_GIT_UPDATE_TEXT] update_text=common.notifyStrings[common.NOTIFY_GIT_UPDATE_TEXT]
title=common.notifyStrings[common.NOTIFY_GIT_UPDATE] title=common.notifyStrings[common.NOTIFY_GIT_UPDATE]
@ -72,11 +72,11 @@ class ProwlNotifier:
if prowl_priority == None: if prowl_priority == None:
prowl_priority = sickbeard.PROWL_PRIORITY prowl_priority = sickbeard.PROWL_PRIORITY
title = "SickGear" title = 'SickGear'
logger.log("PROWL: Sending notice with details: event=\"%s\", message=\"%s\", priority=%s, api=%s" % (event, message, prowl_priority, prowl_api), logger.DEBUG) logger.log('PROWL: Sending notice with details: event="%s", message="%s", priority=%s, api=%s' % (event, message, prowl_priority, prowl_api), logger.DEBUG)
http_handler = moves.http_client.HTTPSConnection("api.prowlapp.com") http_handler = moves.http_client.HTTPSConnection('api.prowlapp.com')
data = {'apikey': prowl_api, data = {'apikey': prowl_api,
'application': title, 'application': title,
@ -85,24 +85,24 @@ class ProwlNotifier:
'priority': prowl_priority} 'priority': prowl_priority}
try: try:
http_handler.request("POST", http_handler.request('POST',
"/publicapi/add", '/publicapi/add',
headers={'Content-type': "application/x-www-form-urlencoded"}, headers={'Content-type': 'application/x-www-form-urlencoded'},
body=urlencode(data)) body=urlencode(data))
except (SSLError, moves.http_client.HTTPException, socket.error): except (SSLError, moves.http_client.HTTPException, socket.error):
logger.log(u"Prowl notification failed.", logger.ERROR) logger.log(u'Prowl notification failed.', logger.ERROR)
return False return False
response = http_handler.getresponse() response = http_handler.getresponse()
request_status = response.status request_status = response.status
if request_status == 200: if request_status == 200:
logger.log(u"Prowl notifications sent.", logger.MESSAGE) logger.log(u'Prowl notifications sent.', logger.MESSAGE)
return True return True
elif request_status == 401: elif request_status == 401:
logger.log(u"Prowl authentication failed: %s" % response.reason, logger.ERROR) logger.log(u'Prowl authentication failed: %s' % response.reason, logger.ERROR)
return False return False
else: else:
logger.log(u"Prowl notification failed.", logger.ERROR) logger.log(u'Prowl notification failed.', logger.ERROR)
return False return False

View file

@ -29,8 +29,8 @@ from sickbeard import logger, common
class PushalotNotifier: class PushalotNotifier:
def test_notify(self, pushalot_authorizationtoken): def test_notify(self, pushalot_authorizationtoken):
return self._sendPushalot(pushalot_authorizationtoken, event="Test", return self._sendPushalot(pushalot_authorizationtoken, event='Test',
message="Testing Pushalot settings from SickGear", force=True) message='Testing Pushalot settings from SickGear', force=True)
def notify_snatch(self, ep_name): def notify_snatch(self, ep_name):
if sickbeard.PUSHALOT_NOTIFY_ONSNATCH: if sickbeard.PUSHALOT_NOTIFY_ONSNATCH:
@ -46,9 +46,9 @@ class PushalotNotifier:
if sickbeard.PUSHALOT_NOTIFY_ONSUBTITLEDOWNLOAD: if sickbeard.PUSHALOT_NOTIFY_ONSUBTITLEDOWNLOAD:
self._sendPushalot(pushalot_authorizationtoken=None, self._sendPushalot(pushalot_authorizationtoken=None,
event=common.notifyStrings[common.NOTIFY_SUBTITLE_DOWNLOAD], event=common.notifyStrings[common.NOTIFY_SUBTITLE_DOWNLOAD],
message=ep_name + ": " + lang) message=ep_name + ': ' + lang)
def notify_git_update(self, new_version = "??"): def notify_git_update(self, new_version = '??'):
if sickbeard.USE_PUSHALOT: if sickbeard.USE_PUSHALOT:
update_text=common.notifyStrings[common.NOTIFY_GIT_UPDATE_TEXT] update_text=common.notifyStrings[common.NOTIFY_GIT_UPDATE_TEXT]
title=common.notifyStrings[common.NOTIFY_GIT_UPDATE] title=common.notifyStrings[common.NOTIFY_GIT_UPDATE]
@ -64,35 +64,35 @@ class PushalotNotifier:
if pushalot_authorizationtoken == None: if pushalot_authorizationtoken == None:
pushalot_authorizationtoken = sickbeard.PUSHALOT_AUTHORIZATIONTOKEN pushalot_authorizationtoken = sickbeard.PUSHALOT_AUTHORIZATIONTOKEN
logger.log(u"Pushalot event: " + event, logger.DEBUG) logger.log(u'Pushalot event: ' + event, logger.DEBUG)
logger.log(u"Pushalot message: " + message, logger.DEBUG) logger.log(u'Pushalot message: ' + message, logger.DEBUG)
logger.log(u"Pushalot api: " + pushalot_authorizationtoken, logger.DEBUG) logger.log(u'Pushalot api: ' + pushalot_authorizationtoken, logger.DEBUG)
http_handler = moves.http_client.HTTPSConnection("pushalot.com") http_handler = moves.http_client.HTTPSConnection('pushalot.com')
data = {'AuthorizationToken': pushalot_authorizationtoken, data = {'AuthorizationToken': pushalot_authorizationtoken,
'Title': event.encode('utf-8'), 'Title': event.encode('utf-8'),
'Body': message.encode('utf-8')} 'Body': message.encode('utf-8')}
try: try:
http_handler.request("POST", http_handler.request('POST',
"/api/sendmessage", '/api/sendmessage',
headers={'Content-type': "application/x-www-form-urlencoded"}, headers={'Content-type': 'application/x-www-form-urlencoded'},
body=urlencode(data)) body=urlencode(data))
except (SSLError, moves.http_client.HTTPException, socket.error): except (SSLError, moves.http_client.HTTPException, socket.error):
logger.log(u"Pushalot notification failed.", logger.ERROR) logger.log(u'Pushalot notification failed.', logger.ERROR)
return False return False
response = http_handler.getresponse() response = http_handler.getresponse()
request_status = response.status request_status = response.status
if request_status == 200: if request_status == 200:
logger.log(u"Pushalot notifications sent.", logger.DEBUG) logger.log(u'Pushalot notifications sent.', logger.DEBUG)
return True return True
elif request_status == 410: elif request_status == 410:
logger.log(u"Pushalot authentication failed: %s" % response.reason, logger.ERROR) logger.log(u'Pushalot authentication failed: %s' % response.reason, logger.ERROR)
return False return False
else: else:
logger.log(u"Pushalot notification failed.", logger.ERROR) logger.log(u'Pushalot notification failed.', logger.ERROR)
return False return False

View file

@ -91,7 +91,7 @@ class PushbulletNotifier:
if not device_iden: if not device_iden:
device_iden = sickbeard.PUSHBULLET_DEVICE_IDEN device_iden = sickbeard.PUSHBULLET_DEVICE_IDEN
logger.log(u'PUSHBULLET: Sending notice with details: \"%s - %s\", device_iden: %s' % (title, body, device_iden), logger.DEBUG) logger.log(u'PUSHBULLET: Sending notice with details: "%s - %s", device_iden: %s' % (title, body, device_iden), logger.DEBUG)
return self._sendPushbullet(title, body, accessToken, device_iden) return self._sendPushbullet(title, body, accessToken, device_iden)

View file

@ -73,19 +73,19 @@ class pyTivoNotifier:
# Some show names have colons in them which are illegal in a path location, so strip them out. # Some show names have colons in them which are illegal in a path location, so strip them out.
# (Are there other characters?) # (Are there other characters?)
showName = showName.replace(":", "") showName = showName.replace(':', '')
root = showPath.replace(showName, "") root = showPath.replace(showName, '')
showAndSeason = rootShowAndSeason.replace(root, "") showAndSeason = rootShowAndSeason.replace(root, '')
container = shareName + "/" + showAndSeason container = shareName + '/' + showAndSeason
file = "/" + absPath.replace(root, "") file = '/' + absPath.replace(root, '')
# Finally create the url and make request # Finally create the url and make request
requestUrl = "http://" + host + "/TiVoConnect?" + urlencode( requestUrl = 'http://' + host + '/TiVoConnect?' + urlencode(
{'Command': 'Push', 'Container': container, 'File': file, 'tsn': tsn}) {'Command': 'Push', 'Container': container, 'File': file, 'tsn': tsn})
logger.log(u"pyTivo notification: Requesting " + requestUrl, logger.DEBUG) logger.log(u'pyTivo notification: Requesting ' + requestUrl, logger.DEBUG)
request = Request(requestUrl) request = Request(requestUrl)
@ -93,16 +93,16 @@ class pyTivoNotifier:
response = urlopen(request) #@UnusedVariable response = urlopen(request) #@UnusedVariable
except HTTPError as e: except HTTPError as e:
if hasattr(e, 'reason'): if hasattr(e, 'reason'):
logger.log(u"pyTivo notification: Error, failed to reach a server - " + e.reason, logger.ERROR) logger.log(u'pyTivo notification: Error, failed to reach a server - ' + e.reason, logger.ERROR)
return False return False
elif hasattr(e, 'code'): elif hasattr(e, 'code'):
logger.log(u"pyTivo notification: Error, the server couldn't fulfill the request - " + e.code, logger.ERROR) logger.log(u"pyTivo notification: Error, the server couldn't fulfill the request - " + e.code, logger.ERROR)
return False return False
except Exception as e: except Exception as e:
logger.log(u"PYTIVO: Unknown exception: " + ex(e), logger.ERROR) logger.log(u'PYTIVO: Unknown exception: ' + ex(e), logger.ERROR)
return False return False
else: else:
logger.log(u"pyTivo notification: Successfully requested transfer of file") logger.log(u'pyTivo notification: Successfully requested transfer of file')
return True return True

View file

@ -51,15 +51,15 @@ class synoIndexNotifier:
if sickbeard.USE_SYNOINDEX: if sickbeard.USE_SYNOINDEX:
synoindex_cmd = ['/usr/syno/bin/synoindex', '-N', ek.ek(os.path.abspath, new_path), synoindex_cmd = ['/usr/syno/bin/synoindex', '-N', ek.ek(os.path.abspath, new_path),
ek.ek(os.path.abspath, old_path)] ek.ek(os.path.abspath, old_path)]
logger.log(u"Executing command " + str(synoindex_cmd), logger.DEBUG) logger.log(u'Executing command ' + str(synoindex_cmd), logger.DEBUG)
logger.log(u"Absolute path to command: " + ek.ek(os.path.abspath, synoindex_cmd[0]), logger.DEBUG) logger.log(u'Absolute path to command: ' + ek.ek(os.path.abspath, synoindex_cmd[0]), logger.DEBUG)
try: try:
p = subprocess.Popen(synoindex_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, p = subprocess.Popen(synoindex_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
cwd=sickbeard.PROG_DIR) cwd=sickbeard.PROG_DIR)
out, err = p.communicate() #@UnusedVariable out, err = p.communicate() #@UnusedVariable
logger.log(u"Script result: " + str(out), logger.DEBUG) logger.log(u'Script result: ' + str(out), logger.DEBUG)
except OSError as e: except OSError as e:
logger.log(u"Unable to run synoindex: " + ex(e), logger.ERROR) logger.log(u'Unable to run synoindex: ' + ex(e), logger.ERROR)
def deleteFolder(self, cur_path): def deleteFolder(self, cur_path):
self.makeObject('-D', cur_path) self.makeObject('-D', cur_path)
@ -76,15 +76,15 @@ class synoIndexNotifier:
def makeObject(self, cmd_arg, cur_path): def makeObject(self, cmd_arg, cur_path):
if sickbeard.USE_SYNOINDEX: if sickbeard.USE_SYNOINDEX:
synoindex_cmd = ['/usr/syno/bin/synoindex', cmd_arg, ek.ek(os.path.abspath, cur_path)] synoindex_cmd = ['/usr/syno/bin/synoindex', cmd_arg, ek.ek(os.path.abspath, cur_path)]
logger.log(u"Executing command " + str(synoindex_cmd), logger.DEBUG) logger.log(u'Executing command ' + str(synoindex_cmd), logger.DEBUG)
logger.log(u"Absolute path to command: " + ek.ek(os.path.abspath, synoindex_cmd[0]), logger.DEBUG) logger.log(u'Absolute path to command: ' + ek.ek(os.path.abspath, synoindex_cmd[0]), logger.DEBUG)
try: try:
p = subprocess.Popen(synoindex_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, p = subprocess.Popen(synoindex_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
cwd=sickbeard.PROG_DIR) cwd=sickbeard.PROG_DIR)
out, err = p.communicate() #@UnusedVariable out, err = p.communicate() #@UnusedVariable
logger.log(u"Script result: " + str(out), logger.DEBUG) logger.log(u'Script result: ' + str(out), logger.DEBUG)
except OSError as e: except OSError as e:
logger.log(u"Unable to run synoindex: " + ex(e), logger.ERROR) logger.log(u'Unable to run synoindex: ' + ex(e), logger.ERROR)
notifier = synoIndexNotifier notifier = synoIndexNotifier

View file

@ -39,25 +39,25 @@ class synologyNotifier:
def notify_subtitle_download(self, ep_name, lang): def notify_subtitle_download(self, ep_name, lang):
if sickbeard.SYNOLOGYNOTIFIER_NOTIFY_ONSUBTITLEDOWNLOAD: if sickbeard.SYNOLOGYNOTIFIER_NOTIFY_ONSUBTITLEDOWNLOAD:
self._send_synologyNotifier(ep_name + ": " + lang, common.notifyStrings[common.NOTIFY_SUBTITLE_DOWNLOAD]) self._send_synologyNotifier(ep_name + ': ' + lang, common.notifyStrings[common.NOTIFY_SUBTITLE_DOWNLOAD])
def notify_git_update(self, new_version = "??"): def notify_git_update(self, new_version = '??'):
if sickbeard.USE_SYNOLOGYNOTIFIER: if sickbeard.USE_SYNOLOGYNOTIFIER:
update_text=common.notifyStrings[common.NOTIFY_GIT_UPDATE_TEXT] update_text=common.notifyStrings[common.NOTIFY_GIT_UPDATE_TEXT]
title=common.notifyStrings[common.NOTIFY_GIT_UPDATE] title=common.notifyStrings[common.NOTIFY_GIT_UPDATE]
self._send_synologyNotifier(update_text + new_version, title) self._send_synologyNotifier(update_text + new_version, title)
def _send_synologyNotifier(self, message, title): def _send_synologyNotifier(self, message, title):
synodsmnotify_cmd = ["/usr/syno/bin/synodsmnotify", "@administrators", title, message] synodsmnotify_cmd = ['/usr/syno/bin/synodsmnotify', '@administrators', title, message]
logger.log(u"Executing command " + str(synodsmnotify_cmd)) logger.log(u'Executing command ' + str(synodsmnotify_cmd))
logger.log(u"Absolute path to command: " + ek.ek(os.path.abspath, synodsmnotify_cmd[0]), logger.DEBUG) logger.log(u'Absolute path to command: ' + ek.ek(os.path.abspath, synodsmnotify_cmd[0]), logger.DEBUG)
try: try:
p = subprocess.Popen(synodsmnotify_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, p = subprocess.Popen(synodsmnotify_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
cwd=sickbeard.PROG_DIR) cwd=sickbeard.PROG_DIR)
out, err = p.communicate() #@UnusedVariable out, err = p.communicate() #@UnusedVariable
logger.log(u"Script result: " + str(out), logger.DEBUG) logger.log(u'Script result: ' + str(out), logger.DEBUG)
except OSError as e: except OSError as e:
logger.log(u"Unable to run synodsmnotify: " + ex(e)) logger.log(u'Unable to run synodsmnotify: ' + ex(e))
notifier = synologyNotifier notifier = synologyNotifier

View file

@ -59,9 +59,9 @@ class TraktNotifier:
} }
if data is not None: if data is not None:
TraktCall("show/episode/library/%API%", self._api(), self._username(), self._password(), data) TraktCall('show/episode/library/%API%', self._api(), self._username(), self._password(), data)
if sickbeard.TRAKT_REMOVE_WATCHLIST: if sickbeard.TRAKT_REMOVE_WATCHLIST:
TraktCall("show/episode/unwatchlist/%API%", self._api(), self._username(), self._password(), data) TraktCall('show/episode/unwatchlist/%API%', self._api(), self._username(), self._password(), data)
if sickbeard.TRAKT_REMOVE_SERIESLIST: if sickbeard.TRAKT_REMOVE_SERIESLIST:
data_show = None data_show = None
@ -77,11 +77,11 @@ class TraktNotifier:
] ]
} }
TraktCall("show/unwatchlist/%API%", self._api(), self._username(), self._password(), data) TraktCall('show/unwatchlist/%API%', self._api(), self._username(), self._password(), data)
# Remove all episodes from episode watchlist # Remove all episodes from episode watchlist
# Start by getting all episodes in the watchlist # Start by getting all episodes in the watchlist
watchlist = TraktCall("user/watchlist/episodes.json/%API%/" + sickbeard.TRAKT_USERNAME, sickbeard.TRAKT_API, sickbeard.TRAKT_USERNAME, sickbeard.TRAKT_PASSWORD) watchlist = TraktCall('user/watchlist/episodes.json/%API%/' + sickbeard.TRAKT_USERNAME, sickbeard.TRAKT_API, sickbeard.TRAKT_USERNAME, sickbeard.TRAKT_PASSWORD)
if watchlist is not None: if watchlist is not None:
# Convert watchlist to only contain current show # Convert watchlist to only contain current show
@ -100,7 +100,7 @@ class TraktNotifier:
ep = {'season': episodes['season'], 'episode': episodes['number']} ep = {'season': episodes['season'], 'episode': episodes['number']}
data_show['episodes'].append(ep) data_show['episodes'].append(ep)
if data_show is not None: if data_show is not None:
TraktCall("show/episode/unwatchlist/%API%", sickbeard.TRAKT_API, sickbeard.TRAKT_USERNAME, sickbeard.TRAKT_PASSWORD, data_show) TraktCall('show/episode/unwatchlist/%API%', sickbeard.TRAKT_API, sickbeard.TRAKT_USERNAME, sickbeard.TRAKT_PASSWORD, data_show)
else: else:
logger.log('Failed to get watchlist from trakt. Unable to remove episode from watchlist', logger.log('Failed to get watchlist from trakt. Unable to remove episode from watchlist',
logger.ERROR) logger.ERROR)
@ -117,8 +117,8 @@ class TraktNotifier:
Returns: True if the request succeeded, False otherwise Returns: True if the request succeeded, False otherwise
""" """
data = TraktCall("account/test/%API%", api, username, password) data = TraktCall('account/test/%API%', api, username, password)
if data and data["status"] == "success": if data and data['status'] == 'success':
return True return True
def _username(self): def _username(self):

View file

@ -32,8 +32,8 @@ import lib.pythontwitter as twitter
class TwitterNotifier: class TwitterNotifier:
consumer_key = "vHHtcB6WzpWDG6KYlBMr8g" consumer_key = 'vHHtcB6WzpWDG6KYlBMr8g'
consumer_secret = "zMqq5CB3f8cWKiRO2KzWPTlBanYmV0VYxSXZ0Pxds0E" consumer_secret = 'zMqq5CB3f8cWKiRO2KzWPTlBanYmV0VYxSXZ0Pxds0E'
REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token' REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token'
ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token' ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token'
@ -50,16 +50,16 @@ class TwitterNotifier:
def notify_subtitle_download(self, ep_name, lang): def notify_subtitle_download(self, ep_name, lang):
if sickbeard.TWITTER_NOTIFY_ONSUBTITLEDOWNLOAD: if sickbeard.TWITTER_NOTIFY_ONSUBTITLEDOWNLOAD:
self._notifyTwitter(common.notifyStrings[common.NOTIFY_SUBTITLE_DOWNLOAD] + ' ' + ep_name + ": " + lang) self._notifyTwitter(common.notifyStrings[common.NOTIFY_SUBTITLE_DOWNLOAD] + ' ' + ep_name + ': ' + lang)
def notify_git_update(self, new_version = "??"): def notify_git_update(self, new_version = '??'):
if sickbeard.USE_TWITTER: if sickbeard.USE_TWITTER:
update_text=common.notifyStrings[common.NOTIFY_GIT_UPDATE_TEXT] update_text=common.notifyStrings[common.NOTIFY_GIT_UPDATE_TEXT]
title=common.notifyStrings[common.NOTIFY_GIT_UPDATE] title=common.notifyStrings[common.NOTIFY_GIT_UPDATE]
self._notifyTwitter(title + " - " + update_text + new_version) self._notifyTwitter(title + ' - ' + update_text + new_version)
def test_notify(self): def test_notify(self):
return self._notifyTwitter("This is a test notification from SickGear", force=True) return self._notifyTwitter('This is a test notification from SickGear', force=True)
def _get_authorization(self): def _get_authorization(self):
@ -79,7 +79,7 @@ class TwitterNotifier:
sickbeard.TWITTER_USERNAME = request_token['oauth_token'] sickbeard.TWITTER_USERNAME = request_token['oauth_token']
sickbeard.TWITTER_PASSWORD = request_token['oauth_token_secret'] sickbeard.TWITTER_PASSWORD = request_token['oauth_token_secret']
return self.AUTHORIZATION_URL + "?oauth_token=" + request_token['oauth_token'] return self.AUTHORIZATION_URL + '?oauth_token=' + request_token['oauth_token']
def _get_credentials(self, key): def _get_credentials(self, key):
request_token = {} request_token = {}
@ -123,14 +123,14 @@ class TwitterNotifier:
access_token_key = sickbeard.TWITTER_USERNAME access_token_key = sickbeard.TWITTER_USERNAME
access_token_secret = sickbeard.TWITTER_PASSWORD access_token_secret = sickbeard.TWITTER_PASSWORD
logger.log(u"Sending tweet: " + message, logger.DEBUG) logger.log(u'Sending tweet: ' + message, logger.DEBUG)
api = twitter.Api(username, password, access_token_key, access_token_secret) api = twitter.Api(username, password, access_token_key, access_token_secret)
try: try:
api.PostUpdate(message.encode('utf8')) api.PostUpdate(message.encode('utf8'))
except Exception as e: except Exception as e:
logger.log(u"Error Sending Tweet: " + ex(e), logger.ERROR) logger.log(u'Error Sending Tweet: ' + ex(e), logger.ERROR)
return False return False
return True return True
@ -141,7 +141,7 @@ class TwitterNotifier:
if not sickbeard.USE_TWITTER and not force: if not sickbeard.USE_TWITTER and not force:
return False return False
return self._send_tweet(prefix + ": " + message) return self._send_tweet(prefix + ': ' + message)
notifier = TwitterNotifier notifier = TwitterNotifier

View file

@ -81,7 +81,7 @@ class XBMCNotifier:
socket.setdefaulttimeout(sickbeard.SOCKET_TIMEOUT) socket.setdefaulttimeout(sickbeard.SOCKET_TIMEOUT)
if result: if result:
return result["result"]["version"] return result['result']['version']
else: else:
# fallback to legacy HTTPAPI method # fallback to legacy HTTPAPI method
testCommand = {'command': 'Help'} testCommand = {'command': 'Help'}
@ -92,7 +92,7 @@ class XBMCNotifier:
else: else:
return False return False
def _notify_xbmc(self, message, title="SickGear", host=None, username=None, password=None, force=False): def _notify_xbmc(self, message, title='SickGear', host=None, username=None, password=None, force=False):
"""Internal wrapper for the notify_snatch and notify_download functions """Internal wrapper for the notify_snatch and notify_download functions
Detects JSON-RPC version then branches the logic for either the JSON-RPC or legacy HTTP API methods. Detects JSON-RPC version then branches the logic for either the JSON-RPC or legacy HTTP API methods.
@ -121,34 +121,34 @@ class XBMCNotifier:
# suppress notifications if the notifier is disabled but the notify options are checked # suppress notifications if the notifier is disabled but the notify options are checked
if not sickbeard.USE_XBMC and not force: if not sickbeard.USE_XBMC and not force:
logger.log("Notification for XBMC not enabled, skipping this notification", logger.DEBUG) logger.log('Notification for XBMC not enabled, skipping this notification', logger.DEBUG)
return False return False
result = '' result = ''
for curHost in [x.strip() for x in host.split(",")]: for curHost in [x.strip() for x in host.split(',')]:
logger.log(u"Sending XBMC notification to '" + curHost + "' - " + message, logger.MESSAGE) logger.log(u'Sending XBMC notification to "' + curHost + '" - ' + message, logger.MESSAGE)
xbmcapi = self._get_xbmc_version(curHost, username, password) xbmcapi = self._get_xbmc_version(curHost, username, password)
if xbmcapi: if xbmcapi:
if (xbmcapi <= 4): if (xbmcapi <= 4):
logger.log(u"Detected XBMC version <= 11, using XBMC HTTP API", logger.DEBUG) logger.log(u'Detected XBMC version <= 11, using XBMC HTTP API', logger.DEBUG)
command = {'command': 'ExecBuiltIn', command = {'command': 'ExecBuiltIn',
'parameter': 'Notification(' + title.encode("utf-8") + ',' + message.encode( 'parameter': 'Notification(' + title.encode('utf-8') + ',' + message.encode(
"utf-8") + ')'} 'utf-8') + ')'}
notifyResult = self._send_to_xbmc(command, curHost, username, password) notifyResult = self._send_to_xbmc(command, curHost, username, password)
if notifyResult: if notifyResult:
result += curHost + ':' + str(notifyResult) result += curHost + ':' + str(notifyResult)
else: else:
logger.log(u"Detected XBMC version >= 12, using XBMC JSON API", logger.DEBUG) logger.log(u'Detected XBMC version >= 12, using XBMC JSON API', logger.DEBUG)
command = '{"jsonrpc":"2.0","method":"GUI.ShowNotification","params":{"title":"%s","message":"%s", "image": "%s"},"id":1}' % ( command = '{"jsonrpc":"2.0","method":"GUI.ShowNotification","params":{"title":"%s","message":"%s", "image": "%s"},"id":1}' % (
title.encode("utf-8"), message.encode("utf-8"), self.sb_logo_url) title.encode('utf-8'), message.encode('utf-8'), self.sb_logo_url)
notifyResult = self._send_to_xbmc_json(command, curHost, username, password) notifyResult = self._send_to_xbmc_json(command, curHost, username, password)
if notifyResult.get('result'): if notifyResult.get('result'):
result += curHost + ':' + notifyResult["result"].decode(sickbeard.SYS_ENCODING) result += curHost + ':' + notifyResult['result'].decode(sickbeard.SYS_ENCODING)
else: else:
if sickbeard.XBMC_ALWAYS_ON or force: if sickbeard.XBMC_ALWAYS_ON or force:
logger.log( logger.log(
u"Failed to detect XBMC version for '" + curHost + "', check configuration and try again.", u'Failed to detect XBMC version for "' + curHost + '", check configuration and try again.',
logger.ERROR) logger.ERROR)
result += curHost + ':False' result += curHost + ':False'
@ -168,26 +168,26 @@ class XBMCNotifier:
""" """
logger.log(u"Sending request to update library for XBMC host: '" + host + "'", logger.MESSAGE) logger.log(u'Sending request to update library for XBMC host: "' + host + '"', logger.MESSAGE)
xbmcapi = self._get_xbmc_version(host, sickbeard.XBMC_USERNAME, sickbeard.XBMC_PASSWORD) xbmcapi = self._get_xbmc_version(host, sickbeard.XBMC_USERNAME, sickbeard.XBMC_PASSWORD)
if xbmcapi: if xbmcapi:
if (xbmcapi <= 4): if (xbmcapi <= 4):
# try to update for just the show, if it fails, do full update if enabled # try to update for just the show, if it fails, do full update if enabled
if not self._update_library(host, showName) and sickbeard.XBMC_UPDATE_FULL: if not self._update_library(host, showName) and sickbeard.XBMC_UPDATE_FULL:
logger.log(u"Single show update failed, falling back to full update", logger.WARNING) logger.log(u'Single show update failed, falling back to full update', logger.WARNING)
return self._update_library(host) return self._update_library(host)
else: else:
return True return True
else: else:
# try to update for just the show, if it fails, do full update if enabled # try to update for just the show, if it fails, do full update if enabled
if not self._update_library_json(host, showName) and sickbeard.XBMC_UPDATE_FULL: if not self._update_library_json(host, showName) and sickbeard.XBMC_UPDATE_FULL:
logger.log(u"Single show update failed, falling back to full update", logger.WARNING) logger.log(u'Single show update failed, falling back to full update', logger.WARNING)
return self._update_library_json(host) return self._update_library_json(host)
else: else:
return True return True
else: else:
logger.log(u"Failed to detect XBMC version for '" + host + "', check configuration and try again.", logger.log(u'Failed to detect XBMC version for "' + host + '", check configuration and try again.',
logger.DEBUG) logger.DEBUG)
return False return False
@ -226,7 +226,7 @@ class XBMCNotifier:
command[key] = command[key].encode('utf-8') command[key] = command[key].encode('utf-8')
enc_command = urllib.urlencode(command) enc_command = urllib.urlencode(command)
logger.log(u"XBMC encoded API command: " + enc_command, logger.DEBUG) logger.log(u'XBMC encoded API command: ' + enc_command, logger.DEBUG)
url = 'http://%s/xbmcCmds/xbmcHttp/?%s' % (host, enc_command) url = 'http://%s/xbmcCmds/xbmcHttp/?%s' % (host, enc_command)
try: try:
@ -234,21 +234,21 @@ class XBMCNotifier:
# if we have a password, use authentication # if we have a password, use authentication
if password: if password:
base64string = base64.encodestring('%s:%s' % (username, password))[:-1] base64string = base64.encodestring('%s:%s' % (username, password))[:-1]
authheader = "Basic %s" % base64string authheader = 'Basic %s' % base64string
req.add_header("Authorization", authheader) req.add_header('Authorization', authheader)
logger.log(u"Contacting XBMC (with auth header) via url: " + fixStupidEncodings(url), logger.DEBUG) logger.log(u'Contacting XBMC (with auth header) via url: ' + fixStupidEncodings(url), logger.DEBUG)
else: else:
logger.log(u"Contacting XBMC via url: " + fixStupidEncodings(url), logger.DEBUG) logger.log(u'Contacting XBMC via url: ' + fixStupidEncodings(url), logger.DEBUG)
response = urllib2.urlopen(req) response = urllib2.urlopen(req)
result = response.read().decode(sickbeard.SYS_ENCODING) result = response.read().decode(sickbeard.SYS_ENCODING)
response.close() response.close()
logger.log(u"XBMC HTTP response: " + result.replace('\n', ''), logger.DEBUG) logger.log(u'XBMC HTTP response: ' + result.replace('\n', ''), logger.DEBUG)
return result return result
except (urllib2.URLError, IOError) as e: except (urllib2.URLError, IOError) as e:
logger.log(u"Warning: Couldn't contact XBMC HTTP at " + fixStupidEncodings(url) + " " + ex(e), logger.log(u"Warning: Couldn't contact XBMC HTTP at " + fixStupidEncodings(url) + ' ' + ex(e),
logger.WARNING) logger.WARNING)
return False return False
@ -271,11 +271,11 @@ class XBMCNotifier:
logger.log(u'No XBMC host passed, aborting update', logger.DEBUG) logger.log(u'No XBMC host passed, aborting update', logger.DEBUG)
return False return False
logger.log(u"Updating XMBC library via HTTP method for host: " + host, logger.DEBUG) logger.log(u'Updating XMBC library via HTTP method for host: ' + host, logger.DEBUG)
# if we're doing per-show # if we're doing per-show
if showName: if showName:
logger.log(u"Updating library in XBMC via HTTP method for show " + showName, logger.DEBUG) logger.log(u'Updating library in XBMC via HTTP method for show ' + showName, logger.DEBUG)
pathSql = 'select path.strPath from path, tvshow, tvshowlinkpath where ' \ pathSql = 'select path.strPath from path, tvshow, tvshowlinkpath where ' \
'tvshow.c00 = "%s" and tvshowlinkpath.idShow = tvshow.idShow ' \ 'tvshow.c00 = "%s" and tvshowlinkpath.idShow = tvshow.idShow ' \
@ -298,30 +298,30 @@ class XBMCNotifier:
request = self._send_to_xbmc(resetCommand, host) request = self._send_to_xbmc(resetCommand, host)
if not sqlXML: if not sqlXML:
logger.log(u"Invalid response for " + showName + " on " + host, logger.DEBUG) logger.log(u'Invalid response for ' + showName + ' on ' + host, logger.DEBUG)
return False return False
encSqlXML = urllib.quote(sqlXML, ':\\/<>') encSqlXML = urllib.quote(sqlXML, ':\\/<>')
try: try:
et = etree.fromstring(encSqlXML) et = etree.fromstring(encSqlXML)
except SyntaxError as e: except SyntaxError as e:
logger.log(u"Unable to parse XML returned from XBMC: " + ex(e), logger.ERROR) logger.log(u'Unable to parse XML returned from XBMC: ' + ex(e), logger.ERROR)
return False return False
paths = et.findall('.//field') paths = et.findall('.//field')
if not paths: if not paths:
logger.log(u"No valid paths found for " + showName + " on " + host, logger.DEBUG) logger.log(u'No valid paths found for ' + showName + ' on ' + host, logger.DEBUG)
return False return False
for path in paths: for path in paths:
# we do not need it double-encoded, gawd this is dumb # we do not need it double-encoded, gawd this is dumb
unEncPath = urllib.unquote(path.text).decode(sickbeard.SYS_ENCODING) unEncPath = urllib.unquote(path.text).decode(sickbeard.SYS_ENCODING)
logger.log(u"XBMC Updating " + showName + " on " + host + " at " + unEncPath, logger.DEBUG) logger.log(u'XBMC Updating ' + showName + ' on ' + host + ' at ' + unEncPath, logger.DEBUG)
updateCommand = {'command': 'ExecBuiltIn', 'parameter': 'XBMC.updatelibrary(video, %s)' % (unEncPath)} updateCommand = {'command': 'ExecBuiltIn', 'parameter': 'XBMC.updatelibrary(video, %s)' % (unEncPath)}
request = self._send_to_xbmc(updateCommand, host) request = self._send_to_xbmc(updateCommand, host)
if not request: if not request:
logger.log(u"Update of show directory failed on " + showName + " on " + host + " at " + unEncPath, logger.log(u'Update of show directory failed on ' + showName + ' on ' + host + ' at ' + unEncPath,
logger.ERROR) logger.ERROR)
return False return False
# sleep for a few seconds just to be sure xbmc has a chance to finish each directory # sleep for a few seconds just to be sure xbmc has a chance to finish each directory
@ -329,12 +329,12 @@ class XBMCNotifier:
time.sleep(5) time.sleep(5)
# do a full update if requested # do a full update if requested
else: else:
logger.log(u"Doing Full Library XBMC update on host: " + host, logger.MESSAGE) logger.log(u'Doing Full Library XBMC update on host: ' + host, logger.MESSAGE)
updateCommand = {'command': 'ExecBuiltIn', 'parameter': 'XBMC.updatelibrary(video)'} updateCommand = {'command': 'ExecBuiltIn', 'parameter': 'XBMC.updatelibrary(video)'}
request = self._send_to_xbmc(updateCommand, host) request = self._send_to_xbmc(updateCommand, host)
if not request: if not request:
logger.log(u"XBMC Full Library update failed on: " + host, logger.ERROR) logger.log(u'XBMC Full Library update failed on: ' + host, logger.ERROR)
return False return False
return True return True
@ -368,25 +368,25 @@ class XBMCNotifier:
return False return False
command = command.encode('utf-8') command = command.encode('utf-8')
logger.log(u"XBMC JSON command: " + command, logger.DEBUG) logger.log(u'XBMC JSON command: ' + command, logger.DEBUG)
url = 'http://%s/jsonrpc' % (host) url = 'http://%s/jsonrpc' % (host)
try: try:
req = urllib2.Request(url, command) req = urllib2.Request(url, command)
req.add_header("Content-type", "application/json") req.add_header('Content-type', 'application/json')
# if we have a password, use authentication # if we have a password, use authentication
if password: if password:
base64string = base64.encodestring('%s:%s' % (username, password))[:-1] base64string = base64.encodestring('%s:%s' % (username, password))[:-1]
authheader = "Basic %s" % base64string authheader = 'Basic %s' % base64string
req.add_header("Authorization", authheader) req.add_header('Authorization', authheader)
logger.log(u"Contacting XBMC (with auth header) via url: " + fixStupidEncodings(url), logger.DEBUG) logger.log(u'Contacting XBMC (with auth header) via url: ' + fixStupidEncodings(url), logger.DEBUG)
else: else:
logger.log(u"Contacting XBMC via url: " + fixStupidEncodings(url), logger.DEBUG) logger.log(u'Contacting XBMC via url: ' + fixStupidEncodings(url), logger.DEBUG)
try: try:
response = urllib2.urlopen(req) response = urllib2.urlopen(req)
except urllib2.URLError as e: except urllib2.URLError as e:
logger.log(u"Error while trying to retrieve XBMC API version for " + host + ": " + ex(e), logger.log(u'Error while trying to retrieve XBMC API version for ' + host + ': ' + ex(e),
logger.WARNING) logger.WARNING)
return False return False
@ -394,14 +394,14 @@ class XBMCNotifier:
try: try:
result = json.load(response) result = json.load(response)
response.close() response.close()
logger.log(u"XBMC JSON response: " + str(result), logger.DEBUG) logger.log(u'XBMC JSON response: ' + str(result), logger.DEBUG)
return result # need to return response for parsing return result # need to return response for parsing
except ValueError as e: except ValueError as e:
logger.log(u"Unable to decode JSON: " + response, logger.WARNING) logger.log(u'Unable to decode JSON: ' + response, logger.WARNING)
return False return False
except IOError as e: except IOError as e:
logger.log(u"Warning: Couldn't contact XBMC JSON API at " + fixStupidEncodings(url) + " " + ex(e), logger.log(u"Warning: Couldn't contact XBMC JSON API at " + fixStupidEncodings(url) + ' ' + ex(e),
logger.WARNING) logger.WARNING)
return False return False
@ -424,26 +424,26 @@ class XBMCNotifier:
logger.log(u'No XBMC host passed, aborting update', logger.DEBUG) logger.log(u'No XBMC host passed, aborting update', logger.DEBUG)
return False return False
logger.log(u"Updating XMBC library via JSON method for host: " + host, logger.MESSAGE) logger.log(u'Updating XMBC library via JSON method for host: ' + host, logger.MESSAGE)
# if we're doing per-show # if we're doing per-show
if showName: if showName:
tvshowid = -1 tvshowid = -1
logger.log(u"Updating library in XBMC via JSON method for show " + showName, logger.DEBUG) logger.log(u'Updating library in XBMC via JSON method for show ' + showName, logger.DEBUG)
# get tvshowid by showName # get tvshowid by showName
showsCommand = '{"jsonrpc":"2.0","method":"VideoLibrary.GetTVShows","id":1}' showsCommand = '{"jsonrpc":"2.0","method":"VideoLibrary.GetTVShows","id":1}'
showsResponse = self._send_to_xbmc_json(showsCommand, host) showsResponse = self._send_to_xbmc_json(showsCommand, host)
if showsResponse and "result" in showsResponse and "tvshows" in showsResponse["result"]: if showsResponse and 'result' in showsResponse and 'tvshows' in showsResponse['result']:
shows = showsResponse["result"]["tvshows"] shows = showsResponse['result']['tvshows']
else: else:
logger.log(u"XBMC: No tvshows in XBMC TV show list", logger.DEBUG) logger.log(u'XBMC: No tvshows in XBMC TV show list', logger.DEBUG)
return False return False
for show in shows: for show in shows:
if (show["label"] == showName): if (show['label'] == showName):
tvshowid = show["tvshowid"] tvshowid = show['tvshowid']
break # exit out of loop otherwise the label and showname will not match up break # exit out of loop otherwise the label and showname will not match up
# this can be big, so free some memory # this can be big, so free some memory
@ -459,21 +459,21 @@ class XBMCNotifier:
tvshowid) tvshowid)
pathResponse = self._send_to_xbmc_json(pathCommand, host) pathResponse = self._send_to_xbmc_json(pathCommand, host)
path = pathResponse["result"]["tvshowdetails"]["file"] path = pathResponse['result']['tvshowdetails']['file']
logger.log(u"Received Show: " + showName + " with ID: " + str(tvshowid) + " Path: " + path, logger.log(u'Received Show: ' + showName + ' with ID: ' + str(tvshowid) + ' Path: ' + path,
logger.DEBUG) logger.DEBUG)
if (len(path) < 1): if (len(path) < 1):
logger.log(u"No valid path found for " + showName + " with ID: " + str(tvshowid) + " on " + host, logger.log(u'No valid path found for ' + showName + ' with ID: ' + str(tvshowid) + ' on ' + host,
logger.WARNING) logger.WARNING)
return False return False
logger.log(u"XBMC Updating " + showName + " on " + host + " at " + path, logger.DEBUG) logger.log(u'XBMC Updating ' + showName + ' on ' + host + ' at ' + path, logger.DEBUG)
updateCommand = '{"jsonrpc":"2.0","method":"VideoLibrary.Scan","params":{"directory":%s},"id":1}' % ( updateCommand = '{"jsonrpc":"2.0","method":"VideoLibrary.Scan","params":{"directory":%s},"id":1}' % (
json.dumps(path)) json.dumps(path))
request = self._send_to_xbmc_json(updateCommand, host) request = self._send_to_xbmc_json(updateCommand, host)
if not request: if not request:
logger.log(u"Update of show directory failed on " + showName + " on " + host + " at " + path, logger.log(u'Update of show directory failed on ' + showName + ' on ' + host + ' at ' + path,
logger.ERROR) logger.ERROR)
return False return False
@ -481,18 +481,18 @@ class XBMCNotifier:
for r in request: for r in request:
if 'error' in r: if 'error' in r:
logger.log( logger.log(
u"Error while attempting to update show directory for " + showName + " on " + host + " at " + path, u'Error while attempting to update show directory for ' + showName + ' on ' + host + ' at ' + path,
logger.ERROR) logger.ERROR)
return False return False
# do a full update if requested # do a full update if requested
else: else:
logger.log(u"Doing Full Library XBMC update on host: " + host, logger.MESSAGE) logger.log(u'Doing Full Library XBMC update on host: ' + host, logger.MESSAGE)
updateCommand = '{"jsonrpc":"2.0","method":"VideoLibrary.Scan","id":1}' updateCommand = '{"jsonrpc":"2.0","method":"VideoLibrary.Scan","id":1}'
request = self._send_to_xbmc_json(updateCommand, host, sickbeard.XBMC_USERNAME, sickbeard.XBMC_PASSWORD) request = self._send_to_xbmc_json(updateCommand, host, sickbeard.XBMC_USERNAME, sickbeard.XBMC_PASSWORD)
if not request: if not request:
logger.log(u"XBMC Full Library update failed on: " + host, logger.ERROR) logger.log(u'XBMC Full Library update failed on: ' + host, logger.ERROR)
return False return False
return True return True
@ -511,16 +511,16 @@ class XBMCNotifier:
def notify_subtitle_download(self, ep_name, lang): def notify_subtitle_download(self, ep_name, lang):
if sickbeard.XBMC_NOTIFY_ONSUBTITLEDOWNLOAD: if sickbeard.XBMC_NOTIFY_ONSUBTITLEDOWNLOAD:
self._notify_xbmc(ep_name + ": " + lang, common.notifyStrings[common.NOTIFY_SUBTITLE_DOWNLOAD]) self._notify_xbmc(ep_name + ': ' + lang, common.notifyStrings[common.NOTIFY_SUBTITLE_DOWNLOAD])
def notify_git_update(self, new_version = "??"): def notify_git_update(self, new_version = '??'):
if sickbeard.USE_XBMC: if sickbeard.USE_XBMC:
update_text=common.notifyStrings[common.NOTIFY_GIT_UPDATE_TEXT] update_text=common.notifyStrings[common.NOTIFY_GIT_UPDATE_TEXT]
title=common.notifyStrings[common.NOTIFY_GIT_UPDATE] title=common.notifyStrings[common.NOTIFY_GIT_UPDATE]
self._notify_xbmc(update_text + new_version, title) self._notify_xbmc(update_text + new_version, title)
def test_notify(self, host, username, password): def test_notify(self, host, username, password):
return self._notify_xbmc("Testing XBMC notifications from SickGear", "Test Notification", host, username, return self._notify_xbmc('Testing XBMC notifications from SickGear', 'Test Notification', host, username,
password, force=True) password, force=True)
def update_library(self, showName=None): def update_library(self, showName=None):
@ -541,21 +541,21 @@ class XBMCNotifier:
if sickbeard.USE_XBMC and sickbeard.XBMC_UPDATE_LIBRARY: if sickbeard.USE_XBMC and sickbeard.XBMC_UPDATE_LIBRARY:
if not sickbeard.XBMC_HOST: if not sickbeard.XBMC_HOST:
logger.log(u"No XBMC hosts specified, check your settings", logger.DEBUG) logger.log(u'No XBMC hosts specified, check your settings', logger.DEBUG)
return False return False
# either update each host, or only attempt to update until one successful result # either update each host, or only attempt to update until one successful result
result = 0 result = 0
for host in [x.strip() for x in sickbeard.XBMC_HOST.split(",")]: for host in [x.strip() for x in sickbeard.XBMC_HOST.split(',')]:
if self._send_update_library(host, showName): if self._send_update_library(host, showName):
if sickbeard.XBMC_UPDATE_ONLYFIRST: if sickbeard.XBMC_UPDATE_ONLYFIRST:
logger.log(u"Successfully updated '" + host + "', stopped sending update library commands.", logger.log(u'Successfully updated "' + host + '", stopped sending update library commands.',
logger.DEBUG) logger.DEBUG)
return True return True
else: else:
if sickbeard.XBMC_ALWAYS_ON: if sickbeard.XBMC_ALWAYS_ON:
logger.log( logger.log(
u"Failed to detect XBMC version for '" + host + "', check configuration and try again.", u'Failed to detect XBMC version for "' + host + '", check configuration and try again.',
logger.ERROR) logger.ERROR)
result = result + 1 result = result + 1