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