1 #!/usr/bin/env python 2 3 """ 4 A processing framework for iMIP content. 5 6 Copyright (C) 2014, 2015 Paul Boddie <paul@boddie.org.uk> 7 8 This program is free software; you can redistribute it and/or modify it under 9 the terms of the GNU General Public License as published by the Free Software 10 Foundation; either version 3 of the License, or (at your option) any later 11 version. 12 13 This program is distributed in the hope that it will be useful, but WITHOUT 14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 15 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more 16 details. 17 18 You should have received a copy of the GNU General Public License along with 19 this program. If not, see <http://www.gnu.org/licenses/>. 20 """ 21 22 from email import message_from_file 23 from imiptools.content import handle_itip_part 24 from imiptools.data import get_addresses, get_uri 25 from imiptools.mail import Messenger 26 from imiptools.profile import Preferences 27 import sys 28 29 # Postfix exit codes. 30 31 EX_TEMPFAIL = 75 32 33 # Permitted iTIP content types. 34 35 itip_content_types = [ 36 "text/calendar", # from RFC 6047 37 "text/x-vcalendar", "application/ics", # other possibilities 38 ] 39 40 # Processing of incoming messages. 41 42 def get_all_values(msg, key): 43 l = [] 44 for v in msg.get_all(key) or []: 45 l += [s.strip() for s in v.split(",")] 46 return l 47 48 class Processor: 49 50 "The processing framework." 51 52 def __init__(self, handlers, messenger=None): 53 self.handlers = handlers 54 self.messenger = messenger or Messenger() 55 self.lmtp_socket = None 56 57 def process(self, f, original_recipients, recipients, outgoing_only): 58 59 """ 60 Process content from the stream 'f' accompanied by the given 61 'original_recipients' and 'recipients'. 62 """ 63 64 msg = message_from_file(f) 65 senders = get_addresses(msg.get_all("Reply-To") or msg.get_all("From") or []) 66 original_recipients = original_recipients or get_addresses(get_all_values(msg, "To") or []) 67 68 # Handle messages with iTIP parts. 69 70 for recipient in original_recipients: 71 self.process_for_recipient(msg, recipient, senders, outgoing_only) 72 73 def process_for_recipient(self, msg, recipient, senders, outgoing_only): 74 75 """ 76 Process the given 'msg' for a single 'recipient', having the given 77 'senders', and with the given 'outgoing_only' status. 78 79 Processing individually means that contributions to resulting messages 80 may be constructed according to individual preferences. 81 """ 82 83 handlers = dict([(name, cls(senders, recipient, self.messenger)) for name, cls in self.handlers]) 84 handled = False 85 86 for part in msg.walk(): 87 if part.get_content_type() in itip_content_types and \ 88 part.get_param("method"): 89 90 handle_itip_part(part, handlers) 91 handled = True 92 93 # When processing outgoing messages, no replies or deliveries are 94 # performed. 95 96 if outgoing_only: 97 return 98 99 # Get responses from the handlers. 100 101 all_responses = [] 102 for handler in handlers.values(): 103 all_responses += handler.get_results() 104 105 # Pack any returned parts into messages. 106 107 if all_responses: 108 outgoing_parts = {} 109 forwarded_parts = [] 110 111 for outgoing_recipients, part in all_responses: 112 if outgoing_recipients: 113 for outgoing_recipient in outgoing_recipients: 114 if not outgoing_parts.has_key(outgoing_recipient): 115 outgoing_parts[outgoing_recipient] = [] 116 outgoing_parts[outgoing_recipient].append(part) 117 else: 118 forwarded_parts.append(part) 119 120 # Reply using any outgoing parts in a new message. 121 122 if outgoing_parts: 123 for outgoing_recipient, parts in outgoing_parts.items(): 124 message = self.messenger.make_outgoing_message(parts, [outgoing_recipient]) 125 126 if "-d" in sys.argv: 127 print >>sys.stderr, "Outgoing parts for %s..." % outgoing_recipient 128 print message 129 else: 130 self.messenger.sendmail([outgoing_recipient], message.as_string()) 131 132 # Forward messages to their recipients either wrapping the existing 133 # message, accompanying it or replacing it. 134 135 if forwarded_parts: 136 137 # Determine whether to wrap, accompany or replace the message. 138 139 preferences = Preferences(get_uri(recipient)) 140 141 incoming = preferences.get("incoming") 142 143 if incoming == "message-only": 144 messages = [msg] 145 else: 146 summary = self.messenger.make_summary_message(msg, forwarded_parts) 147 if incoming == "summary-then-message": 148 messages = [summary, msg] 149 elif incoming == "message-then-summary": 150 messages = [msg, summary] 151 elif incoming == "summary-only": 152 messages = [summary] 153 else: # incoming == "summary-wraps-message": 154 messages = [self.messenger.wrap_message(msg, forwarded_parts)] 155 156 for message in messages: 157 if "-d" in sys.argv: 158 print >>sys.stderr, "Forwarded parts..." 159 print message 160 elif self.lmtp_socket: 161 self.messenger.sendmail(recipient, message.as_string(), lmtp_socket=self.lmtp_socket) 162 163 # Unhandled messages are delivered as they are. 164 165 if not handled: 166 if "-d" in sys.argv: 167 print >>sys.stderr, "Unhandled parts..." 168 print msg 169 elif self.lmtp_socket: 170 self.messenger.sendmail(recipient, msg.as_string(), lmtp_socket=self.lmtp_socket) 171 172 def process_args(self, args, stream): 173 174 """ 175 Interpret the given program arguments 'args' and process input from the 176 given 'stream'. 177 """ 178 179 # Obtain the different kinds of recipients plus sender address. 180 181 original_recipients = [] 182 recipients = [] 183 senders = [] 184 lmtp = [] 185 outgoing_only = False 186 187 l = [] 188 189 for arg in args: 190 191 # Detect outgoing processing mode. 192 193 if arg == "-O": 194 outgoing_only = True 195 196 # Switch to collecting recipients. 197 198 if arg == "-o": 199 l = original_recipients 200 elif arg == "-r": 201 l = recipients 202 203 # Switch to collecting senders. 204 205 elif arg == "-s": 206 l = senders 207 208 # Switch to getting the LMTP socket. 209 210 elif arg == "-l": 211 l = lmtp 212 213 # Ignore debugging options. 214 215 elif arg == "-d": 216 pass 217 else: 218 l.append(arg) 219 220 self.messenger.sender = senders and senders[0] or self.messenger.sender 221 self.lmtp_socket = lmtp and lmtp[0] or None 222 self.process(stream, original_recipients, recipients, outgoing_only) 223 224 def __call__(self): 225 226 """ 227 Obtain arguments from the command line to initialise the processor 228 before invoking it. 229 """ 230 231 args = sys.argv[1:] 232 233 if "-d" in args: 234 self.process_args(args, sys.stdin) 235 else: 236 try: 237 self.process_args(args, sys.stdin) 238 except SystemExit, value: 239 sys.exit(value) 240 except Exception, exc: 241 if "-v" in args: 242 raise 243 type, value, tb = sys.exc_info() 244 print >>sys.stderr, "Exception %s at %d" % (exc, tb.tb_lineno) 245 #import traceback 246 #traceback.print_exc(file=open("/tmp/mail.log", "a")) 247 sys.exit(EX_TEMPFAIL) 248 sys.exit(0) 249 250 # vim: tabstop=4 expandtab shiftwidth=4