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@33 | 64 | "DAILY", |
paul@42 | 65 | "HOURLY", |
paul@42 | 66 | "MINUTELY", |
paul@42 | 67 | "SECONDLY" |
paul@33 | 68 | ) |
paul@33 | 69 | |
paul@33 | 70 | # Enumeration levels, employed by BY... qualifiers. |
paul@33 | 71 | |
paul@33 | 72 | enum_levels = ( |
paul@42 | 73 | None, |
paul@42 | 74 | ("BYMONTH",), |
paul@42 | 75 | ("BYWEEKNO",), |
paul@42 | 76 | ("BYDAY", "BYMONTHDAY", "BYYEARDAY"), |
paul@33 | 77 | ("BYHOUR",), |
paul@42 | 78 | ("BYMINUTE",), |
paul@42 | 79 | ("BYSECOND",) |
paul@33 | 80 | ) |
paul@33 | 81 | |
paul@33 | 82 | # Map from levels to lengths of datetime tuples. |
paul@33 | 83 | |
paul@42 | 84 | lengths = [1, 2, 3, 3, 4, 5, 6] |
paul@33 | 85 | positions = [l-1 for l in lengths] |
paul@33 | 86 | |
paul@33 | 87 | # Map from qualifiers to interval units. Here, weeks are defined as 7 days. |
paul@33 | 88 | |
paul@33 | 89 | units = {"WEEKLY" : 7} |
paul@33 | 90 | |
paul@33 | 91 | # Make dictionaries mapping qualifiers to levels. |
paul@33 | 92 | |
paul@33 | 93 | freq = dict([(level, i) for (i, level) in enumerate(freq_levels)]) |
paul@42 | 94 | enum = dict([(level, i) for (i, levels) in enumerate(enum_levels) if levels for level in levels]) |
paul@33 | 95 | |
paul@33 | 96 | # Functions for structuring the recurrences. |
paul@33 | 97 | |
paul@33 | 98 | def get_next(it): |
paul@33 | 99 | try: |
paul@33 | 100 | return it.next() |
paul@33 | 101 | except StopIteration: |
paul@33 | 102 | return None |
paul@33 | 103 | |
paul@33 | 104 | def order_qualifiers(qualifiers): |
paul@33 | 105 | |
paul@33 | 106 | "Return the 'qualifiers' in order of increasing resolution." |
paul@33 | 107 | |
paul@33 | 108 | l = [] |
paul@33 | 109 | |
paul@33 | 110 | for qualifier, args in qualifiers: |
paul@33 | 111 | if enum.has_key(qualifier): |
paul@33 | 112 | level = enum[qualifier] |
paul@35 | 113 | if special_enum_levels.has_key(qualifier): |
paul@33 | 114 | args["interval"] = 1 |
paul@35 | 115 | selector = special_enum_levels[qualifier] |
paul@33 | 116 | else: |
paul@33 | 117 | selector = Enum |
paul@33 | 118 | else: |
paul@33 | 119 | level = freq[qualifier] |
paul@33 | 120 | selector = Pattern |
paul@33 | 121 | |
paul@42 | 122 | l.append(selector(level, args, qualifier)) |
paul@33 | 123 | |
paul@42 | 124 | l.sort(key=lambda x: x.level) |
paul@33 | 125 | return l |
paul@33 | 126 | |
paul@33 | 127 | def get_datetime_structure(datetime): |
paul@33 | 128 | |
paul@33 | 129 | "Return the structure of 'datetime' for recurrence production." |
paul@33 | 130 | |
paul@33 | 131 | l = [] |
paul@42 | 132 | offset = 0 |
paul@42 | 133 | for level, value in enumerate(datetime): |
paul@42 | 134 | if level == 2: |
paul@42 | 135 | offset = 1 |
paul@42 | 136 | l.append(Enum(level + offset, {"values" : [value]}, "DT")) |
paul@33 | 137 | return l |
paul@33 | 138 | |
paul@33 | 139 | def combine_datetime_with_qualifiers(datetime, qualifiers): |
paul@33 | 140 | |
paul@33 | 141 | """ |
paul@33 | 142 | Combine 'datetime' with 'qualifiers' to produce a structure for recurrence |
paul@33 | 143 | production. |
paul@33 | 144 | """ |
paul@33 | 145 | |
paul@33 | 146 | iter_dt = iter(get_datetime_structure(datetime)) |
paul@33 | 147 | iter_q = iter(order_qualifiers(qualifiers)) |
paul@33 | 148 | |
paul@33 | 149 | l = [] |
paul@33 | 150 | |
paul@33 | 151 | from_dt = get_next(iter_dt) |
paul@33 | 152 | from_q = get_next(iter_q) |
paul@33 | 153 | |
paul@33 | 154 | have_q = False |
paul@33 | 155 | context = [] |
paul@39 | 156 | context.append(from_dt.args["values"][0]) |
paul@33 | 157 | |
paul@33 | 158 | # Consume from both lists, merging entries. |
paul@33 | 159 | |
paul@33 | 160 | while from_dt and from_q: |
paul@42 | 161 | _level = from_dt.level |
paul@42 | 162 | level = from_q.level |
paul@33 | 163 | |
paul@33 | 164 | # Datetime value at wider resolution. |
paul@33 | 165 | |
paul@42 | 166 | if _level < level: |
paul@39 | 167 | from_dt = get_next(iter_dt) |
paul@38 | 168 | context.append(from_dt.args["values"][0]) |
paul@33 | 169 | |
paul@33 | 170 | # Qualifier at wider or same resolution as datetime value. |
paul@33 | 171 | |
paul@33 | 172 | else: |
paul@33 | 173 | if not have_q: |
paul@42 | 174 | if isinstance(from_q, Enum) and level > 0: |
paul@42 | 175 | repeat = Pattern(level - 1, {"interval" : 1}, "REPEAT") |
paul@38 | 176 | repeat.context = tuple(context) |
paul@33 | 177 | l.append(repeat) |
paul@33 | 178 | else: |
paul@33 | 179 | from_q.context = tuple(context) |
paul@33 | 180 | have_q = True |
paul@33 | 181 | |
paul@33 | 182 | # Either introduce the qualifier first. |
paul@33 | 183 | |
paul@42 | 184 | if _level > level: |
paul@33 | 185 | l.append(from_q) |
paul@33 | 186 | |
paul@33 | 187 | # Or combine the qualifier and value details. |
paul@33 | 188 | |
paul@33 | 189 | else: |
paul@38 | 190 | l.append(combine_context_with_qualifier(context, from_q)) |
paul@33 | 191 | from_dt = get_next(iter_dt) |
paul@39 | 192 | context.append(from_dt.args["values"][0]) |
paul@33 | 193 | |
paul@33 | 194 | from_q = get_next(iter_q) |
paul@33 | 195 | |
paul@33 | 196 | # Complete the list. |
paul@33 | 197 | |
paul@33 | 198 | while from_dt: |
paul@33 | 199 | l.append(from_dt) |
paul@33 | 200 | from_dt = get_next(iter_dt) |
paul@33 | 201 | |
paul@33 | 202 | while from_q: |
paul@33 | 203 | if not have_q: |
paul@42 | 204 | if isinstance(from_q, Enum) and level > 0: |
paul@42 | 205 | repeat = Pattern(level - 1, {"interval" : 1}, "REPEAT") |
paul@38 | 206 | repeat.context = tuple(context) |
paul@33 | 207 | l.append(repeat) |
paul@33 | 208 | else: |
paul@33 | 209 | from_q.context = tuple(context) |
paul@33 | 210 | have_q = True |
paul@33 | 211 | l.append(from_q) |
paul@33 | 212 | from_q = get_next(iter_q) |
paul@33 | 213 | |
paul@33 | 214 | return l |
paul@33 | 215 | |
paul@38 | 216 | def combine_context_with_qualifier(context, from_q): |
paul@33 | 217 | |
paul@33 | 218 | """ |
paul@38 | 219 | Combine 'context' information (a datetime) and 'from_q' (a qualifier), |
paul@38 | 220 | imposing the datetime value information on any qualifiers. |
paul@33 | 221 | """ |
paul@33 | 222 | |
paul@39 | 223 | from_q.context = tuple(context) |
paul@33 | 224 | return from_q |
paul@33 | 225 | |
paul@33 | 226 | # Datetime arithmetic. |
paul@33 | 227 | |
paul@33 | 228 | def combine(t1, t2): |
paul@33 | 229 | return tuple(map(lambda x, y: x or y, t1, t2)) |
paul@33 | 230 | |
paul@33 | 231 | def scale(interval, pos): |
paul@33 | 232 | return (0,) * pos + (interval,) |
paul@33 | 233 | |
paul@33 | 234 | def get_seconds(t): |
paul@33 | 235 | |
paul@33 | 236 | "Convert the sub-day part of 't' into seconds." |
paul@33 | 237 | |
paul@33 | 238 | t = t + (0,) * (6 - len(t)) |
paul@33 | 239 | return (t[3] * 60 + t[4]) * 60 + t[5] |
paul@33 | 240 | |
paul@33 | 241 | def update(t, step): |
paul@33 | 242 | |
paul@33 | 243 | "Update 't' by 'step' at the resolution of 'step'." |
paul@33 | 244 | |
paul@33 | 245 | i = len(step) |
paul@33 | 246 | |
paul@33 | 247 | # Years only. |
paul@33 | 248 | |
paul@33 | 249 | if i == 1: |
paul@33 | 250 | return (t[0] + step[0],) + tuple(t[1:]) |
paul@33 | 251 | |
paul@33 | 252 | # Years and months. |
paul@33 | 253 | |
paul@33 | 254 | elif i == 2: |
paul@33 | 255 | month = t[1] + step[1] |
paul@33 | 256 | return (t[0] + step[0] + (month - 1) / 12, (month - 1) % 12 + 1) + tuple(t[2:]) |
paul@33 | 257 | |
paul@33 | 258 | # Dates and datetimes. |
paul@33 | 259 | |
paul@33 | 260 | else: |
paul@33 | 261 | updated_for_months = update(t, step[:2]) |
paul@33 | 262 | |
paul@33 | 263 | # Dates only. |
paul@33 | 264 | |
paul@33 | 265 | if i == 3: |
paul@33 | 266 | d = datetime(*updated_for_months) |
paul@33 | 267 | s = timedelta(step[2]) |
paul@33 | 268 | |
paul@33 | 269 | # Datetimes. |
paul@33 | 270 | |
paul@33 | 271 | else: |
paul@33 | 272 | d = datetime(*updated_for_months) |
paul@33 | 273 | s = timedelta(step[2], get_seconds(step)) |
paul@33 | 274 | |
paul@39 | 275 | return to_tuple(d + s, len(t)) |
paul@39 | 276 | |
paul@39 | 277 | def to_tuple(d, n): |
paul@39 | 278 | return d.timetuple()[:n] |
paul@39 | 279 | |
paul@39 | 280 | def get_first_day(first_day, weekday): |
paul@39 | 281 | first_day = date(*first_day) |
paul@39 | 282 | first_weekday = first_day.isoweekday() |
paul@39 | 283 | if first_weekday > weekday: |
paul@39 | 284 | return first_day + timedelta(7 - first_weekday + weekday) |
paul@39 | 285 | else: |
paul@39 | 286 | return first_day + timedelta(weekday - first_weekday) |
paul@39 | 287 | |
paul@39 | 288 | def get_last_day(last_day, weekday): |
paul@39 | 289 | last_day = date(*last_day) |
paul@39 | 290 | last_weekday = last_day.isoweekday() |
paul@39 | 291 | if last_weekday < weekday: |
paul@39 | 292 | return last_day - timedelta(last_weekday + 7 - weekday) |
paul@39 | 293 | else: |
paul@39 | 294 | return last_day - timedelta(last_weekday - weekday) |
paul@33 | 295 | |
paul@33 | 296 | # Classes for producing instances from recurrence structures. |
paul@33 | 297 | |
paul@33 | 298 | class Selector: |
paul@42 | 299 | def __init__(self, level, args, qualifier, selecting=None): |
paul@42 | 300 | self.level = level |
paul@42 | 301 | self.pos = positions[level] |
paul@33 | 302 | self.args = args |
paul@33 | 303 | self.qualifier = qualifier |
paul@33 | 304 | self.context = () |
paul@33 | 305 | self.selecting = selecting |
paul@33 | 306 | |
paul@33 | 307 | def __repr__(self): |
paul@42 | 308 | return "%s(%r, %r, %r, %r)" % (self.__class__.__name__, self.level, self.args, self.qualifier, self.context) |
paul@33 | 309 | |
paul@35 | 310 | def materialise(self, start, end, count=None): |
paul@33 | 311 | counter = count and [0, count] |
paul@39 | 312 | results = self.materialise_items(self.context, start, end, counter) |
paul@39 | 313 | results.sort() |
paul@41 | 314 | return results[:count] |
paul@33 | 315 | |
paul@35 | 316 | def materialise_item(self, current, last, next, counter): |
paul@34 | 317 | if counter is None or counter[0] < counter[1]: |
paul@34 | 318 | if self.selecting: |
paul@35 | 319 | return self.selecting.materialise_items(current, last, next, counter) |
paul@35 | 320 | elif last <= current: |
paul@34 | 321 | if counter is not None: |
paul@34 | 322 | counter[0] += 1 |
paul@34 | 323 | return [current] |
paul@35 | 324 | return [] |
paul@33 | 325 | |
paul@33 | 326 | class Pattern(Selector): |
paul@35 | 327 | def materialise_items(self, context, start, end, counter): |
paul@38 | 328 | first = scale(self.context[self.pos], self.pos) |
paul@34 | 329 | |
paul@34 | 330 | # Define the step between items. |
paul@34 | 331 | |
paul@33 | 332 | interval = self.args.get("interval", 1) * units.get(self.qualifier, 1) |
paul@33 | 333 | step = scale(interval, self.pos) |
paul@34 | 334 | |
paul@34 | 335 | # Define the scale of a single item. |
paul@34 | 336 | |
paul@33 | 337 | unit_interval = units.get(self.qualifier, 1) |
paul@33 | 338 | unit_step = scale(unit_interval, self.pos) |
paul@34 | 339 | |
paul@34 | 340 | current = combine(context, first) |
paul@33 | 341 | results = [] |
paul@34 | 342 | |
paul@33 | 343 | while current < end and (counter is None or counter[0] < counter[1]): |
paul@33 | 344 | next = update(current, step) |
paul@33 | 345 | current_end = update(current, unit_step) |
paul@35 | 346 | results += self.materialise_item(current, max(current, start), min(current_end, end), counter) |
paul@33 | 347 | current = next |
paul@34 | 348 | |
paul@33 | 349 | return results |
paul@33 | 350 | |
paul@35 | 351 | class WeekDayFilter(Selector): |
paul@35 | 352 | def materialise_items(self, context, start, end, counter): |
paul@39 | 353 | step = scale(1, 2) |
paul@33 | 354 | results = [] |
paul@34 | 355 | |
paul@39 | 356 | # Get weekdays in the year. |
paul@39 | 357 | |
paul@39 | 358 | if len(context) == 1: |
paul@39 | 359 | first_day = (context[0], 1, 1) |
paul@39 | 360 | last_day = (context[0], 12, 31) |
paul@39 | 361 | |
paul@39 | 362 | # Get weekdays in the month. |
paul@39 | 363 | |
paul@39 | 364 | elif len(context) == 2: |
paul@39 | 365 | first_day = (context[0], context[1], 1) |
paul@39 | 366 | last_day = update((context[0], context[1], 1), (0, 1, 0)) |
paul@39 | 367 | last_day = update(last_day, (0, 0, -1)) |
paul@39 | 368 | |
paul@39 | 369 | # Get weekdays in the week. |
paul@39 | 370 | |
paul@39 | 371 | else: |
paul@39 | 372 | current = context |
paul@39 | 373 | values = [value for (value, index) in self.args["values"]] |
paul@39 | 374 | |
paul@39 | 375 | while current < end and (counter is None or counter[0] < counter[1]): |
paul@39 | 376 | next = update(current, step) |
paul@39 | 377 | if date(*current).isoweekday() in values: |
paul@39 | 378 | results += self.materialise_item(current, max(current, start), min(next, end), counter) |
paul@39 | 379 | current = next |
paul@39 | 380 | return results |
paul@39 | 381 | |
paul@39 | 382 | # Find each of the given days. |
paul@39 | 383 | |
paul@39 | 384 | for value, index in self.args["values"]: |
paul@39 | 385 | if index is not None: |
paul@39 | 386 | offset = timedelta(7 * (abs(index) - 1)) |
paul@39 | 387 | |
paul@39 | 388 | if index < 0: |
paul@39 | 389 | current = to_tuple(get_last_day(last_day, value) - offset, 3) |
paul@39 | 390 | else: |
paul@39 | 391 | current = to_tuple(get_first_day(first_day, value) + offset, 3) |
paul@39 | 392 | |
paul@41 | 393 | if current < end: |
paul@39 | 394 | next = update(current, step) |
paul@39 | 395 | results += self.materialise_item(current, max(current, start), min(next, end), counter) |
paul@39 | 396 | |
paul@39 | 397 | else: |
paul@39 | 398 | if index < 0: |
paul@39 | 399 | current = to_tuple(get_last_day(last_day, value), 3) |
paul@39 | 400 | direction = operator.sub |
paul@39 | 401 | else: |
paul@39 | 402 | current = to_tuple(get_first_day(first_day, value), 3) |
paul@39 | 403 | direction = operator.add |
paul@39 | 404 | |
paul@39 | 405 | while first_day <= current <= last_day: |
paul@41 | 406 | if current < end: |
paul@39 | 407 | next = update(current, step) |
paul@39 | 408 | results += self.materialise_item(current, max(current, start), min(next, end), counter) |
paul@39 | 409 | current = to_tuple(direction(date(*current), timedelta(7)), 3) |
paul@34 | 410 | |
paul@33 | 411 | return results |
paul@33 | 412 | |
paul@33 | 413 | class Enum(Selector): |
paul@35 | 414 | def materialise_items(self, context, start, end, counter): |
paul@33 | 415 | step = scale(1, self.pos) |
paul@33 | 416 | results = [] |
paul@33 | 417 | for value in self.args["values"]: |
paul@33 | 418 | current = combine(context, scale(value, self.pos)) |
paul@41 | 419 | if current < end: |
paul@33 | 420 | next = update(current, step) |
paul@35 | 421 | results += self.materialise_item(current, max(current, start), min(next, end), counter) |
paul@35 | 422 | return results |
paul@35 | 423 | |
paul@35 | 424 | class MonthDayFilter(Enum): |
paul@35 | 425 | def materialise_items(self, context, start, end, counter): |
paul@35 | 426 | last_day = monthrange(context[0], context[1])[1] |
paul@35 | 427 | step = scale(1, self.pos) |
paul@35 | 428 | results = [] |
paul@35 | 429 | for value in self.args["values"]: |
paul@35 | 430 | if value < 0: |
paul@35 | 431 | value = last_day + 1 + value |
paul@35 | 432 | current = combine(context, scale(value, self.pos)) |
paul@41 | 433 | if current < end: |
paul@35 | 434 | next = update(current, step) |
paul@35 | 435 | results += self.materialise_item(current, max(current, start), min(next, end), counter) |
paul@33 | 436 | return results |
paul@33 | 437 | |
paul@37 | 438 | class YearDayFilter(Enum): |
paul@37 | 439 | def materialise_items(self, context, start, end, counter): |
paul@37 | 440 | first_day = date(context[0], 1, 1) |
paul@37 | 441 | next_first_day = date(context[0] + 1, 1, 1) |
paul@37 | 442 | year_length = (next_first_day - first_day).days |
paul@37 | 443 | step = scale(1, self.pos) |
paul@37 | 444 | results = [] |
paul@37 | 445 | for value in self.args["values"]: |
paul@37 | 446 | if value < 0: |
paul@37 | 447 | value = year_length + 1 + value |
paul@39 | 448 | current = to_tuple(first_day + timedelta(value - 1), 3) |
paul@41 | 449 | if current < end: |
paul@37 | 450 | next = update(current, step) |
paul@37 | 451 | results += self.materialise_item(current, max(current, start), min(next, end), counter) |
paul@37 | 452 | return results |
paul@37 | 453 | |
paul@33 | 454 | def process(selectors): |
paul@33 | 455 | current = selectors[0] |
paul@33 | 456 | for selector in selectors[1:]: |
paul@33 | 457 | current.selecting = selector |
paul@33 | 458 | current = selector |
paul@33 | 459 | return selectors[0] |
paul@33 | 460 | |
paul@35 | 461 | special_enum_levels = { |
paul@35 | 462 | "BYDAY" : WeekDayFilter, |
paul@35 | 463 | "BYMONTHDAY" : MonthDayFilter, |
paul@37 | 464 | "BYYEARDAY" : YearDayFilter, |
paul@35 | 465 | } |
paul@35 | 466 | |
paul@33 | 467 | # vim: tabstop=4 expandtab shiftwidth=4 |