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 original_recipients = original_recipients or msg.get_all("To") 176 177 # Handle messages with iTIP parts. 178 179 all_parts = [] 180 181 for part in msg.walk(): 182 if part.get_content_type() in itip_content_types and \ 183 part.get_param("method"): 184 185 all_parts += handle_itip_part(part, original_recipients) 186 187 # Pack the parts into a single message. 188 189 if all_parts: 190 text_part = MIMEText(MESSAGE_TEXT) 191 all_parts.insert(0, text_part) 192 message = MIMEMultipart("alternative", _subparts=all_parts) 193 message.preamble = MESSAGE_TEXT 194 195 message["From"] = this_sender 196 for sender in senders: 197 message["To"] = sender 198 message["Subject"] = MESSAGE_SUBJECT 199 200 if "-d" in sys.argv: 201 print message 202 else: 203 sendmail(this_sender, senders, message.as_string()) 204 205 def to_part(method, calendar): 206 207 """ 208 Write using the given 'method', the 'calendar' details to a MIME 209 text/calendar part. 210 """ 211 212 encoding = "utf-8" 213 out = StringIO() 214 try: 215 imip_store.to_stream(out, imip_store.make_calendar(calendar, method), encoding) 216 part = MIMEText(out.getvalue(), "calendar", encoding) 217 part.set_param("method", method) 218 return part 219 220 finally: 221 out.close() 222 223 def parse_object(f, encoding, objtype): 224 225 """ 226 Parse the iTIP content from 'f' having the given 'encoding'. Return None if 227 the content was not readable or suitable. 228 """ 229 230 try: 231 try: 232 doctype, attrs, elements = obj = parse(f, encoding=encoding) 233 if doctype == objtype: 234 return to_dict(obj)[objtype][0] 235 finally: 236 f.close() 237 except (ParseError, ValueError): 238 pass 239 240 return None 241 242 def handle_itip_part(part, recipients): 243 244 "Handle the given iTIP 'part' for the given 'recipients'." 245 246 method = part.get_param("method") 247 248 # Decode the data and parse it. 249 250 f = StringIO(part.get_payload(decode=True)) 251 252 itip = parse_object(f, part.get_content_charset(), "VCALENDAR") 253 254 # Ignore the part if not a calendar object. 255 256 if not itip: 257 return [] 258 259 # Only handle calendar information. 260 261 all_parts = [] 262 263 # Require consistency between declared and employed methods. 264 265 if get_value(itip, "METHOD") == method: 266 267 # Look for different kinds of sections. 268 269 all_objects = [] 270 271 for name, cls in handlers: 272 for details in get_values(itip, name) or []: 273 274 # Dispatch to a handler and obtain any response. 275 276 handler = cls(details, recipients) 277 object = methods[method](handler)() 278 279 # Concatenate responses for a single calendar object. 280 281 if object: 282 all_objects += object 283 284 # Obtain a message part for the objects. 285 286 if all_objects: 287 all_parts.append(to_part(response_methods[method], all_objects)) 288 289 return all_parts 290 291 class Handler: 292 293 "General handler support." 294 295 def __init__(self, details, recipients): 296 297 """ 298 Initialise the handler with the 'details' of a calendar object and the 299 'recipients' of the object. 300 """ 301 302 self.details = details 303 self.recipients = set(recipients) 304 305 self.uid = get_value(details, "UID") 306 self.sequence = get_value(details, "SEQUENCE") 307 self.dtstamp = get_value(details, "DTSTAMP") 308 309 self.store = imip_store.FileStore() 310 311 try: 312 self.publisher = imip_store.FilePublisher() 313 except OSError: 314 self.publisher = None 315 316 def get_items(self, name, all=True): 317 return get_items(self.details, name, all) 318 319 def get_item(self, name): 320 return get_item(self.details, name) 321 322 def get_value_map(self, name): 323 return get_value_map(self.details, name) 324 325 def get_values(self, name, all=True): 326 return get_values(self.details, name, all) 327 328 def get_value(self, name): 329 return get_value(self.details, name) 330 331 def get_utc_datetime(self, name): 332 return get_utc_datetime(self.details, name) 333 334 def filter_by_recipients(self, values): 335 return self.recipients.intersection(map(get_address, values)) 336 337 def require_organiser_and_attendees(self): 338 attendee_map = self.get_value_map("ATTENDEE") 339 organiser = self.get_item("ORGANIZER") 340 341 # Only provide details for recipients who are also attendees. 342 343 attendees = {} 344 for attendee in map(get_uri, self.filter_by_recipients(attendee_map)): 345 attendees[attendee] = attendee_map[attendee] 346 347 if not attendees and not organiser: 348 return None 349 350 return organiser, attendees 351 352 class Event(Handler): 353 354 "An event handler." 355 356 def add(self): 357 pass 358 359 def cancel(self): 360 pass 361 362 def counter(self): 363 364 "Since this handler does not send requests, it will not handle replies." 365 366 pass 367 368 def declinecounter(self): 369 370 """ 371 Since this handler does not send counter proposals, it will not handle 372 replies to such proposals. 373 """ 374 375 pass 376 377 def publish(self): 378 pass 379 380 def refresh(self): 381 pass 382 383 def reply(self): 384 385 "Since this handler does not send requests, it will not handle replies." 386 387 pass 388 389 def request(self): 390 391 """ 392 Respond to a request by preparing a reply containing accept/decline 393 information for each indicated attendee. 394 395 No support for countering requests is implemented. 396 """ 397 398 oa = self.require_organiser_and_attendees() 399 if not oa: 400 return None 401 402 (organiser, organiser_attr), attendees = oa 403 404 # Process each attendee separately. 405 406 calendar = [] 407 408 for attendee, attendee_attr in attendees.items(): 409 410 # Check for event using UID. 411 412 f = self.store.get_event(attendee, self.uid) 413 event = f and parse_object(f, "utf-8", "VEVENT") 414 415 # If found, compare SEQUENCE and potentially DTSTAMP. 416 417 if event: 418 sequence = get_value(event, "SEQUENCE") 419 dtstamp = get_value(event, "DTSTAMP") 420 421 # If the request refers to an older version of the event, ignore 422 # it. 423 424 old_dtstamp = self.dtstamp < dtstamp 425 426 if sequence is not None and ( 427 int(self.sequence) < int(sequence) or 428 int(self.sequence) == int(sequence) and old_dtstamp 429 ) or old_dtstamp: 430 431 continue 432 433 # If newer than any old version, discard old details from the 434 # free/busy record and check for suitability. 435 436 dtstart = self.get_utc_datetime("DTSTART") 437 dtend = self.get_utc_datetime("DTEND") 438 439 conflict = False 440 freebusy = self.store.get_freebusy(attendee) 441 442 if freebusy: 443 remove_period(freebusy, self.uid) 444 conflict = period_overlaps(freebusy, (dtstart, dtend)) 445 else: 446 freebusy = [] 447 448 # If the event can be scheduled, it is registered and a reply sent 449 # accepting the event. (The attendee has PARTSTAT=ACCEPTED as an 450 # attribute.) 451 452 if not conflict: 453 insert_period(freebusy, (dtstart, dtend, self.uid)) 454 455 if self.get_value("TRANSP") in (None, "OPAQUE"): 456 self.store.set_freebusy(attendee, freebusy) 457 458 if self.publisher: 459 self.publisher.set_freebusy(attendee, freebusy) 460 461 self.store.set_event(attendee, self.uid, to_node( 462 {"VEVENT" : [(self.details, {})]} 463 )) 464 attendee_attr["PARTSTAT"] = "ACCEPTED" 465 466 # If the event cannot be scheduled, it is not registered and a reply 467 # sent declining the event. (The attendee has PARTSTAT=DECLINED as an 468 # attribute.) 469 470 else: 471 attendee_attr["PARTSTAT"] = "DECLINED" 472 473 self.details["ATTENDEE"] = [(attendee, attendee_attr)] 474 calendar.append(to_node( 475 {"VEVENT" : [(self.details, {})]} 476 )) 477 478 return calendar 479 480 class Freebusy(Handler): 481 482 "A free/busy handler." 483 484 def publish(self): 485 pass 486 487 def reply(self): 488 489 "Since this handler does not send requests, it will not handle replies." 490 491 pass 492 493 def request(self): 494 495 """ 496 Respond to a request by preparing a reply containing free/busy 497 information for each indicated attendee. 498 """ 499 500 oa = self.require_organiser_and_attendees() 501 if not oa: 502 return None 503 504 (organiser, organiser_attr), attendees = oa 505 506 # Construct an appropriate fragment. 507 508 calendar = [] 509 cwrite = calendar.append 510 511 # Get the details for each attendee. 512 513 for attendee, attendee_attr in attendees.items(): 514 freebusy = self.store.get_freebusy(attendee) 515 516 if freebusy: 517 record = [] 518 rwrite = record.append 519 520 rwrite(("ORGANIZER", organiser_attr, organiser)) 521 rwrite(("ATTENDEE", attendee_attr, attendee)) 522 rwrite(("UID", {}, self.uid)) 523 524 for start, end, uid in freebusy: 525 rwrite(("FREEBUSY", {"FBTYPE" : "BUSY"}, [start, end])) 526 527 cwrite(("VFREEBUSY", {}, record)) 528 529 # Return the reply. 530 531 return calendar 532 533 class Journal(Handler): 534 535 "A journal entry handler." 536 537 def add(self): 538 pass 539 540 def cancel(self): 541 pass 542 543 def publish(self): 544 pass 545 546 class Todo(Handler): 547 548 "A to-do item handler." 549 550 def add(self): 551 pass 552 553 def cancel(self): 554 pass 555 556 def counter(self): 557 558 "Since this handler does not send requests, it will not handle replies." 559 560 pass 561 562 def declinecounter(self): 563 564 """ 565 Since this handler does not send counter proposals, it will not handle 566 replies to such proposals. 567 """ 568 569 pass 570 571 def publish(self): 572 pass 573 574 def refresh(self): 575 pass 576 577 def reply(self): 578 579 "Since this handler does not send requests, it will not handle replies." 580 581 pass 582 583 def request(self): 584 pass 585 586 # Handler registry. 587 588 handlers = [ 589 ("VFREEBUSY", Freebusy), 590 ("VEVENT", Event), 591 ("VTODO", Todo), 592 ("VJOURNAL", Journal), 593 ] 594 595 methods = { 596 "ADD" : lambda handler: handler.add, 597 "CANCEL" : lambda handler: handler.cancel, 598 "COUNTER" : lambda handler: handler.counter, 599 "DECLINECOUNTER" : lambda handler: handler.declinecounter, 600 "PUBLISH" : lambda handler: handler.publish, 601 "REFRESH" : lambda handler: handler.refresh, 602 "REPLY" : lambda handler: handler.reply, 603 "REQUEST" : lambda handler: handler.request, 604 } 605 606 response_methods = { 607 "REQUEST" : "REPLY", 608 } 609 610 def main(): 611 612 "Interpret program arguments and process input." 613 614 # Obtain the different kinds of recipients plus sender address. 615 616 original_recipients = [] 617 recipients = [] 618 senders = [] 619 620 l = [] 621 622 for arg in sys.argv[1:]: 623 624 # Switch to collecting recipients. 625 626 if arg == "-o": 627 l = original_recipients 628 elif arg == "-r": 629 l = recipients 630 631 # Switch to collecting senders. 632 633 elif arg == "-s": 634 l = senders 635 636 # Ignore debugging options. 637 638 elif arg == "-d": 639 pass 640 else: 641 l.append(arg) 642 643 process(sys.stdin, original_recipients, recipients, senders and senders[0] or MESSAGE_SENDER) 644 645 if __name__ == "__main__": 646 if "-d" in sys.argv[1:]: 647 main() 648 else: 649 try: 650 main() 651 except SystemExit, value: 652 sys.exit(value) 653 except Exception, exc: 654 type, value, tb = sys.exc_info() 655 print >>sys.stderr, "Exception %s at %d" % (exc, tb.tb_lineno) 656 sys.exit(EX_TEMPFAIL) 657 sys.exit(0) 658 659 # vim: tabstop=4 expandtab shiftwidth=4