paul@48 | 1 | #!/usr/bin/env python |
paul@48 | 2 | |
paul@48 | 3 | """ |
paul@48 | 4 | Interpretation and preparation of iMIP content, together with a content handling |
paul@48 | 5 | mechanism employed by specific recipients. |
paul@48 | 6 | """ |
paul@48 | 7 | |
paul@75 | 8 | from datetime import date, datetime, timedelta |
paul@48 | 9 | from email.mime.text import MIMEText |
paul@48 | 10 | from pytz import timezone, UnknownTimeZoneError |
paul@48 | 11 | from vCalendar import parse, ParseError, to_dict |
paul@75 | 12 | from vRecurrence import get_parameters, get_rule |
paul@48 | 13 | import imip_store |
paul@48 | 14 | import re |
paul@48 | 15 | |
paul@48 | 16 | try: |
paul@48 | 17 | from cStringIO import StringIO |
paul@48 | 18 | except ImportError: |
paul@48 | 19 | from StringIO import StringIO |
paul@48 | 20 | |
paul@48 | 21 | # iCalendar date and datetime parsing (from DateSupport in MoinSupport). |
paul@48 | 22 | |
paul@48 | 23 | date_icalendar_regexp_str = ur'(?P<year>[0-9]{4})(?P<month>[0-9]{2})(?P<day>[0-9]{2})' |
paul@48 | 24 | datetime_icalendar_regexp_str = date_icalendar_regexp_str + \ |
paul@48 | 25 | ur'(?:' \ |
paul@48 | 26 | ur'T(?P<hour>[0-2][0-9])(?P<minute>[0-5][0-9])(?P<second>[0-6][0-9])' \ |
paul@48 | 27 | ur'(?P<utc>Z)?' \ |
paul@48 | 28 | ur')?' |
paul@48 | 29 | |
paul@48 | 30 | match_date_icalendar = re.compile(date_icalendar_regexp_str, re.UNICODE).match |
paul@48 | 31 | match_datetime_icalendar = re.compile(datetime_icalendar_regexp_str, re.UNICODE).match |
paul@48 | 32 | |
paul@48 | 33 | # Content interpretation. |
paul@48 | 34 | |
paul@48 | 35 | def get_items(d, name, all=True): |
paul@48 | 36 | |
paul@48 | 37 | """ |
paul@48 | 38 | Get all items from 'd' with the given 'name', returning single items if |
paul@48 | 39 | 'all' is specified and set to a false value and if only one value is |
paul@48 | 40 | present for the name. Return None if no items are found for the name. |
paul@48 | 41 | """ |
paul@48 | 42 | |
paul@48 | 43 | if d.has_key(name): |
paul@48 | 44 | values = d[name] |
paul@48 | 45 | if not all and len(values) == 1: |
paul@48 | 46 | return values[0] |
paul@48 | 47 | else: |
paul@48 | 48 | return values |
paul@48 | 49 | else: |
paul@48 | 50 | return None |
paul@48 | 51 | |
paul@48 | 52 | def get_item(d, name): |
paul@48 | 53 | return get_items(d, name, False) |
paul@48 | 54 | |
paul@48 | 55 | def get_value_map(d, name): |
paul@48 | 56 | |
paul@48 | 57 | """ |
paul@48 | 58 | Return a dictionary for all items in 'd' having the given 'name'. The |
paul@48 | 59 | dictionary will map values for the name to any attributes or qualifiers |
paul@48 | 60 | that may have been present. |
paul@48 | 61 | """ |
paul@48 | 62 | |
paul@48 | 63 | items = get_items(d, name) |
paul@48 | 64 | if items: |
paul@48 | 65 | return dict(items) |
paul@48 | 66 | else: |
paul@48 | 67 | return {} |
paul@48 | 68 | |
paul@48 | 69 | def get_values(d, name, all=True): |
paul@48 | 70 | if d.has_key(name): |
paul@48 | 71 | values = d[name] |
paul@48 | 72 | if not all and len(values) == 1: |
paul@48 | 73 | return values[0][0] |
paul@48 | 74 | else: |
paul@48 | 75 | return map(lambda x: x[0], values) |
paul@48 | 76 | else: |
paul@48 | 77 | return None |
paul@48 | 78 | |
paul@48 | 79 | def get_value(d, name): |
paul@48 | 80 | return get_values(d, name, False) |
paul@48 | 81 | |
paul@48 | 82 | def get_utc_datetime(d, name): |
paul@48 | 83 | value, attr = get_item(d, name) |
paul@48 | 84 | dt = get_datetime(value, attr) |
paul@48 | 85 | return to_utc_datetime(dt) |
paul@48 | 86 | |
paul@48 | 87 | def to_utc_datetime(dt): |
paul@48 | 88 | if not dt: |
paul@48 | 89 | return None |
paul@48 | 90 | elif isinstance(dt, datetime): |
paul@48 | 91 | return dt.astimezone(timezone("UTC")) |
paul@48 | 92 | else: |
paul@48 | 93 | return dt |
paul@48 | 94 | |
paul@71 | 95 | def to_timezone(dt, name): |
paul@71 | 96 | try: |
paul@71 | 97 | tz = name and timezone(name) or None |
paul@71 | 98 | except UnknownTimeZoneError: |
paul@71 | 99 | tz = None |
paul@71 | 100 | if tz is not None: |
paul@71 | 101 | if not dt.tzinfo: |
paul@71 | 102 | return tz.localize(dt) |
paul@71 | 103 | else: |
paul@71 | 104 | return dt.astimezone(tz) |
paul@71 | 105 | else: |
paul@71 | 106 | return dt |
paul@71 | 107 | |
paul@48 | 108 | def format_datetime(dt): |
paul@48 | 109 | if not dt: |
paul@48 | 110 | return None |
paul@48 | 111 | elif isinstance(dt, datetime): |
paul@71 | 112 | if dt.tzname() == "UTC": |
paul@71 | 113 | return dt.strftime("%Y%m%dT%H%M%SZ") |
paul@71 | 114 | else: |
paul@71 | 115 | return dt.strftime("%Y%m%dT%H%M%S") |
paul@48 | 116 | else: |
paul@48 | 117 | return dt.strftime("%Y%m%d") |
paul@48 | 118 | |
paul@48 | 119 | def get_address(value): |
paul@48 | 120 | return value.startswith("mailto:") and value[7:] or value |
paul@48 | 121 | |
paul@48 | 122 | def get_uri(value): |
paul@48 | 123 | return value.startswith("mailto:") and value or "mailto:%s" % value |
paul@48 | 124 | |
paul@71 | 125 | def get_datetime(value, attr=None): |
paul@48 | 126 | |
paul@71 | 127 | """ |
paul@71 | 128 | Return a datetime object from the given 'value' in iCalendar format, using |
paul@71 | 129 | the 'attr' mapping (if specified) to control the conversion. |
paul@71 | 130 | """ |
paul@71 | 131 | |
paul@71 | 132 | if not attr or attr.get("VALUE") in (None, "DATE-TIME"): |
paul@48 | 133 | m = match_datetime_icalendar(value) |
paul@48 | 134 | if m: |
paul@48 | 135 | dt = datetime( |
paul@48 | 136 | int(m.group("year")), int(m.group("month")), int(m.group("day")), |
paul@48 | 137 | int(m.group("hour")), int(m.group("minute")), int(m.group("second")) |
paul@48 | 138 | ) |
paul@48 | 139 | |
paul@48 | 140 | # Impose the indicated timezone. |
paul@48 | 141 | # NOTE: This needs an ambiguity policy for DST changes. |
paul@48 | 142 | |
paul@71 | 143 | return to_timezone(dt, m.group("utc") and "UTC" or attr and attr.get("TZID") or None) |
paul@48 | 144 | |
paul@71 | 145 | if not attr or attr.get("VALUE") == "DATE": |
paul@48 | 146 | m = match_date_icalendar(value) |
paul@48 | 147 | if m: |
paul@48 | 148 | return date( |
paul@48 | 149 | int(m.group("year")), int(m.group("month")), int(m.group("day")) |
paul@48 | 150 | ) |
paul@48 | 151 | return None |
paul@48 | 152 | |
paul@75 | 153 | # NOTE: Need to expose the 100 day window for recurring events in the |
paul@75 | 154 | # NOTE: configuration. |
paul@75 | 155 | |
paul@75 | 156 | def get_periods(obj, window_size=100): |
paul@75 | 157 | |
paul@75 | 158 | dtstart = get_utc_datetime(obj, "DTSTART") |
paul@75 | 159 | dtend = get_utc_datetime(obj, "DTEND") |
paul@75 | 160 | |
paul@75 | 161 | # NOTE: Need also DURATION support. |
paul@75 | 162 | |
paul@75 | 163 | duration = dtend - dtstart |
paul@75 | 164 | |
paul@75 | 165 | # Recurrence rules create multiple instances to be checked. |
paul@75 | 166 | # Conflicts may only be assessed within a period defined by policy |
paul@75 | 167 | # for the agent, with instances outside that period being considered |
paul@75 | 168 | # unchecked. |
paul@75 | 169 | |
paul@75 | 170 | window_end = datetime.now() + timedelta(window_size) |
paul@75 | 171 | |
paul@75 | 172 | # NOTE: Need also RDATE and EXDATE support. |
paul@75 | 173 | |
paul@75 | 174 | rrule = get_value(obj, "RRULE") |
paul@75 | 175 | |
paul@75 | 176 | if rrule: |
paul@75 | 177 | selector = get_rule(dtstart, rrule) |
paul@75 | 178 | parameters = get_parameters(rrule) |
paul@75 | 179 | periods = [] |
paul@75 | 180 | for start in selector.materialise(dtstart, window_end, parameters.get("COUNT"), parameters.get("BYSETPOS")): |
paul@75 | 181 | start = datetime(*start, tzinfo=timezone("UTC")) |
paul@75 | 182 | end = start + duration |
paul@75 | 183 | periods.append((format_datetime(start), format_datetime(end))) |
paul@75 | 184 | else: |
paul@75 | 185 | periods = [(format_datetime(dtstart), format_datetime(dtend))] |
paul@75 | 186 | |
paul@75 | 187 | return periods |
paul@75 | 188 | |
paul@48 | 189 | # Handler mechanism objects. |
paul@48 | 190 | |
paul@48 | 191 | def handle_itip_part(part, recipients, handlers): |
paul@48 | 192 | |
paul@48 | 193 | """ |
paul@48 | 194 | Handle the given iTIP 'part' for the given 'recipients' using the given |
paul@60 | 195 | 'handlers'. Return a list of responses, each response being a tuple of the |
paul@60 | 196 | form (is-outgoing, message-part). |
paul@48 | 197 | """ |
paul@48 | 198 | |
paul@48 | 199 | method = part.get_param("method") |
paul@48 | 200 | |
paul@48 | 201 | # Decode the data and parse it. |
paul@48 | 202 | |
paul@48 | 203 | f = StringIO(part.get_payload(decode=True)) |
paul@48 | 204 | |
paul@48 | 205 | itip = parse_object(f, part.get_content_charset(), "VCALENDAR") |
paul@48 | 206 | |
paul@48 | 207 | # Ignore the part if not a calendar object. |
paul@48 | 208 | |
paul@48 | 209 | if not itip: |
paul@48 | 210 | return [] |
paul@48 | 211 | |
paul@48 | 212 | # Require consistency between declared and employed methods. |
paul@48 | 213 | |
paul@48 | 214 | if get_value(itip, "METHOD") == method: |
paul@48 | 215 | |
paul@48 | 216 | # Look for different kinds of sections. |
paul@48 | 217 | |
paul@60 | 218 | all_results = [] |
paul@48 | 219 | |
paul@48 | 220 | for name, cls in handlers: |
paul@48 | 221 | for details in get_values(itip, name) or []: |
paul@48 | 222 | |
paul@48 | 223 | # Dispatch to a handler and obtain any response. |
paul@48 | 224 | |
paul@48 | 225 | handler = cls(details, recipients) |
paul@60 | 226 | result = methods[method](handler)() |
paul@48 | 227 | |
paul@48 | 228 | # Concatenate responses for a single calendar object. |
paul@48 | 229 | |
paul@60 | 230 | if result: |
paul@60 | 231 | response_method, part = result |
paul@60 | 232 | outgoing = method != response_method |
paul@60 | 233 | all_results.append((outgoing, part)) |
paul@48 | 234 | |
paul@60 | 235 | return all_results |
paul@48 | 236 | |
paul@60 | 237 | return [] |
paul@48 | 238 | |
paul@70 | 239 | def parse_object(f, encoding, objtype=None): |
paul@48 | 240 | |
paul@48 | 241 | """ |
paul@70 | 242 | Parse the iTIP content from 'f' having the given 'encoding'. If 'objtype' is |
paul@70 | 243 | given, only objects of that type will be returned. |
paul@70 | 244 | |
paul@70 | 245 | Return None if the content was not readable or suitable. |
paul@48 | 246 | """ |
paul@48 | 247 | |
paul@48 | 248 | try: |
paul@48 | 249 | try: |
paul@48 | 250 | doctype, attrs, elements = obj = parse(f, encoding=encoding) |
paul@70 | 251 | if objtype and doctype == objtype: |
paul@48 | 252 | return to_dict(obj)[objtype][0] |
paul@70 | 253 | elif not objtype: |
paul@70 | 254 | return to_dict(obj)[doctype][0] |
paul@48 | 255 | finally: |
paul@48 | 256 | f.close() |
paul@48 | 257 | except (ParseError, ValueError): |
paul@48 | 258 | pass |
paul@48 | 259 | |
paul@48 | 260 | return None |
paul@48 | 261 | |
paul@48 | 262 | def to_part(method, calendar): |
paul@48 | 263 | |
paul@48 | 264 | """ |
paul@48 | 265 | Write using the given 'method', the 'calendar' details to a MIME |
paul@48 | 266 | text/calendar part. |
paul@48 | 267 | """ |
paul@48 | 268 | |
paul@48 | 269 | encoding = "utf-8" |
paul@48 | 270 | out = StringIO() |
paul@48 | 271 | try: |
paul@48 | 272 | imip_store.to_stream(out, imip_store.make_calendar(calendar, method), encoding) |
paul@48 | 273 | part = MIMEText(out.getvalue(), "calendar", encoding) |
paul@48 | 274 | part.set_param("method", method) |
paul@48 | 275 | return part |
paul@48 | 276 | |
paul@48 | 277 | finally: |
paul@48 | 278 | out.close() |
paul@48 | 279 | |
paul@48 | 280 | class Handler: |
paul@48 | 281 | |
paul@48 | 282 | "General handler support." |
paul@48 | 283 | |
paul@48 | 284 | def __init__(self, details, recipients): |
paul@48 | 285 | |
paul@48 | 286 | """ |
paul@48 | 287 | Initialise the handler with the 'details' of a calendar object and the |
paul@48 | 288 | 'recipients' of the object. |
paul@48 | 289 | """ |
paul@48 | 290 | |
paul@48 | 291 | self.details = details |
paul@48 | 292 | self.recipients = set(recipients) |
paul@48 | 293 | |
paul@48 | 294 | self.uid = get_value(details, "UID") |
paul@48 | 295 | self.sequence = get_value(details, "SEQUENCE") |
paul@48 | 296 | self.dtstamp = get_value(details, "DTSTAMP") |
paul@48 | 297 | |
paul@48 | 298 | self.store = imip_store.FileStore() |
paul@48 | 299 | |
paul@48 | 300 | try: |
paul@48 | 301 | self.publisher = imip_store.FilePublisher() |
paul@48 | 302 | except OSError: |
paul@48 | 303 | self.publisher = None |
paul@48 | 304 | |
paul@70 | 305 | # Access to calendar structures and other data. |
paul@70 | 306 | |
paul@48 | 307 | def get_items(self, name, all=True): |
paul@48 | 308 | return get_items(self.details, name, all) |
paul@48 | 309 | |
paul@48 | 310 | def get_item(self, name): |
paul@48 | 311 | return get_item(self.details, name) |
paul@48 | 312 | |
paul@48 | 313 | def get_value_map(self, name): |
paul@48 | 314 | return get_value_map(self.details, name) |
paul@48 | 315 | |
paul@48 | 316 | def get_values(self, name, all=True): |
paul@48 | 317 | return get_values(self.details, name, all) |
paul@48 | 318 | |
paul@48 | 319 | def get_value(self, name): |
paul@48 | 320 | return get_value(self.details, name) |
paul@48 | 321 | |
paul@48 | 322 | def get_utc_datetime(self, name): |
paul@48 | 323 | return get_utc_datetime(self.details, name) |
paul@48 | 324 | |
paul@75 | 325 | def get_periods(self): |
paul@75 | 326 | return get_periods(self.details) |
paul@75 | 327 | |
paul@48 | 328 | def filter_by_recipients(self, values): |
paul@48 | 329 | return self.recipients.intersection(map(get_address, values)) |
paul@48 | 330 | |
paul@48 | 331 | def require_organiser_and_attendees(self): |
paul@51 | 332 | |
paul@51 | 333 | """ |
paul@51 | 334 | Return the organiser and attendees for the current object, filtered by |
paul@51 | 335 | the recipients of interest. Return None if no identities are eligible. |
paul@51 | 336 | """ |
paul@51 | 337 | |
paul@48 | 338 | attendee_map = self.get_value_map("ATTENDEE") |
paul@48 | 339 | organiser = self.get_item("ORGANIZER") |
paul@48 | 340 | |
paul@48 | 341 | # Only provide details for recipients who are also attendees. |
paul@48 | 342 | |
paul@48 | 343 | attendees = {} |
paul@48 | 344 | for attendee in map(get_uri, self.filter_by_recipients(attendee_map)): |
paul@48 | 345 | attendees[attendee] = attendee_map[attendee] |
paul@48 | 346 | |
paul@48 | 347 | if not attendees and not organiser: |
paul@48 | 348 | return None |
paul@48 | 349 | |
paul@48 | 350 | return organiser, attendees |
paul@48 | 351 | |
paul@51 | 352 | def have_new_object(self, attendee, objtype): |
paul@51 | 353 | |
paul@51 | 354 | """ |
paul@51 | 355 | Return whether the current object is new to the 'attendee' for the |
paul@51 | 356 | given 'objtype'. |
paul@51 | 357 | """ |
paul@51 | 358 | |
paul@51 | 359 | f = self.store.get_event(attendee, self.uid) |
paul@51 | 360 | event = f and parse_object(f, "utf-8", objtype) |
paul@51 | 361 | |
paul@51 | 362 | # If found, compare SEQUENCE and potentially DTSTAMP. |
paul@51 | 363 | |
paul@51 | 364 | if event: |
paul@51 | 365 | sequence = get_value(event, "SEQUENCE") |
paul@51 | 366 | dtstamp = get_value(event, "DTSTAMP") |
paul@51 | 367 | |
paul@51 | 368 | # If the request refers to an older version of the event, ignore |
paul@51 | 369 | # it. |
paul@51 | 370 | |
paul@51 | 371 | old_dtstamp = self.dtstamp < dtstamp |
paul@51 | 372 | |
paul@51 | 373 | if sequence is not None and ( |
paul@51 | 374 | int(self.sequence) < int(sequence) or |
paul@51 | 375 | int(self.sequence) == int(sequence) and old_dtstamp |
paul@51 | 376 | ) or old_dtstamp: |
paul@51 | 377 | |
paul@51 | 378 | return False |
paul@51 | 379 | |
paul@51 | 380 | return True |
paul@51 | 381 | |
paul@48 | 382 | # Handler registry. |
paul@48 | 383 | |
paul@48 | 384 | methods = { |
paul@48 | 385 | "ADD" : lambda handler: handler.add, |
paul@48 | 386 | "CANCEL" : lambda handler: handler.cancel, |
paul@48 | 387 | "COUNTER" : lambda handler: handler.counter, |
paul@48 | 388 | "DECLINECOUNTER" : lambda handler: handler.declinecounter, |
paul@48 | 389 | "PUBLISH" : lambda handler: handler.publish, |
paul@48 | 390 | "REFRESH" : lambda handler: handler.refresh, |
paul@48 | 391 | "REPLY" : lambda handler: handler.reply, |
paul@48 | 392 | "REQUEST" : lambda handler: handler.request, |
paul@48 | 393 | } |
paul@48 | 394 | |
paul@48 | 395 | # vim: tabstop=4 expandtab shiftwidth=4 |