1 #
2 # Copyright (c) 2001 Bizar Software Pty Ltd (http://www.bizarsoftware.com.au/)
3 # This module is free software, and you may redistribute it and/or modify
4 # under the same terms as Python, so long as this copyright message and
5 # disclaimer are retained in their original form.
6 #
7 # IN NO EVENT SHALL BIZAR SOFTWARE PTY LTD BE LIABLE TO ANY PARTY FOR
8 # DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING
9 # OUT OF THE USE OF THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE
10 # POSSIBILITY OF SUCH DAMAGE.
11 #
12 # BIZAR SOFTWARE PTY LTD SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
13 # BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
14 # FOR A PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS"
15 # BASIS, AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
16 # SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
17 #
18 '''
19 An e-mail gateway for Roundup.
21 Incoming messages are examined for multiple parts:
22 . In a multipart/mixed message or part, each subpart is extracted and
23 examined. The text/plain subparts are assembled to form the textual
24 body of the message, to be stored in the file associated with a "msg"
25 class node. Any parts of other types are each stored in separate files
26 and given "file" class nodes that are linked to the "msg" node.
27 . In a multipart/alternative message or part, we look for a text/plain
28 subpart and ignore the other parts.
30 Summary
31 -------
32 The "summary" property on message nodes is taken from the first non-quoting
33 section in the message body. The message body is divided into sections by
34 blank lines. Sections where the second and all subsequent lines begin with
35 a ">" or "|" character are considered "quoting sections". The first line of
36 the first non-quoting section becomes the summary of the message.
38 Addresses
39 ---------
40 All of the addresses in the To: and Cc: headers of the incoming message are
41 looked up among the user nodes, and the corresponding users are placed in
42 the "recipients" property on the new "msg" node. The address in the From:
43 header similarly determines the "author" property of the new "msg"
44 node. The default handling for addresses that don't have corresponding
45 users is to create new users with no passwords and a username equal to the
46 address. (The web interface does not permit logins for users with no
47 passwords.) If we prefer to reject mail from outside sources, we can simply
48 register an auditor on the "user" class that prevents the creation of user
49 nodes with no passwords.
51 Actions
52 -------
53 The subject line of the incoming message is examined to determine whether
54 the message is an attempt to create a new item or to discuss an existing
55 item. A designator enclosed in square brackets is sought as the first thing
56 on the subject line (after skipping any "Fwd:" or "Re:" prefixes).
58 If an item designator (class name and id number) is found there, the newly
59 created "msg" node is added to the "messages" property for that item, and
60 any new "file" nodes are added to the "files" property for the item.
62 If just an item class name is found there, we attempt to create a new item
63 of that class with its "messages" property initialized to contain the new
64 "msg" node and its "files" property initialized to contain any new "file"
65 nodes.
67 Triggers
68 --------
69 Both cases may trigger detectors (in the first case we are calling the
70 set() method to add the message to the item's spool; in the second case we
71 are calling the create() method to create a new node). If an auditor raises
72 an exception, the original message is bounced back to the sender with the
73 explanatory message given in the exception.
75 $Id: mailgw.py,v 1.32 2001-11-12 22:04:29 richard Exp $
76 '''
79 import string, re, os, mimetools, cStringIO, smtplib, socket, binascii, quopri
80 import traceback
81 import hyperdb, date, password
83 class MailGWError(ValueError):
84 pass
86 class MailUsageError(ValueError):
87 pass
89 class Message(mimetools.Message):
90 ''' subclass mimetools.Message so we can retrieve the parts of the
91 message...
92 '''
93 def getPart(self):
94 ''' Get a single part of a multipart message and return it as a new
95 Message instance.
96 '''
97 boundary = self.getparam('boundary')
98 mid, end = '--'+boundary, '--'+boundary+'--'
99 s = cStringIO.StringIO()
100 while 1:
101 line = self.fp.readline()
102 if not line:
103 break
104 if line.strip() in (mid, end):
105 break
106 s.write(line)
107 if not s.getvalue().strip():
108 return None
109 s.seek(0)
110 return Message(s)
112 subject_re = re.compile(r'(?P<refwd>\s*\W?\s*(fwd|re)\s*\W?\s*)*'
113 r'\s*(\[(?P<classname>[^\d]+)(?P<nodeid>\d+)?\])'
114 r'\s*(?P<title>[^\[]+)(\[(?P<args>.+?)\])?', re.I)
116 class MailGW:
117 def __init__(self, db):
118 self.db = db
120 def main(self, fp):
121 ''' fp - the file from which to read the Message.
122 '''
123 self.handle_Message(Message(fp))
125 def handle_Message(self, message):
126 '''Handle an RFC822 Message
128 Hanle the Message object by calling handle_message() and then cope
129 with any errors raised by handle_message.
130 This method's job is to make that call and handle any
131 errors in a sane manner. It should be replaced if you wish to
132 handle errors in a different manner.
133 '''
134 m = []
135 # in some rare cases, a particularly stuffed-up e-mail will make
136 # its way into here... try to handle it gracefully
137 sendto = message.getaddrlist('from')
138 if sendto:
139 try:
140 self.handle_message(message)
141 return
142 except MailUsageError, value:
143 # bounce the message back to the sender with the usage message
144 fulldoc = '\n'.join(string.split(__doc__, '\n')[2:])
145 sendto = [sendto[0][1]]
146 m = ['Subject: Failed issue tracker submission', '']
147 m.append(str(value))
148 m.append('\n\nMail Gateway Help\n=================')
149 m.append(fulldoc)
150 except:
151 # bounce the message back to the sender with the error message
152 sendto = [sendto[0][1]]
153 m = ['Subject: failed issue tracker submission', '']
154 # TODO as attachments?
155 m.append('---- traceback of failure ----')
156 s = cStringIO.StringIO()
157 import traceback
158 traceback.print_exc(None, s)
159 m.append(s.getvalue())
160 m.append('---- failed message follows ----')
161 try:
162 message.fp.seek(0)
163 except:
164 pass
165 m.append(message.fp.read())
166 else:
167 # very bad-looking message - we don't even know who sent it
168 sendto = [self.ADMIN_EMAIL]
169 m = ['Subject: badly formed message from mail gateway']
170 m.append('')
171 m.append('The mail gateway retrieved a message which has no From:')
172 m.append('line, indicating that it is corrupt. Please check your')
173 m.append('mail gateway source.')
174 m.append('')
175 m.append('---- failed message follows ----')
176 try:
177 message.fp.seek(0)
178 except:
179 pass
180 m.append(message.fp.read())
182 # now send the message
183 try:
184 smtp = smtplib.SMTP(self.MAILHOST)
185 smtp.sendmail(self.ADMIN_EMAIL, sendto, '\n'.join(m))
186 except socket.error, value:
187 raise MailGWError, "Couldn't send confirmation email: "\
188 "mailhost %s"%value
189 except smtplib.SMTPException, value:
190 raise MailGWError, "Couldn't send confirmation email: %s"%value
192 def handle_message(self, message):
193 ''' message - a Message instance
195 Parse the message as per the module docstring.
196 '''
197 # handle the subject line
198 subject = message.getheader('subject', '')
199 m = subject_re.match(subject)
200 if not m:
201 raise MailUsageError, '''
202 The message you sent to roundup did not contain a properly formed subject
203 line. The subject must contain a class name or designator to indicate the
204 "topic" of the message. For example:
205 Subject: [issue] This is a new issue
206 - this will create a new issue in the tracker with the title "This is
207 a new issue".
208 Subject: [issue1234] This is a followup to issue 1234
209 - this will append the message's contents to the existing issue 1234
210 in the tracker.
212 Subject was: "%s"
213 '''%subject
214 classname = m.group('classname')
215 nodeid = m.group('nodeid')
216 title = m.group('title').strip()
217 subject_args = m.group('args')
218 try:
219 cl = self.db.getclass(classname)
220 except KeyError:
221 raise MailUsageError, '''
222 The class name you identified in the subject line ("%s") does not exist in the
223 database.
225 Valid class names are: %s
226 Subject was: "%s"
227 '''%(classname, ', '.join(self.db.getclasses()), subject)
229 # If there's no nodeid, check to see if this is a followup and
230 # maybe someone's responded to the initial mail that created an
231 # entry. Try to find the matching nodes with the same title, and
232 # use the _last_ one matched (since that'll _usually_ be the most
233 # recent...)
234 if not nodeid and m.group('refwd'):
235 l = cl.stringFind(title=title)
236 if l:
237 nodeid = l[-1]
239 # start of the props
240 properties = cl.getprops()
241 props = {}
243 # handle the args
244 args = m.group('args')
245 if args:
246 for prop in string.split(args, ';'):
247 try:
248 key, value = prop.split('=')
249 except ValueError, message:
250 raise MailUsageError, '''
251 Subject argument list not of form [arg=value,value,...;arg=value,value...]
252 (specific exception message was "%s")
254 Subject was: "%s"
255 '''%(message, subject)
256 try:
257 type = properties[key]
258 except KeyError:
259 raise MailUsageError, '''
260 Subject argument list refers to an invalid property: "%s"
262 Subject was: "%s"
263 '''%(key, subject)
264 if isinstance(type, hyperdb.String):
265 props[key] = value
266 if isinstance(type, hyperdb.Password):
267 props[key] = password.Password(value)
268 elif isinstance(type, hyperdb.Date):
269 try:
270 props[key] = date.Date(value)
271 except ValueError, message:
272 raise UsageError, '''
273 Subject argument list contains an invalid date for %s.
275 Error was: %s
276 Subject was: "%s"
277 '''%(key, message, subject)
278 elif isinstance(type, hyperdb.Interval):
279 try:
280 props[key] = date.Interval(value)
281 except ValueError, message:
282 raise UsageError, '''
283 Subject argument list contains an invalid date interval for %s.
285 Error was: %s
286 Subject was: "%s"
287 '''%(key, message, subject)
288 elif isinstance(type, hyperdb.Link):
289 props[key] = value
290 elif isinstance(type, hyperdb.Multilink):
291 props[key] = value.split(',')
293 #
294 # handle the users
295 #
296 author = self.db.uidFromAddress(message.getaddrlist('from')[0])
297 recipients = []
298 tracker_email = self.ISSUE_TRACKER_EMAIL.lower()
299 for recipient in message.getaddrlist('to') + message.getaddrlist('cc'):
300 if recipient[1].strip().lower() == tracker_email:
301 continue
302 recipients.append(self.db.uidFromAddress(recipient))
304 # now handle the body - find the message
305 content_type = message.gettype()
306 attachments = []
307 if content_type == 'multipart/mixed':
308 # skip over the intro to the first boundary
309 part = message.getPart()
310 content = None
311 while 1:
312 # get the next part
313 part = message.getPart()
314 if part is None:
315 break
316 # parse it
317 subtype = part.gettype()
318 if subtype == 'text/plain' and not content:
319 # add all text/plain parts to the message content
320 if content is None:
321 content = part.fp.read()
322 else:
323 content = content + part.fp.read()
325 elif subtype == 'message/rfc822':
326 # handle message/rfc822 specially - the name should be
327 # the subject of the actual e-mail embedded here
328 i = part.fp.tell()
329 mailmess = Message(part.fp)
330 name = mailmess.getheader('subject')
331 part.fp.seek(i)
332 attachments.append((name, 'message/rfc822', part.fp.read()))
334 else:
335 # try name on Content-Type
336 name = part.getparam('name')
337 # this is just an attachment
338 encoding = part.getencoding()
339 if encoding == 'base64':
340 data = binascii.a2b_base64(part.fp.read())
341 elif encoding == 'quoted-printable':
342 # the quopri module wants to work with files
343 decoded = cStringIO.StringIO()
344 quopri.decode(part.fp, decoded)
345 data = decoded.getvalue()
346 elif encoding == 'uuencoded':
347 data = binascii.a2b_uu(part.fp.read())
348 attachments.append((name, part.gettype(), data))
350 if content is None:
351 raise MailUsageError, '''
352 Roundup requires the submission to be plain text. The message parser could
353 not find a text/plain part to use.
354 '''
356 elif content_type[:10] == 'multipart/':
357 # skip over the intro to the first boundary
358 message.getPart()
359 content = None
360 while 1:
361 # get the next part
362 part = message.getPart()
363 if part is None:
364 break
365 # parse it
366 if part.gettype() == 'text/plain' and not content:
367 # this one's our content
368 content = part.fp.read()
369 if content is None:
370 raise MailUsageError, '''
371 Roundup requires the submission to be plain text. The message parser could
372 not find a text/plain part to use.
373 '''
375 elif content_type != 'text/plain':
376 raise MailUsageError, '''
377 Roundup requires the submission to be plain text. The message parser could
378 not find a text/plain part to use.
379 '''
381 else:
382 content = message.fp.read()
384 summary, content = parseContent(content)
386 # handle the files
387 files = []
388 for (name, type, data) in attachments:
389 files.append(self.db.file.create(type=type, name=name,
390 content=data))
392 # now handle the db stuff
393 if nodeid:
394 # If an item designator (class name and id number) is found there,
395 # the newly created "msg" node is added to the "messages" property
396 # for that item, and any new "file" nodes are added to the "files"
397 # property for the item.
398 message_id = self.db.msg.create(author=author,
399 recipients=recipients, date=date.Date('.'), summary=summary,
400 content=content, files=files)
401 try:
402 messages = cl.get(nodeid, 'messages')
403 except IndexError:
404 raise MailUsageError, '''
405 The node specified by the designator in the subject of your message ("%s")
406 does not exist.
408 Subject was: "%s"
409 '''%(nodeid, subject)
410 messages.append(message_id)
411 props['messages'] = messages
413 # if the message is currently 'unread' or 'resolved', then set
414 # it to 'chatting'
415 if properties.has_key('status'):
416 try:
417 # determine the id of 'unread', 'resolved' and 'chatting'
418 unread_id = self.db.status.lookup('unread')
419 resolved_id = self.db.status.lookup('resolved')
420 chatting_id = self.db.status.lookup('chatting')
421 except KeyError:
422 pass
423 else:
424 if (not props.has_key('status') or
425 props['status'] == unread_id or
426 props['status'] == resolved_id):
427 props['status'] = chatting_id
429 try:
430 cl.set(nodeid, **props)
431 except (TypeError, IndexError, ValueError), message:
432 raise MailUsageError, '''
433 There was a problem with the message you sent:
434 %s
435 '''%message
436 else:
437 # If just an item class name is found there, we attempt to create a
438 # new item of that class with its "messages" property initialized to
439 # contain the new "msg" node and its "files" property initialized to
440 # contain any new "file" nodes.
441 message_id = self.db.msg.create(author=author,
442 recipients=recipients, date=date.Date('.'), summary=summary,
443 content=content, files=files)
444 # fill out the properties with defaults where required
445 if properties.has_key('assignedto') and \
446 not props.has_key('assignedto'):
447 props['assignedto'] = '1' # "admin"
449 # pre-set the issue to unread
450 if properties.has_key('status') and not props.has_key('status'):
451 try:
452 # determine the id of 'unread'
453 unread_id = self.db.status.lookup('unread')
454 except KeyError:
455 pass
456 else:
457 props['status'] = '1'
459 # set the title to the subject
460 if properties.has_key('title') and not props.has_key('title'):
461 props['title'] = title
463 # pre-load the messages list and nosy list
464 props['messages'] = [message_id]
465 props['nosy'] = props.get('nosy', []) + recipients
466 props['nosy'].append(author)
467 props['nosy'].sort()
469 # and attempt to create the new node
470 try:
471 nodeid = cl.create(**props)
472 except (TypeError, IndexError, ValueError), message:
473 raise MailUsageError, '''
474 There was a problem with the message you sent:
475 %s
476 '''%message
478 def parseContent(content, blank_line=re.compile(r'[\r\n]+\s*[\r\n]+'),
479 eol=re.compile(r'[\r\n]+'), signature=re.compile(r'^[>|\s]*[-_]+\s*$')):
480 ''' The message body is divided into sections by blank lines.
481 Sections where the second and all subsequent lines begin with a ">" or "|"
482 character are considered "quoting sections". The first line of the first
483 non-quoting section becomes the summary of the message.
484 '''
485 # strip off leading carriage-returns / newlines
486 i = 0
487 for i in range(len(content)):
488 if content[i] not in '\r\n':
489 break
490 if i > 0:
491 sections = blank_line.split(content[i:])
492 else:
493 sections = blank_line.split(content)
495 # extract out the summary from the message
496 summary = ''
497 l = []
498 for section in sections:
499 #section = section.strip()
500 if not section:
501 continue
502 lines = eol.split(section)
503 if lines[0] and lines[0][0] in '>|':
504 continue
505 if len(lines) > 1 and lines[1] and lines[1][0] in '>|':
506 continue
507 if not summary:
508 summary = lines[0]
509 l.append(section)
510 continue
511 if signature.match(lines[0]):
512 break
513 l.append(section)
514 return summary, '\n\n'.join(l)
516 #
517 # $Log: not supported by cvs2svn $
518 # Revision 1.31 2001/11/12 22:01:06 richard
519 # Fixed issues with nosy reaction and author copies.
520 #
521 # Revision 1.30 2001/11/09 22:33:28 richard
522 # More error handling fixes.
523 #
524 # Revision 1.29 2001/11/07 05:29:26 richard
525 # Modified roundup-mailgw so it can read e-mails from a local mail spool
526 # file. Truncates the spool file after parsing.
527 # Fixed a couple of small bugs introduced in roundup.mailgw when I started
528 # the popgw.
529 #
530 # Revision 1.28 2001/11/01 22:04:37 richard
531 # Started work on supporting a pop3-fetching server
532 # Fixed bugs:
533 # . bug #477104 ] HTML tag error in roundup-server
534 # . bug #477107 ] HTTP header problem
535 #
536 # Revision 1.27 2001/10/30 11:26:10 richard
537 # Case-insensitive match for ISSUE_TRACKER_EMAIL in address in e-mail.
538 #
539 # Revision 1.26 2001/10/30 00:54:45 richard
540 # Features:
541 # . #467129 ] Lossage when username=e-mail-address
542 # . #473123 ] Change message generation for author
543 # . MailGW now moves 'resolved' to 'chatting' on receiving e-mail for an issue.
544 #
545 # Revision 1.25 2001/10/28 23:22:28 richard
546 # fixed bug #474749 ] Indentations lost
547 #
548 # Revision 1.24 2001/10/23 22:57:52 richard
549 # Fix unread->chatting auto transition, thanks Roch'e
550 #
551 # Revision 1.23 2001/10/21 04:00:20 richard
552 # MailGW now moves 'unread' to 'chatting' on receiving e-mail for an issue.
553 #
554 # Revision 1.22 2001/10/21 03:35:13 richard
555 # bug #473125: Paragraph in e-mails
556 #
557 # Revision 1.21 2001/10/21 00:53:42 richard
558 # bug #473130: Nosy list not set correctly
559 #
560 # Revision 1.20 2001/10/17 23:13:19 richard
561 # Did a fair bit of work on the admin tool. Now has an extra command "table"
562 # which displays node information in a tabular format. Also fixed import and
563 # export so they work. Removed freshen.
564 # Fixed quopri usage in mailgw from bug reports.
565 #
566 # Revision 1.19 2001/10/11 23:43:04 richard
567 # Implemented the comma-separated printing option in the admin tool.
568 # Fixed a typo (more of a vim-o actually :) in mailgw.
569 #
570 # Revision 1.18 2001/10/11 06:38:57 richard
571 # Initial cut at trying to handle people responding to CC'ed messages that
572 # create an issue.
573 #
574 # Revision 1.17 2001/10/09 07:25:59 richard
575 # Added the Password property type. See "pydoc roundup.password" for
576 # implementation details. Have updated some of the documentation too.
577 #
578 # Revision 1.16 2001/10/05 02:23:24 richard
579 # . roundup-admin create now prompts for property info if none is supplied
580 # on the command-line.
581 # . hyperdb Class getprops() method may now return only the mutable
582 # properties.
583 # . Login now uses cookies, which makes it a whole lot more flexible. We can
584 # now support anonymous user access (read-only, unless there's an
585 # "anonymous" user, in which case write access is permitted). Login
586 # handling has been moved into cgi_client.Client.main()
587 # . The "extended" schema is now the default in roundup init.
588 # . The schemas have had their page headings modified to cope with the new
589 # login handling. Existing installations should copy the interfaces.py
590 # file from the roundup lib directory to their instance home.
591 # . Incorrectly had a Bizar Software copyright on the cgitb.py module from
592 # Ping - has been removed.
593 # . Fixed a whole bunch of places in the CGI interface where we should have
594 # been returning Not Found instead of throwing an exception.
595 # . Fixed a deviation from the spec: trying to modify the 'id' property of
596 # an item now throws an exception.
597 #
598 # Revision 1.15 2001/08/30 06:01:17 richard
599 # Fixed missing import in mailgw :(
600 #
601 # Revision 1.14 2001/08/13 23:02:54 richard
602 # Make the mail parser a little more robust.
603 #
604 # Revision 1.13 2001/08/12 06:32:36 richard
605 # using isinstance(blah, Foo) now instead of isFooType
606 #
607 # Revision 1.12 2001/08/08 01:27:00 richard
608 # Added better error handling to mailgw.
609 #
610 # Revision 1.11 2001/08/08 00:08:03 richard
611 # oops ;)
612 #
613 # Revision 1.10 2001/08/07 00:24:42 richard
614 # stupid typo
615 #
616 # Revision 1.9 2001/08/07 00:15:51 richard
617 # Added the copyright/license notice to (nearly) all files at request of
618 # Bizar Software.
619 #
620 # Revision 1.8 2001/08/05 07:06:07 richard
621 # removed some print statements
622 #
623 # Revision 1.7 2001/08/03 07:18:22 richard
624 # Implemented correct mail splitting (was taking a shortcut). Added unit
625 # tests. Also snips signatures now too.
626 #
627 # Revision 1.6 2001/08/01 04:24:21 richard
628 # mailgw was assuming certain properties existed on the issues being created.
629 #
630 # Revision 1.5 2001/07/29 07:01:39 richard
631 # Added vim command to all source so that we don't get no steenkin' tabs :)
632 #
633 # Revision 1.4 2001/07/28 06:43:02 richard
634 # Multipart message class has the getPart method now. Added some tests for it.
635 #
636 # Revision 1.3 2001/07/28 00:34:34 richard
637 # Fixed some non-string node ids.
638 #
639 # Revision 1.2 2001/07/22 12:09:32 richard
640 # Final commit of Grande Splite
641 #
642 #
643 # vim: set filetype=python ts=4 sw=4 et si