a114a5898d530eaa07767e2620a1584f771d9444
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.72 2002-05-22 01:24:51 richard 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 return 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)
296 # check for well-formed subject line
297 if m:
298 # get the classname
299 classname = m.group('classname')
300 if classname is None:
301 # no classname, fallback on the default
302 if hasattr(self.instance, 'MAIL_DEFAULT_CLASS') and \
303 self.instance.MAIL_DEFAULT_CLASS:
304 classname = self.instance.MAIL_DEFAULT_CLASS
305 else:
306 # fail
307 m = None
309 if not m:
310 raise MailUsageError, '''
311 The message you sent to roundup did not contain a properly formed subject
312 line. The subject must contain a class name or designator to indicate the
313 "topic" of the message. For example:
314 Subject: [issue] This is a new issue
315 - this will create a new issue in the tracker with the title "This is
316 a new issue".
317 Subject: [issue1234] This is a followup to issue 1234
318 - this will append the message's contents to the existing issue 1234
319 in the tracker.
321 Subject was: "%s"
322 '''%subject
324 # get the class
325 try:
326 cl = self.db.getclass(classname)
327 except KeyError:
328 raise MailUsageError, '''
329 The class name you identified in the subject line ("%s") does not exist in the
330 database.
332 Valid class names are: %s
333 Subject was: "%s"
334 '''%(classname, ', '.join(self.db.getclasses()), subject)
336 # get the optional nodeid
337 nodeid = m.group('nodeid')
339 # title is optional too
340 title = m.group('title')
341 if title:
342 title = title.strip()
343 else:
344 title = ''
346 # but we do need either a title or a nodeid...
347 if not nodeid and not title:
348 raise MailUsageError, '''
349 I cannot match your message to a node in the database - you need to either
350 supply a full node identifier (with number, eg "[issue123]" or keep the
351 previous subject title intact so I can match that.
353 Subject was: "%s"
354 '''%subject
356 # extract the args
357 subject_args = m.group('args')
359 # If there's no nodeid, check to see if this is a followup and
360 # maybe someone's responded to the initial mail that created an
361 # entry. Try to find the matching nodes with the same title, and
362 # use the _last_ one matched (since that'll _usually_ be the most
363 # recent...)
364 if not nodeid and m.group('refwd'):
365 l = cl.stringFind(title=title)
366 if l:
367 nodeid = l[-1]
369 # start of the props
370 properties = cl.getprops()
371 props = {}
373 # handle the args
374 args = m.group('args')
375 if args:
376 for prop in string.split(args, ';'):
377 # extract the property name and value
378 try:
379 key, value = prop.split('=')
380 except ValueError, message:
381 raise MailUsageError, '''
382 Subject argument list not of form [arg=value,value,...;arg=value,value...]
383 (specific exception message was "%s")
385 Subject was: "%s"
386 '''%(message, subject)
388 # ensure it's a valid property name
389 key = key.strip()
390 try:
391 proptype = properties[key]
392 except KeyError:
393 raise MailUsageError, '''
394 Subject argument list refers to an invalid property: "%s"
396 Subject was: "%s"
397 '''%(key, subject)
399 # convert the string value to a real property value
400 if isinstance(proptype, hyperdb.String):
401 props[key] = value.strip()
402 if isinstance(proptype, hyperdb.Password):
403 props[key] = password.Password(value.strip())
404 elif isinstance(proptype, hyperdb.Date):
405 try:
406 props[key] = date.Date(value.strip())
407 except ValueError, message:
408 raise UsageError, '''
409 Subject argument list contains an invalid date for %s.
411 Error was: %s
412 Subject was: "%s"
413 '''%(key, message, subject)
414 elif isinstance(proptype, hyperdb.Interval):
415 try:
416 props[key] = date.Interval(value) # no strip needed
417 except ValueError, message:
418 raise UsageError, '''
419 Subject argument list contains an invalid date interval for %s.
421 Error was: %s
422 Subject was: "%s"
423 '''%(key, message, subject)
424 elif isinstance(proptype, hyperdb.Link):
425 linkcl = self.db.classes[proptype.classname]
426 propkey = linkcl.labelprop(default_to_id=1)
427 try:
428 props[key] = linkcl.lookup(value)
429 except KeyError, message:
430 raise MailUsageError, '''
431 Subject argument list contains an invalid value for %s.
433 Error was: %s
434 Subject was: "%s"
435 '''%(key, message, subject)
436 elif isinstance(proptype, hyperdb.Multilink):
437 # get the linked class
438 linkcl = self.db.classes[proptype.classname]
439 propkey = linkcl.labelprop(default_to_id=1)
440 for item in value.split(','):
441 item = item.strip()
442 try:
443 item = linkcl.lookup(item)
444 except KeyError, message:
445 raise MailUsageError, '''
446 Subject argument list contains an invalid value for %s.
448 Error was: %s
449 Subject was: "%s"
450 '''%(key, message, subject)
451 if props.has_key(key):
452 props[key].append(item)
453 else:
454 props[key] = [item]
456 #
457 # handle the users
458 #
460 # Don't create users if ANONYMOUS_REGISTER_MAIL is denied
461 # ... fall back on ANONYMOUS_REGISTER if the other doesn't exist
462 create = 1
463 if hasattr(self.instance, 'ANONYMOUS_REGISTER_MAIL'):
464 if self.instance.ANONYMOUS_REGISTER_MAIL == 'deny':
465 create = 0
466 elif self.instance.ANONYMOUS_REGISTER == 'deny':
467 create = 0
469 author = self.db.uidFromAddress(message.getaddrlist('from')[0],
470 create=create)
471 if not author:
472 raise UnAuthorized, '''
473 You are not a registered user.
475 Unknown address: %s
476 '''%message.getaddrlist('from')[0][1]
478 # the author may have been created - make sure the change is
479 # committed before we reopen the database
480 self.db.commit()
482 # reopen the database as the author
483 username = self.db.user.get(author, 'username')
484 self.db = self.instance.open(username)
486 # re-get the class with the new database connection
487 cl = self.db.getclass(classname)
489 # now update the recipients list
490 recipients = []
491 tracker_email = self.instance.ISSUE_TRACKER_EMAIL.lower()
492 for recipient in message.getaddrlist('to') + message.getaddrlist('cc'):
493 r = recipient[1].strip().lower()
494 if r == tracker_email or not r:
495 continue
497 # look up the recipient - create if necessary (and we're
498 # allowed to)
499 recipient = self.db.uidFromAddress(recipient, create)
501 # if all's well, add the recipient to the list
502 if recipient:
503 recipients.append(recipient)
505 #
506 # handle message-id and in-reply-to
507 #
508 messageid = message.getheader('message-id')
509 inreplyto = message.getheader('in-reply-to') or ''
510 # generate a messageid if there isn't one
511 if not messageid:
512 messageid = "<%s.%s.%s%s@%s>"%(time.time(), random.random(),
513 classname, nodeid, self.instance.MAIL_DOMAIN)
515 #
516 # now handle the body - find the message
517 #
518 content_type = message.gettype()
519 attachments = []
520 # General multipart handling:
521 # Take the first text/plain part, anything else is considered an
522 # attachment.
523 # multipart/mixed: multiple "unrelated" parts.
524 # multipart/signed (rfc 1847):
525 # The control information is carried in the second of the two
526 # required body parts.
527 # ACTION: Default, so if content is text/plain we get it.
528 # multipart/encrypted (rfc 1847):
529 # The control information is carried in the first of the two
530 # required body parts.
531 # ACTION: Not handleable as the content is encrypted.
532 # multipart/related (rfc 1872, 2112, 2387):
533 # The Multipart/Related content-type addresses the MIME
534 # representation of compound objects.
535 # ACTION: Default. If we are lucky there is a text/plain.
536 # TODO: One should use the start part and look for an Alternative
537 # that is text/plain.
538 # multipart/Alternative (rfc 1872, 1892):
539 # only in "related" ?
540 # multipart/report (rfc 1892):
541 # e.g. mail system delivery status reports.
542 # ACTION: Default. Could be ignored or used for Delivery Notification
543 # flagging.
544 # multipart/form-data:
545 # For web forms only.
546 if content_type == 'multipart/mixed':
547 # skip over the intro to the first boundary
548 part = message.getPart()
549 content = None
550 while 1:
551 # get the next part
552 part = message.getPart()
553 if part is None:
554 break
555 # parse it
556 subtype = part.gettype()
557 if subtype == 'text/plain' and not content:
558 # The first text/plain part is the message content.
559 content = self.get_part_data_decoded(part)
560 elif subtype == 'message/rfc822':
561 # handle message/rfc822 specially - the name should be
562 # the subject of the actual e-mail embedded here
563 i = part.fp.tell()
564 mailmess = Message(part.fp)
565 name = mailmess.getheader('subject')
566 part.fp.seek(i)
567 attachments.append((name, 'message/rfc822', part.fp.read()))
568 else:
569 # try name on Content-Type
570 name = part.getparam('name')
571 # this is just an attachment
572 data = self.get_part_data_decoded(part)
573 attachments.append((name, part.gettype(), data))
574 if content is None:
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 elif content_type[:10] == 'multipart/':
581 # skip over the intro to the first boundary
582 message.getPart()
583 content = None
584 while 1:
585 # get the next part
586 part = message.getPart()
587 if part is None:
588 break
589 # parse it
590 if part.gettype() == 'text/plain' and not content:
591 content = self.get_part_data_decoded(part)
592 if content is None:
593 raise MailUsageError, '''
594 Roundup requires the submission to be plain text. The message parser could
595 not find a text/plain part to use.
596 '''
598 elif content_type != 'text/plain':
599 raise MailUsageError, '''
600 Roundup requires the submission to be plain text. The message parser could
601 not find a text/plain part to use.
602 '''
604 else:
605 content = self.get_part_data_decoded(message)
607 # figure how much we should muck around with the email body
608 keep_citations = getattr(self.instance, 'EMAIL_KEEP_QUOTED_TEXT',
609 'no') == 'yes'
610 keep_body = getattr(self.instance, 'EMAIL_LEAVE_BODY_UNCHANGED',
611 'no') == 'yes'
613 # parse the body of the message, stripping out bits as appropriate
614 summary, content = parseContent(content, keep_citations,
615 keep_body)
617 #
618 # handle the attachments
619 #
620 files = []
621 for (name, mime_type, data) in attachments:
622 if not name:
623 name = "unnamed"
624 files.append(self.db.file.create(type=mime_type, name=name,
625 content=data))
627 #
628 # now handle the db stuff
629 #
630 if nodeid:
631 # If an item designator (class name and id number) is found there,
632 # the newly created "msg" node is added to the "messages" property
633 # for that item, and any new "file" nodes are added to the "files"
634 # property for the item.
636 # if the message is currently 'unread' or 'resolved', then set
637 # it to 'chatting'
638 if properties.has_key('status'):
639 try:
640 # determine the id of 'unread', 'resolved' and 'chatting'
641 unread_id = self.db.status.lookup('unread')
642 resolved_id = self.db.status.lookup('resolved')
643 chatting_id = self.db.status.lookup('chatting')
644 except KeyError:
645 pass
646 else:
647 current_status = cl.get(nodeid, 'status')
648 if (not props.has_key('status') and
649 current_status == unread_id or
650 current_status == resolved_id):
651 props['status'] = chatting_id
653 # update the nosy list
654 current = {}
655 for nid in cl.get(nodeid, 'nosy'):
656 current[nid] = 1
657 self.updateNosy(props, author, recipients, current)
659 # create the message
660 message_id = self.db.msg.create(author=author,
661 recipients=recipients, date=date.Date('.'), summary=summary,
662 content=content, files=files, messageid=messageid,
663 inreplyto=inreplyto)
664 try:
665 messages = cl.get(nodeid, 'messages')
666 except IndexError:
667 raise MailUsageError, '''
668 The node specified by the designator in the subject of your message ("%s")
669 does not exist.
671 Subject was: "%s"
672 '''%(nodeid, subject)
673 messages.append(message_id)
674 props['messages'] = messages
676 # now apply the changes
677 try:
678 cl.set(nodeid, **props)
679 except (TypeError, IndexError, ValueError), message:
680 raise MailUsageError, '''
681 There was a problem with the message you sent:
682 %s
683 '''%message
684 # commit the changes to the DB
685 self.db.commit()
686 else:
687 # If just an item class name is found there, we attempt to create a
688 # new item of that class with its "messages" property initialized to
689 # contain the new "msg" node and its "files" property initialized to
690 # contain any new "file" nodes.
691 message_id = self.db.msg.create(author=author,
692 recipients=recipients, date=date.Date('.'), summary=summary,
693 content=content, files=files, messageid=messageid,
694 inreplyto=inreplyto)
696 # pre-set the issue to unread
697 if properties.has_key('status') and not props.has_key('status'):
698 try:
699 # determine the id of 'unread'
700 unread_id = self.db.status.lookup('unread')
701 except KeyError:
702 pass
703 else:
704 props['status'] = '1'
706 # set the title to the subject
707 if properties.has_key('title') and not props.has_key('title'):
708 props['title'] = title
710 # pre-load the messages list
711 props['messages'] = [message_id]
713 # set up (clean) the nosy list
714 self.updateNosy(props, author, recipients)
716 # and attempt to create the new node
717 try:
718 nodeid = cl.create(**props)
719 except (TypeError, IndexError, ValueError), message:
720 raise MailUsageError, '''
721 There was a problem with the message you sent:
722 %s
723 '''%message
725 # commit the new node(s) to the DB
726 self.db.commit()
728 return nodeid
730 def updateNosy(self, props, author, recipients, current=None):
731 '''Determine what the nosy list should be given:
733 props: properties specified on the subject line of the message
734 author: the sender of the message
735 recipients: the recipients (to, cc) of the message
736 current: if the issue already exists, this is the current nosy
737 list, as a dictionary.
738 '''
739 if current is None:
740 current = {}
741 ok = ('new', 'yes')
742 else:
743 ok = ('yes',)
745 # add nosy in arguments to issue's nosy list
746 nosy = props.get('nosy', [])
747 for value in nosy:
748 if not self.db.hasnode('user', value):
749 continue
750 if not current.has_key(value):
751 current[value] = 1
753 # add the author to the nosy list
754 if getattr(self.instance, 'ADD_AUTHOR_TO_NOSY', 'new') in ok:
755 if not current.has_key(author):
756 current[author] = 1
758 # add on the recipients of the message
759 if getattr(self.instance, 'ADD_RECIPIENTS_TO_NOSY', 'new') in ok:
760 for recipient in recipients:
761 if not current.has_key(recipient):
762 current[recipient] = 1
764 # add assignedto to the nosy list
765 if props.has_key('assignedto'):
766 assignedto = props['assignedto']
767 if not current.has_key(assignedto):
768 current[assignedto] = 1
770 props['nosy'] = current.keys()
772 def parseContent(content, keep_citations, keep_body,
773 blank_line=re.compile(r'[\r\n]+\s*[\r\n]+'),
774 eol=re.compile(r'[\r\n]+'),
775 signature=re.compile(r'^[>|\s]*[-_]+\s*$'),
776 original_message=re.compile(r'^[>|\s]*-----Original Message-----$')):
777 ''' The message body is divided into sections by blank lines.
778 Sections where the second and all subsequent lines begin with a ">" or "|"
779 character are considered "quoting sections". The first line of the first
780 non-quoting section becomes the summary of the message.
781 '''
782 # strip off leading carriage-returns / newlines
783 i = 0
784 for i in range(len(content)):
785 if content[i] not in '\r\n':
786 break
787 if i > 0:
788 sections = blank_line.split(content[i:])
789 else:
790 sections = blank_line.split(content)
792 # extract out the summary from the message
793 summary = ''
794 l = []
795 for section in sections:
796 #section = section.strip()
797 if not section:
798 continue
799 lines = eol.split(section)
800 if (lines[0] and lines[0][0] in '>|') or (len(lines) > 1 and
801 lines[1] and lines[1][0] in '>|'):
802 # see if there's a response somewhere inside this section (ie.
803 # no blank line between quoted message and response)
804 for line in lines[1:]:
805 if line[0] not in '>|':
806 break
807 else:
808 # we keep quoted bits if specified in the config
809 if keep_citations:
810 l.append(section)
811 continue
812 # keep this section - it has reponse stuff in it
813 if not summary:
814 # and while we're at it, use the first non-quoted bit as
815 # our summary
816 summary = line
817 lines = lines[lines.index(line):]
818 section = '\n'.join(lines)
820 if not summary:
821 # if we don't have our summary yet use the first line of this
822 # section
823 summary = lines[0]
824 elif signature.match(lines[0]) and 2 <= len(lines) <= 10:
825 # lose any signature
826 break
827 elif original_message.match(lines[0]):
828 # ditch the stupid Outlook quoting of the entire original message
829 break
831 # and add the section to the output
832 l.append(section)
833 # we only set content for those who want to delete cruft from the
834 # message body, otherwise the body is left untouched.
835 if not keep_body:
836 content = '\n\n'.join(l)
837 return summary, content
839 #
840 # $Log: not supported by cvs2svn $
841 # Revision 1.71 2002/05/08 02:40:55 richard
842 # grr
843 #
844 # Revision 1.70 2002/05/06 23:40:07 richard
845 # hrm
846 #
847 # Revision 1.69 2002/05/06 23:37:21 richard
848 # Tweaking the signature deletion from mail messages.
849 # Added nuking of the "-----Original Message-----" crap from Outlook.
850 #
851 # Revision 1.68 2002/05/02 07:56:34 richard
852 # . added option to automatically add the authors and recipients of messages
853 # to the nosy lists with the options ADD_AUTHOR_TO_NOSY (default 'new') and
854 # ADD_RECIPIENTS_TO_NOSY (default 'new'). These settings emulate the current
855 # behaviour. Setting them to 'yes' will add the author/recipients to the nosy
856 # on messages that create issues and followup messages.
857 # . added missing documentation for a few of the config option values
858 #
859 # Revision 1.67 2002/04/23 15:46:49 rochecompaan
860 # . stripping of the email message body can now be controlled through
861 # the config variables EMAIL_KEEP_QUOTED_TEST and
862 # EMAIL_LEAVE_BODY_UNCHANGED.
863 #
864 # Revision 1.66 2002/03/14 23:59:24 richard
865 # . #517734 ] web header customisation is obscure
866 #
867 # Revision 1.65 2002/02/15 00:13:38 richard
868 # . #503204 ] mailgw needs a default class
869 # - partially done - the setting of additional properties can wait for a
870 # better configuration system.
871 #
872 # Revision 1.64 2002/02/14 23:46:02 richard
873 # . #516883 ] mail interface + ANONYMOUS_REGISTER
874 #
875 # Revision 1.63 2002/02/12 08:08:55 grubert
876 # . Clean up mail handling, multipart handling.
877 #
878 # Revision 1.62 2002/02/05 14:15:29 grubert
879 # . respect encodings in non multipart messages.
880 #
881 # Revision 1.61 2002/02/04 09:40:21 grubert
882 # . add test for multipart messages with first part being encoded.
883 #
884 # Revision 1.60 2002/02/01 07:43:12 grubert
885 # . mailgw checks encoding on first part too.
886 #
887 # Revision 1.59 2002/01/23 21:43:23 richard
888 # tabnuke
889 #
890 # Revision 1.58 2002/01/23 21:41:56 richard
891 # . mailgw failures (unexpected ones) are forwarded to the roundup admin
892 #
893 # Revision 1.57 2002/01/22 22:27:43 richard
894 # . handle stripping of "AW:" from subject line
895 #
896 # Revision 1.56 2002/01/22 11:54:45 rochecompaan
897 # Fixed status change in mail gateway.
898 #
899 # Revision 1.55 2002/01/21 10:05:47 rochecompaan
900 # Feature:
901 # . the mail gateway now responds with an error message when invalid
902 # values for arguments are specified for link or multilink properties
903 # . modified unit test to check nosy and assignedto when specified as
904 # arguments
905 #
906 # Fixed:
907 # . fixed setting nosy as argument in subject line
908 #
909 # Revision 1.54 2002/01/16 09:14:45 grubert
910 # . if the attachment has no name, name it unnamed, happens with tnefs.
911 #
912 # Revision 1.53 2002/01/16 07:20:54 richard
913 # simple help command for mailgw
914 #
915 # Revision 1.52 2002/01/15 00:12:40 richard
916 # #503340 ] creating issue with [asignedto=p.ohly]
917 #
918 # Revision 1.51 2002/01/14 02:20:15 richard
919 # . changed all config accesses so they access either the instance or the
920 # config attriubute on the db. This means that all config is obtained from
921 # instance_config instead of the mish-mash of classes. This will make
922 # switching to a ConfigParser setup easier too, I hope.
923 #
924 # At a minimum, this makes migration a _little_ easier (a lot easier in the
925 # 0.5.0 switch, I hope!)
926 #
927 # Revision 1.50 2002/01/11 22:59:01 richard
928 # . #502342 ] pipe interface
929 #
930 # Revision 1.49 2002/01/10 06:19:18 richard
931 # followup lines directly after a quoted section were being eaten.
932 #
933 # Revision 1.48 2002/01/08 04:12:05 richard
934 # Changed message-id format to "<%s.%s.%s%s@%s>" so it complies with RFC822
935 #
936 # Revision 1.47 2002/01/02 02:32:38 richard
937 # ANONYMOUS_ACCESS -> ANONYMOUS_REGISTER
938 #
939 # Revision 1.46 2002/01/02 02:31:38 richard
940 # Sorry for the huge checkin message - I was only intending to implement #496356
941 # but I found a number of places where things had been broken by transactions:
942 # . modified ROUNDUPDBSENDMAILDEBUG to be SENDMAILDEBUG and hold a filename
943 # for _all_ roundup-generated smtp messages to be sent to.
944 # . the transaction cache had broken the roundupdb.Class set() reactors
945 # . newly-created author users in the mailgw weren't being committed to the db
946 #
947 # Stuff that made it into CHANGES.txt (ie. the stuff I was actually working
948 # on when I found that stuff :):
949 # . #496356 ] Use threading in messages
950 # . detectors were being registered multiple times
951 # . added tests for mailgw
952 # . much better attaching of erroneous messages in the mail gateway
953 #
954 # Revision 1.45 2001/12/20 15:43:01 rochecompaan
955 # Features added:
956 # . Multilink properties are now displayed as comma separated values in
957 # a textbox
958 # . The add user link is now only visible to the admin user
959 # . Modified the mail gateway to reject submissions from unknown
960 # addresses if ANONYMOUS_ACCESS is denied
961 #
962 # Revision 1.44 2001/12/18 15:30:34 rochecompaan
963 # Fixed bugs:
964 # . Fixed file creation and retrieval in same transaction in anydbm
965 # backend
966 # . Cgi interface now renders new issue after issue creation
967 # . Could not set issue status to resolved through cgi interface
968 # . Mail gateway was changing status back to 'chatting' if status was
969 # omitted as an argument
970 #
971 # Revision 1.43 2001/12/15 19:39:01 rochecompaan
972 # Oops.
973 #
974 # Revision 1.42 2001/12/15 19:24:39 rochecompaan
975 # . Modified cgi interface to change properties only once all changes are
976 # collected, files created and messages generated.
977 # . Moved generation of change note to nosyreactors.
978 # . We now check for changes to "assignedto" to ensure it's added to the
979 # nosy list.
980 #
981 # Revision 1.41 2001/12/10 00:57:38 richard
982 # From CHANGES:
983 # . Added the "display" command to the admin tool - displays a node's values
984 # . #489760 ] [issue] only subject
985 # . fixed the doc/index.html to include the quoting in the mail alias.
986 #
987 # Also:
988 # . fixed roundup-admin so it works with transactions
989 # . disabled the back_anydbm module if anydbm tries to use dumbdbm
990 #
991 # Revision 1.40 2001/12/05 14:26:44 rochecompaan
992 # Removed generation of change note from "sendmessage" in roundupdb.py.
993 # The change note is now generated when the message is created.
994 #
995 # Revision 1.39 2001/12/02 05:06:16 richard
996 # . We now use weakrefs in the Classes to keep the database reference, so
997 # the close() method on the database is no longer needed.
998 # I bumped the minimum python requirement up to 2.1 accordingly.
999 # . #487480 ] roundup-server
1000 # . #487476 ] INSTALL.txt
1001 #
1002 # I also cleaned up the change message / post-edit stuff in the cgi client.
1003 # There's now a clearly marked "TODO: append the change note" where I believe
1004 # the change note should be added there. The "changes" list will obviously
1005 # have to be modified to be a dict of the changes, or somesuch.
1006 #
1007 # More testing needed.
1008 #
1009 # Revision 1.38 2001/12/01 07:17:50 richard
1010 # . We now have basic transaction support! Information is only written to
1011 # the database when the commit() method is called. Only the anydbm
1012 # backend is modified in this way - neither of the bsddb backends have been.
1013 # The mail, admin and cgi interfaces all use commit (except the admin tool
1014 # doesn't have a commit command, so interactive users can't commit...)
1015 # . Fixed login/registration forwarding the user to the right page (or not,
1016 # on a failure)
1017 #
1018 # Revision 1.37 2001/11/28 21:55:35 richard
1019 # . login_action and newuser_action return values were being ignored
1020 # . Woohoo! Found that bloody re-login bug that was killing the mail
1021 # gateway.
1022 # (also a minor cleanup in hyperdb)
1023 #
1024 # Revision 1.36 2001/11/26 22:55:56 richard
1025 # Feature:
1026 # . Added INSTANCE_NAME to configuration - used in web and email to identify
1027 # the instance.
1028 # . Added EMAIL_SIGNATURE_POSITION to indicate where to place the roundup
1029 # signature info in e-mails.
1030 # . Some more flexibility in the mail gateway and more error handling.
1031 # . Login now takes you to the page you back to the were denied access to.
1032 #
1033 # Fixed:
1034 # . Lots of bugs, thanks Roché and others on the devel mailing list!
1035 #
1036 # Revision 1.35 2001/11/22 15:46:42 jhermann
1037 # Added module docstrings to all modules.
1038 #
1039 # Revision 1.34 2001/11/15 10:24:27 richard
1040 # handle the case where there is no file attached
1041 #
1042 # Revision 1.33 2001/11/13 21:44:44 richard
1043 # . re-open the database as the author in mail handling
1044 #
1045 # Revision 1.32 2001/11/12 22:04:29 richard
1046 # oops, left debug in there
1047 #
1048 # Revision 1.31 2001/11/12 22:01:06 richard
1049 # Fixed issues with nosy reaction and author copies.
1050 #
1051 # Revision 1.30 2001/11/09 22:33:28 richard
1052 # More error handling fixes.
1053 #
1054 # Revision 1.29 2001/11/07 05:29:26 richard
1055 # Modified roundup-mailgw so it can read e-mails from a local mail spool
1056 # file. Truncates the spool file after parsing.
1057 # Fixed a couple of small bugs introduced in roundup.mailgw when I started
1058 # the popgw.
1059 #
1060 # Revision 1.28 2001/11/01 22:04:37 richard
1061 # Started work on supporting a pop3-fetching server
1062 # Fixed bugs:
1063 # . bug #477104 ] HTML tag error in roundup-server
1064 # . bug #477107 ] HTTP header problem
1065 #
1066 # Revision 1.27 2001/10/30 11:26:10 richard
1067 # Case-insensitive match for ISSUE_TRACKER_EMAIL in address in e-mail.
1068 #
1069 # Revision 1.26 2001/10/30 00:54:45 richard
1070 # Features:
1071 # . #467129 ] Lossage when username=e-mail-address
1072 # . #473123 ] Change message generation for author
1073 # . MailGW now moves 'resolved' to 'chatting' on receiving e-mail for an issue.
1074 #
1075 # Revision 1.25 2001/10/28 23:22:28 richard
1076 # fixed bug #474749 ] Indentations lost
1077 #
1078 # Revision 1.24 2001/10/23 22:57:52 richard
1079 # Fix unread->chatting auto transition, thanks Roch'e
1080 #
1081 # Revision 1.23 2001/10/21 04:00:20 richard
1082 # MailGW now moves 'unread' to 'chatting' on receiving e-mail for an issue.
1083 #
1084 # Revision 1.22 2001/10/21 03:35:13 richard
1085 # bug #473125: Paragraph in e-mails
1086 #
1087 # Revision 1.21 2001/10/21 00:53:42 richard
1088 # bug #473130: Nosy list not set correctly
1089 #
1090 # Revision 1.20 2001/10/17 23:13:19 richard
1091 # Did a fair bit of work on the admin tool. Now has an extra command "table"
1092 # which displays node information in a tabular format. Also fixed import and
1093 # export so they work. Removed freshen.
1094 # Fixed quopri usage in mailgw from bug reports.
1095 #
1096 # Revision 1.19 2001/10/11 23:43:04 richard
1097 # Implemented the comma-separated printing option in the admin tool.
1098 # Fixed a typo (more of a vim-o actually :) in mailgw.
1099 #
1100 # Revision 1.18 2001/10/11 06:38:57 richard
1101 # Initial cut at trying to handle people responding to CC'ed messages that
1102 # create an issue.
1103 #
1104 # Revision 1.17 2001/10/09 07:25:59 richard
1105 # Added the Password property type. See "pydoc roundup.password" for
1106 # implementation details. Have updated some of the documentation too.
1107 #
1108 # Revision 1.16 2001/10/05 02:23:24 richard
1109 # . roundup-admin create now prompts for property info if none is supplied
1110 # on the command-line.
1111 # . hyperdb Class getprops() method may now return only the mutable
1112 # properties.
1113 # . Login now uses cookies, which makes it a whole lot more flexible. We can
1114 # now support anonymous user access (read-only, unless there's an
1115 # "anonymous" user, in which case write access is permitted). Login
1116 # handling has been moved into cgi_client.Client.main()
1117 # . The "extended" schema is now the default in roundup init.
1118 # . The schemas have had their page headings modified to cope with the new
1119 # login handling. Existing installations should copy the interfaces.py
1120 # file from the roundup lib directory to their instance home.
1121 # . Incorrectly had a Bizar Software copyright on the cgitb.py module from
1122 # Ping - has been removed.
1123 # . Fixed a whole bunch of places in the CGI interface where we should have
1124 # been returning Not Found instead of throwing an exception.
1125 # . Fixed a deviation from the spec: trying to modify the 'id' property of
1126 # an item now throws an exception.
1127 #
1128 # Revision 1.15 2001/08/30 06:01:17 richard
1129 # Fixed missing import in mailgw :(
1130 #
1131 # Revision 1.14 2001/08/13 23:02:54 richard
1132 # Make the mail parser a little more robust.
1133 #
1134 # Revision 1.13 2001/08/12 06:32:36 richard
1135 # using isinstance(blah, Foo) now instead of isFooType
1136 #
1137 # Revision 1.12 2001/08/08 01:27:00 richard
1138 # Added better error handling to mailgw.
1139 #
1140 # Revision 1.11 2001/08/08 00:08:03 richard
1141 # oops ;)
1142 #
1143 # Revision 1.10 2001/08/07 00:24:42 richard
1144 # stupid typo
1145 #
1146 # Revision 1.9 2001/08/07 00:15:51 richard
1147 # Added the copyright/license notice to (nearly) all files at request of
1148 # Bizar Software.
1149 #
1150 # Revision 1.8 2001/08/05 07:06:07 richard
1151 # removed some print statements
1152 #
1153 # Revision 1.7 2001/08/03 07:18:22 richard
1154 # Implemented correct mail splitting (was taking a shortcut). Added unit
1155 # tests. Also snips signatures now too.
1156 #
1157 # Revision 1.6 2001/08/01 04:24:21 richard
1158 # mailgw was assuming certain properties existed on the issues being created.
1159 #
1160 # Revision 1.5 2001/07/29 07:01:39 richard
1161 # Added vim command to all source so that we don't get no steenkin' tabs :)
1162 #
1163 # Revision 1.4 2001/07/28 06:43:02 richard
1164 # Multipart message class has the getPart method now. Added some tests for it.
1165 #
1166 # Revision 1.3 2001/07/28 00:34:34 richard
1167 # Fixed some non-string node ids.
1168 #
1169 # Revision 1.2 2001/07/22 12:09:32 richard
1170 # Final commit of Grande Splite
1171 #
1172 #
1173 # vim: set filetype=python ts=4 sw=4 et si