paul@33 | 1 | #!/usr/bin/env python |
paul@33 | 2 | |
paul@33 | 3 | """ |
paul@33 | 4 | Recurrence rule calculation. |
paul@33 | 5 | |
paul@1237 | 6 | Copyright (C) 2014, 2015, 2017 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@521 | 34 | COUNT defines a number of instances |
paul@521 | 35 | UNTIL defines a limit to the selection. |
paul@33 | 36 | |
paul@33 | 37 | BY... qualifiers select instances within each outer selection instance according |
paul@33 | 38 | to the recurrence of instances of the next highest resolution. For example, |
paul@33 | 39 | BYDAY selects days in weeks. Thus, if no explicit week recurrence is indicated, |
paul@33 | 40 | all weeks are selected within the selection of the next highest explicitly |
paul@33 | 41 | specified resolution, whether this is months or years. |
paul@33 | 42 | |
paul@33 | 43 | BYSETPOS in conjunction with BY... qualifiers permit the selection of specific |
paul@33 | 44 | instances. |
paul@33 | 45 | |
paul@33 | 46 | Within the FREQ resolution, BY... qualifiers refine selected instances. |
paul@33 | 47 | |
paul@33 | 48 | Outside the FREQ resolution, BY... qualifiers select instances at the resolution |
paul@33 | 49 | concerned. |
paul@33 | 50 | |
paul@33 | 51 | Thus, FREQ and BY... qualifiers need to be ordered in terms of increasing |
paul@33 | 52 | resolution (or decreasing scope). |
paul@33 | 53 | """ |
paul@33 | 54 | |
paul@34 | 55 | from calendar import monthrange |
paul@33 | 56 | from datetime import date, datetime, timedelta |
paul@33 | 57 | import operator |
paul@33 | 58 | |
paul@33 | 59 | # Frequency levels, specified by FREQ in iCalendar. |
paul@33 | 60 | |
paul@33 | 61 | freq_levels = ( |
paul@42 | 62 | "YEARLY", |
paul@42 | 63 | "MONTHLY", |
paul@42 | 64 | "WEEKLY", |
paul@44 | 65 | None, |
paul@44 | 66 | None, |
paul@33 | 67 | "DAILY", |
paul@42 | 68 | "HOURLY", |
paul@42 | 69 | "MINUTELY", |
paul@42 | 70 | "SECONDLY" |
paul@33 | 71 | ) |
paul@33 | 72 | |
paul@33 | 73 | # Enumeration levels, employed by BY... qualifiers. |
paul@33 | 74 | |
paul@33 | 75 | enum_levels = ( |
paul@42 | 76 | None, |
paul@44 | 77 | "BYMONTH", |
paul@44 | 78 | "BYWEEKNO", |
paul@44 | 79 | "BYYEARDAY", |
paul@44 | 80 | "BYMONTHDAY", |
paul@44 | 81 | "BYDAY", |
paul@44 | 82 | "BYHOUR", |
paul@44 | 83 | "BYMINUTE", |
paul@44 | 84 | "BYSECOND" |
paul@33 | 85 | ) |
paul@33 | 86 | |
paul@33 | 87 | # Map from levels to lengths of datetime tuples. |
paul@33 | 88 | |
paul@44 | 89 | lengths = [1, 2, 3, 3, 3, 3, 4, 5, 6] |
paul@33 | 90 | positions = [l-1 for l in lengths] |
paul@33 | 91 | |
paul@33 | 92 | # Map from qualifiers to interval units. Here, weeks are defined as 7 days. |
paul@33 | 93 | |
paul@33 | 94 | units = {"WEEKLY" : 7} |
paul@33 | 95 | |
paul@33 | 96 | # Make dictionaries mapping qualifiers to levels. |
paul@33 | 97 | |
paul@44 | 98 | freq = dict([(level, i) for (i, level) in enumerate(freq_levels) if level]) |
paul@44 | 99 | enum = dict([(level, i) for (i, level) in enumerate(enum_levels) if level]) |
paul@46 | 100 | weekdays = dict([(weekday, i+1) for (i, weekday) in enumerate(["MO", "TU", "WE", "TH", "FR", "SA", "SU"])]) |
paul@33 | 101 | |
paul@33 | 102 | # Functions for structuring the recurrences. |
paul@33 | 103 | |
paul@33 | 104 | def get_next(it): |
paul@33 | 105 | try: |
paul@33 | 106 | return it.next() |
paul@33 | 107 | except StopIteration: |
paul@33 | 108 | return None |
paul@33 | 109 | |
paul@46 | 110 | def get_parameters(values): |
paul@46 | 111 | |
paul@46 | 112 | "Return parameters from the given list of 'values'." |
paul@46 | 113 | |
paul@46 | 114 | d = {} |
paul@46 | 115 | for value in values: |
paul@46 | 116 | parts = value.split("=", 1) |
paul@46 | 117 | if len(parts) < 2: |
paul@46 | 118 | continue |
paul@46 | 119 | key, value = parts |
paul@46 | 120 | if key in ("COUNT", "BYSETPOS"): |
paul@46 | 121 | d[key] = int(value) |
paul@521 | 122 | else: |
paul@521 | 123 | d[key] = value |
paul@46 | 124 | return d |
paul@46 | 125 | |
paul@46 | 126 | def get_qualifiers(values): |
paul@46 | 127 | |
paul@46 | 128 | """ |
paul@46 | 129 | Process the list of 'values' of the form "key=value", returning a list of |
paul@358 | 130 | qualifiers of the form (qualifier name, args). |
paul@46 | 131 | """ |
paul@46 | 132 | |
paul@46 | 133 | qualifiers = [] |
paul@46 | 134 | frequency = None |
paul@46 | 135 | interval = 1 |
paul@46 | 136 | |
paul@46 | 137 | for value in values: |
paul@46 | 138 | parts = value.split("=", 1) |
paul@46 | 139 | if len(parts) < 2: |
paul@46 | 140 | continue |
paul@46 | 141 | key, value = parts |
paul@1239 | 142 | |
paul@1239 | 143 | # Accept frequency indicators as qualifiers. |
paul@1239 | 144 | |
paul@46 | 145 | if key == "FREQ" and freq.has_key(value): |
paul@46 | 146 | qualifier = frequency = (value, {}) |
paul@1239 | 147 | |
paul@1239 | 148 | # Accept interval indicators for frequency qualifier parameterisation. |
paul@1239 | 149 | |
paul@46 | 150 | elif key == "INTERVAL": |
paul@46 | 151 | interval = int(value) |
paul@46 | 152 | continue |
paul@1239 | 153 | |
paul@1239 | 154 | # Accept enumerators as qualifiers. |
paul@1239 | 155 | |
paul@46 | 156 | elif enum.has_key(key): |
paul@46 | 157 | qualifier = (key, {"values" : get_qualifier_values(key, value)}) |
paul@1239 | 158 | |
paul@1239 | 159 | # Ignore other items. |
paul@1239 | 160 | |
paul@46 | 161 | else: |
paul@46 | 162 | continue |
paul@46 | 163 | |
paul@46 | 164 | qualifiers.append(qualifier) |
paul@46 | 165 | |
paul@1239 | 166 | # Parameterise any frequency qualifier with the interval. |
paul@1239 | 167 | |
paul@46 | 168 | if frequency: |
paul@46 | 169 | frequency[1]["interval"] = interval |
paul@46 | 170 | |
paul@46 | 171 | return qualifiers |
paul@46 | 172 | |
paul@46 | 173 | def get_qualifier_values(qualifier, value): |
paul@46 | 174 | |
paul@46 | 175 | """ |
paul@46 | 176 | For the given 'qualifier', process the 'value' string, returning a list of |
paul@46 | 177 | suitable values. |
paul@46 | 178 | """ |
paul@46 | 179 | |
paul@46 | 180 | if qualifier != "BYDAY": |
paul@46 | 181 | return map(int, value.split(",")) |
paul@46 | 182 | |
paul@46 | 183 | values = [] |
paul@46 | 184 | for part in value.split(","): |
paul@46 | 185 | weekday = weekdays.get(part[-2:]) |
paul@46 | 186 | if not weekday: |
paul@46 | 187 | continue |
paul@46 | 188 | index = part[:-2] |
paul@46 | 189 | if index: |
paul@46 | 190 | index = int(index) |
paul@46 | 191 | else: |
paul@46 | 192 | index = None |
paul@46 | 193 | values.append((weekday, index)) |
paul@46 | 194 | |
paul@46 | 195 | return values |
paul@46 | 196 | |
paul@33 | 197 | def order_qualifiers(qualifiers): |
paul@33 | 198 | |
paul@33 | 199 | "Return the 'qualifiers' in order of increasing resolution." |
paul@33 | 200 | |
paul@33 | 201 | l = [] |
paul@33 | 202 | |
paul@33 | 203 | for qualifier, args in qualifiers: |
paul@1237 | 204 | |
paul@1237 | 205 | # Distinguish between enumerators, used to select particular periods, |
paul@1237 | 206 | # and frequencies, used to select repeating periods. |
paul@1237 | 207 | |
paul@33 | 208 | if enum.has_key(qualifier): |
paul@33 | 209 | level = enum[qualifier] |
paul@35 | 210 | if special_enum_levels.has_key(qualifier): |
paul@33 | 211 | args["interval"] = 1 |
paul@35 | 212 | selector = special_enum_levels[qualifier] |
paul@33 | 213 | else: |
paul@33 | 214 | selector = Enum |
paul@33 | 215 | else: |
paul@33 | 216 | level = freq[qualifier] |
paul@33 | 217 | selector = Pattern |
paul@33 | 218 | |
paul@42 | 219 | l.append(selector(level, args, qualifier)) |
paul@33 | 220 | |
paul@42 | 221 | l.sort(key=lambda x: x.level) |
paul@33 | 222 | return l |
paul@33 | 223 | |
paul@33 | 224 | def get_datetime_structure(datetime): |
paul@33 | 225 | |
paul@33 | 226 | "Return the structure of 'datetime' for recurrence production." |
paul@33 | 227 | |
paul@33 | 228 | l = [] |
paul@42 | 229 | offset = 0 |
paul@1237 | 230 | |
paul@42 | 231 | for level, value in enumerate(datetime): |
paul@1237 | 232 | |
paul@1237 | 233 | # At the day number, adjust the frequency level offset to reference |
paul@1237 | 234 | # days (and then hours, minutes, seconds). |
paul@1237 | 235 | |
paul@42 | 236 | if level == 2: |
paul@44 | 237 | offset = 3 |
paul@1237 | 238 | |
paul@42 | 239 | l.append(Enum(level + offset, {"values" : [value]}, "DT")) |
paul@1237 | 240 | |
paul@33 | 241 | return l |
paul@33 | 242 | |
paul@33 | 243 | def combine_datetime_with_qualifiers(datetime, qualifiers): |
paul@33 | 244 | |
paul@33 | 245 | """ |
paul@33 | 246 | Combine 'datetime' with 'qualifiers' to produce a structure for recurrence |
paul@33 | 247 | production. |
paul@33 | 248 | """ |
paul@33 | 249 | |
paul@33 | 250 | iter_dt = iter(get_datetime_structure(datetime)) |
paul@33 | 251 | iter_q = iter(order_qualifiers(qualifiers)) |
paul@33 | 252 | |
paul@33 | 253 | l = [] |
paul@33 | 254 | |
paul@33 | 255 | from_dt = get_next(iter_dt) |
paul@33 | 256 | from_q = get_next(iter_q) |
paul@33 | 257 | |
paul@33 | 258 | have_q = False |
paul@1237 | 259 | |
paul@1237 | 260 | # The initial context for any qualifiers is taken from the first datetime |
paul@1237 | 261 | # value, which should be the year. |
paul@1237 | 262 | |
paul@33 | 263 | context = [] |
paul@39 | 264 | context.append(from_dt.args["values"][0]) |
paul@33 | 265 | |
paul@33 | 266 | # Consume from both lists, merging entries. |
paul@33 | 267 | |
paul@33 | 268 | while from_dt and from_q: |
paul@42 | 269 | _level = from_dt.level |
paul@42 | 270 | level = from_q.level |
paul@33 | 271 | |
paul@1237 | 272 | # Datetime value at wider resolution. Use the datetime value to expand |
paul@1237 | 273 | # the context within which qualifiers will operate. |
paul@33 | 274 | |
paul@42 | 275 | if _level < level: |
paul@39 | 276 | from_dt = get_next(iter_dt) |
paul@38 | 277 | context.append(from_dt.args["values"][0]) |
paul@33 | 278 | |
paul@33 | 279 | # Qualifier at wider or same resolution as datetime value. |
paul@33 | 280 | |
paul@33 | 281 | else: |
paul@1237 | 282 | # Without any previous qualifier, introduce a special qualifier to |
paul@1237 | 283 | # provide context for this qualifier. |
paul@1237 | 284 | |
paul@33 | 285 | if not have_q: |
paul@1237 | 286 | add_initial_qualifier(from_q, level, context, l) |
paul@33 | 287 | have_q = True |
paul@33 | 288 | |
paul@1237 | 289 | # Associate the datetime context with the qualifier and add it to |
paul@1237 | 290 | # the combined list. |
paul@1237 | 291 | |
paul@43 | 292 | from_q.context = tuple(context) |
paul@43 | 293 | l.append(from_q) |
paul@1237 | 294 | |
paul@1237 | 295 | # Datetime value at same resolution. Expand the context using the |
paul@1237 | 296 | # value. |
paul@33 | 297 | |
paul@43 | 298 | if _level == level: |
paul@33 | 299 | from_dt = get_next(iter_dt) |
paul@1237 | 300 | if from_dt: |
paul@1237 | 301 | context.append(from_dt.args["values"][0]) |
paul@33 | 302 | |
paul@1237 | 303 | # Get the next qualifier. |
paul@1237 | 304 | |
paul@1237 | 305 | from_q = get_next(iter_q) |
paul@1237 | 306 | |
paul@1237 | 307 | # Complete the list by adding remaining datetime enumerators. |
paul@33 | 308 | |
paul@33 | 309 | while from_dt: |
paul@33 | 310 | l.append(from_dt) |
paul@33 | 311 | from_dt = get_next(iter_dt) |
paul@33 | 312 | |
paul@1237 | 313 | # Complete the list by adding remaining qualifiers. |
paul@1237 | 314 | |
paul@33 | 315 | while from_q: |
paul@33 | 316 | if not have_q: |
paul@1237 | 317 | add_initial_qualifier(from_q, level, context, l) |
paul@33 | 318 | have_q = True |
paul@43 | 319 | |
paul@1237 | 320 | # Associate the datetime context with the qualifier and add it to the |
paul@1237 | 321 | # combined list. |
paul@1237 | 322 | |
paul@43 | 323 | from_q.context = tuple(context) |
paul@33 | 324 | l.append(from_q) |
paul@1237 | 325 | |
paul@1237 | 326 | # Get the next qualifier. |
paul@1237 | 327 | |
paul@33 | 328 | from_q = get_next(iter_q) |
paul@33 | 329 | |
paul@33 | 330 | return l |
paul@33 | 331 | |
paul@1237 | 332 | def add_initial_qualifier(from_q, level, context, l): |
paul@1237 | 333 | |
paul@1237 | 334 | """ |
paul@1237 | 335 | Take the first qualifier 'from_q' at the given resolution 'level', using it |
paul@1237 | 336 | to create an initial qualifier providing appropriate context, using the |
paul@1237 | 337 | given 'context', adding it to the combined list 'l' if required. |
paul@1237 | 338 | """ |
paul@1237 | 339 | |
paul@1237 | 340 | if isinstance(from_q, Enum) and level > 0: |
paul@1237 | 341 | repeat = Pattern(level - 1, {"interval" : 1}, None) |
paul@1237 | 342 | repeat.context = tuple(context) |
paul@1237 | 343 | l.append(repeat) |
paul@1237 | 344 | |
paul@33 | 345 | # Datetime arithmetic. |
paul@33 | 346 | |
paul@33 | 347 | def combine(t1, t2): |
paul@322 | 348 | |
paul@322 | 349 | """ |
paul@322 | 350 | Combine tuples 't1' and 't2', returning a copy of 't1' filled with values |
paul@322 | 351 | from 't2' in positions where 0 appeared in 't1'. |
paul@322 | 352 | """ |
paul@322 | 353 | |
paul@33 | 354 | return tuple(map(lambda x, y: x or y, t1, t2)) |
paul@33 | 355 | |
paul@33 | 356 | def scale(interval, pos): |
paul@322 | 357 | |
paul@322 | 358 | """ |
paul@322 | 359 | Scale the given 'interval' value to the indicated position 'pos', returning |
paul@322 | 360 | a tuple with leading zero elements and 'interval' at the stated position. |
paul@322 | 361 | """ |
paul@322 | 362 | |
paul@33 | 363 | return (0,) * pos + (interval,) |
paul@33 | 364 | |
paul@33 | 365 | def get_seconds(t): |
paul@33 | 366 | |
paul@33 | 367 | "Convert the sub-day part of 't' into seconds." |
paul@33 | 368 | |
paul@33 | 369 | t = t + (0,) * (6 - len(t)) |
paul@33 | 370 | return (t[3] * 60 + t[4]) * 60 + t[5] |
paul@33 | 371 | |
paul@33 | 372 | def update(t, step): |
paul@33 | 373 | |
paul@33 | 374 | "Update 't' by 'step' at the resolution of 'step'." |
paul@33 | 375 | |
paul@33 | 376 | i = len(step) |
paul@33 | 377 | |
paul@33 | 378 | # Years only. |
paul@33 | 379 | |
paul@33 | 380 | if i == 1: |
paul@33 | 381 | return (t[0] + step[0],) + tuple(t[1:]) |
paul@33 | 382 | |
paul@33 | 383 | # Years and months. |
paul@33 | 384 | |
paul@33 | 385 | elif i == 2: |
paul@33 | 386 | month = t[1] + step[1] |
paul@33 | 387 | return (t[0] + step[0] + (month - 1) / 12, (month - 1) % 12 + 1) + tuple(t[2:]) |
paul@33 | 388 | |
paul@33 | 389 | # Dates and datetimes. |
paul@33 | 390 | |
paul@33 | 391 | else: |
paul@33 | 392 | updated_for_months = update(t, step[:2]) |
paul@33 | 393 | |
paul@33 | 394 | # Dates only. |
paul@33 | 395 | |
paul@33 | 396 | if i == 3: |
paul@33 | 397 | d = datetime(*updated_for_months) |
paul@33 | 398 | s = timedelta(step[2]) |
paul@33 | 399 | |
paul@33 | 400 | # Datetimes. |
paul@33 | 401 | |
paul@33 | 402 | else: |
paul@33 | 403 | d = datetime(*updated_for_months) |
paul@33 | 404 | s = timedelta(step[2], get_seconds(step)) |
paul@33 | 405 | |
paul@39 | 406 | return to_tuple(d + s, len(t)) |
paul@39 | 407 | |
paul@46 | 408 | def to_tuple(d, n=None): |
paul@322 | 409 | |
paul@322 | 410 | "Return 'd' as a tuple, optionally trimming the result to 'n' positions." |
paul@322 | 411 | |
paul@46 | 412 | if not isinstance(d, date): |
paul@46 | 413 | return d |
paul@46 | 414 | if n is None: |
paul@46 | 415 | if isinstance(d, datetime): |
paul@46 | 416 | n = 6 |
paul@46 | 417 | else: |
paul@46 | 418 | n = 3 |
paul@39 | 419 | return d.timetuple()[:n] |
paul@39 | 420 | |
paul@39 | 421 | def get_first_day(first_day, weekday): |
paul@322 | 422 | |
paul@322 | 423 | "Return the first occurrence at or after 'first_day' of 'weekday'." |
paul@322 | 424 | |
paul@39 | 425 | first_day = date(*first_day) |
paul@39 | 426 | first_weekday = first_day.isoweekday() |
paul@39 | 427 | if first_weekday > weekday: |
paul@39 | 428 | return first_day + timedelta(7 - first_weekday + weekday) |
paul@39 | 429 | else: |
paul@39 | 430 | return first_day + timedelta(weekday - first_weekday) |
paul@39 | 431 | |
paul@39 | 432 | def get_last_day(last_day, weekday): |
paul@322 | 433 | |
paul@322 | 434 | "Return the last occurrence at or before 'last_day' of 'weekday'." |
paul@322 | 435 | |
paul@39 | 436 | last_day = date(*last_day) |
paul@39 | 437 | last_weekday = last_day.isoweekday() |
paul@39 | 438 | if last_weekday < weekday: |
paul@39 | 439 | return last_day - timedelta(last_weekday + 7 - weekday) |
paul@39 | 440 | else: |
paul@39 | 441 | return last_day - timedelta(last_weekday - weekday) |
paul@33 | 442 | |
paul@33 | 443 | # Classes for producing instances from recurrence structures. |
paul@33 | 444 | |
paul@33 | 445 | class Selector: |
paul@358 | 446 | |
paul@358 | 447 | "A generic selector." |
paul@358 | 448 | |
paul@42 | 449 | def __init__(self, level, args, qualifier, selecting=None): |
paul@358 | 450 | |
paul@358 | 451 | """ |
paul@358 | 452 | Initialise at the given 'level' a selector employing the given 'args' |
paul@358 | 453 | defined in the interpretation of recurrence rule qualifiers, with the |
paul@358 | 454 | 'qualifier' being the name of the rule qualifier, and 'selecting' being |
paul@358 | 455 | an optional selector used to find more specific instances from those |
paul@358 | 456 | found by this selector. |
paul@358 | 457 | """ |
paul@358 | 458 | |
paul@42 | 459 | self.level = level |
paul@33 | 460 | self.args = args |
paul@33 | 461 | self.qualifier = qualifier |
paul@1237 | 462 | self.selecting = selecting |
paul@1237 | 463 | |
paul@1237 | 464 | # Define an empty context to be overridden. |
paul@1237 | 465 | |
paul@33 | 466 | self.context = () |
paul@1237 | 467 | |
paul@1237 | 468 | # Define the index of values from datetimes involved with this selector. |
paul@1237 | 469 | |
paul@1237 | 470 | self.pos = positions[level] |
paul@33 | 471 | |
paul@33 | 472 | def __repr__(self): |
paul@42 | 473 | return "%s(%r, %r, %r, %r)" % (self.__class__.__name__, self.level, self.args, self.qualifier, self.context) |
paul@33 | 474 | |
paul@359 | 475 | def materialise(self, start, end, count=None, setpos=None, inclusive=False): |
paul@358 | 476 | |
paul@358 | 477 | """ |
paul@358 | 478 | Starting at 'start', materialise instances up to but not including any |
paul@358 | 479 | at 'end' or later, returning at most 'count' if specified, and returning |
paul@358 | 480 | only the occurrences indicated by 'setpos' if specified. A list of |
paul@358 | 481 | instances is returned. |
paul@359 | 482 | |
paul@359 | 483 | If 'inclusive' is specified, the selection of instances will include the |
paul@359 | 484 | end of the search period if present in the results. |
paul@358 | 485 | """ |
paul@358 | 486 | |
paul@46 | 487 | start = to_tuple(start) |
paul@46 | 488 | end = to_tuple(end) |
paul@33 | 489 | counter = count and [0, count] |
paul@359 | 490 | results = self.materialise_items(self.context, start, end, counter, setpos, inclusive) |
paul@39 | 491 | results.sort() |
paul@41 | 492 | return results[:count] |
paul@33 | 493 | |
paul@359 | 494 | def materialise_item(self, current, earliest, next, counter, setpos=None, inclusive=False): |
paul@358 | 495 | |
paul@358 | 496 | """ |
paul@358 | 497 | Given the 'current' instance, the 'earliest' acceptable instance, the |
paul@358 | 498 | 'next' instance, an instance 'counter', and the optional 'setpos' |
paul@358 | 499 | criteria, return a list of result items. Where no selection within the |
paul@358 | 500 | current instance occurs, the current instance will be returned as a |
paul@358 | 501 | result if the same or later than the earliest acceptable instance. |
paul@358 | 502 | """ |
paul@358 | 503 | |
paul@45 | 504 | if self.selecting: |
paul@359 | 505 | return self.selecting.materialise_items(current, earliest, next, counter, setpos, inclusive) |
paul@358 | 506 | elif earliest <= current: |
paul@45 | 507 | return [current] |
paul@45 | 508 | else: |
paul@45 | 509 | return [] |
paul@45 | 510 | |
paul@45 | 511 | def convert_positions(self, setpos): |
paul@358 | 512 | |
paul@358 | 513 | "Convert 'setpos' to 0-based indexes." |
paul@358 | 514 | |
paul@45 | 515 | l = [] |
paul@45 | 516 | for pos in setpos: |
paul@45 | 517 | lower = pos < 0 and pos or pos - 1 |
paul@45 | 518 | upper = pos > 0 and pos or pos < -1 and pos + 1 or None |
paul@45 | 519 | l.append((lower, upper)) |
paul@45 | 520 | return l |
paul@45 | 521 | |
paul@45 | 522 | def select_positions(self, results, setpos): |
paul@358 | 523 | |
paul@358 | 524 | "Select in 'results' the 1-based positions given by 'setpos'." |
paul@358 | 525 | |
paul@45 | 526 | results.sort() |
paul@45 | 527 | l = [] |
paul@45 | 528 | for lower, upper in self.convert_positions(setpos): |
paul@45 | 529 | l += results[lower:upper] |
paul@45 | 530 | return l |
paul@45 | 531 | |
paul@359 | 532 | def filter_by_period(self, results, start, end, inclusive): |
paul@358 | 533 | |
paul@358 | 534 | """ |
paul@358 | 535 | Filter 'results' so that only those at or after 'start' and before 'end' |
paul@358 | 536 | are returned. |
paul@359 | 537 | |
paul@359 | 538 | If 'inclusive' is specified, the selection of instances will include the |
paul@359 | 539 | end of the search period if present in the results. |
paul@358 | 540 | """ |
paul@358 | 541 | |
paul@45 | 542 | l = [] |
paul@45 | 543 | for result in results: |
paul@359 | 544 | if start <= result and (inclusive and result <= end or result < end): |
paul@45 | 545 | l.append(result) |
paul@45 | 546 | return l |
paul@33 | 547 | |
paul@33 | 548 | class Pattern(Selector): |
paul@358 | 549 | |
paul@1237 | 550 | "A selector of time periods according to a repeating pattern." |
paul@358 | 551 | |
paul@359 | 552 | def materialise_items(self, context, start, end, counter, setpos=None, inclusive=False): |
paul@1237 | 553 | |
paul@1237 | 554 | """ |
paul@1237 | 555 | Bounded by the given 'context', return periods within 'start' to 'end', |
paul@1237 | 556 | updating the 'counter', selecting only the indexes specified by 'setpos' |
paul@1237 | 557 | (if given). |
paul@1237 | 558 | |
paul@1237 | 559 | If 'inclusive' is specified, the selection of periods will include those |
paul@1237 | 560 | starting at the end of the search period, if present in the results. |
paul@1237 | 561 | """ |
paul@1237 | 562 | |
paul@1237 | 563 | # Obtain the pattern context's value at the appropriate level. |
paul@1237 | 564 | |
paul@38 | 565 | first = scale(self.context[self.pos], self.pos) |
paul@34 | 566 | |
paul@1237 | 567 | # Define the step between result periods. |
paul@34 | 568 | |
paul@33 | 569 | interval = self.args.get("interval", 1) * units.get(self.qualifier, 1) |
paul@33 | 570 | step = scale(interval, self.pos) |
paul@34 | 571 | |
paul@1237 | 572 | # Define the scale of a single period. |
paul@34 | 573 | |
paul@33 | 574 | unit_interval = units.get(self.qualifier, 1) |
paul@33 | 575 | unit_step = scale(unit_interval, self.pos) |
paul@34 | 576 | |
paul@1239 | 577 | # Combine supplied context details with the pattern context. This should |
paul@1239 | 578 | # provide additional resolution information that may be missing from the |
paul@1239 | 579 | # supplied context. For example, the outer selector may indicate a month |
paul@1239 | 580 | # context, but this selector may need day information. |
paul@1237 | 581 | |
paul@34 | 582 | current = combine(context, first) |
paul@33 | 583 | results = [] |
paul@34 | 584 | |
paul@1237 | 585 | # Obtain periods before the end (and also at the end if inclusive), |
paul@1237 | 586 | # provided that any limit imposed by the counter has not been exceeded. |
paul@1237 | 587 | |
paul@1237 | 588 | while (inclusive and current <= end or current < end) and \ |
paul@1237 | 589 | (counter is None or counter[0] < counter[1]): |
paul@1237 | 590 | |
paul@1237 | 591 | # Increment the current datetime by the step for the next period. |
paul@1237 | 592 | |
paul@33 | 593 | next = update(current, step) |
paul@1237 | 594 | |
paul@1237 | 595 | # Determine the end point of the current period. |
paul@1237 | 596 | |
paul@33 | 597 | current_end = update(current, unit_step) |
paul@1237 | 598 | |
paul@1237 | 599 | # Obtain any period or periods within the bounds defined by the |
paul@1237 | 600 | # current period and any contraining start and end points, plus |
paul@1237 | 601 | # counter, setpos and inclusive details. |
paul@1237 | 602 | |
paul@359 | 603 | interval_results = self.materialise_item(current, max(current, start), min(current_end, end), counter, setpos, inclusive) |
paul@1237 | 604 | |
paul@1237 | 605 | # Update the counter with the number of identified results. |
paul@1237 | 606 | |
paul@45 | 607 | if counter is not None: |
paul@45 | 608 | counter[0] += len(interval_results) |
paul@1237 | 609 | |
paul@1237 | 610 | # Accumulate the results. |
paul@1237 | 611 | |
paul@45 | 612 | results += interval_results |
paul@1237 | 613 | |
paul@1237 | 614 | # Visit the next instance. |
paul@1237 | 615 | |
paul@33 | 616 | current = next |
paul@34 | 617 | |
paul@33 | 618 | return results |
paul@33 | 619 | |
paul@35 | 620 | class WeekDayFilter(Selector): |
paul@358 | 621 | |
paul@358 | 622 | "A selector of instances specified in terms of day numbers." |
paul@358 | 623 | |
paul@359 | 624 | def materialise_items(self, context, start, end, counter, setpos=None, inclusive=False): |
paul@39 | 625 | step = scale(1, 2) |
paul@33 | 626 | results = [] |
paul@34 | 627 | |
paul@39 | 628 | # Get weekdays in the year. |
paul@39 | 629 | |
paul@39 | 630 | if len(context) == 1: |
paul@39 | 631 | first_day = (context[0], 1, 1) |
paul@39 | 632 | last_day = (context[0], 12, 31) |
paul@39 | 633 | |
paul@39 | 634 | # Get weekdays in the month. |
paul@39 | 635 | |
paul@39 | 636 | elif len(context) == 2: |
paul@39 | 637 | first_day = (context[0], context[1], 1) |
paul@39 | 638 | last_day = update((context[0], context[1], 1), (0, 1, 0)) |
paul@39 | 639 | last_day = update(last_day, (0, 0, -1)) |
paul@39 | 640 | |
paul@39 | 641 | # Get weekdays in the week. |
paul@39 | 642 | |
paul@39 | 643 | else: |
paul@39 | 644 | current = context |
paul@39 | 645 | values = [value for (value, index) in self.args["values"]] |
paul@39 | 646 | |
paul@359 | 647 | while (inclusive and current <= end or current < end): |
paul@39 | 648 | next = update(current, step) |
paul@39 | 649 | if date(*current).isoweekday() in values: |
paul@359 | 650 | results += self.materialise_item(current, max(current, start), min(next, end), counter, inclusive=inclusive) |
paul@39 | 651 | current = next |
paul@45 | 652 | |
paul@45 | 653 | if setpos: |
paul@45 | 654 | return self.select_positions(results, setpos) |
paul@45 | 655 | else: |
paul@45 | 656 | return results |
paul@39 | 657 | |
paul@39 | 658 | # Find each of the given days. |
paul@39 | 659 | |
paul@39 | 660 | for value, index in self.args["values"]: |
paul@39 | 661 | if index is not None: |
paul@39 | 662 | offset = timedelta(7 * (abs(index) - 1)) |
paul@39 | 663 | |
paul@39 | 664 | if index < 0: |
paul@39 | 665 | current = to_tuple(get_last_day(last_day, value) - offset, 3) |
paul@39 | 666 | else: |
paul@39 | 667 | current = to_tuple(get_first_day(first_day, value) + offset, 3) |
paul@39 | 668 | |
paul@45 | 669 | next = update(current, step) |
paul@45 | 670 | |
paul@45 | 671 | # To support setpos, only current and next bound the search, not |
paul@45 | 672 | # the period in addition. |
paul@45 | 673 | |
paul@359 | 674 | results += self.materialise_item(current, current, next, counter, inclusive=inclusive) |
paul@39 | 675 | |
paul@39 | 676 | else: |
paul@39 | 677 | if index < 0: |
paul@39 | 678 | current = to_tuple(get_last_day(last_day, value), 3) |
paul@39 | 679 | direction = operator.sub |
paul@39 | 680 | else: |
paul@39 | 681 | current = to_tuple(get_first_day(first_day, value), 3) |
paul@39 | 682 | direction = operator.add |
paul@39 | 683 | |
paul@39 | 684 | while first_day <= current <= last_day: |
paul@45 | 685 | next = update(current, step) |
paul@45 | 686 | |
paul@45 | 687 | # To support setpos, only current and next bound the search, not |
paul@45 | 688 | # the period in addition. |
paul@45 | 689 | |
paul@359 | 690 | results += self.materialise_item(current, current, next, counter, inclusive=inclusive) |
paul@39 | 691 | current = to_tuple(direction(date(*current), timedelta(7)), 3) |
paul@34 | 692 | |
paul@45 | 693 | # Extract selected positions and remove out-of-period instances. |
paul@45 | 694 | |
paul@45 | 695 | if setpos: |
paul@45 | 696 | results = self.select_positions(results, setpos) |
paul@45 | 697 | |
paul@359 | 698 | return self.filter_by_period(results, start, end, inclusive) |
paul@33 | 699 | |
paul@33 | 700 | class Enum(Selector): |
paul@359 | 701 | def materialise_items(self, context, start, end, counter, setpos=None, inclusive=False): |
paul@33 | 702 | step = scale(1, self.pos) |
paul@33 | 703 | results = [] |
paul@33 | 704 | for value in self.args["values"]: |
paul@33 | 705 | current = combine(context, scale(value, self.pos)) |
paul@45 | 706 | next = update(current, step) |
paul@45 | 707 | |
paul@45 | 708 | # To support setpos, only current and next bound the search, not |
paul@45 | 709 | # the period in addition. |
paul@45 | 710 | |
paul@359 | 711 | results += self.materialise_item(current, current, next, counter, setpos, inclusive) |
paul@45 | 712 | |
paul@45 | 713 | # Extract selected positions and remove out-of-period instances. |
paul@45 | 714 | |
paul@45 | 715 | if setpos: |
paul@45 | 716 | results = self.select_positions(results, setpos) |
paul@45 | 717 | |
paul@359 | 718 | return self.filter_by_period(results, start, end, inclusive) |
paul@35 | 719 | |
paul@35 | 720 | class MonthDayFilter(Enum): |
paul@359 | 721 | def materialise_items(self, context, start, end, counter, setpos=None, inclusive=False): |
paul@35 | 722 | last_day = monthrange(context[0], context[1])[1] |
paul@35 | 723 | step = scale(1, self.pos) |
paul@35 | 724 | results = [] |
paul@35 | 725 | for value in self.args["values"]: |
paul@35 | 726 | if value < 0: |
paul@35 | 727 | value = last_day + 1 + value |
paul@35 | 728 | current = combine(context, scale(value, self.pos)) |
paul@45 | 729 | next = update(current, step) |
paul@45 | 730 | |
paul@45 | 731 | # To support setpos, only current and next bound the search, not |
paul@45 | 732 | # the period in addition. |
paul@45 | 733 | |
paul@359 | 734 | results += self.materialise_item(current, current, next, counter, inclusive=inclusive) |
paul@45 | 735 | |
paul@45 | 736 | # Extract selected positions and remove out-of-period instances. |
paul@45 | 737 | |
paul@45 | 738 | if setpos: |
paul@45 | 739 | results = self.select_positions(results, setpos) |
paul@45 | 740 | |
paul@359 | 741 | return self.filter_by_period(results, start, end, inclusive) |
paul@33 | 742 | |
paul@37 | 743 | class YearDayFilter(Enum): |
paul@359 | 744 | def materialise_items(self, context, start, end, counter, setpos=None, inclusive=False): |
paul@37 | 745 | first_day = date(context[0], 1, 1) |
paul@37 | 746 | next_first_day = date(context[0] + 1, 1, 1) |
paul@37 | 747 | year_length = (next_first_day - first_day).days |
paul@37 | 748 | step = scale(1, self.pos) |
paul@37 | 749 | results = [] |
paul@37 | 750 | for value in self.args["values"]: |
paul@37 | 751 | if value < 0: |
paul@37 | 752 | value = year_length + 1 + value |
paul@39 | 753 | current = to_tuple(first_day + timedelta(value - 1), 3) |
paul@45 | 754 | next = update(current, step) |
paul@45 | 755 | |
paul@45 | 756 | # To support setpos, only current and next bound the search, not |
paul@45 | 757 | # the period in addition. |
paul@45 | 758 | |
paul@359 | 759 | results += self.materialise_item(current, current, next, counter, inclusive=inclusive) |
paul@45 | 760 | |
paul@45 | 761 | # Extract selected positions and remove out-of-period instances. |
paul@45 | 762 | |
paul@45 | 763 | if setpos: |
paul@45 | 764 | results = self.select_positions(results, setpos) |
paul@45 | 765 | |
paul@359 | 766 | return self.filter_by_period(results, start, end, inclusive) |
paul@37 | 767 | |
paul@46 | 768 | special_enum_levels = { |
paul@46 | 769 | "BYDAY" : WeekDayFilter, |
paul@46 | 770 | "BYMONTHDAY" : MonthDayFilter, |
paul@46 | 771 | "BYYEARDAY" : YearDayFilter, |
paul@46 | 772 | } |
paul@46 | 773 | |
paul@46 | 774 | # Public functions. |
paul@46 | 775 | |
paul@46 | 776 | def connect_selectors(selectors): |
paul@358 | 777 | |
paul@358 | 778 | """ |
paul@358 | 779 | Make the 'selectors' reference each other in a hierarchy so that |
paul@358 | 780 | materialising the principal selector causes the more specific ones to be |
paul@358 | 781 | employed in the operation. |
paul@358 | 782 | """ |
paul@358 | 783 | |
paul@33 | 784 | current = selectors[0] |
paul@33 | 785 | for selector in selectors[1:]: |
paul@33 | 786 | current.selecting = selector |
paul@33 | 787 | current = selector |
paul@33 | 788 | return selectors[0] |
paul@33 | 789 | |
paul@46 | 790 | def get_selector(dt, qualifiers): |
paul@322 | 791 | |
paul@322 | 792 | """ |
paul@322 | 793 | Combine the initial datetime 'dt' with the given 'qualifiers', returning an |
paul@322 | 794 | object that can be used to select recurrences described by the 'qualifiers'. |
paul@322 | 795 | """ |
paul@322 | 796 | |
paul@46 | 797 | dt = to_tuple(dt) |
paul@46 | 798 | return connect_selectors(combine_datetime_with_qualifiers(dt, qualifiers)) |
paul@46 | 799 | |
paul@46 | 800 | def get_rule(dt, rule): |
paul@317 | 801 | |
paul@317 | 802 | """ |
paul@317 | 803 | Using the given initial datetime 'dt', interpret the 'rule' (a semicolon- |
paul@317 | 804 | separated collection of "key=value" strings), and return the resulting |
paul@317 | 805 | selector object. |
paul@317 | 806 | """ |
paul@317 | 807 | |
paul@351 | 808 | if not isinstance(rule, tuple): |
paul@351 | 809 | rule = rule.split(";") |
paul@351 | 810 | qualifiers = get_qualifiers(rule) |
paul@46 | 811 | return get_selector(dt, qualifiers) |
paul@35 | 812 | |
paul@33 | 813 | # vim: tabstop=4 expandtab shiftwidth=4 |