1 #!/usr/bin/env python 2 3 """ 4 Interpretation of vCalendar content. 5 6 Copyright (C) 2014, 2015 Paul Boddie <paul@boddie.org.uk> 7 8 This program is free software; you can redistribute it and/or modify it under 9 the terms of the GNU General Public License as published by the Free Software 10 Foundation; either version 3 of the License, or (at your option) any later 11 version. 12 13 This program is distributed in the hope that it will be useful, but WITHOUT 14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 15 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more 16 details. 17 18 You should have received a copy of the GNU General Public License along with 19 this program. If not, see <http://www.gnu.org/licenses/>. 20 """ 21 22 from bisect import bisect_left 23 from datetime import datetime, timedelta 24 from email.mime.text import MIMEText 25 from imiptools.dates import format_datetime, get_datetime, get_duration, \ 26 get_freebusy_period, get_period, to_datetime, \ 27 to_timezone, to_utc_datetime 28 from imiptools.period import FreeBusyPeriod, Period, period_overlaps 29 from pytz import timezone 30 from vCalendar import iterwrite, parse, ParseError, to_dict, to_node 31 from vRecurrence import get_parameters, get_rule 32 import email.utils 33 34 try: 35 from cStringIO import StringIO 36 except ImportError: 37 from StringIO import StringIO 38 39 class Object: 40 41 "Access to calendar structures." 42 43 def __init__(self, fragment): 44 self.objtype, (self.details, self.attr) = fragment.items()[0] 45 46 def get_items(self, name, all=True): 47 return get_items(self.details, name, all) 48 49 def get_item(self, name): 50 return get_item(self.details, name) 51 52 def get_value_map(self, name): 53 return get_value_map(self.details, name) 54 55 def get_values(self, name, all=True): 56 return get_values(self.details, name, all) 57 58 def get_value(self, name): 59 return get_value(self.details, name) 60 61 def get_utc_datetime(self, name): 62 return get_utc_datetime(self.details, name) 63 64 def get_date_values(self, name, tzid=None): 65 items = get_date_value_items(self.details, name, tzid) 66 return items and [value for value, attr in items] 67 68 def get_date_value_items(self, name, tzid=None): 69 return get_date_value_items(self.details, name, tzid) 70 71 def get_datetime(self, name): 72 dt, attr = get_datetime_item(self.details, name) 73 return dt 74 75 def get_datetime_item(self, name): 76 return get_datetime_item(self.details, name) 77 78 def get_duration(self, name): 79 return get_duration(self.get_value(name)) 80 81 def to_node(self): 82 return to_node({self.objtype : [(self.details, self.attr)]}) 83 84 def to_part(self, method): 85 return to_part(method, [self.to_node()]) 86 87 # Direct access to the structure. 88 89 def has_key(self, name): 90 return self.details.has_key(name) 91 92 def __getitem__(self, name): 93 return self.details[name] 94 95 def __setitem__(self, name, value): 96 self.details[name] = value 97 98 def __delitem__(self, name): 99 del self.details[name] 100 101 # Computed results. 102 103 def has_recurrence(self, tzid, recurrence): 104 recurrences = [p.start for p in get_periods(self, tzid, recurrence, inclusive=True)] 105 return recurrence in recurrences 106 107 def get_periods(self, tzid, end): 108 return get_periods(self, tzid, end) 109 110 def get_periods_for_freebusy(self, tzid, end): 111 periods = self.get_periods(tzid, end) 112 return get_periods_for_freebusy(self, periods, tzid) 113 114 def get_tzid(self): 115 dtstart, dtstart_attr = self.get_datetime_item("DTSTART") 116 dtend, dtend_attr = self.get_datetime_item("DTEND") 117 return get_tzid(dtstart_attr, dtend_attr) 118 119 # Construction and serialisation. 120 121 def make_calendar(nodes, method=None): 122 123 """ 124 Return a complete calendar node wrapping the given 'nodes' and employing the 125 given 'method', if indicated. 126 """ 127 128 return ("VCALENDAR", {}, 129 (method and [("METHOD", {}, method)] or []) + 130 [("VERSION", {}, "2.0")] + 131 nodes 132 ) 133 134 def make_freebusy(freebusy, uid, organiser, organiser_attr=None, attendee=None, 135 attendee_attr=None, dtstart=None, dtend=None): 136 137 """ 138 Return a calendar node defining the free/busy details described in the given 139 'freebusy' list, employing the given 'uid', for the given 'organiser' and 140 optional 'organiser_attr', with the optional 'attendee' providing recipient 141 details together with the optional 'attendee_attr'. 142 143 The result will be constrained to the 'dtstart' and 'dtend' period if these 144 parameters are given. 145 """ 146 147 record = [] 148 rwrite = record.append 149 150 rwrite(("ORGANIZER", organiser_attr or {}, organiser)) 151 152 if attendee: 153 rwrite(("ATTENDEE", attendee_attr or {}, attendee)) 154 155 rwrite(("UID", {}, uid)) 156 157 if freebusy: 158 159 # Get a constrained view if start and end limits are specified. 160 161 periods = dtstart and dtend and \ 162 period_overlaps(freebusy, Period(dtstart, dtend), True) or \ 163 freebusy 164 165 # Write the limits of the resource. 166 167 rwrite(("DTSTART", {"VALUE" : "DATE-TIME"}, periods[0][0])) 168 rwrite(("DTEND", {"VALUE" : "DATE-TIME"}, periods[-1][1])) 169 170 for p in periods: 171 if p.transp == "OPAQUE": 172 rwrite(("FREEBUSY", {"FBTYPE" : "BUSY"}, "/".join([p.start, p.end]))) 173 174 return ("VFREEBUSY", {}, record) 175 176 def parse_object(f, encoding, objtype=None): 177 178 """ 179 Parse the iTIP content from 'f' having the given 'encoding'. If 'objtype' is 180 given, only objects of that type will be returned. Otherwise, the root of 181 the content will be returned as a dictionary with a single key indicating 182 the object type. 183 184 Return None if the content was not readable or suitable. 185 """ 186 187 try: 188 try: 189 doctype, attrs, elements = obj = parse(f, encoding=encoding) 190 if objtype and doctype == objtype: 191 return to_dict(obj)[objtype][0] 192 elif not objtype: 193 return to_dict(obj) 194 finally: 195 f.close() 196 197 # NOTE: Handle parse errors properly. 198 199 except (ParseError, ValueError): 200 pass 201 202 return None 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 to_stream(out, 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 to_stream(out, fragment, encoding="utf-8"): 223 iterwrite(out, encoding=encoding).append(fragment) 224 225 # Structure access functions. 226 227 def get_items(d, name, all=True): 228 229 """ 230 Get all items from 'd' for the given 'name', returning single items if 231 'all' is specified and set to a false value and if only one value is 232 present for the name. Return None if no items are found for the name or if 233 many items are found but 'all' is set to a false value. 234 """ 235 236 if d.has_key(name): 237 values = d[name] 238 if all: 239 return values 240 elif len(values) == 1: 241 return values[0] 242 else: 243 return None 244 else: 245 return None 246 247 def get_item(d, name): 248 return get_items(d, name, False) 249 250 def get_value_map(d, name): 251 252 """ 253 Return a dictionary for all items in 'd' having the given 'name'. The 254 dictionary will map values for the name to any attributes or qualifiers 255 that may have been present. 256 """ 257 258 items = get_items(d, name) 259 if items: 260 return dict(items) 261 else: 262 return {} 263 264 def get_values(d, name, all=True): 265 if d.has_key(name): 266 values = d[name] 267 if not all and len(values) == 1: 268 return values[0][0] 269 else: 270 return map(lambda x: x[0], values) 271 else: 272 return None 273 274 def get_value(d, name): 275 return get_values(d, name, False) 276 277 def get_date_value_items(d, name, tzid=None): 278 279 """ 280 Obtain items from 'd' having the given 'name', where a single item yields 281 potentially many values. Return a list of tuples of the form (value, 282 attributes) where the attributes have been given for the property in 'd'. 283 """ 284 285 items = get_items(d, name) 286 if items: 287 all_items = [] 288 for item in items: 289 values, attr = item 290 if not attr.has_key("TZID") and tzid: 291 attr["TZID"] = tzid 292 if not isinstance(values, list): 293 values = [values] 294 for value in values: 295 all_items.append((get_datetime(value, attr) or get_period(value, attr), attr)) 296 return all_items 297 else: 298 return None 299 300 def get_utc_datetime(d, name): 301 t = get_datetime_item(d, name) 302 if not t: 303 return None 304 else: 305 dt, attr = t 306 return to_utc_datetime(dt) 307 308 def get_datetime_item(d, name): 309 t = get_item(d, name) 310 if not t: 311 return None 312 else: 313 value, attr = t 314 return get_datetime(value, attr), attr 315 316 def get_addresses(values): 317 return [address for name, address in email.utils.getaddresses(values)] 318 319 def get_address(value): 320 value = value.lower() 321 return value.startswith("mailto:") and value[7:] or value 322 323 def get_uri(value): 324 return value.lower().startswith("mailto:") and value.lower() or ":" in value and value or "mailto:%s" % value.lower() 325 326 uri_value = get_uri 327 328 def uri_values(values): 329 return map(get_uri, values) 330 331 def uri_dict(d): 332 return dict([(get_uri(key), value) for key, value in d.items()]) 333 334 def uri_item(item): 335 return get_uri(item[0]), item[1] 336 337 def uri_items(items): 338 return [(get_uri(value), attr) for value, attr in items] 339 340 # Operations on structure data. 341 342 def is_new_object(old_sequence, new_sequence, old_dtstamp, new_dtstamp, partstat_set): 343 344 """ 345 Return for the given 'old_sequence' and 'new_sequence', 'old_dtstamp' and 346 'new_dtstamp', and the 'partstat_set' indication, whether the object 347 providing the new information is really newer than the object providing the 348 old information. 349 """ 350 351 have_sequence = old_sequence is not None and new_sequence is not None 352 is_same_sequence = have_sequence and int(new_sequence) == int(old_sequence) 353 354 have_dtstamp = old_dtstamp and new_dtstamp 355 is_old_dtstamp = have_dtstamp and new_dtstamp < old_dtstamp or old_dtstamp and not new_dtstamp 356 357 is_old_sequence = have_sequence and ( 358 int(new_sequence) < int(old_sequence) or 359 is_same_sequence and is_old_dtstamp 360 ) 361 362 return is_same_sequence and partstat_set or not is_old_sequence 363 364 # NOTE: Need to expose the 100 day window for recurring events in the 365 # NOTE: configuration. 366 367 def get_window_end(tzid, window_size=100): 368 return to_timezone(datetime.now(), tzid) + timedelta(window_size) 369 370 def get_tzid(dtstart_attr, dtend_attr): 371 return dtstart_attr.get("TZID") or dtend_attr.get("TZID") 372 373 class RecurringPeriod(Period): 374 375 "A period with origin information from the object." 376 377 def __init__(self, start, end, origin): 378 Period.__init__(self, start, end) 379 self.origin = origin 380 381 def __repr__(self): 382 return "RecurringPeriod(%r, %r, %r)" % (self.start, self.end, self.origin) 383 384 def get_periods(obj, tzid, window_end, inclusive=False): 385 386 """ 387 Return periods for the given object 'obj', confining materialised periods 388 to before the given 'window_end' datetime. If 'inclusive' is set to a true 389 value, any period occurring at the 'window_end' will be included. 390 """ 391 392 rrule = obj.get_value("RRULE") 393 394 # Use localised datetimes. 395 396 dtstart, dtstart_attr = obj.get_datetime_item("DTSTART") 397 398 if obj.has_key("DTEND"): 399 dtend, dtend_attr = obj.get_datetime_item("DTEND") 400 duration = dtend - dtstart 401 elif obj.has_key("DURATION"): 402 duration = obj.get_duration("DURATION") 403 dtend = dtstart + duration 404 dtend_attr = dtstart_attr 405 else: 406 dtend, dtend_attr = dtstart, dtstart_attr 407 408 tzid = get_tzid(dtstart_attr, dtend_attr) or tzid 409 410 if not rrule: 411 periods = [RecurringPeriod(dtstart, dtend, "DTSTART")] 412 else: 413 # Recurrence rules create multiple instances to be checked. 414 # Conflicts may only be assessed within a period defined by policy 415 # for the agent, with instances outside that period being considered 416 # unchecked. 417 418 selector = get_rule(dtstart, rrule) 419 parameters = get_parameters(rrule) 420 periods = [] 421 422 for start in selector.materialise(dtstart, window_end, parameters.get("COUNT"), parameters.get("BYSETPOS"), inclusive): 423 start = to_timezone(datetime(*start), tzid) 424 end = start + duration 425 periods.append(RecurringPeriod(start, end, "RRULE")) 426 427 # Add recurrence dates. 428 429 periods = set(periods) 430 rdates = obj.get_date_values("RDATE", tzid) 431 432 if rdates: 433 for rdate in rdates: 434 if isinstance(rdate, tuple): 435 periods.add(RecurringPeriod(rdate[0], rdate[1], "RDATE")) 436 else: 437 periods.add(RecurringPeriod(rdate, rdate + duration, "RDATE")) 438 439 # Return a sorted list of the periods. 440 441 periods = list(periods) 442 periods.sort(cmp=compare_periods(tzid)) 443 444 # Exclude exception dates. 445 446 exdates = obj.get_date_values("EXDATE", tzid) 447 448 if exdates: 449 for exdate in exdates: 450 if isinstance(exdate, tuple): 451 period = Period(exdate[0], exdate[1]) 452 else: 453 period = Period(exdate, exdate + duration) 454 i = bisect_left(periods, period) 455 while i < len(periods) and periods[i] == period: 456 del periods[i] 457 458 return periods 459 460 class compare_periods: 461 462 "Compare periods for exception date purposes." 463 464 def __init__(self, tzid): 465 self.tzid = tzid 466 467 def __call__(self, first, second): 468 return cmp( 469 (to_datetime(first.start, self.tzid), to_datetime(first.end, self.tzid)), 470 (to_datetime(second.start, self.tzid), to_datetime(second.end, self.tzid)) 471 ) 472 473 def get_periods_for_freebusy(obj, periods, tzid): 474 475 """ 476 Get free/busy-compliant periods employed by 'obj' from the given 'periods', 477 using the indicated 'tzid' to convert dates to datetimes. 478 """ 479 480 start, start_attr = obj.get_datetime_item("DTSTART") 481 if obj.has_key("DTEND"): 482 end, end_attr = obj.get_datetime_item("DTEND") 483 elif obj.has_key("DURATION"): 484 duration = obj.get_duration("DURATION") 485 end = start + duration 486 else: 487 end, end_attr = start, start_attr 488 489 tzid = get_tzid(start_attr, end_attr) or tzid 490 491 l = [] 492 493 for p in periods: 494 start, end = get_freebusy_period(p.start, p.end, tzid) 495 start, end = [to_timezone(x, "UTC") for x in start, end] 496 497 # Create a new period for free/busy purposes with the converted 498 # datetime information. 499 500 l.append( 501 FreeBusyPeriod( 502 format_datetime(start), format_datetime(end), 503 *p.as_tuple()[2:] 504 )) 505 506 return l 507 508 # vim: tabstop=4 expandtab shiftwidth=4