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 #
19 __doc__ = '''
20 An e-mail gateway for Roundup.
22 Incoming messages are examined for multiple parts:
23 . In a multipart/mixed message or part, each subpart is extracted and
24 examined. The text/plain subparts are assembled to form the textual
25 body of the message, to be stored in the file associated with a "msg"
26 class node. Any parts of other types are each stored in separate files
27 and given "file" class nodes that are linked to the "msg" node.
28 . In a multipart/alternative message or part, we look for a text/plain
29 subpart and ignore the other parts.
31 Summary
32 -------
33 The "summary" property on message nodes is taken from the first non-quoting
34 section in the message body. The message body is divided into sections by
35 blank lines. Sections where the second and all subsequent lines begin with
36 a ">" or "|" character are considered "quoting sections". The first line of
37 the first non-quoting section becomes the summary of the message.
39 Addresses
40 ---------
41 All of the addresses in the To: and Cc: headers of the incoming message are
42 looked up among the user nodes, and the corresponding users are placed in
43 the "recipients" property on the new "msg" node. The address in the From:
44 header similarly determines the "author" property of the new "msg"
45 node. The default handling for addresses that don't have corresponding
46 users is to create new users with no passwords and a username equal to the
47 address. (The web interface does not permit logins for users with no
48 passwords.) If we prefer to reject mail from outside sources, we can simply
49 register an auditor on the "user" class that prevents the creation of user
50 nodes with no passwords.
52 Actions
53 -------
54 The subject line of the incoming message is examined to determine whether
55 the message is an attempt to create a new item or to discuss an existing
56 item. A designator enclosed in square brackets is sought as the first thing
57 on the subject line (after skipping any "Fwd:" or "Re:" prefixes).
59 If an item designator (class name and id number) is found there, the newly
60 created "msg" node is added to the "messages" property for that item, and
61 any new "file" nodes are added to the "files" property for the item.
63 If just an item class name is found there, we attempt to create a new item
64 of that class with its "messages" property initialized to contain the new
65 "msg" node and its "files" property initialized to contain any new "file"
66 nodes.
68 Triggers
69 --------
70 Both cases may trigger detectors (in the first case we are calling the
71 set() method to add the message to the item's spool; in the second case we
72 are calling the create() method to create a new node). If an auditor raises
73 an exception, the original message is bounced back to the sender with the
74 explanatory message given in the exception.
76 $Id: mailgw.py,v 1.63 2002-02-12 08:08:55 grubert Exp $
77 '''
80 import string, re, os, mimetools, cStringIO, smtplib, socket, binascii, quopri
81 import time, random
82 import traceback, MimeWriter
83 import hyperdb, date, password
85 SENDMAILDEBUG = os.environ.get('SENDMAILDEBUG', '')
87 class MailGWError(ValueError):
88 pass
90 class MailUsageError(ValueError):
91 pass
93 class MailUsageHelp(Exception):
94 pass
96 class UnAuthorized(Exception):
97 """ Access denied """
99 class Message(mimetools.Message):
100 ''' subclass mimetools.Message so we can retrieve the parts of the
101 message...
102 '''
103 def getPart(self):
104 ''' Get a single part of a multipart message and return it as a new
105 Message instance.
106 '''
107 boundary = self.getparam('boundary')
108 mid, end = '--'+boundary, '--'+boundary+'--'
109 s = cStringIO.StringIO()
110 while 1:
111 line = self.fp.readline()
112 if not line:
113 break
114 if line.strip() in (mid, end):
115 break
116 s.write(line)
117 if not s.getvalue().strip():
118 return None
119 s.seek(0)
120 return Message(s)
122 subject_re = re.compile(r'(?P<refwd>\s*\W?\s*(fwd|re|aw)\s*\W?\s*)*'
123 r'\s*(\[(?P<classname>[^\d\s]+)(?P<nodeid>\d+)?\])'
124 r'\s*(?P<title>[^[]+)?(\[(?P<args>.+?)\])?', re.I)
126 class MailGW:
127 def __init__(self, instance, db):
128 self.instance = instance
129 self.db = db
131 def main(self, fp):
132 ''' fp - the file from which to read the Message.
133 '''
134 self.handle_Message(Message(fp))
136 def handle_Message(self, message):
137 '''Handle an RFC822 Message
139 Handle the Message object by calling handle_message() and then cope
140 with any errors raised by handle_message.
141 This method's job is to make that call and handle any
142 errors in a sane manner. It should be replaced if you wish to
143 handle errors in a different manner.
144 '''
145 # in some rare cases, a particularly stuffed-up e-mail will make
146 # its way into here... try to handle it gracefully
147 sendto = message.getaddrlist('from')
148 if sendto:
149 try:
150 return self.handle_message(message)
151 except MailUsageHelp:
152 # bounce the message back to the sender with the usage message
153 fulldoc = '\n'.join(string.split(__doc__, '\n')[2:])
154 sendto = [sendto[0][1]]
155 m = ['']
156 m.append('\n\nMail Gateway Help\n=================')
157 m.append(fulldoc)
158 m = self.bounce_message(message, sendto, m,
159 subject="Mail Gateway Help")
160 except MailUsageError, value:
161 # bounce the message back to the sender with the usage message
162 fulldoc = '\n'.join(string.split(__doc__, '\n')[2:])
163 sendto = [sendto[0][1]]
164 m = ['']
165 m.append(str(value))
166 m.append('\n\nMail Gateway Help\n=================')
167 m.append(fulldoc)
168 m = self.bounce_message(message, sendto, m)
169 except UnAuthorized, value:
170 # just inform the user that he is not authorized
171 sendto = [sendto[0][1]]
172 m = ['']
173 m.append(str(value))
174 m = self.bounce_message(message, sendto, m)
175 except:
176 # bounce the message back to the sender with the error message
177 sendto = [sendto[0][1], self.instance.ADMIN_EMAIL]
178 m = ['']
179 m.append('An unexpected error occurred during the processing')
180 m.append('of your message. The tracker administrator is being')
181 m.append('notified.\n')
182 m.append('---- traceback of failure ----')
183 s = cStringIO.StringIO()
184 import traceback
185 traceback.print_exc(None, s)
186 m.append(s.getvalue())
187 m = self.bounce_message(message, sendto, m)
188 else:
189 # very bad-looking message - we don't even know who sent it
190 sendto = [self.instance.ADMIN_EMAIL]
191 m = ['Subject: badly formed message from mail gateway']
192 m.append('')
193 m.append('The mail gateway retrieved a message which has no From:')
194 m.append('line, indicating that it is corrupt. Please check your')
195 m.append('mail gateway source. Failed message is attached.')
196 m.append('')
197 m = self.bounce_message(message, sendto, m,
198 subject='Badly formed message from mail gateway')
200 # now send the message
201 if SENDMAILDEBUG:
202 open(SENDMAILDEBUG, 'w').write('From: %s\nTo: %s\n%s\n'%(
203 self.instance.ADMIN_EMAIL, ', '.join(sendto), m.getvalue()))
204 else:
205 try:
206 smtp = smtplib.SMTP(self.instance.MAILHOST)
207 smtp.sendmail(self.instance.ADMIN_EMAIL, sendto, m.getvalue())
208 except socket.error, value:
209 raise MailGWError, "Couldn't send error email: "\
210 "mailhost %s"%value
211 except smtplib.SMTPException, value:
212 raise MailGWError, "Couldn't send error email: %s"%value
214 def bounce_message(self, message, sendto, error,
215 subject='Failed issue tracker submission'):
216 ''' create a message that explains the reason for the failed
217 issue submission to the author and attach the original
218 message.
219 '''
220 msg = cStringIO.StringIO()
221 writer = MimeWriter.MimeWriter(msg)
222 writer.addheader('Subject', subject)
223 writer.addheader('From', '%s <%s>'% (self.instance.INSTANCE_NAME,
224 self.instance.ISSUE_TRACKER_EMAIL))
225 writer.addheader('To', ','.join(sendto))
226 writer.addheader('MIME-Version', '1.0')
227 part = writer.startmultipartbody('mixed')
228 part = writer.nextpart()
229 body = part.startbody('text/plain')
230 body.write('\n'.join(error))
232 # reconstruct the original message
233 m = cStringIO.StringIO()
234 w = MimeWriter.MimeWriter(m)
235 # default the content_type, just in case...
236 content_type = 'text/plain'
237 # add the headers except the content-type
238 for header in message.headers:
239 header_name = header.split(':')[0]
240 if header_name.lower() == 'content-type':
241 content_type = message.getheader(header_name)
242 elif message.getheader(header_name):
243 w.addheader(header_name, message.getheader(header_name))
244 # now attach the message body
245 body = w.startbody(content_type)
246 try:
247 message.rewindbody()
248 except IOError:
249 body.write("*** couldn't include message body: read from pipe ***")
250 else:
251 body.write(message.fp.read())
253 # attach the original message to the returned message
254 part = writer.nextpart()
255 part.addheader('Content-Disposition','attachment')
256 part.addheader('Content-Description','Message you sent')
257 part.addheader('Content-Transfer-Encoding', '7bit')
258 body = part.startbody('message/rfc822')
259 body.write(m.getvalue())
261 writer.lastpart()
262 return msg
264 def get_part_data_decoded(self,part):
265 encoding = part.getencoding()
266 data = None
267 if encoding == 'base64':
268 # BUG: is base64 really used for text encoding or
269 # are we inserting zip files here.
270 data = binascii.a2b_base64(part.fp.read())
271 elif encoding == 'quoted-printable':
272 # the quopri module wants to work with files
273 decoded = cStringIO.StringIO()
274 quopri.decode(part.fp, decoded)
275 data = decoded.getvalue()
276 elif encoding == 'uuencoded':
277 data = binascii.a2b_uu(part.fp.read())
278 else:
279 # take it as text
280 data = part.fp.read()
281 return data
283 def handle_message(self, message):
284 ''' message - a Message instance
286 Parse the message as per the module docstring.
287 '''
288 # handle the subject line
289 subject = message.getheader('subject', '')
291 if subject.strip() == 'help':
292 raise MailUsageHelp
294 m = subject_re.match(subject)
295 if not m:
296 raise MailUsageError, '''
297 The message you sent to roundup did not contain a properly formed subject
298 line. The subject must contain a class name or designator to indicate the
299 "topic" of the message. For example:
300 Subject: [issue] This is a new issue
301 - this will create a new issue in the tracker with the title "This is
302 a new issue".
303 Subject: [issue1234] This is a followup to issue 1234
304 - this will append the message's contents to the existing issue 1234
305 in the tracker.
307 Subject was: "%s"
308 '''%subject
310 # get the classname
311 classname = m.group('classname')
312 try:
313 cl = self.db.getclass(classname)
314 except KeyError:
315 raise MailUsageError, '''
316 The class name you identified in the subject line ("%s") does not exist in the
317 database.
319 Valid class names are: %s
320 Subject was: "%s"
321 '''%(classname, ', '.join(self.db.getclasses()), subject)
323 # get the optional nodeid
324 nodeid = m.group('nodeid')
326 # title is optional too
327 title = m.group('title')
328 if title:
329 title = title.strip()
330 else:
331 title = ''
333 # but we do need either a title or a nodeid...
334 if not nodeid and not title:
335 raise MailUsageError, '''
336 I cannot match your message to a node in the database - you need to either
337 supply a full node identifier (with number, eg "[issue123]" or keep the
338 previous subject title intact so I can match that.
340 Subject was: "%s"
341 '''%subject
343 # extract the args
344 subject_args = m.group('args')
346 # If there's no nodeid, check to see if this is a followup and
347 # maybe someone's responded to the initial mail that created an
348 # entry. Try to find the matching nodes with the same title, and
349 # use the _last_ one matched (since that'll _usually_ be the most
350 # recent...)
351 if not nodeid and m.group('refwd'):
352 l = cl.stringFind(title=title)
353 if l:
354 nodeid = l[-1]
356 # start of the props
357 properties = cl.getprops()
358 props = {}
360 # handle the args
361 args = m.group('args')
362 if args:
363 for prop in string.split(args, ';'):
364 # extract the property name and value
365 try:
366 key, value = prop.split('=')
367 except ValueError, message:
368 raise MailUsageError, '''
369 Subject argument list not of form [arg=value,value,...;arg=value,value...]
370 (specific exception message was "%s")
372 Subject was: "%s"
373 '''%(message, subject)
375 # ensure it's a valid property name
376 key = key.strip()
377 try:
378 proptype = properties[key]
379 except KeyError:
380 raise MailUsageError, '''
381 Subject argument list refers to an invalid property: "%s"
383 Subject was: "%s"
384 '''%(key, subject)
386 # convert the string value to a real property value
387 if isinstance(proptype, hyperdb.String):
388 props[key] = value.strip()
389 if isinstance(proptype, hyperdb.Password):
390 props[key] = password.Password(value.strip())
391 elif isinstance(proptype, hyperdb.Date):
392 try:
393 props[key] = date.Date(value.strip())
394 except ValueError, message:
395 raise UsageError, '''
396 Subject argument list contains an invalid date for %s.
398 Error was: %s
399 Subject was: "%s"
400 '''%(key, message, subject)
401 elif isinstance(proptype, hyperdb.Interval):
402 try:
403 props[key] = date.Interval(value) # no strip needed
404 except ValueError, message:
405 raise UsageError, '''
406 Subject argument list contains an invalid date interval for %s.
408 Error was: %s
409 Subject was: "%s"
410 '''%(key, message, subject)
411 elif isinstance(proptype, hyperdb.Link):
412 linkcl = self.db.classes[proptype.classname]
413 propkey = linkcl.labelprop(default_to_id=1)
414 try:
415 props[key] = linkcl.lookup(value)
416 except KeyError, message:
417 raise MailUsageError, '''
418 Subject argument list contains an invalid value for %s.
420 Error was: %s
421 Subject was: "%s"
422 '''%(key, message, subject)
423 elif isinstance(proptype, hyperdb.Multilink):
424 # get the linked class
425 linkcl = self.db.classes[proptype.classname]
426 propkey = linkcl.labelprop(default_to_id=1)
427 for item in value.split(','):
428 item = item.strip()
429 try:
430 item = linkcl.lookup(item)
431 except KeyError, message:
432 raise MailUsageError, '''
433 Subject argument list contains an invalid value for %s.
435 Error was: %s
436 Subject was: "%s"
437 '''%(key, message, subject)
438 if props.has_key(key):
439 props[key].append(item)
440 else:
441 props[key] = [item]
443 #
444 # handle the users
445 #
447 # Don't create users if ANONYMOUS_REGISTER is denied
448 if self.instance.ANONYMOUS_REGISTER == 'deny':
449 create = 0
450 else:
451 create = 1
452 author = self.db.uidFromAddress(message.getaddrlist('from')[0],
453 create=create)
454 if not author:
455 raise UnAuthorized, '''
456 You are not a registered user.
458 Unknown address: %s
459 '''%message.getaddrlist('from')[0][1]
461 # the author may have been created - make sure the change is
462 # committed before we reopen the database
463 self.db.commit()
465 # reopen the database as the author
466 username = self.db.user.get(author, 'username')
467 self.db = self.instance.open(username)
469 # re-get the class with the new database connection
470 cl = self.db.getclass(classname)
472 # now update the recipients list
473 recipients = []
474 tracker_email = self.instance.ISSUE_TRACKER_EMAIL.lower()
475 for recipient in message.getaddrlist('to') + message.getaddrlist('cc'):
476 r = recipient[1].strip().lower()
477 if r == tracker_email or not r:
478 continue
479 recipients.append(self.db.uidFromAddress(recipient))
481 #
482 # handle message-id and in-reply-to
483 #
484 messageid = message.getheader('message-id')
485 inreplyto = message.getheader('in-reply-to') or ''
486 # generate a messageid if there isn't one
487 if not messageid:
488 messageid = "<%s.%s.%s%s@%s>"%(time.time(), random.random(),
489 classname, nodeid, self.instance.MAIL_DOMAIN)
491 #
492 # now handle the body - find the message
493 #
494 content_type = message.gettype()
495 attachments = []
496 # General multipart handling:
497 # Take the first text/plain part, anything else is considered an
498 # attachment.
499 # multipart/mixed: multiple "unrelated" parts.
500 # multipart/signed (rfc 1847):
501 # The control information is carried in the second of the two
502 # required body parts.
503 # ACTION: Default, so if content is text/plain we get it.
504 # multipart/encrypted (rfc 1847):
505 # The control information is carried in the first of the two
506 # required body parts.
507 # ACTION: Not handleable as the content is encrypted.
508 # multipart/related (rfc 1872, 2112, 2387):
509 # The Multipart/Related content-type addresses the MIME representation
510 # of compound objects.
511 # ACTION: Default. If we are lucky there is a text/plain.
512 # TODO: One should use the start part and look for an Alternative
513 # that is text/plain.
514 # multipart/Alternative (rfc 1872, 1892):
515 # only in "related" ?
516 # multipart/report (rfc 1892):
517 # e.g. mail system delivery status reports.
518 # ACTION: Default. Could be ignored or used for Delivery Notification
519 # flagging.
520 # multipart/form-data:
521 # For web forms only.
522 if content_type == 'multipart/mixed':
523 # skip over the intro to the first boundary
524 part = message.getPart()
525 content = None
526 while 1:
527 # get the next part
528 part = message.getPart()
529 if part is None:
530 break
531 # parse it
532 subtype = part.gettype()
533 if subtype == 'text/plain' and not content:
534 # The first text/plain part is the message content.
535 content = self.get_part_data_decoded(part)
536 elif subtype == 'message/rfc822':
537 # handle message/rfc822 specially - the name should be
538 # the subject of the actual e-mail embedded here
539 i = part.fp.tell()
540 mailmess = Message(part.fp)
541 name = mailmess.getheader('subject')
542 part.fp.seek(i)
543 attachments.append((name, 'message/rfc822', part.fp.read()))
544 else:
545 # try name on Content-Type
546 name = part.getparam('name')
547 # this is just an attachment
548 data = self.get_part_data_decoded(part)
549 attachments.append((name, part.gettype(), data))
550 if content is None:
551 raise MailUsageError, '''
552 Roundup requires the submission to be plain text. The message parser could
553 not find a text/plain part to use.
554 '''
556 elif content_type[:10] == 'multipart/':
557 # skip over the intro to the first boundary
558 message.getPart()
559 content = None
560 while 1:
561 # get the next part
562 part = message.getPart()
563 if part is None:
564 break
565 # parse it
566 if part.gettype() == 'text/plain' and not content:
567 content = self.get_part_data_decoded(part)
568 if content is None:
569 raise MailUsageError, '''
570 Roundup requires the submission to be plain text. The message parser could
571 not find a text/plain part to use.
572 '''
574 elif content_type != 'text/plain':
575 raise MailUsageError, '''
576 Roundup requires the submission to be plain text. The message parser could
577 not find a text/plain part to use.
578 '''
580 else:
581 content = self.get_part_data_decoded(message)
583 summary, content = parseContent(content)
585 #
586 # handle the attachments
587 #
588 files = []
589 for (name, mime_type, data) in attachments:
590 if not name:
591 name = "unnamed"
592 files.append(self.db.file.create(type=mime_type, name=name,
593 content=data))
595 #
596 # now handle the db stuff
597 #
598 if nodeid:
599 # If an item designator (class name and id number) is found there,
600 # the newly created "msg" node is added to the "messages" property
601 # for that item, and any new "file" nodes are added to the "files"
602 # property for the item.
604 # if the message is currently 'unread' or 'resolved', then set
605 # it to 'chatting'
606 if properties.has_key('status'):
607 try:
608 # determine the id of 'unread', 'resolved' and 'chatting'
609 unread_id = self.db.status.lookup('unread')
610 resolved_id = self.db.status.lookup('resolved')
611 chatting_id = self.db.status.lookup('chatting')
612 except KeyError:
613 pass
614 else:
615 current_status = cl.get(nodeid, 'status')
616 if (not props.has_key('status') and
617 current_status == unread_id or
618 current_status == resolved_id):
619 props['status'] = chatting_id
621 # add nosy in arguments to issue's nosy list
622 if not props.has_key('nosy'): props['nosy'] = []
623 n = {}
624 for nid in cl.get(nodeid, 'nosy'):
625 n[nid] = 1
626 for value in props['nosy']:
627 if self.db.hasnode('user', value):
628 nid = value
629 else:
630 continue
631 if n.has_key(nid): continue
632 n[nid] = 1
633 props['nosy'] = n.keys()
634 # add assignedto to the nosy list
635 if props.has_key('assignedto'):
636 assignedto = props['assignedto']
637 if assignedto not in props['nosy']:
638 props['nosy'].append(assignedto)
640 message_id = self.db.msg.create(author=author,
641 recipients=recipients, date=date.Date('.'), summary=summary,
642 content=content, files=files, messageid=messageid,
643 inreplyto=inreplyto)
644 try:
645 messages = cl.get(nodeid, 'messages')
646 except IndexError:
647 raise MailUsageError, '''
648 The node specified by the designator in the subject of your message ("%s")
649 does not exist.
651 Subject was: "%s"
652 '''%(nodeid, subject)
653 messages.append(message_id)
654 props['messages'] = messages
656 # now apply the changes
657 try:
658 cl.set(nodeid, **props)
659 except (TypeError, IndexError, ValueError), message:
660 raise MailUsageError, '''
661 There was a problem with the message you sent:
662 %s
663 '''%message
664 # commit the changes to the DB
665 self.db.commit()
666 else:
667 # If just an item class name is found there, we attempt to create a
668 # new item of that class with its "messages" property initialized to
669 # contain the new "msg" node and its "files" property initialized to
670 # contain any new "file" nodes.
671 message_id = self.db.msg.create(author=author,
672 recipients=recipients, date=date.Date('.'), summary=summary,
673 content=content, files=files, messageid=messageid,
674 inreplyto=inreplyto)
676 # pre-set the issue to unread
677 if properties.has_key('status') and not props.has_key('status'):
678 try:
679 # determine the id of 'unread'
680 unread_id = self.db.status.lookup('unread')
681 except KeyError:
682 pass
683 else:
684 props['status'] = '1'
686 # set the title to the subject
687 if properties.has_key('title') and not props.has_key('title'):
688 props['title'] = title
690 # pre-load the messages list
691 props['messages'] = [message_id]
693 # set up (clean) the nosy list
694 nosy = props.get('nosy', [])
695 n = {}
696 for value in nosy:
697 nid = value
698 if n.has_key(nid): continue
699 n[nid] = 1
700 props['nosy'] = n.keys()
701 # add on the recipients of the message
702 for recipient in recipients:
703 if not n.has_key(recipient):
704 props['nosy'].append(recipient)
705 n[recipient] = 1
707 # add the author to the nosy list
708 if not n.has_key(author):
709 props['nosy'].append(author)
710 n[author] = 1
712 # add assignedto to the nosy list
713 if properties.has_key('assignedto') and props.has_key('assignedto'):
714 assignedto = props['assignedto']
715 if not n.has_key(assignedto):
716 props['nosy'].append(assignedto)
717 n[assignedto] = 1
719 # and attempt to create the new node
720 try:
721 nodeid = cl.create(**props)
722 except (TypeError, IndexError, ValueError), message:
723 raise MailUsageError, '''
724 There was a problem with the message you sent:
725 %s
726 '''%message
728 # commit the new node(s) to the DB
729 self.db.commit()
731 def parseContent(content, blank_line=re.compile(r'[\r\n]+\s*[\r\n]+'),
732 eol=re.compile(r'[\r\n]+'), signature=re.compile(r'^[>|\s]*[-_]+\s*$')):
733 ''' The message body is divided into sections by blank lines.
734 Sections where the second and all subsequent lines begin with a ">" or "|"
735 character are considered "quoting sections". The first line of the first
736 non-quoting section becomes the summary of the message.
737 '''
738 # strip off leading carriage-returns / newlines
739 i = 0
740 for i in range(len(content)):
741 if content[i] not in '\r\n':
742 break
743 if i > 0:
744 sections = blank_line.split(content[i:])
745 else:
746 sections = blank_line.split(content)
748 # extract out the summary from the message
749 summary = ''
750 l = []
751 for section in sections:
752 #section = section.strip()
753 if not section:
754 continue
755 lines = eol.split(section)
756 if (lines[0] and lines[0][0] in '>|') or (len(lines) > 1 and
757 lines[1] and lines[1][0] in '>|'):
758 # see if there's a response somewhere inside this section (ie.
759 # no blank line between quoted message and response)
760 for line in lines[1:]:
761 if line[0] not in '>|':
762 break
763 else:
764 # TODO: people who want to keep quoted bits will want the
765 # next line...
766 # l.append(section)
767 continue
768 # keep this section - it has reponse stuff in it
769 if not summary:
770 # and while we're at it, use the first non-quoted bit as
771 # our summary
772 summary = line
773 lines = lines[lines.index(line):]
774 section = '\n'.join(lines)
776 if not summary:
777 # if we don't have our summary yet use the first line of this
778 # section
779 summary = lines[0]
780 elif signature.match(lines[0]):
781 break
783 # and add the section to the output
784 l.append(section)
785 return summary, '\n\n'.join(l)
787 #
788 # $Log: not supported by cvs2svn $
789 # Revision 1.62 2002/02/05 14:15:29 grubert
790 # . respect encodings in non multipart messages.
791 #
792 # Revision 1.61 2002/02/04 09:40:21 grubert
793 # . add test for multipart messages with first part being encoded.
794 #
795 # Revision 1.60 2002/02/01 07:43:12 grubert
796 # . mailgw checks encoding on first part too.
797 #
798 # Revision 1.59 2002/01/23 21:43:23 richard
799 # tabnuke
800 #
801 # Revision 1.58 2002/01/23 21:41:56 richard
802 # . mailgw failures (unexpected ones) are forwarded to the roundup admin
803 #
804 # Revision 1.57 2002/01/22 22:27:43 richard
805 # . handle stripping of "AW:" from subject line
806 #
807 # Revision 1.56 2002/01/22 11:54:45 rochecompaan
808 # Fixed status change in mail gateway.
809 #
810 # Revision 1.55 2002/01/21 10:05:47 rochecompaan
811 # Feature:
812 # . the mail gateway now responds with an error message when invalid
813 # values for arguments are specified for link or multilink properties
814 # . modified unit test to check nosy and assignedto when specified as
815 # arguments
816 #
817 # Fixed:
818 # . fixed setting nosy as argument in subject line
819 #
820 # Revision 1.54 2002/01/16 09:14:45 grubert
821 # . if the attachment has no name, name it unnamed, happens with tnefs.
822 #
823 # Revision 1.53 2002/01/16 07:20:54 richard
824 # simple help command for mailgw
825 #
826 # Revision 1.52 2002/01/15 00:12:40 richard
827 # #503340 ] creating issue with [asignedto=p.ohly]
828 #
829 # Revision 1.51 2002/01/14 02:20:15 richard
830 # . changed all config accesses so they access either the instance or the
831 # config attriubute on the db. This means that all config is obtained from
832 # instance_config instead of the mish-mash of classes. This will make
833 # switching to a ConfigParser setup easier too, I hope.
834 #
835 # At a minimum, this makes migration a _little_ easier (a lot easier in the
836 # 0.5.0 switch, I hope!)
837 #
838 # Revision 1.50 2002/01/11 22:59:01 richard
839 # . #502342 ] pipe interface
840 #
841 # Revision 1.49 2002/01/10 06:19:18 richard
842 # followup lines directly after a quoted section were being eaten.
843 #
844 # Revision 1.48 2002/01/08 04:12:05 richard
845 # Changed message-id format to "<%s.%s.%s%s@%s>" so it complies with RFC822
846 #
847 # Revision 1.47 2002/01/02 02:32:38 richard
848 # ANONYMOUS_ACCESS -> ANONYMOUS_REGISTER
849 #
850 # Revision 1.46 2002/01/02 02:31:38 richard
851 # Sorry for the huge checkin message - I was only intending to implement #496356
852 # but I found a number of places where things had been broken by transactions:
853 # . modified ROUNDUPDBSENDMAILDEBUG to be SENDMAILDEBUG and hold a filename
854 # for _all_ roundup-generated smtp messages to be sent to.
855 # . the transaction cache had broken the roundupdb.Class set() reactors
856 # . newly-created author users in the mailgw weren't being committed to the db
857 #
858 # Stuff that made it into CHANGES.txt (ie. the stuff I was actually working
859 # on when I found that stuff :):
860 # . #496356 ] Use threading in messages
861 # . detectors were being registered multiple times
862 # . added tests for mailgw
863 # . much better attaching of erroneous messages in the mail gateway
864 #
865 # Revision 1.45 2001/12/20 15:43:01 rochecompaan
866 # Features added:
867 # . Multilink properties are now displayed as comma separated values in
868 # a textbox
869 # . The add user link is now only visible to the admin user
870 # . Modified the mail gateway to reject submissions from unknown
871 # addresses if ANONYMOUS_ACCESS is denied
872 #
873 # Revision 1.44 2001/12/18 15:30:34 rochecompaan
874 # Fixed bugs:
875 # . Fixed file creation and retrieval in same transaction in anydbm
876 # backend
877 # . Cgi interface now renders new issue after issue creation
878 # . Could not set issue status to resolved through cgi interface
879 # . Mail gateway was changing status back to 'chatting' if status was
880 # omitted as an argument
881 #
882 # Revision 1.43 2001/12/15 19:39:01 rochecompaan
883 # Oops.
884 #
885 # Revision 1.42 2001/12/15 19:24:39 rochecompaan
886 # . Modified cgi interface to change properties only once all changes are
887 # collected, files created and messages generated.
888 # . Moved generation of change note to nosyreactors.
889 # . We now check for changes to "assignedto" to ensure it's added to the
890 # nosy list.
891 #
892 # Revision 1.41 2001/12/10 00:57:38 richard
893 # From CHANGES:
894 # . Added the "display" command to the admin tool - displays a node's values
895 # . #489760 ] [issue] only subject
896 # . fixed the doc/index.html to include the quoting in the mail alias.
897 #
898 # Also:
899 # . fixed roundup-admin so it works with transactions
900 # . disabled the back_anydbm module if anydbm tries to use dumbdbm
901 #
902 # Revision 1.40 2001/12/05 14:26:44 rochecompaan
903 # Removed generation of change note from "sendmessage" in roundupdb.py.
904 # The change note is now generated when the message is created.
905 #
906 # Revision 1.39 2001/12/02 05:06:16 richard
907 # . We now use weakrefs in the Classes to keep the database reference, so
908 # the close() method on the database is no longer needed.
909 # I bumped the minimum python requirement up to 2.1 accordingly.
910 # . #487480 ] roundup-server
911 # . #487476 ] INSTALL.txt
912 #
913 # I also cleaned up the change message / post-edit stuff in the cgi client.
914 # There's now a clearly marked "TODO: append the change note" where I believe
915 # the change note should be added there. The "changes" list will obviously
916 # have to be modified to be a dict of the changes, or somesuch.
917 #
918 # More testing needed.
919 #
920 # Revision 1.38 2001/12/01 07:17:50 richard
921 # . We now have basic transaction support! Information is only written to
922 # the database when the commit() method is called. Only the anydbm
923 # backend is modified in this way - neither of the bsddb backends have been.
924 # The mail, admin and cgi interfaces all use commit (except the admin tool
925 # doesn't have a commit command, so interactive users can't commit...)
926 # . Fixed login/registration forwarding the user to the right page (or not,
927 # on a failure)
928 #
929 # Revision 1.37 2001/11/28 21:55:35 richard
930 # . login_action and newuser_action return values were being ignored
931 # . Woohoo! Found that bloody re-login bug that was killing the mail
932 # gateway.
933 # (also a minor cleanup in hyperdb)
934 #
935 # Revision 1.36 2001/11/26 22:55:56 richard
936 # Feature:
937 # . Added INSTANCE_NAME to configuration - used in web and email to identify
938 # the instance.
939 # . Added EMAIL_SIGNATURE_POSITION to indicate where to place the roundup
940 # signature info in e-mails.
941 # . Some more flexibility in the mail gateway and more error handling.
942 # . Login now takes you to the page you back to the were denied access to.
943 #
944 # Fixed:
945 # . Lots of bugs, thanks Roché and others on the devel mailing list!
946 #
947 # Revision 1.35 2001/11/22 15:46:42 jhermann
948 # Added module docstrings to all modules.
949 #
950 # Revision 1.34 2001/11/15 10:24:27 richard
951 # handle the case where there is no file attached
952 #
953 # Revision 1.33 2001/11/13 21:44:44 richard
954 # . re-open the database as the author in mail handling
955 #
956 # Revision 1.32 2001/11/12 22:04:29 richard
957 # oops, left debug in there
958 #
959 # Revision 1.31 2001/11/12 22:01:06 richard
960 # Fixed issues with nosy reaction and author copies.
961 #
962 # Revision 1.30 2001/11/09 22:33:28 richard
963 # More error handling fixes.
964 #
965 # Revision 1.29 2001/11/07 05:29:26 richard
966 # Modified roundup-mailgw so it can read e-mails from a local mail spool
967 # file. Truncates the spool file after parsing.
968 # Fixed a couple of small bugs introduced in roundup.mailgw when I started
969 # the popgw.
970 #
971 # Revision 1.28 2001/11/01 22:04:37 richard
972 # Started work on supporting a pop3-fetching server
973 # Fixed bugs:
974 # . bug #477104 ] HTML tag error in roundup-server
975 # . bug #477107 ] HTTP header problem
976 #
977 # Revision 1.27 2001/10/30 11:26:10 richard
978 # Case-insensitive match for ISSUE_TRACKER_EMAIL in address in e-mail.
979 #
980 # Revision 1.26 2001/10/30 00:54:45 richard
981 # Features:
982 # . #467129 ] Lossage when username=e-mail-address
983 # . #473123 ] Change message generation for author
984 # . MailGW now moves 'resolved' to 'chatting' on receiving e-mail for an issue.
985 #
986 # Revision 1.25 2001/10/28 23:22:28 richard
987 # fixed bug #474749 ] Indentations lost
988 #
989 # Revision 1.24 2001/10/23 22:57:52 richard
990 # Fix unread->chatting auto transition, thanks Roch'e
991 #
992 # Revision 1.23 2001/10/21 04:00:20 richard
993 # MailGW now moves 'unread' to 'chatting' on receiving e-mail for an issue.
994 #
995 # Revision 1.22 2001/10/21 03:35:13 richard
996 # bug #473125: Paragraph in e-mails
997 #
998 # Revision 1.21 2001/10/21 00:53:42 richard
999 # bug #473130: Nosy list not set correctly
1000 #
1001 # Revision 1.20 2001/10/17 23:13:19 richard
1002 # Did a fair bit of work on the admin tool. Now has an extra command "table"
1003 # which displays node information in a tabular format. Also fixed import and
1004 # export so they work. Removed freshen.
1005 # Fixed quopri usage in mailgw from bug reports.
1006 #
1007 # Revision 1.19 2001/10/11 23:43:04 richard
1008 # Implemented the comma-separated printing option in the admin tool.
1009 # Fixed a typo (more of a vim-o actually :) in mailgw.
1010 #
1011 # Revision 1.18 2001/10/11 06:38:57 richard
1012 # Initial cut at trying to handle people responding to CC'ed messages that
1013 # create an issue.
1014 #
1015 # Revision 1.17 2001/10/09 07:25:59 richard
1016 # Added the Password property type. See "pydoc roundup.password" for
1017 # implementation details. Have updated some of the documentation too.
1018 #
1019 # Revision 1.16 2001/10/05 02:23:24 richard
1020 # . roundup-admin create now prompts for property info if none is supplied
1021 # on the command-line.
1022 # . hyperdb Class getprops() method may now return only the mutable
1023 # properties.
1024 # . Login now uses cookies, which makes it a whole lot more flexible. We can
1025 # now support anonymous user access (read-only, unless there's an
1026 # "anonymous" user, in which case write access is permitted). Login
1027 # handling has been moved into cgi_client.Client.main()
1028 # . The "extended" schema is now the default in roundup init.
1029 # . The schemas have had their page headings modified to cope with the new
1030 # login handling. Existing installations should copy the interfaces.py
1031 # file from the roundup lib directory to their instance home.
1032 # . Incorrectly had a Bizar Software copyright on the cgitb.py module from
1033 # Ping - has been removed.
1034 # . Fixed a whole bunch of places in the CGI interface where we should have
1035 # been returning Not Found instead of throwing an exception.
1036 # . Fixed a deviation from the spec: trying to modify the 'id' property of
1037 # an item now throws an exception.
1038 #
1039 # Revision 1.15 2001/08/30 06:01:17 richard
1040 # Fixed missing import in mailgw :(
1041 #
1042 # Revision 1.14 2001/08/13 23:02:54 richard
1043 # Make the mail parser a little more robust.
1044 #
1045 # Revision 1.13 2001/08/12 06:32:36 richard
1046 # using isinstance(blah, Foo) now instead of isFooType
1047 #
1048 # Revision 1.12 2001/08/08 01:27:00 richard
1049 # Added better error handling to mailgw.
1050 #
1051 # Revision 1.11 2001/08/08 00:08:03 richard
1052 # oops ;)
1053 #
1054 # Revision 1.10 2001/08/07 00:24:42 richard
1055 # stupid typo
1056 #
1057 # Revision 1.9 2001/08/07 00:15:51 richard
1058 # Added the copyright/license notice to (nearly) all files at request of
1059 # Bizar Software.
1060 #
1061 # Revision 1.8 2001/08/05 07:06:07 richard
1062 # removed some print statements
1063 #
1064 # Revision 1.7 2001/08/03 07:18:22 richard
1065 # Implemented correct mail splitting (was taking a shortcut). Added unit
1066 # tests. Also snips signatures now too.
1067 #
1068 # Revision 1.6 2001/08/01 04:24:21 richard
1069 # mailgw was assuming certain properties existed on the issues being created.
1070 #
1071 # Revision 1.5 2001/07/29 07:01:39 richard
1072 # Added vim command to all source so that we don't get no steenkin' tabs :)
1073 #
1074 # Revision 1.4 2001/07/28 06:43:02 richard
1075 # Multipart message class has the getPart method now. Added some tests for it.
1076 #
1077 # Revision 1.3 2001/07/28 00:34:34 richard
1078 # Fixed some non-string node ids.
1079 #
1080 # Revision 1.2 2001/07/22 12:09:32 richard
1081 # Final commit of Grande Splite
1082 #
1083 #
1084 # vim: set filetype=python ts=4 sw=4 et si