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@48 | 8 | from datetime import date, datetime |
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@48 | 12 | import imip_store |
paul@48 | 13 | import re |
paul@48 | 14 | |
paul@48 | 15 | try: |
paul@48 | 16 | from cStringIO import StringIO |
paul@48 | 17 | except ImportError: |
paul@48 | 18 | from StringIO import StringIO |
paul@48 | 19 | |
paul@48 | 20 | # iCalendar date and datetime parsing (from DateSupport in MoinSupport). |
paul@48 | 21 | |
paul@48 | 22 | date_icalendar_regexp_str = ur'(?P<year>[0-9]{4})(?P<month>[0-9]{2})(?P<day>[0-9]{2})' |
paul@48 | 23 | datetime_icalendar_regexp_str = date_icalendar_regexp_str + \ |
paul@48 | 24 | ur'(?:' \ |
paul@48 | 25 | ur'T(?P<hour>[0-2][0-9])(?P<minute>[0-5][0-9])(?P<second>[0-6][0-9])' \ |
paul@48 | 26 | ur'(?P<utc>Z)?' \ |
paul@48 | 27 | ur')?' |
paul@48 | 28 | |
paul@48 | 29 | match_date_icalendar = re.compile(date_icalendar_regexp_str, re.UNICODE).match |
paul@48 | 30 | match_datetime_icalendar = re.compile(datetime_icalendar_regexp_str, re.UNICODE).match |
paul@48 | 31 | |
paul@48 | 32 | # Content interpretation. |
paul@48 | 33 | |
paul@48 | 34 | def get_items(d, name, all=True): |
paul@48 | 35 | |
paul@48 | 36 | """ |
paul@48 | 37 | Get all items from 'd' with the given 'name', returning single items if |
paul@48 | 38 | 'all' is specified and set to a false value and if only one value is |
paul@48 | 39 | present for the name. Return None if no items are found for the name. |
paul@48 | 40 | """ |
paul@48 | 41 | |
paul@48 | 42 | if d.has_key(name): |
paul@48 | 43 | values = d[name] |
paul@48 | 44 | if not all and len(values) == 1: |
paul@48 | 45 | return values[0] |
paul@48 | 46 | else: |
paul@48 | 47 | return values |
paul@48 | 48 | else: |
paul@48 | 49 | return None |
paul@48 | 50 | |
paul@48 | 51 | def get_item(d, name): |
paul@48 | 52 | return get_items(d, name, False) |
paul@48 | 53 | |
paul@48 | 54 | def get_value_map(d, name): |
paul@48 | 55 | |
paul@48 | 56 | """ |
paul@48 | 57 | Return a dictionary for all items in 'd' having the given 'name'. The |
paul@48 | 58 | dictionary will map values for the name to any attributes or qualifiers |
paul@48 | 59 | that may have been present. |
paul@48 | 60 | """ |
paul@48 | 61 | |
paul@48 | 62 | items = get_items(d, name) |
paul@48 | 63 | if items: |
paul@48 | 64 | return dict(items) |
paul@48 | 65 | else: |
paul@48 | 66 | return {} |
paul@48 | 67 | |
paul@48 | 68 | def get_values(d, name, all=True): |
paul@48 | 69 | if d.has_key(name): |
paul@48 | 70 | values = d[name] |
paul@48 | 71 | if not all and len(values) == 1: |
paul@48 | 72 | return values[0][0] |
paul@48 | 73 | else: |
paul@48 | 74 | return map(lambda x: x[0], values) |
paul@48 | 75 | else: |
paul@48 | 76 | return None |
paul@48 | 77 | |
paul@48 | 78 | def get_value(d, name): |
paul@48 | 79 | return get_values(d, name, False) |
paul@48 | 80 | |
paul@48 | 81 | def get_utc_datetime(d, name): |
paul@48 | 82 | value, attr = get_item(d, name) |
paul@48 | 83 | dt = get_datetime(value, attr) |
paul@48 | 84 | return to_utc_datetime(dt) |
paul@48 | 85 | |
paul@48 | 86 | def to_utc_datetime(dt): |
paul@48 | 87 | if not dt: |
paul@48 | 88 | return None |
paul@48 | 89 | elif isinstance(dt, datetime): |
paul@48 | 90 | return dt.astimezone(timezone("UTC")) |
paul@48 | 91 | else: |
paul@48 | 92 | return dt |
paul@48 | 93 | |
paul@48 | 94 | def format_datetime(dt): |
paul@48 | 95 | if not dt: |
paul@48 | 96 | return None |
paul@48 | 97 | elif isinstance(dt, datetime): |
paul@48 | 98 | return dt.strftime("%Y%m%dT%H%M%SZ") |
paul@48 | 99 | else: |
paul@48 | 100 | return dt.strftime("%Y%m%d") |
paul@48 | 101 | |
paul@48 | 102 | def get_address(value): |
paul@48 | 103 | return value.startswith("mailto:") and value[7:] or value |
paul@48 | 104 | |
paul@48 | 105 | def get_uri(value): |
paul@48 | 106 | return value.startswith("mailto:") and value or "mailto:%s" % value |
paul@48 | 107 | |
paul@48 | 108 | def get_datetime(value, attr): |
paul@48 | 109 | try: |
paul@48 | 110 | tz = attr.has_key("TZID") and timezone(attr["TZID"]) or None |
paul@48 | 111 | except UnknownTimeZoneError: |
paul@48 | 112 | tz = None |
paul@48 | 113 | |
paul@48 | 114 | if attr.get("VALUE") in (None, "DATE-TIME"): |
paul@48 | 115 | m = match_datetime_icalendar(value) |
paul@48 | 116 | if m: |
paul@48 | 117 | dt = datetime( |
paul@48 | 118 | int(m.group("year")), int(m.group("month")), int(m.group("day")), |
paul@48 | 119 | int(m.group("hour")), int(m.group("minute")), int(m.group("second")) |
paul@48 | 120 | ) |
paul@48 | 121 | |
paul@48 | 122 | # Impose the indicated timezone. |
paul@48 | 123 | # NOTE: This needs an ambiguity policy for DST changes. |
paul@48 | 124 | |
paul@48 | 125 | tz = m.group("utc") and timezone("UTC") or tz or None |
paul@48 | 126 | if tz is not None: |
paul@48 | 127 | return tz.localize(dt) |
paul@48 | 128 | else: |
paul@48 | 129 | return dt |
paul@48 | 130 | |
paul@48 | 131 | if attr.get("VALUE") == "DATE": |
paul@48 | 132 | m = match_date_icalendar(value) |
paul@48 | 133 | if m: |
paul@48 | 134 | return date( |
paul@48 | 135 | int(m.group("year")), int(m.group("month")), int(m.group("day")) |
paul@48 | 136 | ) |
paul@48 | 137 | return None |
paul@48 | 138 | |
paul@48 | 139 | # Handler mechanism objects. |
paul@48 | 140 | |
paul@48 | 141 | def handle_itip_part(part, recipients, handlers): |
paul@48 | 142 | |
paul@48 | 143 | """ |
paul@48 | 144 | Handle the given iTIP 'part' for the given 'recipients' using the given |
paul@48 | 145 | 'handlers'. |
paul@48 | 146 | """ |
paul@48 | 147 | |
paul@48 | 148 | method = part.get_param("method") |
paul@48 | 149 | |
paul@48 | 150 | # Decode the data and parse it. |
paul@48 | 151 | |
paul@48 | 152 | f = StringIO(part.get_payload(decode=True)) |
paul@48 | 153 | |
paul@48 | 154 | itip = parse_object(f, part.get_content_charset(), "VCALENDAR") |
paul@48 | 155 | |
paul@48 | 156 | # Ignore the part if not a calendar object. |
paul@48 | 157 | |
paul@48 | 158 | if not itip: |
paul@48 | 159 | return [] |
paul@48 | 160 | |
paul@48 | 161 | # Only handle calendar information. |
paul@48 | 162 | |
paul@48 | 163 | all_parts = [] |
paul@48 | 164 | |
paul@48 | 165 | # Require consistency between declared and employed methods. |
paul@48 | 166 | |
paul@48 | 167 | if get_value(itip, "METHOD") == method: |
paul@48 | 168 | |
paul@48 | 169 | # Look for different kinds of sections. |
paul@48 | 170 | |
paul@48 | 171 | all_objects = [] |
paul@48 | 172 | |
paul@48 | 173 | for name, cls in handlers: |
paul@48 | 174 | for details in get_values(itip, name) or []: |
paul@48 | 175 | |
paul@48 | 176 | # Dispatch to a handler and obtain any response. |
paul@48 | 177 | |
paul@48 | 178 | handler = cls(details, recipients) |
paul@48 | 179 | object = methods[method](handler)() |
paul@48 | 180 | |
paul@48 | 181 | # Concatenate responses for a single calendar object. |
paul@48 | 182 | |
paul@48 | 183 | if object: |
paul@48 | 184 | all_objects += object |
paul@48 | 185 | |
paul@48 | 186 | # Obtain a message part for the objects. |
paul@48 | 187 | |
paul@48 | 188 | if all_objects: |
paul@48 | 189 | all_parts.append(to_part(response_methods[method], all_objects)) |
paul@48 | 190 | |
paul@48 | 191 | return all_parts |
paul@48 | 192 | |
paul@48 | 193 | def parse_object(f, encoding, objtype): |
paul@48 | 194 | |
paul@48 | 195 | """ |
paul@48 | 196 | Parse the iTIP content from 'f' having the given 'encoding'. Return None if |
paul@48 | 197 | the content was not readable or suitable. |
paul@48 | 198 | """ |
paul@48 | 199 | |
paul@48 | 200 | try: |
paul@48 | 201 | try: |
paul@48 | 202 | doctype, attrs, elements = obj = parse(f, encoding=encoding) |
paul@48 | 203 | if doctype == objtype: |
paul@48 | 204 | return to_dict(obj)[objtype][0] |
paul@48 | 205 | finally: |
paul@48 | 206 | f.close() |
paul@48 | 207 | except (ParseError, ValueError): |
paul@48 | 208 | pass |
paul@48 | 209 | |
paul@48 | 210 | return None |
paul@48 | 211 | |
paul@48 | 212 | def to_part(method, calendar): |
paul@48 | 213 | |
paul@48 | 214 | """ |
paul@48 | 215 | Write using the given 'method', the 'calendar' details to a MIME |
paul@48 | 216 | text/calendar part. |
paul@48 | 217 | """ |
paul@48 | 218 | |
paul@48 | 219 | encoding = "utf-8" |
paul@48 | 220 | out = StringIO() |
paul@48 | 221 | try: |
paul@48 | 222 | imip_store.to_stream(out, imip_store.make_calendar(calendar, method), encoding) |
paul@48 | 223 | part = MIMEText(out.getvalue(), "calendar", encoding) |
paul@48 | 224 | part.set_param("method", method) |
paul@48 | 225 | return part |
paul@48 | 226 | |
paul@48 | 227 | finally: |
paul@48 | 228 | out.close() |
paul@48 | 229 | |
paul@48 | 230 | class Handler: |
paul@48 | 231 | |
paul@48 | 232 | "General handler support." |
paul@48 | 233 | |
paul@48 | 234 | def __init__(self, details, recipients): |
paul@48 | 235 | |
paul@48 | 236 | """ |
paul@48 | 237 | Initialise the handler with the 'details' of a calendar object and the |
paul@48 | 238 | 'recipients' of the object. |
paul@48 | 239 | """ |
paul@48 | 240 | |
paul@48 | 241 | self.details = details |
paul@48 | 242 | self.recipients = set(recipients) |
paul@48 | 243 | |
paul@48 | 244 | self.uid = get_value(details, "UID") |
paul@48 | 245 | self.sequence = get_value(details, "SEQUENCE") |
paul@48 | 246 | self.dtstamp = get_value(details, "DTSTAMP") |
paul@48 | 247 | |
paul@48 | 248 | self.store = imip_store.FileStore() |
paul@48 | 249 | |
paul@48 | 250 | try: |
paul@48 | 251 | self.publisher = imip_store.FilePublisher() |
paul@48 | 252 | except OSError: |
paul@48 | 253 | self.publisher = None |
paul@48 | 254 | |
paul@48 | 255 | def get_items(self, name, all=True): |
paul@48 | 256 | return get_items(self.details, name, all) |
paul@48 | 257 | |
paul@48 | 258 | def get_item(self, name): |
paul@48 | 259 | return get_item(self.details, name) |
paul@48 | 260 | |
paul@48 | 261 | def get_value_map(self, name): |
paul@48 | 262 | return get_value_map(self.details, name) |
paul@48 | 263 | |
paul@48 | 264 | def get_values(self, name, all=True): |
paul@48 | 265 | return get_values(self.details, name, all) |
paul@48 | 266 | |
paul@48 | 267 | def get_value(self, name): |
paul@48 | 268 | return get_value(self.details, name) |
paul@48 | 269 | |
paul@48 | 270 | def get_utc_datetime(self, name): |
paul@48 | 271 | return get_utc_datetime(self.details, name) |
paul@48 | 272 | |
paul@48 | 273 | def filter_by_recipients(self, values): |
paul@48 | 274 | return self.recipients.intersection(map(get_address, values)) |
paul@48 | 275 | |
paul@48 | 276 | def require_organiser_and_attendees(self): |
paul@48 | 277 | attendee_map = self.get_value_map("ATTENDEE") |
paul@48 | 278 | organiser = self.get_item("ORGANIZER") |
paul@48 | 279 | |
paul@48 | 280 | # Only provide details for recipients who are also attendees. |
paul@48 | 281 | |
paul@48 | 282 | attendees = {} |
paul@48 | 283 | for attendee in map(get_uri, self.filter_by_recipients(attendee_map)): |
paul@48 | 284 | attendees[attendee] = attendee_map[attendee] |
paul@48 | 285 | |
paul@48 | 286 | if not attendees and not organiser: |
paul@48 | 287 | return None |
paul@48 | 288 | |
paul@48 | 289 | return organiser, attendees |
paul@48 | 290 | |
paul@48 | 291 | # Handler registry. |
paul@48 | 292 | |
paul@48 | 293 | methods = { |
paul@48 | 294 | "ADD" : lambda handler: handler.add, |
paul@48 | 295 | "CANCEL" : lambda handler: handler.cancel, |
paul@48 | 296 | "COUNTER" : lambda handler: handler.counter, |
paul@48 | 297 | "DECLINECOUNTER" : lambda handler: handler.declinecounter, |
paul@48 | 298 | "PUBLISH" : lambda handler: handler.publish, |
paul@48 | 299 | "REFRESH" : lambda handler: handler.refresh, |
paul@48 | 300 | "REPLY" : lambda handler: handler.reply, |
paul@48 | 301 | "REQUEST" : lambda handler: handler.request, |
paul@48 | 302 | } |
paul@48 | 303 | |
paul@48 | 304 | response_methods = { |
paul@48 | 305 | "REQUEST" : "REPLY", |
paul@48 | 306 | } |
paul@48 | 307 | |
paul@48 | 308 | # vim: tabstop=4 expandtab shiftwidth=4 |