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