Skip to content

Instantly share code, notes, and snippets.

@psawaya
Created July 22, 2011 00:17
Show Gist options
  • Save psawaya/1098553 to your computer and use it in GitHub Desktop.
Save psawaya/1098553 to your computer and use it in GitHub Desktop.
import asyncore
import email
import json
import logging
import smtpd
from paster.deploy import appconfig
from notifserver.storage import get_message_backend
from services.util import convert_config
from validate import NotificationValidator
class NotificationsSMTPServer(smtpd.SMTPServer):
def initPnotifsBackend(self,config,validator):
self.msg_backend = get_message_backend(config)
self.msg_queue_name = config['notifs_queue_name']
self.validator = validator
def process_message(self, peer, mailfrom, rcpttos, data):
parsedMsg = email.message_from_string(data)
if parsedMsg.is_multipart():
for subMsg in parsedMsg.get_payload():
print subMsg.get_content_type()
if subMsg.get_content_type() == 'text/json':
if self.validator:
# If we're validating ourselves route message directly
return self.route_message(subMsg)
else:
# Otherwise forward message to be validated later
return self.forward_message(subMsg)
else:
pass
# TODO: Forward e-mail
return
def route_message(self, request):
"""Validates and routes message to recipient."""
msg = json.loads(request)
body = json.loads(msg['body'])
self.validator.validate(msg, body)
try:
self.msg_backend.publish_message(json.dumps(msg), body['token'])
return HTTPAccepted()
except:
logger.error("Error publishing message with token '%s'" % body['token'])
raise
def forward_message(self, request):
"""Queues messages in the message broker to be validated at a later time."""
try:
self.msg_backend.queue_message(request, self.msg_queue_name)
return HTTPAccepted()
except:
logger.error("Error queueing message in message broker")
raise
class SMTPInterface(object):
def __init__(self):
pass
logger = logging.getLogger('smtpinterface')
def make_smtp_interface(global_config, **local_config):
server = NotificationsSMTPServer(('127.0.0.1', 1025), None)
config = global_config.copy()
config.update(local_config)
params = convert_config(config)
server.initPnotifsBackend(params,NotificationValidator())
asyncore.loop()
return server
make_smtp_interface(config)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment