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 all_responses = [] 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 all_responses += handle_itip_part(part, senders, recipient, self.handlers, self.messenger) 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 # Pack any returned parts into messages. 102 103 if all_responses: 104 outgoing_parts = {} 105 forwarded_parts = [] 106 107 for outgoing_recipients, part in all_responses: 108 if outgoing_recipients: 109 for outgoing_recipient in outgoing_recipients: 110 if not outgoing_parts.has_key(outgoing_recipient): 111 outgoing_parts[outgoing_recipient] = [] 112 outgoing_parts[outgoing_recipient].append(part) 113 else: 114 forwarded_parts.append(part) 115 116 # Reply using any outgoing parts in a new message. 117 118 if outgoing_parts: 119 120 # Obtain free/busy details, if configured to do so. 121 122 fb = self.get_freebusy_for_recipient(recipient) 123 124 for outgoing_recipient, parts in outgoing_parts.items(): 125 126 # Bundle free/busy messages, if configured to do so. 127 128 if fb: parts.append(fb) 129 message = self.messenger.make_outgoing_message(parts, [outgoing_recipient]) 130 131 if "-d" in sys.argv: 132 print >>sys.stderr, "Outgoing parts for %s..." % outgoing_recipient 133 print message 134 else: 135 self.messenger.sendmail([outgoing_recipient], message.as_string()) 136 137 # Forward messages to their recipients either wrapping the existing 138 # message, accompanying it or replacing it. 139 140 if forwarded_parts: 141 142 # Determine whether to wrap, accompany or replace the message. 143 144 preferences = Preferences(get_uri(recipient)) 145 146 incoming = preferences.get("incoming") 147 148 if incoming == "message-only": 149 messages = [msg] 150 else: 151 summary = self.messenger.make_summary_message(msg, forwarded_parts) 152 if incoming == "summary-then-message": 153 messages = [summary, msg] 154 elif incoming == "message-then-summary": 155 messages = [msg, summary] 156 elif incoming == "summary-only": 157 messages = [summary] 158 else: # incoming == "summary-wraps-message": 159 messages = [self.messenger.wrap_message(msg, forwarded_parts)] 160 161 for message in messages: 162 if "-d" in sys.argv: 163 print >>sys.stderr, "Forwarded parts..." 164 print message 165 elif self.lmtp_socket: 166 self.messenger.sendmail(recipient, message.as_string(), lmtp_socket=self.lmtp_socket) 167 168 # Unhandled messages are delivered as they are. 169 170 if not handled: 171 if "-d" in sys.argv: 172 print >>sys.stderr, "Unhandled parts..." 173 print msg 174 elif self.lmtp_socket: 175 self.messenger.sendmail(recipient, msg.as_string(), lmtp_socket=self.lmtp_socket) 176 177 def get_freebusy_for_recipient(self, recipient): 178 179 """ 180 Return a list of responses containing free/busy information for the 181 given 'recipient'. 182 """ 183 184 organiser = get_uri(recipient) 185 preferences = Preferences(organiser) 186 187 if preferences.get("freebusy_sharing") == "share" and \ 188 preferences.get("freebusy_bundling") == "always": 189 190 # Invent a unique identifier. 191 192 utcnow = get_timestamp() 193 uid = "imip-agent-%s-%s" % (utcnow, recipient) 194 195 freebusy = imip_store.FileStore().get_freebusy(organiser) 196 return to_part("PUBLISH", [make_freebusy(freebusy, uid, organiser)]) 197 198 def process_args(self, args, stream): 199 200 """ 201 Interpret the given program arguments 'args' and process input from the 202 given 'stream'. 203 """ 204 205 # Obtain the different kinds of recipients plus sender address. 206 207 original_recipients = [] 208 recipients = [] 209 senders = [] 210 lmtp = [] 211 outgoing_only = False 212 213 l = [] 214 215 for arg in args: 216 217 # Detect outgoing processing mode. 218 219 if arg == "-O": 220 outgoing_only = True 221 222 # Switch to collecting recipients. 223 224 if arg == "-o": 225 l = original_recipients 226 elif arg == "-r": 227 l = recipients 228 229 # Switch to collecting senders. 230 231 elif arg == "-s": 232 l = senders 233 234 # Switch to getting the LMTP socket. 235 236 elif arg == "-l": 237 l = lmtp 238 239 # Ignore debugging options. 240 241 elif arg == "-d": 242 pass 243 else: 244 l.append(arg) 245 246 self.messenger.sender = senders and senders[0] or self.messenger.sender 247 self.lmtp_socket = lmtp and lmtp[0] or None 248 self.process(stream, original_recipients, recipients, outgoing_only) 249 250 def __call__(self): 251 252 """ 253 Obtain arguments from the command line to initialise the processor 254 before invoking it. 255 """ 256 257 args = sys.argv[1:] 258 259 if "-d" in args: 260 self.process_args(args, sys.stdin) 261 else: 262 try: 263 self.process_args(args, sys.stdin) 264 except SystemExit, value: 265 sys.exit(value) 266 except Exception, exc: 267 if "-v" in args: 268 raise 269 type, value, tb = sys.exc_info() 270 print >>sys.stderr, "Exception %s at %d" % (exc, tb.tb_lineno) 271 #import traceback 272 #traceback.print_exc(file=open("/tmp/mail.log", "a")) 273 sys.exit(EX_TEMPFAIL) 274 sys.exit(0) 275 276 # vim: tabstop=4 expandtab shiftwidth=4