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