Send comment by email via SRMail

pull/6/head
Yax 10 years ago
parent 692b90d7d9
commit 033e0821b2

@ -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()

@ -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', '') token = data.get('token', '')
author_name = data.get('author', '') url = data.get('url', '')
author_email = data.get('email', '') author_name = data.get('author', '')
author_site = data.get('site', '') author_email = data.get('email', '')
message = data.get('message', '') author_site = data.get('site', '')
subscribe = data.get('subscribe', '') message = data.get('message', '')
subscribe = data.get('subscribe', '')
# create a new comment row
site = Site.select().where(Site.token == token).get() # create a new comment row
site = Site.select().where(Site.token == token).get()
logger.info('new comment received: %s' % data)
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")
# add a row to Comment table
comment = Comment(site=site, url=url, author_name=author_name, comment = Comment(site=site, url=url, author_name=author_name,
author_site=author_site, author_email=author_email, author_site=author_site, author_email=author_email,
content=message, created=created, published=None) content=message, created=created, published=None)
comment.save() 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,
# Send email 'site: %s' % author_site,
mail(pecosys.get_config('post', 'from_email'), 'date: %s' % created,
pecosys.get_config('post', 'to_email'), 'url: %s' % url,
'[' + branch_name + '-' + article + ']', email_body) '',
'%s' % message,
# Reader subscribes to further comments ''
if subscribe and email: )
subscribe_reader(email, article, url) comment_text = '\n'.join(comment_list)
email_body = get_template('new_comment').render(url=url, comment=comment_text)
logger.debug("new comment processed ")
except: # send email
logger.exception("new_comment failure") # TODO subject should embed a key
subject = '%s: %d' % (site.name, 1)
mail(site.admin_email, subject, email_body)
# TODO support subscription
# Reader subscribes to further comments
#if subscribe and email:
# subscribe_reader(email, article, url)
logger.debug("new comment processed ")
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):

@ -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

@ -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

@ -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__':

Loading…
Cancel
Save