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.92 2002-09-26 03:03:18 richard Exp $
77 '''
79 import string, re, os, mimetools, cStringIO, smtplib, socket, binascii, quopri
80 import time, random, sys
81 import traceback, MimeWriter
82 import hyperdb, date, password
84 SENDMAILDEBUG = os.environ.get('SENDMAILDEBUG', '')
86 class MailGWError(ValueError):
87 pass
89 class MailUsageError(ValueError):
90 pass
92 class MailUsageHelp(Exception):
93 pass
95 class Unauthorized(Exception):
96 """ Access denied """
98 def initialiseSecurity(security):
99 ''' Create some Permissions and Roles on the security object
101 This function is directly invoked by security.Security.__init__()
102 as a part of the Security object instantiation.
103 '''
104 security.addPermission(name="Email Registration",
105 description="Anonymous may register through e-mail")
106 p = security.addPermission(name="Email Access",
107 description="User may use the email interface")
108 security.addPermissionToRole('Admin', p)
110 class Message(mimetools.Message):
111 ''' subclass mimetools.Message so we can retrieve the parts of the
112 message...
113 '''
114 def getPart(self):
115 ''' Get a single part of a multipart message and return it as a new
116 Message instance.
117 '''
118 boundary = self.getparam('boundary')
119 mid, end = '--'+boundary, '--'+boundary+'--'
120 s = cStringIO.StringIO()
121 while 1:
122 line = self.fp.readline()
123 if not line:
124 break
125 if line.strip() in (mid, end):
126 break
127 s.write(line)
128 if not s.getvalue().strip():
129 return None
130 s.seek(0)
131 return Message(s)
133 subject_re = re.compile(r'(?P<refwd>\s*\W?\s*(fwd|re|aw)\s*\W?\s*)*'
134 r'\s*(?P<quote>")?(\[(?P<classname>[^\d\s]+)(?P<nodeid>\d+)?\])?'
135 r'\s*(?P<title>[^[]+)?"?(\[(?P<args>.+?)\])?', re.I)
137 class MailGW:
138 def __init__(self, instance, db):
139 self.instance = instance
140 self.db = db
142 # should we trap exceptions (normal usage) or pass them through
143 # (for testing)
144 self.trapExceptions = 1
146 def do_pipe(self):
147 ''' Read a message from standard input and pass it to the mail handler.
148 '''
149 self.main(sys.stdin)
150 return 0
152 def do_mailbox(self, filename):
153 ''' Read a series of messages from the specified unix mailbox file and
154 pass each to the mail handler.
155 '''
156 # open the spool file and lock it
157 import fcntl, FCNTL
158 f = open(filename, 'r+')
159 fcntl.flock(f.fileno(), FCNTL.LOCK_EX)
161 # handle and clear the mailbox
162 try:
163 from mailbox import UnixMailbox
164 mailbox = UnixMailbox(f, factory=Message)
165 # grab one message
166 message = mailbox.next()
167 while message:
168 # handle this message
169 self.handle_Message(message)
170 message = mailbox.next()
171 # nuke the file contents
172 os.ftruncate(f.fileno(), 0)
173 except:
174 import traceback
175 traceback.print_exc()
176 return 1
177 fcntl.flock(f.fileno(), FCNTL.LOCK_UN)
178 return 0
180 def do_pop(self, server, user='', password=''):
181 '''Read a series of messages from the specified POP server.
182 '''
183 import getpass, poplib, socket
184 try:
185 if not user:
186 user = raw_input(_('User: '))
187 if not password:
188 password = getpass.getpass()
189 except (KeyboardInterrupt, EOFError):
190 # Ctrl C or D maybe also Ctrl Z under Windows.
191 print "\nAborted by user."
192 return 1
194 # open a connection to the server and retrieve all messages
195 try:
196 server = poplib.POP3(server)
197 except socket.error, message:
198 print "POP server error:", message
199 return 1
200 server.user(user)
201 server.pass_(password)
202 numMessages = len(server.list()[1])
203 for i in range(1, numMessages+1):
204 # retr: returns
205 # [ pop response e.g. '+OK 459 octets',
206 # [ array of message lines ],
207 # number of octets ]
208 lines = server.retr(i)[1]
209 s = cStringIO.StringIO('\n'.join(lines))
210 s.seek(0)
211 self.handle_Message(Message(s))
212 # delete the message
213 server.dele(i)
215 # quit the server to commit changes.
216 server.quit()
217 return 0
219 def main(self, fp):
220 ''' fp - the file from which to read the Message.
221 '''
222 return self.handle_Message(Message(fp))
224 def handle_Message(self, message):
225 '''Handle an RFC822 Message
227 Handle the Message object by calling handle_message() and then cope
228 with any errors raised by handle_message.
229 This method's job is to make that call and handle any
230 errors in a sane manner. It should be replaced if you wish to
231 handle errors in a different manner.
232 '''
233 # in some rare cases, a particularly stuffed-up e-mail will make
234 # its way into here... try to handle it gracefully
235 sendto = message.getaddrlist('from')
236 if sendto:
237 if not self.trapExceptions:
238 return self.handle_message(message)
239 try:
240 return self.handle_message(message)
241 except MailUsageHelp:
242 # bounce the message back to the sender with the usage message
243 fulldoc = '\n'.join(string.split(__doc__, '\n')[2:])
244 sendto = [sendto[0][1]]
245 m = ['']
246 m.append('\n\nMail Gateway Help\n=================')
247 m.append(fulldoc)
248 m = self.bounce_message(message, sendto, m,
249 subject="Mail Gateway Help")
250 except MailUsageError, value:
251 # bounce the message back to the sender with the usage message
252 fulldoc = '\n'.join(string.split(__doc__, '\n')[2:])
253 sendto = [sendto[0][1]]
254 m = ['']
255 m.append(str(value))
256 m.append('\n\nMail Gateway Help\n=================')
257 m.append(fulldoc)
258 m = self.bounce_message(message, sendto, m)
259 except Unauthorized, value:
260 # just inform the user that he is not authorized
261 sendto = [sendto[0][1]]
262 m = ['']
263 m.append(str(value))
264 m = self.bounce_message(message, sendto, m)
265 except:
266 # bounce the message back to the sender with the error message
267 sendto = [sendto[0][1], self.instance.config.ADMIN_EMAIL]
268 m = ['']
269 m.append('An unexpected error occurred during the processing')
270 m.append('of your message. The tracker administrator is being')
271 m.append('notified.\n')
272 m.append('---- traceback of failure ----')
273 s = cStringIO.StringIO()
274 import traceback
275 traceback.print_exc(None, s)
276 m.append(s.getvalue())
277 m = self.bounce_message(message, sendto, m)
278 else:
279 # very bad-looking message - we don't even know who sent it
280 sendto = [self.instance.config.ADMIN_EMAIL]
281 m = ['Subject: badly formed message from mail gateway']
282 m.append('')
283 m.append('The mail gateway retrieved a message which has no From:')
284 m.append('line, indicating that it is corrupt. Please check your')
285 m.append('mail gateway source. Failed message is attached.')
286 m.append('')
287 m = self.bounce_message(message, sendto, m,
288 subject='Badly formed message from mail gateway')
290 # now send the message
291 if SENDMAILDEBUG:
292 open(SENDMAILDEBUG, 'w').write('From: %s\nTo: %s\n%s\n'%(
293 self.instance.config.ADMIN_EMAIL, ', '.join(sendto),
294 m.getvalue()))
295 else:
296 try:
297 smtp = smtplib.SMTP(self.instance.config.MAILHOST)
298 smtp.sendmail(self.instance.config.ADMIN_EMAIL, sendto,
299 m.getvalue())
300 except socket.error, value:
301 raise MailGWError, "Couldn't send error email: "\
302 "mailhost %s"%value
303 except smtplib.SMTPException, value:
304 raise MailGWError, "Couldn't send error email: %s"%value
306 def bounce_message(self, message, sendto, error,
307 subject='Failed issue tracker submission'):
308 ''' create a message that explains the reason for the failed
309 issue submission to the author and attach the original
310 message.
311 '''
312 msg = cStringIO.StringIO()
313 writer = MimeWriter.MimeWriter(msg)
314 writer.addheader('Subject', subject)
315 writer.addheader('From', '%s <%s>'% (self.instance.config.TRACKER_NAME,
316 self.instance.config.TRACKER_EMAIL))
317 writer.addheader('To', ','.join(sendto))
318 writer.addheader('MIME-Version', '1.0')
319 part = writer.startmultipartbody('mixed')
320 part = writer.nextpart()
321 body = part.startbody('text/plain')
322 body.write('\n'.join(error))
324 # reconstruct the original message
325 m = cStringIO.StringIO()
326 w = MimeWriter.MimeWriter(m)
327 # default the content_type, just in case...
328 content_type = 'text/plain'
329 # add the headers except the content-type
330 for header in message.headers:
331 header_name = header.split(':')[0]
332 if header_name.lower() == 'content-type':
333 content_type = message.getheader(header_name)
334 elif message.getheader(header_name):
335 w.addheader(header_name, message.getheader(header_name))
336 # now attach the message body
337 body = w.startbody(content_type)
338 try:
339 message.rewindbody()
340 except IOError:
341 body.write("*** couldn't include message body: read from pipe ***")
342 else:
343 body.write(message.fp.read())
345 # attach the original message to the returned message
346 part = writer.nextpart()
347 part.addheader('Content-Disposition','attachment')
348 part.addheader('Content-Description','Message you sent')
349 part.addheader('Content-Transfer-Encoding', '7bit')
350 body = part.startbody('message/rfc822')
351 body.write(m.getvalue())
353 writer.lastpart()
354 return msg
356 def get_part_data_decoded(self,part):
357 encoding = part.getencoding()
358 data = None
359 if encoding == 'base64':
360 # BUG: is base64 really used for text encoding or
361 # are we inserting zip files here.
362 data = binascii.a2b_base64(part.fp.read())
363 elif encoding == 'quoted-printable':
364 # the quopri module wants to work with files
365 decoded = cStringIO.StringIO()
366 quopri.decode(part.fp, decoded)
367 data = decoded.getvalue()
368 elif encoding == 'uuencoded':
369 data = binascii.a2b_uu(part.fp.read())
370 else:
371 # take it as text
372 data = part.fp.read()
373 return data
375 def handle_message(self, message):
376 ''' message - a Message instance
378 Parse the message as per the module docstring.
379 '''
380 # handle the subject line
381 subject = message.getheader('subject', '')
383 if subject.strip() == 'help':
384 raise MailUsageHelp
386 m = subject_re.match(subject)
388 # check for well-formed subject line
389 if m:
390 # get the classname
391 classname = m.group('classname')
392 if classname is None:
393 # no classname, fallback on the default
394 if hasattr(self.instance.config, 'MAIL_DEFAULT_CLASS') and \
395 self.instance.config.MAIL_DEFAULT_CLASS:
396 classname = self.instance.config.MAIL_DEFAULT_CLASS
397 else:
398 # fail
399 m = None
401 if not m:
402 raise MailUsageError, '''
403 The message you sent to roundup did not contain a properly formed subject
404 line. The subject must contain a class name or designator to indicate the
405 "topic" of the message. For example:
406 Subject: [issue] This is a new issue
407 - this will create a new issue in the tracker with the title "This is
408 a new issue".
409 Subject: [issue1234] This is a followup to issue 1234
410 - this will append the message's contents to the existing issue 1234
411 in the tracker.
413 Subject was: "%s"
414 '''%subject
416 # get the class
417 try:
418 cl = self.db.getclass(classname)
419 except KeyError:
420 raise MailUsageError, '''
421 The class name you identified in the subject line ("%s") does not exist in the
422 database.
424 Valid class names are: %s
425 Subject was: "%s"
426 '''%(classname, ', '.join(self.db.getclasses()), subject)
428 # get the optional nodeid
429 nodeid = m.group('nodeid')
431 # title is optional too
432 title = m.group('title')
433 if title:
434 title = title.strip()
435 else:
436 title = ''
438 # strip off the quotes that dumb emailers put around the subject, like
439 # Re: "[issue1] bla blah"
440 if m.group('quote') and title.endswith('"'):
441 title = title[:-1]
443 # but we do need either a title or a nodeid...
444 if nodeid is None and not title:
445 raise MailUsageError, '''
446 I cannot match your message to a node in the database - you need to either
447 supply a full node identifier (with number, eg "[issue123]" or keep the
448 previous subject title intact so I can match that.
450 Subject was: "%s"
451 '''%subject
453 # If there's no nodeid, check to see if this is a followup and
454 # maybe someone's responded to the initial mail that created an
455 # entry. Try to find the matching nodes with the same title, and
456 # use the _last_ one matched (since that'll _usually_ be the most
457 # recent...)
458 if nodeid is None and m.group('refwd'):
459 l = cl.stringFind(title=title)
460 if l:
461 nodeid = l[-1]
463 # if a nodeid was specified, make sure it's valid
464 if nodeid is not None and not cl.hasnode(nodeid):
465 raise MailUsageError, '''
466 The node specified by the designator in the subject of your message ("%s")
467 does not exist.
469 Subject was: "%s"
470 '''%(nodeid, subject)
472 #
473 # handle the users
474 #
475 # Don't create users if anonymous isn't allowed to register
476 create = 1
477 anonid = self.db.user.lookup('anonymous')
478 if not self.db.security.hasPermission('Email Registration', anonid):
479 create = 0
481 # ok, now figure out who the author is - create a new user if the
482 # "create" flag is true
483 author = uidFromAddress(self.db, message.getaddrlist('from')[0],
484 create=create)
486 # no author? means we're not author
487 if not author:
488 raise Unauthorized, '''
489 You are not a registered user.
491 Unknown address: %s
492 '''%message.getaddrlist('from')[0][1]
494 # make sure the author has permission to use the email interface
495 if not self.db.security.hasPermission('Email Access', author):
496 raise Unauthorized, 'You are not permitted to access this tracker.'
498 # make sure they're allowed to edit this class of information
499 if not self.db.security.hasPermission('Edit', author, classname):
500 raise Unauthorized, 'You are not permitted to edit %s.'%classname
502 # the author may have been created - make sure the change is
503 # committed before we reopen the database
504 self.db.commit()
506 # reopen the database as the author
507 username = self.db.user.get(author, 'username')
508 self.db.close()
509 self.db = self.instance.open(username)
511 # re-get the class with the new database connection
512 cl = self.db.getclass(classname)
514 # now update the recipients list
515 recipients = []
516 tracker_email = self.instance.config.TRACKER_EMAIL.lower()
517 for recipient in message.getaddrlist('to') + message.getaddrlist('cc'):
518 r = recipient[1].strip().lower()
519 if r == tracker_email or not r:
520 continue
522 # look up the recipient - create if necessary (and we're
523 # allowed to)
524 recipient = uidFromAddress(self.db, recipient, create)
526 # if all's well, add the recipient to the list
527 if recipient:
528 recipients.append(recipient)
530 #
531 # extract the args
532 #
533 subject_args = m.group('args')
535 #
536 # handle the subject argument list
537 #
538 # figure what the properties of this Class are
539 properties = cl.getprops()
540 props = {}
541 args = m.group('args')
542 if args:
543 errors = []
544 for prop in string.split(args, ';'):
545 # extract the property name and value
546 try:
547 propname, value = prop.split('=')
548 except ValueError, message:
549 errors.append('not of form [arg=value,'
550 'value,...;arg=value,value...]')
551 break
553 # ensure it's a valid property name
554 propname = propname.strip()
555 try:
556 proptype = properties[propname]
557 except KeyError:
558 errors.append('refers to an invalid property: '
559 '"%s"'%propname)
560 continue
562 # convert the string value to a real property value
563 if isinstance(proptype, hyperdb.String):
564 props[propname] = value.strip()
565 if isinstance(proptype, hyperdb.Password):
566 props[propname] = password.Password(value.strip())
567 elif isinstance(proptype, hyperdb.Date):
568 try:
569 props[propname] = date.Date(value.strip())
570 except ValueError, message:
571 errors.append('contains an invalid date for '
572 '%s.'%propname)
573 elif isinstance(proptype, hyperdb.Interval):
574 try:
575 props[propname] = date.Interval(value)
576 except ValueError, message:
577 errors.append('contains an invalid date interval'
578 'for %s.'%propname)
579 elif isinstance(proptype, hyperdb.Link):
580 linkcl = self.db.classes[proptype.classname]
581 propkey = linkcl.labelprop(default_to_id=1)
582 try:
583 props[propname] = linkcl.lookup(value)
584 except KeyError, message:
585 errors.append('"%s" is not a value for %s.'%(value,
586 propname))
587 elif isinstance(proptype, hyperdb.Multilink):
588 # get the linked class
589 linkcl = self.db.classes[proptype.classname]
590 propkey = linkcl.labelprop(default_to_id=1)
591 if nodeid:
592 curvalue = cl.get(nodeid, propname)
593 else:
594 curvalue = []
596 # handle each add/remove in turn
597 # keep an extra list for all items that are
598 # definitely in the new list (in case of e.g.
599 # <propname>=A,+B, which should replace the old
600 # list with A,B)
601 set = 0
602 newvalue = []
603 for item in value.split(','):
604 item = item.strip()
606 # handle +/-
607 remove = 0
608 if item.startswith('-'):
609 remove = 1
610 item = item[1:]
611 elif item.startswith('+'):
612 item = item[1:]
613 else:
614 set = 1
616 # look up the value
617 try:
618 item = linkcl.lookup(item)
619 except KeyError, message:
620 errors.append('"%s" is not a value for %s.'%(item,
621 propname))
622 continue
624 # perform the add/remove
625 if remove:
626 try:
627 curvalue.remove(item)
628 except ValueError:
629 errors.append('"%s" is not currently in '
630 'for %s.'%(item, propname))
631 continue
632 else:
633 newvalue.append(item)
634 if item not in curvalue:
635 curvalue.append(item)
637 # that's it, set the new Multilink property value,
638 # or overwrite it completely
639 if set:
640 props[propname] = newvalue
641 else:
642 props[propname] = curvalue
643 elif isinstance(proptype, hyperdb.Boolean):
644 value = value.strip()
645 props[propname] = value.lower() in ('yes', 'true', 'on', '1')
646 elif isinstance(proptype, hyperdb.Number):
647 value = value.strip()
648 props[propname] = int(value)
650 # handle any errors parsing the argument list
651 if errors:
652 errors = '\n- '.join(errors)
653 raise MailUsageError, '''
654 There were problems handling your subject line argument list:
655 - %s
657 Subject was: "%s"
658 '''%(errors, subject)
660 #
661 # handle message-id and in-reply-to
662 #
663 messageid = message.getheader('message-id')
664 inreplyto = message.getheader('in-reply-to') or ''
665 # generate a messageid if there isn't one
666 if not messageid:
667 messageid = "<%s.%s.%s%s@%s>"%(time.time(), random.random(),
668 classname, nodeid, self.instance.config.MAIL_DOMAIN)
670 #
671 # now handle the body - find the message
672 #
673 content_type = message.gettype()
674 attachments = []
675 # General multipart handling:
676 # Take the first text/plain part, anything else is considered an
677 # attachment.
678 # multipart/mixed: multiple "unrelated" parts.
679 # multipart/signed (rfc 1847):
680 # The control information is carried in the second of the two
681 # required body parts.
682 # ACTION: Default, so if content is text/plain we get it.
683 # multipart/encrypted (rfc 1847):
684 # The control information is carried in the first of the two
685 # required body parts.
686 # ACTION: Not handleable as the content is encrypted.
687 # multipart/related (rfc 1872, 2112, 2387):
688 # The Multipart/Related content-type addresses the MIME
689 # representation of compound objects.
690 # ACTION: Default. If we are lucky there is a text/plain.
691 # TODO: One should use the start part and look for an Alternative
692 # that is text/plain.
693 # multipart/Alternative (rfc 1872, 1892):
694 # only in "related" ?
695 # multipart/report (rfc 1892):
696 # e.g. mail system delivery status reports.
697 # ACTION: Default. Could be ignored or used for Delivery Notification
698 # flagging.
699 # multipart/form-data:
700 # For web forms only.
701 if content_type == 'multipart/mixed':
702 # skip over the intro to the first boundary
703 part = message.getPart()
704 content = None
705 while 1:
706 # get the next part
707 part = message.getPart()
708 if part is None:
709 break
710 # parse it
711 subtype = part.gettype()
712 if subtype == 'text/plain' and not content:
713 # The first text/plain part is the message content.
714 content = self.get_part_data_decoded(part)
715 elif subtype == 'message/rfc822':
716 # handle message/rfc822 specially - the name should be
717 # the subject of the actual e-mail embedded here
718 i = part.fp.tell()
719 mailmess = Message(part.fp)
720 name = mailmess.getheader('subject')
721 part.fp.seek(i)
722 attachments.append((name, 'message/rfc822', part.fp.read()))
723 else:
724 # try name on Content-Type
725 name = part.getparam('name')
726 # this is just an attachment
727 data = self.get_part_data_decoded(part)
728 attachments.append((name, part.gettype(), data))
729 if content is None:
730 raise MailUsageError, '''
731 Roundup requires the submission to be plain text. The message parser could
732 not find a text/plain part to use.
733 '''
735 elif content_type[:10] == 'multipart/':
736 # skip over the intro to the first boundary
737 message.getPart()
738 content = None
739 while 1:
740 # get the next part
741 part = message.getPart()
742 if part is None:
743 break
744 # parse it
745 if part.gettype() == 'text/plain' and not content:
746 content = self.get_part_data_decoded(part)
747 if content is None:
748 raise MailUsageError, '''
749 Roundup requires the submission to be plain text. The message parser could
750 not find a text/plain part to use.
751 '''
753 elif content_type != 'text/plain':
754 raise MailUsageError, '''
755 Roundup requires the submission to be plain text. The message parser could
756 not find a text/plain part to use.
757 '''
759 else:
760 content = self.get_part_data_decoded(message)
762 # figure how much we should muck around with the email body
763 keep_citations = getattr(self.instance, 'EMAIL_KEEP_QUOTED_TEXT',
764 'no') == 'yes'
765 keep_body = getattr(self.instance, 'EMAIL_LEAVE_BODY_UNCHANGED',
766 'no') == 'yes'
768 # parse the body of the message, stripping out bits as appropriate
769 summary, content = parseContent(content, keep_citations,
770 keep_body)
772 #
773 # handle the attachments
774 #
775 files = []
776 for (name, mime_type, data) in attachments:
777 if not name:
778 name = "unnamed"
779 files.append(self.db.file.create(type=mime_type, name=name,
780 content=data))
782 #
783 # create the message if there's a message body (content)
784 #
785 if content:
786 message_id = self.db.msg.create(author=author,
787 recipients=recipients, date=date.Date('.'), summary=summary,
788 content=content, files=files, messageid=messageid,
789 inreplyto=inreplyto)
791 # attach the message to the node
792 if nodeid:
793 # add the message to the node's list
794 messages = cl.get(nodeid, 'messages')
795 messages.append(message_id)
796 props['messages'] = messages
797 else:
798 # pre-load the messages list
799 props['messages'] = [message_id]
801 # set the title to the subject
802 if properties.has_key('title') and not props.has_key('title'):
803 props['title'] = title
805 #
806 # perform the node change / create
807 #
808 try:
809 if nodeid:
810 cl.set(nodeid, **props)
811 else:
812 nodeid = cl.create(**props)
813 except (TypeError, IndexError, ValueError), message:
814 raise MailUsageError, '''
815 There was a problem with the message you sent:
816 %s
817 '''%message
819 # commit the changes to the DB
820 self.db.commit()
822 return nodeid
824 def extractUserFromList(userClass, users):
825 '''Given a list of users, try to extract the first non-anonymous user
826 and return that user, otherwise return None
827 '''
828 if len(users) > 1:
829 for user in users:
830 # make sure we don't match the anonymous or admin user
831 if userClass.get(user, 'username') in ('admin', 'anonymous'):
832 continue
833 # first valid match will do
834 return user
835 # well, I guess we have no choice
836 return user[0]
837 elif users:
838 return users[0]
839 return None
841 def uidFromAddress(db, address, create=1):
842 ''' address is from the rfc822 module, and therefore is (name, addr)
844 user is created if they don't exist in the db already
845 '''
846 (realname, address) = address
848 # try a straight match of the address
849 user = extractUserFromList(db.user, db.user.stringFind(address=address))
850 if user is not None: return user
852 # try the user alternate addresses if possible
853 props = db.user.getprops()
854 if props.has_key('alternate_addresses'):
855 users = db.user.filter(None, {'alternate_addresses': address},
856 [], [])
857 user = extractUserFromList(db.user, users)
858 if user is not None: return user
860 # try to match the username to the address (for local
861 # submissions where the address is empty)
862 user = extractUserFromList(db.user, db.user.stringFind(username=address))
864 # couldn't match address or username, so create a new user
865 if create:
866 return db.user.create(username=address, address=address,
867 realname=realname, roles=db.config.NEW_EMAIL_USER_ROLES)
868 else:
869 return 0
871 def parseContent(content, keep_citations, keep_body,
872 blank_line=re.compile(r'[\r\n]+\s*[\r\n]+'),
873 eol=re.compile(r'[\r\n]+'),
874 signature=re.compile(r'^[>|\s]*[-_]+\s*$'),
875 original_message=re.compile(r'^[>|\s]*-----Original Message-----$')):
876 ''' The message body is divided into sections by blank lines.
877 Sections where the second and all subsequent lines begin with a ">"
878 or "|" character are considered "quoting sections". The first line of
879 the first non-quoting section becomes the summary of the message.
881 If keep_citations is true, then we keep the "quoting sections" in the
882 content.
883 If keep_body is true, we even keep the signature sections.
884 '''
885 # strip off leading carriage-returns / newlines
886 i = 0
887 for i in range(len(content)):
888 if content[i] not in '\r\n':
889 break
890 if i > 0:
891 sections = blank_line.split(content[i:])
892 else:
893 sections = blank_line.split(content)
895 # extract out the summary from the message
896 summary = ''
897 l = []
898 for section in sections:
899 #section = section.strip()
900 if not section:
901 continue
902 lines = eol.split(section)
903 if (lines[0] and lines[0][0] in '>|') or (len(lines) > 1 and
904 lines[1] and lines[1][0] in '>|'):
905 # see if there's a response somewhere inside this section (ie.
906 # no blank line between quoted message and response)
907 for line in lines[1:]:
908 if line and line[0] not in '>|':
909 break
910 else:
911 # we keep quoted bits if specified in the config
912 if keep_citations:
913 l.append(section)
914 continue
915 # keep this section - it has reponse stuff in it
916 if not summary:
917 # and while we're at it, use the first non-quoted bit as
918 # our summary
919 summary = line
920 lines = lines[lines.index(line):]
921 section = '\n'.join(lines)
923 if not summary:
924 # if we don't have our summary yet use the first line of this
925 # section
926 summary = lines[0]
927 elif signature.match(lines[0]) and 2 <= len(lines) <= 10:
928 # lose any signature
929 break
930 elif original_message.match(lines[0]):
931 # ditch the stupid Outlook quoting of the entire original message
932 break
934 # and add the section to the output
935 l.append(section)
937 # Now reconstitute the message content minus the bits we don't care
938 # about.
939 if not keep_body:
940 content = '\n\n'.join(l)
942 return summary, content
944 # vim: set filetype=python ts=4 sw=4 et si