SickGear/sickbeard/notifiers/emailnotify.py

184 lines
6.7 KiB
Python
Raw Normal View History

# Authors:
# Derek Battams <derek@battams.ca>
# Pedro Jose Pereira Vieito (@pvieito) <pvieito@gmail.com>
#
# URL: https://github.com/sickgear/sickgear
#
# This file is part of SickGear.
#
# SickGear is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# SickGear is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with SickGear. If not, see <http://www.gnu.org/licenses/>.
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formatdate
import re
2016-01-17 18:50:26 +00:00
import smtplib
import sickbeard
from sickbeard import db
from sickbeard.notifiers.generic import Notifier, notify_strings
class EmailNotifier(Notifier):
2016-01-17 18:50:26 +00:00
def __init__(self):
super(EmailNotifier, self).__init__()
2016-01-17 18:50:26 +00:00
self.last_err = None
def _sendmail(self, host, port, smtp_from, use_tls, user, pwd, to, msg, smtp_debug=False):
2016-01-17 18:50:26 +00:00
use_tls = 1 == sickbeard.helpers.tryInt(use_tls)
login = any(user) and any(pwd)
self._log_debug(u'Sendmail HOST: %s; PORT: %s; LOGIN: %s, TLS: %s, USER: %s, FROM: %s, TO: %s' % (
host, port, login, use_tls, user, smtp_from, to))
try:
srv = smtplib.SMTP(host, int(port))
if smtp_debug:
srv.set_debuglevel(1)
2016-01-17 18:50:26 +00:00
if use_tls or login:
srv.ehlo()
self._log_debug(u'Sent initial EHLO command')
if use_tls:
srv.starttls()
srv.ehlo()
self._log_debug(u'Sent STARTTLS and EHLO command')
if login:
srv.login(user, pwd)
self._log_debug(u'Sent LOGIN command')
srv.sendmail(smtp_from, to, msg.as_string())
srv.quit()
except Exception as e:
self.last_err = '%s' % e
return False
return True
@staticmethod
def _get_recipients(show_name=None):
email_list = []
# Grab the global recipients
if sickbeard.EMAIL_LIST:
for email_address in sickbeard.EMAIL_LIST.split(','):
if any(email_address.strip()):
email_list.append(email_address)
# Grab the recipients for the show
if None is not show_name:
my_db = db.DBConnection()
for result in my_db.select('SELECT notify_list FROM tv_shows WHERE show_name = ?', (show_name,)):
if result['notify_list']:
for email_address in result['notify_list'].split(','):
if any(email_address.strip()):
email_list.append(email_address)
return list(set(email_list))
2016-01-17 18:50:26 +00:00
def _notify(self, title, body, lang='', extra='', **kwargs):
show = body.split(' - ')[0]
2016-01-23 23:39:50 +00:00
to = self._get_recipients(show)
2016-01-17 18:50:26 +00:00
if not any(to):
self._log_warning(u'No email recipients to notify, skipping')
2016-01-17 18:50:26 +00:00
return
self._log_debug(u'Email recipients to notify: %s' % to)
2016-01-23 23:39:50 +00:00
2016-01-17 18:50:26 +00:00
try:
msg = MIMEMultipart('alternative')
msg.attach(MIMEText(
'<body style="font-family:Helvetica, Arial, sans-serif;">' +
'<h3>SickGear Notification - %s</h3>\n' % title +
2016-01-23 23:39:50 +00:00
'<p>Show: <b>' + show.encode('ascii', 'xmlcharrefreplace') +
'</b></p>\n<p>Episode: <b>' +
unicode(re.search('.+ - (.+?-.+) -.+', body).group(1)).encode('ascii', 'xmlcharrefreplace') +
2016-01-17 18:50:26 +00:00
extra +
'</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'))
except (StandardError, Exception):
2016-01-17 18:50:26 +00:00
try:
msg = MIMEText(body)
except (StandardError, Exception):
2016-01-17 18:50:26 +00:00
msg = MIMEText('Episode %s' % title)
msg['Subject'] = '%s%s: %s' % (lang, title, body)
2016-01-17 18:50:26 +00:00
msg['From'] = sickbeard.EMAIL_FROM
msg['To'] = ','.join(to)
msg['Date'] = formatdate(localtime=True)
if self._sendmail(sickbeard.EMAIL_HOST, sickbeard.EMAIL_PORT, sickbeard.EMAIL_FROM, sickbeard.EMAIL_TLS,
sickbeard.EMAIL_USER, sickbeard.EMAIL_PASSWORD, to, msg):
self._log_debug(u'%s notification sent to [%s] for "%s"' % (title, to, body))
2016-01-17 18:50:26 +00:00
else:
self._log_error(u'%s notification ERROR: %s' % (title, self.last_err))
def test_notify(self, host, port, smtp_from, use_tls, user, pwd, to):
self._testing = True
msg = MIMEText('Success. This is a SickGear test message. Typically sent on, %s' % notify_strings['download'])
msg['Subject'] = 'SickGear: Test message'
msg['From'] = smtp_from
msg['To'] = to
msg['Date'] = formatdate(localtime=True)
2016-01-17 18:50:26 +00:00
r = self._sendmail(host, port, smtp_from, use_tls, user, pwd, [to], msg, True)
return self._choose(('Success, notification sent.',
'Failed to send notification: %s' % self.last_err)[not r], r)
def notify_snatch(self, ep_name, title=None):
"""
Send a notification that an episode was snatched
2016-01-17 18:50:26 +00:00
:param ep_name: The name of the episode that was snatched
:param title: The title of the notification (optional)
"""
Fixed issues with editing/saving custom scene exceptions. Fixed charmap issues for anime show names. Fixed issues with display show page and epCat key errors. Fixed duplicate log messages for clearing provider caches. Fixed issues with email notifier ep names not properly being encoded to UTF-8. TVDB<->TVRAGE Indexer ID mapping is now performed on demand to be used when needed such as newznab providers can be searched with tvrage_id's and some will return tvrage_id's that later can be used to create show objects from for faster and more accurate name parsing, mapping is done via Trakt API calls. Added stop event signals to schedualed tasks, SR now waits indefinate till task has been fully stopped before completing a restart or shutdown event. NameParserCache is now persistent and stores 200 parsed results at any given time for quicker lookups and better performance, this helps maintain results between updates or shutdown/startup events. Black and White lists for anime now only get used for anime shows as intended, performance gain for non-anime shows that dont need to load these lists. Internal name cache now builds it self on demand when needed per show request plus checks if show is already in cache and if true exits routine to save time. Schedualer and QueueItems classes are now a sub-class of threading.Thread and a stop threading event signal has been added to each. If I forgot to list something it doesn't mean its not fixed so please test and report back if anything is wrong or has been corrected by this new release.
2014-07-15 02:00:53 +00:00
title = sickbeard.EMAIL_OLD_SUBJECTS and 'Snatched' or title or notify_strings['snatch']
self._notify(title, ep_name)
2016-01-17 18:50:26 +00:00
def notify_download(self, ep_name, title=None):
"""
Send a notification that an episode was downloaded
2016-01-17 18:50:26 +00:00
:param ep_name: The name of the episode that was downloaded
:param title: The title of the notification (optional)
"""
Fixed issues with editing/saving custom scene exceptions. Fixed charmap issues for anime show names. Fixed issues with display show page and epCat key errors. Fixed duplicate log messages for clearing provider caches. Fixed issues with email notifier ep names not properly being encoded to UTF-8. TVDB<->TVRAGE Indexer ID mapping is now performed on demand to be used when needed such as newznab providers can be searched with tvrage_id's and some will return tvrage_id's that later can be used to create show objects from for faster and more accurate name parsing, mapping is done via Trakt API calls. Added stop event signals to schedualed tasks, SR now waits indefinate till task has been fully stopped before completing a restart or shutdown event. NameParserCache is now persistent and stores 200 parsed results at any given time for quicker lookups and better performance, this helps maintain results between updates or shutdown/startup events. Black and White lists for anime now only get used for anime shows as intended, performance gain for non-anime shows that dont need to load these lists. Internal name cache now builds it self on demand when needed per show request plus checks if show is already in cache and if true exits routine to save time. Schedualer and QueueItems classes are now a sub-class of threading.Thread and a stop threading event signal has been added to each. If I forgot to list something it doesn't mean its not fixed so please test and report back if anything is wrong or has been corrected by this new release.
2014-07-15 02:00:53 +00:00
title = sickbeard.EMAIL_OLD_SUBJECTS and 'Downloaded' or title or notify_strings['download']
self._notify(title, ep_name)
2016-01-17 18:50:26 +00:00
def notify_subtitle_download(self, ep_name, lang, title=None):
"""
2016-01-17 18:50:26 +00:00
Send a notification that a subtitle was downloaded
2016-01-17 18:50:26 +00:00
:param ep_name: The name of the episode that was downloaded
:param lang: Subtitle language
:param title: The title of the notification (optional)
"""
Fixed issues with editing/saving custom scene exceptions. Fixed charmap issues for anime show names. Fixed issues with display show page and epCat key errors. Fixed duplicate log messages for clearing provider caches. Fixed issues with email notifier ep names not properly being encoded to UTF-8. TVDB<->TVRAGE Indexer ID mapping is now performed on demand to be used when needed such as newznab providers can be searched with tvrage_id's and some will return tvrage_id's that later can be used to create show objects from for faster and more accurate name parsing, mapping is done via Trakt API calls. Added stop event signals to schedualed tasks, SR now waits indefinate till task has been fully stopped before completing a restart or shutdown event. NameParserCache is now persistent and stores 200 parsed results at any given time for quicker lookups and better performance, this helps maintain results between updates or shutdown/startup events. Black and White lists for anime now only get used for anime shows as intended, performance gain for non-anime shows that dont need to load these lists. Internal name cache now builds it self on demand when needed per show request plus checks if show is already in cache and if true exits routine to save time. Schedualer and QueueItems classes are now a sub-class of threading.Thread and a stop threading event signal has been added to each. If I forgot to list something it doesn't mean its not fixed so please test and report back if anything is wrong or has been corrected by this new release.
2014-07-15 02:00:53 +00:00
title = sickbeard.EMAIL_OLD_SUBJECTS and 'Subtitle Downloaded' or title or notify_strings['subtitle_download']
self._notify(title, ep_name, '%s ' % lang, '</b></p>\n<p>Language: <b>%s' % lang)
2016-01-17 18:50:26 +00:00
notifier = EmailNotifier