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, make_freebusy, to_part 25 from imiptools.dates import get_timestamp 26 from imiptools.mail import Messenger 27 from imiptools.profile import Preferences 28 import imip_store 29 import sys 30 31 # Postfix exit codes. 32 33 EX_TEMPFAIL = 75 34 35 # Permitted iTIP content types. 36 37 itip_content_types = [ 38 "text/calendar", # from RFC 6047 39 "text/x-vcalendar", "application/ics", # other possibilities 40 ] 41 42 # Processing of incoming messages. 43 44 def get_all_values(msg, key): 45 l = [] 46 for v in msg.get_all(key) or []: 47 l += [s.strip() for s in v.split(",")] 48 return l 49 50 class Processor: 51 52 "The processing framework." 53 54 def __init__(self, handlers, messenger=None): 55 self.handlers = handlers 56 self.messenger = messenger or Messenger() 57 self.lmtp_socket = None 58 59 def process(self, f, original_recipients, recipients, outgoing_only): 60 61 """ 62 Process content from the stream 'f' accompanied by the given 63 'original_recipients' and 'recipients'. 64 """ 65 66 msg = message_from_file(f) 67 senders = get_addresses(msg.get_all("Reply-To") or msg.get_all("From") or []) 68 original_recipients = original_recipients or get_addresses(get_all_values(msg, "To") or []) 69 70 # Handle messages with iTIP parts. 71 72 for recipient in original_recipients: 73 self.process_for_recipient(msg, recipient, senders, outgoing_only) 74 75 def process_for_recipient(self, msg, recipient, senders, outgoing_only): 76 77 """ 78 Process the given 'msg' for a single 'recipient', having the given 79 'senders', and with the given 'outgoing_only' status. 80 81 Processing individually means that contributions to resulting messages 82 may be constructed according to individual preferences. 83 """ 84 85 handlers = dict([(name, cls(senders, recipient, self.messenger)) for name, cls in self.handlers]) 86 handled = False 87 88 for part in msg.walk(): 89 if part.get_content_type() in itip_content_types and \ 90 part.get_param("method"): 91 92 handle_itip_part(part, handlers) 93 handled = True 94 95 # When processing outgoing messages, no replies or deliveries are 96 # performed. 97 98 if outgoing_only: 99 return 100 101 # Get responses from the handlers. 102 103 all_responses = [] 104 for handler in handlers.values(): 105 all_responses += handler.get_results() 106 107 # Pack any returned parts into messages. 108 109 if all_responses: 110 outgoing_parts = {} 111 forwarded_parts = [] 112 113 for outgoing_recipients, part in all_responses: 114 if outgoing_recipients: 115 for outgoing_recipient in outgoing_recipients: 116 if not outgoing_parts.has_key(outgoing_recipient): 117 outgoing_parts[outgoing_recipient] = [] 118 outgoing_parts[outgoing_recipient].append(part) 119 else: 120 forwarded_parts.append(part) 121 122 # Reply using any outgoing parts in a new message. 123 124 if outgoing_parts: 125 126 # Obtain free/busy details, if configured to do so. 127 128 fb = self.can_provide_freebusy(handlers) and self.get_freebusy_for_recipient(recipient) 129 130 for outgoing_recipient, parts in outgoing_parts.items(): 131 132 # Bundle free/busy messages, if configured to do so. 133 134 if fb: parts.append(fb) 135 message = self.messenger.make_outgoing_message(parts, [outgoing_recipient]) 136 137 if "-d" in sys.argv: 138 print >>sys.stderr, "Outgoing parts for %s..." % outgoing_recipient 139 print message 140 else: 141 self.messenger.sendmail([outgoing_recipient], message.as_string()) 142 143 # Forward messages to their recipients either wrapping the existing 144 # message, accompanying it or replacing it. 145 146 if forwarded_parts: 147 148 # Determine whether to wrap, accompany or replace the message. 149 150 preferences = Preferences(get_uri(recipient)) 151 152 incoming = preferences.get("incoming") 153 154 if incoming == "message-only": 155 messages = [msg] 156 else: 157 summary = self.messenger.make_summary_message(msg, forwarded_parts) 158 if incoming == "summary-then-message": 159 messages = [summary, msg] 160 elif incoming == "message-then-summary": 161 messages = [msg, summary] 162 elif incoming == "summary-only": 163 messages = [summary] 164 else: # incoming == "summary-wraps-message": 165 messages = [self.messenger.wrap_message(msg, forwarded_parts)] 166 167 for message in messages: 168 if "-d" in sys.argv: 169 print >>sys.stderr, "Forwarded parts..." 170 print message 171 elif self.lmtp_socket: 172 self.messenger.sendmail(recipient, message.as_string(), lmtp_socket=self.lmtp_socket) 173 174 # Unhandled messages are delivered as they are. 175 176 if not handled: 177 if "-d" in sys.argv: 178 print >>sys.stderr, "Unhandled parts..." 179 print msg 180 elif self.lmtp_socket: 181 self.messenger.sendmail(recipient, msg.as_string(), lmtp_socket=self.lmtp_socket) 182 183 def can_provide_freebusy(self, handlers): 184 185 "Test for any free/busy information produced by 'handlers'." 186 187 fbhandler = handlers.get("VFREEBUSY") 188 if fbhandler: 189 fbmethods = fbhandler.get_outgoing_methods() 190 return not "REPLY" in fbmethods and not "PUBLISH" in fbmethods 191 else: 192 return False 193 194 def get_freebusy_for_recipient(self, recipient): 195 196 """ 197 Return a list of responses containing free/busy information for the 198 given 'recipient'. 199 """ 200 201 organiser = get_uri(recipient) 202 preferences = Preferences(organiser) 203 204 organiser_attr = self.messenger and {"SENT-BY" : get_uri(self.messenger.sender)} or {} 205 206 if preferences.get("freebusy_sharing") == "share" and \ 207 preferences.get("freebusy_bundling") == "always": 208 209 # Invent a unique identifier. 210 211 utcnow = get_timestamp() 212 uid = "imip-agent-%s-%s" % (utcnow, recipient) 213 214 freebusy = imip_store.FileStore().get_freebusy(organiser) 215 return to_part("PUBLISH", [make_freebusy(freebusy, uid, organiser, organiser_attr)]) 216 217 return None 218 219 def process_args(self, args, stream): 220 221 """ 222 Interpret the given program arguments 'args' and process input from the 223 given 'stream'. 224 """ 225 226 # Obtain the different kinds of recipients plus sender address. 227 228 original_recipients = [] 229 recipients = [] 230 senders = [] 231 lmtp = [] 232 outgoing_only = False 233 234 l = [] 235 236 for arg in args: 237 238 # Detect outgoing processing mode. 239 240 if arg == "-O": 241 outgoing_only = True 242 243 # Switch to collecting recipients. 244 245 if arg == "-o": 246 l = original_recipients 247 elif arg == "-r": 248 l = recipients 249 250 # Switch to collecting senders. 251 252 elif arg == "-s": 253 l = senders 254 255 # Switch to getting the LMTP socket. 256 257 elif arg == "-l": 258 l = lmtp 259 260 # Ignore debugging options. 261 262 elif arg == "-d": 263 pass 264 else: 265 l.append(arg) 266 267 self.messenger.sender = senders and senders[0] or self.messenger.sender 268 self.lmtp_socket = lmtp and lmtp[0] or None 269 self.process(stream, original_recipients, recipients, outgoing_only) 270 271 def __call__(self): 272 273 """ 274 Obtain arguments from the command line to initialise the processor 275 before invoking it. 276 """ 277 278 args = sys.argv[1:] 279 280 if "-d" in args: 281 self.process_args(args, sys.stdin) 282 else: 283 try: 284 self.process_args(args, sys.stdin) 285 except SystemExit, value: 286 sys.exit(value) 287 except Exception, exc: 288 if "-v" in args: 289 raise 290 type, value, tb = sys.exc_info() 291 while tb.tb_next: 292 tb = tb.tb_next 293 f = tb.tb_frame 294 co = f and f.f_code 295 filename = co and co.co_filename 296 print >>sys.stderr, "Exception %s at %d in %s" % (exc, tb.tb_lineno, filename) 297 #import traceback 298 #traceback.print_exc(file=open("/tmp/mail.log", "a")) 299 sys.exit(EX_TEMPFAIL) 300 sys.exit(0) 301 302 # vim: tabstop=4 expandtab shiftwidth=4