Send comment by email via SRMail

This commit is contained in:
Yax 2015-05-16 18:12:18 +02:00
parent 692b90d7d9
commit 033e0821b2
5 changed files with 78 additions and 68 deletions

View file

@ -10,6 +10,7 @@ class Site(Model):
name = CharField(unique=True) name = CharField(unique=True)
url = CharField() url = CharField()
token = CharField() token = CharField()
admin_email = CharField()
class Meta: class Meta:
database = get_db() database = get_db()

View file

@ -10,6 +10,9 @@ import chardet
from jinja2 import Environment, FileSystemLoader from jinja2 import Environment, FileSystemLoader
from app.models.site import Site from app.models.site import Site
from app.models.comment import Comment from app.models.comment import Comment
import requests
import json
import config
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -28,59 +31,71 @@ class Processor(Thread):
self.is_running = True self.is_running = True
while self.is_running: while self.is_running:
msg = queue.get() try:
if msg['request'] == 'new_comment': msg = queue.get()
new_comment(msg['data']) if msg['request'] == 'new_comment':
#elif msg['type'] == 'reply_comment_email': new_comment(msg['data'])
# reply_comment_email(req['From'], req['Subject'], req['Body']) #elif msg['type'] == 'reply_comment_email':
#elif req['type'] == 'unsubscribe': # reply_comment_email(req['From'], req['Subject'], req['Body'])
# unsubscribe_reader(req['email'], req['article']) #elif req['type'] == 'unsubscribe':
else: # unsubscribe_reader(req['email'], req['article'])
logger.info("Dequeue unknown request " + str(msg)) else:
logger.info("throw unknown request " + str(msg))
except:
logger.exception("processing failure")
def new_comment(data): def new_comment(data):
try: logger.info('new comment received: %s' % data)
token = data.get('token', '')
url = data.get('url', '')
author_name = data.get('author', '')
author_email = data.get('email', '')
author_site = data.get('site', '')
message = data.get('message', '')
subscribe = data.get('subscribe', '')
# create a new comment row token = data.get('token', '')
site = Site.select().where(Site.token == token).get() url = data.get('url', '')
author_name = data.get('author', '')
author_email = data.get('email', '')
author_site = data.get('site', '')
message = data.get('message', '')
subscribe = data.get('subscribe', '')
logger.info('new comment received: %s' % data) # create a new comment row
site = Site.select().where(Site.token == token).get()
if author_site and author_site[:4] != 'http': if author_site and author_site[:4] != 'http':
author_site = 'http://' + author_site author_site = 'http://' + author_site
created = datetime.now().strftime("%Y-%m-%d %H:%M:%S") created = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
comment = Comment(site=site, url=url, author_name=author_name, # add a row to Comment table
author_site=author_site, author_email=author_email, comment = Comment(site=site, url=url, author_name=author_name,
content=message, created=created, published=None) author_site=author_site, author_email=author_email,
comment.save() content=message, created=created, published=None)
comment.save()
1 / 0 # render email body template
# Render email body template comment_list = (
email_body = get_template('new_comment').render(url=url, comment=comment) 'author: %s' % author_name,
'email: %s' % author_email,
'site: %s' % author_site,
'date: %s' % created,
'url: %s' % url,
'',
'%s' % message,
''
)
comment_text = '\n'.join(comment_list)
email_body = get_template('new_comment').render(url=url, comment=comment_text)
# Send email # send email
mail(pecosys.get_config('post', 'from_email'), # TODO subject should embed a key
pecosys.get_config('post', 'to_email'), subject = '%s: %d' % (site.name, 1)
'[' + branch_name + '-' + article + ']', email_body) mail(site.admin_email, subject, email_body)
# Reader subscribes to further comments # TODO support subscription
if subscribe and email: # Reader subscribes to further comments
subscribe_reader(email, article, url) #if subscribe and email:
# subscribe_reader(email, article, url)
logger.debug("new comment processed ") logger.debug("new comment processed ")
except:
logger.exception("new_comment failure")
def reply_comment_email(from_email, subject, message): def reply_comment_email(from_email, subject, message):
@ -184,31 +199,23 @@ def decode_best_effort(string):
return string.decode(info['encoding'], errors='replace') return string.decode(info['encoding'], errors='replace')
def mail(from_email, to_email, subject, *messages): def mail(to_email, subject, message):
# Create the container (outer) email message. headers = {'Content-Type': 'application/json; charset=utf-8'}
msg = MIMEMultipart() msg = {
msg['Subject'] = subject 'to': to_email,
msg['From'] = from_email 'subject': subject,
msg['To'] = to_email 'content': message
msg.preamble = subject }
r = requests.post(config.MAIL_URL, data=json.dumps(msg), headers=headers)
for message in messages: if r.status_code in (200, 201):
part = MIMEText(message, 'plain') logger.debug('Email for %s posted' % to_email)
msg.attach(part) else:
logger.warn('Cannot post email for %s' % to_email)
s = smtplib.SMTP(pecosys.get_config('smtp', 'host'),
pecosys.get_config('smtp', 'port'))
if(pecosys.get_config('smtp', 'starttls')):
s.starttls()
s.login(pecosys.get_config('smtp', 'login'),
pecosys.get_config('smtp', 'password'))
s.sendmail(from_email, to_email, msg.as_string())
s.quit()
def get_template(name): def get_template(name):
return env.get_template(pecosys.get_config('global', 'lang') + '/' + name + '.tpl') return env.get_template(config.LANG + '/' + name + '.tpl')
def enqueue(something): def enqueue(something):

