1 #!/usr/bin/env python 2 3 from bisect import bisect_left, insort_left 4 from datetime import date, datetime 5 from email import message_from_file 6 from email.mime.multipart import MIMEMultipart 7 from email.mime.text import MIMEText 8 from pytz import timezone, UnknownTimeZoneError 9 from smtplib import SMTP 10 from vCalendar import parse, ParseError, to_dict, to_node 11 import imip_store 12 import re 13 import sys 14 15 try: 16 from cStringIO import StringIO 17 except ImportError: 18 from StringIO import StringIO 19 20 MESSAGE_SENDER = "resources+agent@example.com" 21 22 MESSAGE_SUBJECT = "Calendar system message" 23 24 MESSAGE_TEXT = """\ 25 This is a response to a calendar message sent by your calendar program. 26 """ 27 28 # Postfix exit codes. 29 30 EX_TEMPFAIL = 75 31 32 # Permitted iTIP content types. 33 34 itip_content_types = [ 35 "text/calendar", # from RFC 6047 36 "text/x-vcalendar", "application/ics", # other possibilities 37 ] 38 39 # iCalendar date and datetime parsing (from DateSupport in MoinSupport). 40 41 date_icalendar_regexp_str = ur'(?P<year>[0-9]{4})(?P<month>[0-9]{2})(?P<day>[0-9]{2})' 42 datetime_icalendar_regexp_str = date_icalendar_regexp_str + \ 43 ur'(?:' \ 44 ur'T(?P<hour>[0-2][0-9])(?P<minute>[0-5][0-9])(?P<second>[0-6][0-9])' \ 45 ur'(?P<utc>Z)?' \ 46 ur')?' 47 48 match_date_icalendar = re.compile(date_icalendar_regexp_str, re.UNICODE).match 49 match_datetime_icalendar = re.compile(datetime_icalendar_regexp_str, re.UNICODE).match 50 51 # Content interpretation. 52 53 def get_items(d, name, all=True): 54 if d.has_key(name): 55 values = d[name] 56 if not all and len(values) == 1: 57 return values[0] 58 else: 59 return values 60 else: 61 return None 62 63 def get_item(d, name): 64 return get_items(d, name, False) 65 66 def get_value_map(d, name): 67 items = get_items(d, name) 68 if items: 69 return dict(items) 70 else: 71 return {} 72 73 def get_values(d, name, all=True): 74 if d.has_key(name): 75 values = d[name] 76 if not all and len(values) == 1: 77 return values[0][0] 78 else: 79 return map(lambda x: x[0], values) 80 else: 81 return None 82 83 def get_value(d, name): 84 return get_values(d, name, False) 85 86 def get_utc_datetime(d, name): 87 value, attr = get_item(d, name) 88 dt = get_datetime(value, attr) 89 if not dt: 90 return None 91 elif isinstance(dt, datetime): 92 return dt.astimezone(timezone("UTC")).strftime("%Y%m%dT%H%M%SZ") 93 else: 94 return dt.strftime("%Y%m%d") 95 96 def get_address(value): 97 return value.startswith("mailto:") and value[7:] or value 98 99 def get_uri(value): 100 return value.startswith("mailto:") and value or "mailto:%s" % value 101 102 def get_datetime(value, attr): 103 try: 104 tz = attr.has_key("TZID") and timezone(attr["TZID"]) or None 105 except UnknownTimeZoneError: 106 tz = None 107 108 if attr.get("VALUE") in (None, "DATE-TIME"): 109 m = match_datetime_icalendar(value) 110 if m: 111 dt = datetime( 112 int(m.group("year")), int(m.group("month")), int(m.group("day")), 113 int(m.group("hour")), int(m.group("minute")), int(m.group("second")) 114 ) 115 116 # Impose the indicated timezone. 117 # NOTE: This needs an ambiguity policy for DST changes. 118 119 tz = m.group("utc") and timezone("UTC") or tz or None 120 if tz is not None: 121 return tz.localize(dt) 122 else: 123 return dt 124 125 if attr.get("VALUE") == "DATE": 126 m = match_date_icalendar(value) 127 if m: 128 return date( 129 int(m.group("year")), int(m.group("month")), int(m.group("day")) 130 ) 131 return None 132 133 # Time management. 134 135 def insert_period(freebusy, period): 136 insort_left(freebusy, period) 137 138 def remove_period(freebusy, uid): 139 i = 0 140 while i < len(freebusy): 141 t = freebusy[i] 142 if len(t) >= 3 and t[2] == uid: 143 del freebusy[i] 144 else: 145 i += 1 146 147 def period_overlaps(freebusy, period): 148 dtstart, dtend = period[:2] 149 i = bisect_left(freebusy, (dtstart, dtend, None)) 150 return ( 151 i < len(freebusy) and (dtend is None or freebusy[i][0] < dtend) 152 or 153 i > 0 and freebusy[i - 1][1] > dtstart 154 ) 155 156 # Sending of outgoing messages. 157 158 def sendmail(sender, recipients, data): 159 smtp = SMTP("localhost") 160 smtp.sendmail(sender, recipients, data) 161 smtp.quit() 162 163 # Processing of incoming messages. 164 165 def process(f, original_recipients, recipients, this_sender): 166 167 """ 168 Process content from the stream 'f' accompanied by the given 169 'original_recipients' and 'recipients', together with details of 170 'this_sender' (the sender address on messages sent by this service). 171 """ 172 173 msg = message_from_file(f) 174 senders = msg.get_all("Reply-To") or msg.get_all("From") 175 176 # Handle messages with iTIP parts. 177 178 all_parts = [] 179 180 for part in msg.walk(): 181 if part.get_content_type() in itip_content_types and \ 182 part.get_param("method"): 183 184 all_parts += handle_itip_part(part, original_recipients) 185 186 # Pack the parts into a single message. 187 188 if all_parts: 189 text_part = MIMEText(MESSAGE_TEXT) 190 all_parts.insert(0, text_part) 191 message = MIMEMultipart("alternative", _subparts=all_parts) 192 message.preamble = MESSAGE_TEXT 193 194 message["From"] = this_sender 195 for sender in senders: 196 message["To"] = sender 197 message["Subject"] = MESSAGE_SUBJECT 198 199 if "-d" in sys.argv: 200 print message 201 else: 202 sendmail(this_sender, senders, message.as_string()) 203 204 def to_part(method, calendar): 205 206 """ 207 Write using the given 'method', the 'calendar' details to a MIME 208 text/calendar part. 209 """ 210 211 encoding = "utf-8" 212 out = StringIO() 213 try: 214 calendar[:0] = [ 215 ("METHOD", {}, method), 216 ("VERSION", {}, "2.0") 217 ] 218 imip_store.to_stream(out, ("VCALENDAR", {}, calendar), encoding) 219 part = MIMEText(out.getvalue(), "calendar", encoding) 220 part.set_param("method", method) 221 return part 222 223 finally: 224 out.close() 225 226 def parse_object(f, encoding, objtype): 227 228 """ 229 Parse the iTIP content from 'f' having the given 'encoding'. Return None if 230 the content was not readable or suitable. 231 """ 232 233 try: 234 try: 235 doctype, attrs, elements = obj = parse(f, encoding=encoding) 236 if doctype == objtype: 237 return to_dict(obj)[objtype][0] 238 finally: 239 f.close() 240 except (ParseError, ValueError): 241 pass 242 243 return None 244 245 def handle_itip_part(part, recipients): 246 247 "Handle the given iTIP 'part' for the given 'recipients'." 248 249 method = part.get_param("method") 250 251 # Decode the data and parse it. 252 253 f = StringIO(part.get_payload(decode=True)) 254 255 itip = parse_object(f, part.get_content_charset(), "VCALENDAR") 256 257 # Ignore the part if not a calendar object. 258 259 if not itip: 260 return [] 261 262 # Only handle calendar information. 263 264 all_parts = [] 265 266 # Require consistency between declared and employed methods. 267 268 if get_value(itip, "METHOD") == method: 269 270 # Look for different kinds of sections. 271 272 all_objects = [] 273 274 for name, cls in handlers: 275 for details in get_values(itip, name) or []: 276 277 # Dispatch to a handler and obtain any response. 278 279 handler = cls(details, recipients) 280 object = methods[method](handler)() 281 282 # Concatenate responses for a single calendar object. 283 284 if object: 285 all_objects += object 286 287 # Obtain a message part for the objects. 288 289 if all_objects: 290 all_parts.append(to_part(response_methods[method], all_objects)) 291 292 return all_parts 293 294 class Handler: 295 296 "General handler support." 297 298 def __init__(self, details, recipients): 299 300 """ 301 Initialise the handler with the 'details' of a calendar object and the 302 'recipients' of the object. 303 """ 304 305 self.details = details 306 self.recipients = set(recipients) 307 308 self.uid = get_value(details, "UID") 309 self.sequence = get_value(details, "SEQUENCE") 310 self.dtstamp = get_value(details, "DTSTAMP") 311 312 self.store = imip_store.FileStore() 313 314 def get_items(self, name, all=True): 315 return get_items(self.details, name, all) 316 317 def get_item(self, name): 318 return get_item(self.details, name) 319 320 def get_value_map(self, name): 321 return get_value_map(self.details, name) 322 323 def get_values(self, name, all=True): 324 return get_values(self.details, name, all) 325 326 def get_value(self, name): 327 return get_value(self.details, name) 328 329 def get_utc_datetime(self, name): 330 return get_utc_datetime(self.details, name) 331 332 def filter_by_recipients(self, values): 333 return self.recipients.intersection(map(get_address, values)) 334 335 def require_organiser_and_attendees(self): 336 attendee_map = self.get_value_map("ATTENDEE") 337 organiser = self.get_item("ORGANIZER") 338 339 # Only provide details for recipients who are also attendees. 340 341 attendees = {} 342 for attendee in map(get_uri, self.filter_by_recipients(attendee_map)): 343 attendees[attendee] = attendee_map[attendee] 344 345 if not attendees and not organiser: 346 return None 347 348 return organiser, attendees 349 350 class Event(Handler): 351 352 "An event handler." 353 354 def add(self): 355 pass 356 357 def cancel(self): 358 pass 359 360 def counter(self): 361 362 "Since this handler does not send requests, it will not handle replies." 363 364 pass 365 366 def declinecounter(self): 367 368 """ 369 Since this handler does not send counter proposals, it will not handle 370 replies to such proposals. 371 """ 372 373 pass 374 375 def publish(self): 376 pass 377 378 def refresh(self): 379 pass 380 381 def reply(self): 382 383 "Since this handler does not send requests, it will not handle replies." 384 385 pass 386 387 def request(self): 388 389 """ 390 Respond to a request by preparing a reply containing accept/decline 391 information for each indicated attendee. 392 393 No support for countering requests is implemented. 394 """ 395 396 oa = self.require_organiser_and_attendees() 397 if not oa: 398 return None 399 400 (organiser, organiser_attr), attendees = oa 401 402 # Process each attendee separately. 403 404 calendar = [] 405 406 for attendee, attendee_attr in attendees.items(): 407 408 # Check for event using UID. 409 410 f = self.store.get_event(attendee, self.uid) 411 event = f and parse_object(f, "utf-8", "VEVENT") 412 413 # If found, compare SEQUENCE and potentially DTSTAMP. 414 415 if event: 416 sequence = get_value(event, "SEQUENCE") 417 dtstamp = get_value(event, "DTSTAMP") 418 419 # If the request refers to an older version of the event, ignore 420 # it. 421 422 old_dtstamp = self.dtstamp < dtstamp 423 424 if sequence is not None and ( 425 int(self.sequence) < int(sequence) or 426 int(self.sequence) == int(sequence) and old_dtstamp 427 ) or old_dtstamp: 428 429 continue 430 431 # If newer than any old version, discard old details from the 432 # free/busy record and check for suitability. 433 434 dtstart = self.get_utc_datetime("DTSTART") 435 dtend = self.get_utc_datetime("DTEND") 436 437 conflict = False 438 freebusy = self.store.get_freebusy(attendee) 439 440 if freebusy: 441 remove_period(freebusy, self.uid) 442 conflict = period_overlaps(freebusy, (dtstart, dtend)) 443 else: 444 freebusy = [] 445 446 # If the event can be scheduled, it is registered and a reply sent 447 # accepting the event. (The attendee has PARTSTAT=ACCEPTED as an 448 # attribute.) 449 450 if not conflict: 451 insert_period(freebusy, (dtstart, dtend, self.uid)) 452 453 if self.get_value("TRANSP") in (None, "TRANSPARENT"): 454 self.store.set_freebusy(attendee, freebusy) 455 456 self.store.set_event(attendee, self.uid, to_node( 457 {"VEVENT" : [(self.details, {})]} 458 )) 459 attendee_attr["PARTSTAT"] = "ACCEPTED" 460 461 # If the event cannot be scheduled, it is not registered and a reply 462 # sent declining the event. (The attendee has PARTSTAT=DECLINED as an 463 # attribute.) 464 465 else: 466 attendee_attr["PARTSTAT"] = "DECLINED" 467 468 self.details["ATTENDEE"] = [(attendee, attendee_attr)] 469 calendar.append(to_node( 470 {"VEVENT" : [(self.details, {})]} 471 )) 472 473 return calendar 474 475 class Freebusy(Handler): 476 477 "A free/busy handler." 478 479 def publish(self): 480 pass 481 482 def reply(self): 483 484 "Since this handler does not send requests, it will not handle replies." 485 486 pass 487 488 def request(self): 489 490 """ 491 Respond to a request by preparing a reply containing free/busy 492 information for each indicated attendee. 493 """ 494 495 oa = self.require_organiser_and_attendees() 496 if not oa: 497 return None 498 499 (organiser, organiser_attr), attendees = oa 500 501 # Construct an appropriate fragment. 502 503 calendar = [] 504 cwrite = calendar.append 505 506 # Get the details for each attendee. 507 508 for attendee, attendee_attr in attendees.items(): 509 freebusy = self.store.get_freebusy(attendee) 510 511 if freebusy: 512 record = [] 513 rwrite = record.append 514 515 rwrite(("ORGANIZER", organiser_attr, organiser)) 516 rwrite(("ATTENDEE", attendee_attr, attendee)) 517 rwrite(("UID", {}, self.uid)) 518 519 for start, end, uid in freebusy: 520 rwrite(("FREEBUSY", {"FBTYPE" : "BUSY"}, [start, end])) 521 522 cwrite(("VFREEBUSY", {}, record)) 523 524 # Return the reply. 525 526 return calendar 527 528 class Journal(Handler): 529 530 "A journal entry handler." 531 532 def add(self): 533 pass 534 535 def cancel(self): 536 pass 537 538 def publish(self): 539 pass 540 541 class Todo(Handler): 542 543 "A to-do item handler." 544 545 def add(self): 546 pass 547 548 def cancel(self): 549 pass 550 551 def counter(self): 552 553 "Since this handler does not send requests, it will not handle replies." 554 555 pass 556 557 def declinecounter(self): 558 559 """ 560 Since this handler does not send counter proposals, it will not handle 561 replies to such proposals. 562 """ 563 564 pass 565 566 def publish(self): 567 pass 568 569 def refresh(self): 570 pass 571 572 def reply(self): 573 574 "Since this handler does not send requests, it will not handle replies." 575 576 pass 577 578 def request(self): 579 pass 580 581 # Handler registry. 582 583 handlers = [ 584 ("VFREEBUSY", Freebusy), 585 ("VEVENT", Event), 586 ("VTODO", Todo), 587 ("VJOURNAL", Journal), 588 ] 589 590 methods = { 591 "ADD" : lambda handler: handler.add, 592 "CANCEL" : lambda handler: handler.cancel, 593 "COUNTER" : lambda handler: handler.counter, 594 "DECLINECOUNTER" : lambda handler: handler.declinecounter, 595 "PUBLISH" : lambda handler: handler.publish, 596 "REFRESH" : lambda handler: handler.refresh, 597 "REPLY" : lambda handler: handler.reply, 598 "REQUEST" : lambda handler: handler.request, 599 } 600 601 response_methods = { 602 "REQUEST" : "REPLY", 603 } 604 605 def main(): 606 607 "Interpret program arguments and process input." 608 609 # Obtain the different kinds of recipients plus sender address. 610 611 original_recipients = [] 612 recipients = [] 613 senders = [] 614 615 l = [] 616 617 for arg in sys.argv[1:]: 618 619 # Switch to collecting recipients. 620 621 if arg == "-o": 622 l = original_recipients 623 elif arg == "-r": 624 l = recipients 625 626 # Switch to collecting senders. 627 628 elif arg == "-s": 629 l = senders 630 631 # Ignore debugging options. 632 633 elif arg == "-d": 634 pass 635 else: 636 l.append(arg) 637 638 process(sys.stdin, original_recipients, recipients, senders and senders[0] or MESSAGE_SENDER) 639 640 if __name__ == "__main__": 641 if "-d" in sys.argv[1:]: 642 main() 643 else: 644 try: 645 main() 646 except SystemExit, value: 647 sys.exit(value) 648 except Exception, exc: 649 type, value, tb = sys.exc_info() 650 print >>sys.stderr, "Exception %s at %d" % (exc, tb.tb_lineno) 651 sys.exit(EX_TEMPFAIL) 652 sys.exit(0) 653 654 # vim: tabstop=4 expandtab shiftwidth=4