paul@33 | 1 | #!/usr/bin/env python |
paul@33 | 2 | |
paul@33 | 3 | """ |
paul@33 | 4 | Recurrence rule calculation. |
paul@33 | 5 | |
paul@33 | 6 | Copyright (C) 2014 Paul Boddie <paul@boddie.org.uk> |
paul@33 | 7 | |
paul@33 | 8 | This program is free software; you can redistribute it and/or modify it under |
paul@33 | 9 | the terms of the GNU General Public License as published by the Free Software |
paul@33 | 10 | Foundation; either version 3 of the License, or (at your option) any later |
paul@33 | 11 | version. |
paul@33 | 12 | |
paul@33 | 13 | This program is distributed in the hope that it will be useful, but WITHOUT |
paul@33 | 14 | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS |
paul@33 | 15 | FOR A PARTICULAR PURPOSE. See the GNU General Public License for more |
paul@33 | 16 | details. |
paul@33 | 17 | |
paul@33 | 18 | You should have received a copy of the GNU General Public License along with |
paul@33 | 19 | this program. If not, see <http://www.gnu.org/licenses/>. |
paul@33 | 20 | |
paul@33 | 21 | ---- |
paul@33 | 22 | |
paul@33 | 23 | References: |
paul@33 | 24 | |
paul@33 | 25 | RFC 5545: Internet Calendaring and Scheduling Core Object Specification |
paul@33 | 26 | (iCalendar) |
paul@33 | 27 | http://tools.ietf.org/html/rfc5545 |
paul@33 | 28 | |
paul@33 | 29 | ---- |
paul@33 | 30 | |
paul@33 | 31 | FREQ defines the selection resolution. |
paul@33 | 32 | DTSTART defines the start of the selection. |
paul@33 | 33 | INTERVAL defines the step of the selection. |
paul@33 | 34 | COUNT defines a number of instances; UNTIL defines a limit to the selection. |
paul@33 | 35 | |
paul@33 | 36 | BY... qualifiers select instances within each outer selection instance according |
paul@33 | 37 | to the recurrence of instances of the next highest resolution. For example, |
paul@33 | 38 | BYDAY selects days in weeks. Thus, if no explicit week recurrence is indicated, |
paul@33 | 39 | all weeks are selected within the selection of the next highest explicitly |
paul@33 | 40 | specified resolution, whether this is months or years. |
paul@33 | 41 | |
paul@33 | 42 | BYSETPOS in conjunction with BY... qualifiers permit the selection of specific |
paul@33 | 43 | instances. |
paul@33 | 44 | |
paul@33 | 45 | Within the FREQ resolution, BY... qualifiers refine selected instances. |
paul@33 | 46 | |
paul@33 | 47 | Outside the FREQ resolution, BY... qualifiers select instances at the resolution |
paul@33 | 48 | concerned. |
paul@33 | 49 | |
paul@33 | 50 | Thus, FREQ and BY... qualifiers need to be ordered in terms of increasing |
paul@33 | 51 | resolution (or decreasing scope). |
paul@33 | 52 | """ |
paul@33 | 53 | |
paul@34 | 54 | from calendar import monthrange |
paul@33 | 55 | from datetime import date, datetime, timedelta |
paul@33 | 56 | import operator |
paul@33 | 57 | |
paul@33 | 58 | # Frequency levels, specified by FREQ in iCalendar. |
paul@33 | 59 | |
paul@33 | 60 | freq_levels = ( |
paul@42 | 61 | "YEARLY", |
paul@42 | 62 | "MONTHLY", |
paul@42 | 63 | "WEEKLY", |
paul@44 | 64 | None, |
paul@44 | 65 | None, |
paul@33 | 66 | "DAILY", |
paul@42 | 67 | "HOURLY", |
paul@42 | 68 | "MINUTELY", |
paul@42 | 69 | "SECONDLY" |
paul@33 | 70 | ) |
paul@33 | 71 | |
paul@33 | 72 | # Enumeration levels, employed by BY... qualifiers. |
paul@33 | 73 | |
paul@33 | 74 | enum_levels = ( |
paul@42 | 75 | None, |
paul@44 | 76 | "BYMONTH", |
paul@44 | 77 | "BYWEEKNO", |
paul@44 | 78 | "BYYEARDAY", |
paul@44 | 79 | "BYMONTHDAY", |
paul@44 | 80 | "BYDAY", |
paul@44 | 81 | "BYHOUR", |
paul@44 | 82 | "BYMINUTE", |
paul@44 | 83 | "BYSECOND" |
paul@33 | 84 | ) |
paul@33 | 85 | |
paul@33 | 86 | # Map from levels to lengths of datetime tuples. |
paul@33 | 87 | |
paul@44 | 88 | lengths = [1, 2, 3, 3, 3, 3, 4, 5, 6] |
paul@33 | 89 | positions = [l-1 for l in lengths] |
paul@33 | 90 | |
paul@33 | 91 | # Map from qualifiers to interval units. Here, weeks are defined as 7 days. |
paul@33 | 92 | |
paul@33 | 93 | units = {"WEEKLY" : 7} |
paul@33 | 94 | |
paul@33 | 95 | # Make dictionaries mapping qualifiers to levels. |
paul@33 | 96 | |
paul@44 | 97 | freq = dict([(level, i) for (i, level) in enumerate(freq_levels) if level]) |
paul@44 | 98 | enum = dict([(level, i) for (i, level) in enumerate(enum_levels) if level]) |
paul@33 | 99 | |
paul@33 | 100 | # Functions for structuring the recurrences. |
paul@33 | 101 | |
paul@33 | 102 | def get_next(it): |
paul@33 | 103 | try: |
paul@33 | 104 | return it.next() |
paul@33 | 105 | except StopIteration: |
paul@33 | 106 | return None |
paul@33 | 107 | |
paul@33 | 108 | def order_qualifiers(qualifiers): |
paul@33 | 109 | |
paul@33 | 110 | "Return the 'qualifiers' in order of increasing resolution." |
paul@33 | 111 | |
paul@33 | 112 | l = [] |
paul@33 | 113 | |
paul@33 | 114 | for qualifier, args in qualifiers: |
paul@33 | 115 | if enum.has_key(qualifier): |
paul@33 | 116 | level = enum[qualifier] |
paul@35 | 117 | if special_enum_levels.has_key(qualifier): |
paul@33 | 118 | args["interval"] = 1 |
paul@35 | 119 | selector = special_enum_levels[qualifier] |
paul@33 | 120 | else: |
paul@33 | 121 | selector = Enum |
paul@33 | 122 | else: |
paul@33 | 123 | level = freq[qualifier] |
paul@33 | 124 | selector = Pattern |
paul@33 | 125 | |
paul@42 | 126 | l.append(selector(level, args, qualifier)) |
paul@33 | 127 | |
paul@42 | 128 | l.sort(key=lambda x: x.level) |
paul@33 | 129 | return l |
paul@33 | 130 | |
paul@33 | 131 | def get_datetime_structure(datetime): |
paul@33 | 132 | |
paul@33 | 133 | "Return the structure of 'datetime' for recurrence production." |
paul@33 | 134 | |
paul@33 | 135 | l = [] |
paul@42 | 136 | offset = 0 |
paul@42 | 137 | for level, value in enumerate(datetime): |
paul@42 | 138 | if level == 2: |
paul@44 | 139 | offset = 3 |
paul@42 | 140 | l.append(Enum(level + offset, {"values" : [value]}, "DT")) |
paul@33 | 141 | return l |
paul@33 | 142 | |
paul@33 | 143 | def combine_datetime_with_qualifiers(datetime, qualifiers): |
paul@33 | 144 | |
paul@33 | 145 | """ |
paul@33 | 146 | Combine 'datetime' with 'qualifiers' to produce a structure for recurrence |
paul@33 | 147 | production. |
paul@33 | 148 | """ |
paul@33 | 149 | |
paul@33 | 150 | iter_dt = iter(get_datetime_structure(datetime)) |
paul@33 | 151 | iter_q = iter(order_qualifiers(qualifiers)) |
paul@33 | 152 | |
paul@33 | 153 | l = [] |
paul@33 | 154 | |
paul@33 | 155 | from_dt = get_next(iter_dt) |
paul@33 | 156 | from_q = get_next(iter_q) |
paul@33 | 157 | |
paul@33 | 158 | have_q = False |
paul@33 | 159 | context = [] |
paul@39 | 160 | context.append(from_dt.args["values"][0]) |
paul@33 | 161 | |
paul@33 | 162 | # Consume from both lists, merging entries. |
paul@33 | 163 | |
paul@33 | 164 | while from_dt and from_q: |
paul@42 | 165 | _level = from_dt.level |
paul@42 | 166 | level = from_q.level |
paul@33 | 167 | |
paul@33 | 168 | # Datetime value at wider resolution. |
paul@33 | 169 | |
paul@42 | 170 | if _level < level: |
paul@39 | 171 | from_dt = get_next(iter_dt) |
paul@38 | 172 | context.append(from_dt.args["values"][0]) |
paul@33 | 173 | |
paul@33 | 174 | # Qualifier at wider or same resolution as datetime value. |
paul@33 | 175 | |
paul@33 | 176 | else: |
paul@33 | 177 | if not have_q: |
paul@42 | 178 | if isinstance(from_q, Enum) and level > 0: |
paul@42 | 179 | repeat = Pattern(level - 1, {"interval" : 1}, "REPEAT") |
paul@38 | 180 | repeat.context = tuple(context) |
paul@33 | 181 | l.append(repeat) |
paul@33 | 182 | have_q = True |
paul@33 | 183 | |
paul@43 | 184 | from_q.context = tuple(context) |
paul@43 | 185 | l.append(from_q) |
paul@43 | 186 | from_q = get_next(iter_q) |
paul@33 | 187 | |
paul@43 | 188 | if _level == level: |
paul@33 | 189 | from_dt = get_next(iter_dt) |
paul@39 | 190 | context.append(from_dt.args["values"][0]) |
paul@33 | 191 | |
paul@33 | 192 | # Complete the list. |
paul@33 | 193 | |
paul@33 | 194 | while from_dt: |
paul@33 | 195 | l.append(from_dt) |
paul@33 | 196 | from_dt = get_next(iter_dt) |
paul@33 | 197 | |
paul@33 | 198 | while from_q: |
paul@33 | 199 | if not have_q: |
paul@42 | 200 | if isinstance(from_q, Enum) and level > 0: |
paul@42 | 201 | repeat = Pattern(level - 1, {"interval" : 1}, "REPEAT") |
paul@38 | 202 | repeat.context = tuple(context) |
paul@33 | 203 | l.append(repeat) |
paul@33 | 204 | have_q = True |
paul@43 | 205 | |
paul@43 | 206 | from_q.context = tuple(context) |
paul@33 | 207 | l.append(from_q) |
paul@33 | 208 | from_q = get_next(iter_q) |
paul@33 | 209 | |
paul@33 | 210 | return l |
paul@33 | 211 | |
paul@33 | 212 | # Datetime arithmetic. |
paul@33 | 213 | |
paul@33 | 214 | def combine(t1, t2): |
paul@33 | 215 | return tuple(map(lambda x, y: x or y, t1, t2)) |
paul@33 | 216 | |
paul@33 | 217 | def scale(interval, pos): |
paul@33 | 218 | return (0,) * pos + (interval,) |
paul@33 | 219 | |
paul@33 | 220 | def get_seconds(t): |
paul@33 | 221 | |
paul@33 | 222 | "Convert the sub-day part of 't' into seconds." |
paul@33 | 223 | |
paul@33 | 224 | t = t + (0,) * (6 - len(t)) |
paul@33 | 225 | return (t[3] * 60 + t[4]) * 60 + t[5] |
paul@33 | 226 | |
paul@33 | 227 | def update(t, step): |
paul@33 | 228 | |
paul@33 | 229 | "Update 't' by 'step' at the resolution of 'step'." |
paul@33 | 230 | |
paul@33 | 231 | i = len(step) |
paul@33 | 232 | |
paul@33 | 233 | # Years only. |
paul@33 | 234 | |
paul@33 | 235 | if i == 1: |
paul@33 | 236 | return (t[0] + step[0],) + tuple(t[1:]) |
paul@33 | 237 | |
paul@33 | 238 | # Years and months. |
paul@33 | 239 | |
paul@33 | 240 | elif i == 2: |
paul@33 | 241 | month = t[1] + step[1] |
paul@33 | 242 | return (t[0] + step[0] + (month - 1) / 12, (month - 1) % 12 + 1) + tuple(t[2:]) |
paul@33 | 243 | |
paul@33 | 244 | # Dates and datetimes. |
paul@33 | 245 | |
paul@33 | 246 | else: |
paul@33 | 247 | updated_for_months = update(t, step[:2]) |
paul@33 | 248 | |
paul@33 | 249 | # Dates only. |
paul@33 | 250 | |
paul@33 | 251 | if i == 3: |
paul@33 | 252 | d = datetime(*updated_for_months) |
paul@33 | 253 | s = timedelta(step[2]) |
paul@33 | 254 | |
paul@33 | 255 | # Datetimes. |
paul@33 | 256 | |
paul@33 | 257 | else: |
paul@33 | 258 | d = datetime(*updated_for_months) |
paul@33 | 259 | s = timedelta(step[2], get_seconds(step)) |
paul@33 | 260 | |
paul@39 | 261 | return to_tuple(d + s, len(t)) |
paul@39 | 262 | |
paul@39 | 263 | def to_tuple(d, n): |
paul@39 | 264 | return d.timetuple()[:n] |
paul@39 | 265 | |
paul@39 | 266 | def get_first_day(first_day, weekday): |
paul@39 | 267 | first_day = date(*first_day) |
paul@39 | 268 | first_weekday = first_day.isoweekday() |
paul@39 | 269 | if first_weekday > weekday: |
paul@39 | 270 | return first_day + timedelta(7 - first_weekday + weekday) |
paul@39 | 271 | else: |
paul@39 | 272 | return first_day + timedelta(weekday - first_weekday) |
paul@39 | 273 | |
paul@39 | 274 | def get_last_day(last_day, weekday): |
paul@39 | 275 | last_day = date(*last_day) |
paul@39 | 276 | last_weekday = last_day.isoweekday() |
paul@39 | 277 | if last_weekday < weekday: |
paul@39 | 278 | return last_day - timedelta(last_weekday + 7 - weekday) |
paul@39 | 279 | else: |
paul@39 | 280 | return last_day - timedelta(last_weekday - weekday) |
paul@33 | 281 | |
paul@33 | 282 | # Classes for producing instances from recurrence structures. |
paul@33 | 283 | |
paul@33 | 284 | class Selector: |
paul@42 | 285 | def __init__(self, level, args, qualifier, selecting=None): |
paul@42 | 286 | self.level = level |
paul@42 | 287 | self.pos = positions[level] |
paul@33 | 288 | self.args = args |
paul@33 | 289 | self.qualifier = qualifier |
paul@33 | 290 | self.context = () |
paul@33 | 291 | self.selecting = selecting |
paul@33 | 292 | |
paul@33 | 293 | def __repr__(self): |
paul@42 | 294 | return "%s(%r, %r, %r, %r)" % (self.__class__.__name__, self.level, self.args, self.qualifier, self.context) |
paul@33 | 295 | |
paul@35 | 296 | def materialise(self, start, end, count=None): |
paul@33 | 297 | counter = count and [0, count] |
paul@39 | 298 | results = self.materialise_items(self.context, start, end, counter) |
paul@39 | 299 | results.sort() |
paul@41 | 300 | return results[:count] |
paul@33 | 301 | |
paul@35 | 302 | def materialise_item(self, current, last, next, counter): |
paul@34 | 303 | if counter is None or counter[0] < counter[1]: |
paul@34 | 304 | if self.selecting: |
paul@35 | 305 | return self.selecting.materialise_items(current, last, next, counter) |
paul@35 | 306 | elif last <= current: |
paul@34 | 307 | if counter is not None: |
paul@34 | 308 | counter[0] += 1 |
paul@34 | 309 | return [current] |
paul@35 | 310 | return [] |
paul@33 | 311 | |
paul@33 | 312 | class Pattern(Selector): |
paul@35 | 313 | def materialise_items(self, context, start, end, counter): |
paul@38 | 314 | first = scale(self.context[self.pos], self.pos) |
paul@34 | 315 | |
paul@34 | 316 | # Define the step between items. |
paul@34 | 317 | |
paul@33 | 318 | interval = self.args.get("interval", 1) * units.get(self.qualifier, 1) |
paul@33 | 319 | step = scale(interval, self.pos) |
paul@34 | 320 | |
paul@34 | 321 | # Define the scale of a single item. |
paul@34 | 322 | |
paul@33 | 323 | unit_interval = units.get(self.qualifier, 1) |
paul@33 | 324 | unit_step = scale(unit_interval, self.pos) |
paul@34 | 325 | |
paul@34 | 326 | current = combine(context, first) |
paul@33 | 327 | results = [] |
paul@34 | 328 | |
paul@33 | 329 | while current < end and (counter is None or counter[0] < counter[1]): |
paul@33 | 330 | next = update(current, step) |
paul@33 | 331 | current_end = update(current, unit_step) |
paul@35 | 332 | results += self.materialise_item(current, max(current, start), min(current_end, end), counter) |
paul@33 | 333 | current = next |
paul@34 | 334 | |
paul@33 | 335 | return results |
paul@33 | 336 | |
paul@35 | 337 | class WeekDayFilter(Selector): |
paul@35 | 338 | def materialise_items(self, context, start, end, counter): |
paul@39 | 339 | step = scale(1, 2) |
paul@33 | 340 | results = [] |
paul@34 | 341 | |
paul@39 | 342 | # Get weekdays in the year. |
paul@39 | 343 | |
paul@39 | 344 | if len(context) == 1: |
paul@39 | 345 | first_day = (context[0], 1, 1) |
paul@39 | 346 | last_day = (context[0], 12, 31) |
paul@39 | 347 | |
paul@39 | 348 | # Get weekdays in the month. |
paul@39 | 349 | |
paul@39 | 350 | elif len(context) == 2: |
paul@39 | 351 | first_day = (context[0], context[1], 1) |
paul@39 | 352 | last_day = update((context[0], context[1], 1), (0, 1, 0)) |
paul@39 | 353 | last_day = update(last_day, (0, 0, -1)) |
paul@39 | 354 | |
paul@39 | 355 | # Get weekdays in the week. |
paul@39 | 356 | |
paul@39 | 357 | else: |
paul@39 | 358 | current = context |
paul@39 | 359 | values = [value for (value, index) in self.args["values"]] |
paul@39 | 360 | |
paul@39 | 361 | while current < end and (counter is None or counter[0] < counter[1]): |
paul@39 | 362 | next = update(current, step) |
paul@39 | 363 | if date(*current).isoweekday() in values: |
paul@39 | 364 | results += self.materialise_item(current, max(current, start), min(next, end), counter) |
paul@39 | 365 | current = next |
paul@39 | 366 | return results |
paul@39 | 367 | |
paul@39 | 368 | # Find each of the given days. |
paul@39 | 369 | |
paul@39 | 370 | for value, index in self.args["values"]: |
paul@39 | 371 | if index is not None: |
paul@39 | 372 | offset = timedelta(7 * (abs(index) - 1)) |
paul@39 | 373 | |
paul@39 | 374 | if index < 0: |
paul@39 | 375 | current = to_tuple(get_last_day(last_day, value) - offset, 3) |
paul@39 | 376 | else: |
paul@39 | 377 | current = to_tuple(get_first_day(first_day, value) + offset, 3) |
paul@39 | 378 | |
paul@41 | 379 | if current < end: |
paul@39 | 380 | next = update(current, step) |
paul@39 | 381 | results += self.materialise_item(current, max(current, start), min(next, end), counter) |
paul@39 | 382 | |
paul@39 | 383 | else: |
paul@39 | 384 | if index < 0: |
paul@39 | 385 | current = to_tuple(get_last_day(last_day, value), 3) |
paul@39 | 386 | direction = operator.sub |
paul@39 | 387 | else: |
paul@39 | 388 | current = to_tuple(get_first_day(first_day, value), 3) |
paul@39 | 389 | direction = operator.add |
paul@39 | 390 | |
paul@39 | 391 | while first_day <= current <= last_day: |
paul@41 | 392 | if current < end: |
paul@39 | 393 | next = update(current, step) |
paul@39 | 394 | results += self.materialise_item(current, max(current, start), min(next, end), counter) |
paul@39 | 395 | current = to_tuple(direction(date(*current), timedelta(7)), 3) |
paul@34 | 396 | |
paul@33 | 397 | return results |
paul@33 | 398 | |
paul@33 | 399 | class Enum(Selector): |
paul@35 | 400 | def materialise_items(self, context, start, end, counter): |
paul@33 | 401 | step = scale(1, self.pos) |
paul@33 | 402 | results = [] |
paul@33 | 403 | for value in self.args["values"]: |
paul@33 | 404 | current = combine(context, scale(value, self.pos)) |
paul@41 | 405 | if current < end: |
paul@33 | 406 | next = update(current, step) |
paul@35 | 407 | results += self.materialise_item(current, max(current, start), min(next, end), counter) |
paul@35 | 408 | return results |
paul@35 | 409 | |
paul@35 | 410 | class MonthDayFilter(Enum): |
paul@35 | 411 | def materialise_items(self, context, start, end, counter): |
paul@35 | 412 | last_day = monthrange(context[0], context[1])[1] |
paul@35 | 413 | step = scale(1, self.pos) |
paul@35 | 414 | results = [] |
paul@35 | 415 | for value in self.args["values"]: |
paul@35 | 416 | if value < 0: |
paul@35 | 417 | value = last_day + 1 + value |
paul@35 | 418 | current = combine(context, scale(value, self.pos)) |
paul@41 | 419 | if current < end: |
paul@35 | 420 | next = update(current, step) |
paul@35 | 421 | results += self.materialise_item(current, max(current, start), min(next, end), counter) |
paul@33 | 422 | return results |
paul@33 | 423 | |
paul@37 | 424 | class YearDayFilter(Enum): |
paul@37 | 425 | def materialise_items(self, context, start, end, counter): |
paul@37 | 426 | first_day = date(context[0], 1, 1) |
paul@37 | 427 | next_first_day = date(context[0] + 1, 1, 1) |
paul@37 | 428 | year_length = (next_first_day - first_day).days |
paul@37 | 429 | step = scale(1, self.pos) |
paul@37 | 430 | results = [] |
paul@37 | 431 | for value in self.args["values"]: |
paul@37 | 432 | if value < 0: |
paul@37 | 433 | value = year_length + 1 + value |
paul@39 | 434 | current = to_tuple(first_day + timedelta(value - 1), 3) |
paul@41 | 435 | if current < end: |
paul@37 | 436 | next = update(current, step) |
paul@37 | 437 | results += self.materialise_item(current, max(current, start), min(next, end), counter) |
paul@37 | 438 | return results |
paul@37 | 439 | |
paul@33 | 440 | def process(selectors): |
paul@33 | 441 | current = selectors[0] |
paul@33 | 442 | for selector in selectors[1:]: |
paul@33 | 443 | current.selecting = selector |
paul@33 | 444 | current = selector |
paul@33 | 445 | return selectors[0] |
paul@33 | 446 | |
paul@35 | 447 | special_enum_levels = { |
paul@35 | 448 | "BYDAY" : WeekDayFilter, |
paul@35 | 449 | "BYMONTHDAY" : MonthDayFilter, |
paul@37 | 450 | "BYYEARDAY" : YearDayFilter, |
paul@35 | 451 | } |
paul@35 | 452 | |
paul@33 | 453 | # vim: tabstop=4 expandtab shiftwidth=4 |