View file

@ -2,12 +2,12 @@
DEBUG = True DEBUG = True
LANG = "en" LANG = "fr"
#DB_URL = "mysql://stacosys_user:stacosys_password@localhost:3306/stacosys" #DB_URL = "mysql://stacosys_user:stacosys_password@localhost:3306/stacosys"
DB_URL = "sqlite:///db.sqlite" DB_URL = "sqlite:///db.sqlite"
MAIL_URL = "http://localhost:8025" MAIL_URL = "http://localhost:8025/mbox"
HTTP_ADDRESS = "0.0.0.0" HTTP_ADDRESS = "0.0.0.0"
HTTP_PORT = 8000 HTTP_PORT = 8000

View file

@ -7,5 +7,6 @@ Jinja2==2.7.3
MarkupSafe==0.23 MarkupSafe==0.23
peewee==2.6.0 peewee==2.6.0
PyMySQL==0.6.6 PyMySQL==0.6.6
requests==2.7.0
six==1.9.0 six==1.9.0
Werkzeug==0.10.4 Werkzeug==0.10.4

View file

@ -81,7 +81,7 @@ def convert_comment(db, site, root_url, filename):
@provide_db @provide_db
def convert(db, site_name, url, comment_dir): def convert(db, site_name, url, admin_email, comment_dir):
# create DB tables if needed # create DB tables if needed
db.create_tables([Site, Comment], safe=True) db.create_tables([Site, Comment], safe=True)
@ -93,7 +93,8 @@ def convert(db, site_name, url, comment_dir):
except Site.DoesNotExist: except Site.DoesNotExist:
pass pass
site = Site.create(name=site_name, url=url, token=salt(url)) site = Site.create(name=site_name, url=url, token=salt(url),
admin_email=admin_email)
for dirpath, dirs, files in os.walk(comment_dir): for dirpath, dirs, files in os.walk(comment_dir):
for filename in files: for filename in files:
@ -105,8 +106,8 @@ def convert(db, site_name, url, comment_dir):
@clize @clize
def pecosys2stacosys(site, url, comment_dir): def pecosys2stacosys(site, url, admin_email, comment_dir):
convert(site, url, comment_dir) convert(site, url, admin_email, comment_dir)
if __name__ == '__main__': if __name__ == '__main__':