Add posters and HTML support for Telegram

This commit is contained in:
JonnyWong16 2016-05-03 00:39:24 -07:00
parent 4043398e01
commit 65de742f96
3 changed files with 61 additions and 16 deletions

View file

@ -380,6 +380,8 @@ _CONFIG_DEFINITIONS = {
'TELEGRAM_BOT_TOKEN': (str, 'Telegram', ''), 'TELEGRAM_BOT_TOKEN': (str, 'Telegram', ''),
'TELEGRAM_ENABLED': (int, 'Telegram', 0), 'TELEGRAM_ENABLED': (int, 'Telegram', 0),
'TELEGRAM_CHAT_ID': (str, 'Telegram', ''), 'TELEGRAM_CHAT_ID': (str, 'Telegram', ''),
'TELEGRAM_HTML_SUPPORT': (int, 'Telegram', 1),
'TELEGRAM_INCL_POSTER': (int, 'Telegram', 0),
'TELEGRAM_INCL_SUBJECT': (int, 'Telegram', 1), 'TELEGRAM_INCL_SUBJECT': (int, 'Telegram', 1),
'TELEGRAM_ON_PLAY': (int, 'Telegram', 0), 'TELEGRAM_ON_PLAY': (int, 'Telegram', 0),
'TELEGRAM_ON_STOP': (int, 'Telegram', 0), 'TELEGRAM_ON_STOP': (int, 'Telegram', 0),

View file

@ -624,14 +624,17 @@ def build_notify_text(session=None, timeline=None, notify_action=None, agent_id=
if not poster_url and plexpy.CONFIG.NOTIFY_UPLOAD_POSTERS: if not poster_url and plexpy.CONFIG.NOTIFY_UPLOAD_POSTERS:
try: try:
thread_name = str(threading.current_thread().ident) thread_name = str(threading.current_thread().ident)
poster_file = os.path.join(plexpy.CONFIG.CACHE_DIR, 'cache-poster-' + thread_name)
# Retrieve the poster from Plex and cache to file # Retrieve the poster from Plex and cache to file
urllib.urlretrieve(plexpy.CONFIG.PMS_URL + thumb + '?X-Plex-Token=' + plexpy.CONFIG.PMS_TOKEN, urllib.urlretrieve(plexpy.CONFIG.PMS_URL + thumb + '?X-Plex-Token=' + plexpy.CONFIG.PMS_TOKEN,
os.path.join(plexpy.CONFIG.CACHE_DIR, 'cache-poster-'+thread_name+'.jpg')) poster_file)
# Upload thumb to Imgur and get link # Upload thumb to Imgur and get link
poster_url = helpers.uploadToImgur(os.path.join(plexpy.CONFIG.CACHE_DIR, poster_url = helpers.uploadToImgur(poster_file, poster_title)
'cache-poster-'+thread_name+'.jpg'), poster_title)
# Delete the cached poster # Delete the cached poster
os.remove(os.path.join(plexpy.CONFIG.CACHE_DIR, 'cache-poster-'+thread_name+'.jpg')) os.remove(poster_file)
except Exception as e: except Exception as e:
logger.error(u"PlexPy Notifier :: Unable to retrieve poster for rating_key %s: %s." % (str(rating_key), e)) logger.error(u"PlexPy Notifier :: Unable to retrieve poster for rating_key %s: %s." % (str(rating_key), e))
@ -1106,6 +1109,10 @@ def strip_tag(data, agent_id=None):
if agent_id == 7: if agent_id == 7:
p = re.compile(r'<(?!/?(b>|i>|u>)|(a\shref=\"[^\"\'\s]+\"|/a>|font\scolor=\"[^\"\'\s]+\"|/font>)).*?>', p = re.compile(r'<(?!/?(b>|i>|u>)|(a\shref=\"[^\"\'\s]+\"|/a>|font\scolor=\"[^\"\'\s]+\"|/font>)).*?>',
re.IGNORECASE | re.DOTALL) re.IGNORECASE | re.DOTALL)
# Allow tags b, i, code, pre, a[href] for Telegram
elif agent_id == 13:
p = re.compile(r'<(?!/?(b>|i>|code>|pre>)|(a\shref=\"[^\"\'\s]+\"|/a>)).*?>',
re.IGNORECASE | re.DOTALL)
else: else:
p = re.compile(r'<.*?>', re.IGNORECASE | re.DOTALL) p = re.compile(r'<.*?>', re.IGNORECASE | re.DOTALL)

View file

@ -21,6 +21,7 @@ from email.mime.text import MIMEText
import email.utils import email.utils
from httplib import HTTPSConnection from httplib import HTTPSConnection
import os import os
import requests
import shlex import shlex
import smtplib import smtplib
import subprocess import subprocess
@ -481,7 +482,7 @@ def send_notification(agent_id, subject, body, notify_action, **kwargs):
iftttClient.notify(subject=subject, message=body, action=notify_action) iftttClient.notify(subject=subject, message=body, action=notify_action)
elif agent_id == 13: elif agent_id == 13:
telegramClient = TELEGRAM() telegramClient = TELEGRAM()
telegramClient.notify(message=body, event=subject) telegramClient.notify(message=body, event=subject, **kwargs)
elif agent_id == 14: elif agent_id == 14:
slackClient = SLACK() slackClient = SLACK()
slackClient.notify(message=body, event=subject) slackClient.notify(message=body, event=subject)
@ -1175,7 +1176,7 @@ class PUSHOVER(object):
{'label': 'Enable HTML Support', {'label': 'Enable HTML Support',
'value': self.html_support, 'value': self.html_support,
'name': 'pushover_html_support', 'name': 'pushover_html_support',
'description': 'Style your messages using these HTML Tags: b, i, u, a[href], font[color]', 'description': 'Style your messages using these HTML tags: b, i, u, a[href], font[color]',
'input_type': 'checkbox' 'input_type': 'checkbox'
} }
] ]
@ -1668,29 +1669,52 @@ class TELEGRAM(object):
self.enabled = plexpy.CONFIG.TELEGRAM_ENABLED self.enabled = plexpy.CONFIG.TELEGRAM_ENABLED
self.bot_token = plexpy.CONFIG.TELEGRAM_BOT_TOKEN self.bot_token = plexpy.CONFIG.TELEGRAM_BOT_TOKEN
self.chat_id = plexpy.CONFIG.TELEGRAM_CHAT_ID self.chat_id = plexpy.CONFIG.TELEGRAM_CHAT_ID
self.html_support = plexpy.CONFIG.TELEGRAM_HTML_SUPPORT
self.incl_poster = plexpy.CONFIG.TELEGRAM_INCL_POSTER
self.incl_subject = plexpy.CONFIG.TELEGRAM_INCL_SUBJECT self.incl_subject = plexpy.CONFIG.TELEGRAM_INCL_SUBJECT
def conf(self, options): def conf(self, options):
return cherrypy.config['config'].get('Telegram', options) return cherrypy.config['config'].get('Telegram', options)
def notify(self, message, event): def notify(self, message, event, **kwargs):
if not message or not event: if not message or not event:
return return
http_handler = HTTPSConnection("api.telegram.org") data = {'chat_id': self.chat_id}
if self.incl_subject: if self.incl_subject:
text = event.encode('utf-8') + ': ' + message.encode("utf-8") text = event.encode('utf-8') + ': ' + message.encode('utf-8')
else: else:
text = message.encode("utf-8") text = message.encode('utf-8')
data = {'chat_id': self.chat_id, if self.incl_poster and 'metadata' in kwargs:
'text': text} metadata = kwargs['metadata']
poster_url = metadata.get('poster_url','')
http_handler.request("POST", if poster_url:
"/bot%s/%s" % (self.bot_token, "sendMessage"), files = {'photo': (poster_url, urllib.urlopen(poster_url).read())}
headers={'Content-type': "application/x-www-form-urlencoded"}, response = requests.post('https://api.telegram.org/bot%s/%s' % (self.bot_token, 'sendPhoto'),
body=urlencode(data)) data=data,
files=files)
request_status = response.status_code
request_content = json.loads(response.text)
if request_status == 200:
logger.info(u"PlexPy Notifiers :: Telegram poster sent.")
elif request_status >= 400 and request_status < 500:
logger.warn(u"PlexPy Notifiers :: Telegram poster failed: %s" % request_content.get('description'))
else:
logger.warn(u"PlexPy Notifiers :: Telegram poster failed.")
data['text'] = text
if self.html_support:
data['parse_mode'] = 'HTML'
http_handler = HTTPSConnection("api.telegram.org")
http_handler.request('POST',
'/bot%s/%s' % (self.bot_token, 'sendMessage'),
headers={'Content-type': 'application/x-www-form-urlencoded'},
body=urlencode(data))
response = http_handler.getresponse() response = http_handler.getresponse()
request_status = response.status request_status = response.status
@ -1733,11 +1757,23 @@ class TELEGRAM(object):
' on Telegram to get an ID.', ' on Telegram to get an ID.',
'input_type': 'text' 'input_type': 'text'
}, },
{'label': 'Include Poster Image',
'value': self.incl_poster,
'name': 'telegram_incl_poster',
'description': 'Include a poster with the notifications.',
'input_type': 'checkbox'
},
{'label': 'Include Subject Line', {'label': 'Include Subject Line',
'value': self.incl_subject, 'value': self.incl_subject,
'name': 'telegram_incl_subject', 'name': 'telegram_incl_subject',
'description': 'Include the subject line with the notifications.', 'description': 'Include the subject line with the notifications.',
'input_type': 'checkbox' 'input_type': 'checkbox'
},
{'label': 'Enable HTML Support',
'value': self.html_support,
'name': 'telegram_html_support',
'description': 'Style your messages using these HTML tags: b, i, a[href], code, pre',
'input_type': 'checkbox'
} }
] ]