OLD | NEW |
(Empty) | |
| 1 # Copyright (c) 2013 The Chromium Authors. All rights reserved. |
| 2 # Use of this source code is governed by a BSD-style license that can be |
| 3 # found in the LICENSE file. |
| 4 |
| 5 """Main app that handles incoming mail and dispatches it to handlers.""" |
| 6 |
| 7 import logging |
| 8 import re |
| 9 |
| 10 import webapp2 |
| 11 import webob.exc |
| 12 |
| 13 from google.appengine.api import app_identity |
| 14 from google.appengine.api import mail |
| 15 |
| 16 import third_party # pylint: disable=W0611 |
| 17 |
| 18 import handlers.policy_checklist |
| 19 from review import Review |
| 20 from rietveld import Rietveld |
| 21 import util |
| 22 |
| 23 |
| 24 HANDLERS = { |
| 25 'policy_checklist': handlers.policy_checklist.process |
| 26 } |
| 27 |
| 28 |
| 29 class MailDispatcher(webapp2.RequestHandler): |
| 30 """Dispatches mail to handlers based on email addresses.""" |
| 31 |
| 32 def post(self): |
| 33 """Handles POST requests. |
| 34 |
| 35 Parses the incoming mail message. Dispatches to interested handlers based on |
| 36 the list of mail recipients. |
| 37 """ |
| 38 |
| 39 # Singleton Rietveld interface for this request. |
| 40 rietveld = Rietveld() |
| 41 |
| 42 # Parse the message and instantiate the review interface. |
| 43 message = mail.InboundEmailMessage(self.request.body) |
| 44 match = re.search(r'\(issue *(?P<id>\d+)\)$', message.subject) |
| 45 if match is None: |
| 46 raise webob.exc.HTTPBadRequest('Failed to parse issue id: %s' % |
| 47 message.subject) |
| 48 review = Review(match.groupdict()['id'], rietveld) |
| 49 |
| 50 # Determine recipients and run the handlers one by one. |
| 51 recipients = set(util.get_emails(getattr(message, 'to', '')) + |
| 52 util.get_emails(getattr(message, 'cc', ''))) |
| 53 addr_re = re.compile('^([^@]+)@%s.appspotmail.com$' % |
| 54 app_identity.get_application_id()) |
| 55 for addr in recipients: |
| 56 match = addr_re.match(addr) |
| 57 if not match: |
| 58 continue |
| 59 |
| 60 try: |
| 61 handler = HANDLERS[match.group(1)] |
| 62 except KeyError: |
| 63 continue |
| 64 |
| 65 try: |
| 66 handler(addr, message, review, rietveld) |
| 67 except: # pylint: disable=W0702 |
| 68 logging.exception('Handler %s failed!', match.group(1)) |
| 69 |
| 70 def handle_exception(self, exception, debug): |
| 71 """Handles exceptions to print HTTP error details. |
| 72 |
| 73 Args: |
| 74 exception: The exception. |
| 75 debug: Whether we're in debug mode. |
| 76 """ |
| 77 if isinstance(exception, webob.exc.HTTPException): |
| 78 logging.warning('Request %s failed: %d - %s', |
| 79 self.request.url, exception.code, exception.detail) |
| 80 |
| 81 webapp2.RequestHandler.handle_exception(self, exception, debug) |
| 82 |
| 83 |
| 84 app = webapp2.WSGIApplication([('/_ah/mail/.*', MailDispatcher)]) |
OLD | NEW |