You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1672 lines
63 KiB

4 years ago
  1. # -*- coding: utf-8 -*-
  2. """
  3. The rrule module offers a small, complete, and very fast, implementation of
  4. the recurrence rules documented in the
  5. `iCalendar RFC <https://tools.ietf.org/html/rfc5545>`_,
  6. including support for caching of results.
  7. """
  8. import itertools
  9. import datetime
  10. import calendar
  11. import re
  12. import sys
  13. try:
  14. from math import gcd
  15. except ImportError:
  16. from fractions import gcd
  17. from six import advance_iterator, integer_types
  18. from six.moves import _thread, range
  19. import heapq
  20. from ._common import weekday as weekdaybase
  21. from .tz import tzutc, tzlocal
  22. # For warning about deprecation of until and count
  23. from warnings import warn
  24. __all__ = ["rrule", "rruleset", "rrulestr",
  25. "YEARLY", "MONTHLY", "WEEKLY", "DAILY",
  26. "HOURLY", "MINUTELY", "SECONDLY",
  27. "MO", "TU", "WE", "TH", "FR", "SA", "SU"]
  28. # Every mask is 7 days longer to handle cross-year weekly periods.
  29. M366MASK = tuple([1]*31+[2]*29+[3]*31+[4]*30+[5]*31+[6]*30 +
  30. [7]*31+[8]*31+[9]*30+[10]*31+[11]*30+[12]*31+[1]*7)
  31. M365MASK = list(M366MASK)
  32. M29, M30, M31 = list(range(1, 30)), list(range(1, 31)), list(range(1, 32))
  33. MDAY366MASK = tuple(M31+M29+M31+M30+M31+M30+M31+M31+M30+M31+M30+M31+M31[:7])
  34. MDAY365MASK = list(MDAY366MASK)
  35. M29, M30, M31 = list(range(-29, 0)), list(range(-30, 0)), list(range(-31, 0))
  36. NMDAY366MASK = tuple(M31+M29+M31+M30+M31+M30+M31+M31+M30+M31+M30+M31+M31[:7])
  37. NMDAY365MASK = list(NMDAY366MASK)
  38. M366RANGE = (0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366)
  39. M365RANGE = (0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365)
  40. WDAYMASK = [0, 1, 2, 3, 4, 5, 6]*55
  41. del M29, M30, M31, M365MASK[59], MDAY365MASK[59], NMDAY365MASK[31]
  42. MDAY365MASK = tuple(MDAY365MASK)
  43. M365MASK = tuple(M365MASK)
  44. FREQNAMES = ['YEARLY', 'MONTHLY', 'WEEKLY', 'DAILY', 'HOURLY', 'MINUTELY', 'SECONDLY']
  45. (YEARLY,
  46. MONTHLY,
  47. WEEKLY,
  48. DAILY,
  49. HOURLY,
  50. MINUTELY,
  51. SECONDLY) = list(range(7))
  52. # Imported on demand.
  53. easter = None
  54. parser = None
  55. class weekday(weekdaybase):
  56. """
  57. This version of weekday does not allow n = 0.
  58. """
  59. def __init__(self, wkday, n=None):
  60. if n == 0:
  61. raise ValueError("Can't create weekday with n==0")
  62. super(weekday, self).__init__(wkday, n)
  63. MO, TU, WE, TH, FR, SA, SU = weekdays = tuple(weekday(x) for x in range(7))
  64. def _invalidates_cache(f):
  65. """
  66. Decorator for rruleset methods which may invalidate the
  67. cached length.
  68. """
  69. def inner_func(self, *args, **kwargs):
  70. rv = f(self, *args, **kwargs)
  71. self._invalidate_cache()
  72. return rv
  73. return inner_func
  74. class rrulebase(object):
  75. def __init__(self, cache=False):
  76. if cache:
  77. self._cache = []
  78. self._cache_lock = _thread.allocate_lock()
  79. self._invalidate_cache()
  80. else:
  81. self._cache = None
  82. self._cache_complete = False
  83. self._len = None
  84. def __iter__(self):
  85. if self._cache_complete:
  86. return iter(self._cache)
  87. elif self._cache is None:
  88. return self._iter()
  89. else:
  90. return self._iter_cached()
  91. def _invalidate_cache(self):
  92. if self._cache is not None:
  93. self._cache = []
  94. self._cache_complete = False
  95. self._cache_gen = self._iter()
  96. if self._cache_lock.locked():
  97. self._cache_lock.release()
  98. self._len = None
  99. def _iter_cached(self):
  100. i = 0
  101. gen = self._cache_gen
  102. cache = self._cache
  103. acquire = self._cache_lock.acquire
  104. release = self._cache_lock.release
  105. while gen:
  106. if i == len(cache):
  107. acquire()
  108. if self._cache_complete:
  109. break
  110. try:
  111. for j in range(10):
  112. cache.append(advance_iterator(gen))
  113. except StopIteration:
  114. self._cache_gen = gen = None
  115. self._cache_complete = True
  116. break
  117. release()
  118. yield cache[i]
  119. i += 1
  120. while i < self._len:
  121. yield cache[i]
  122. i += 1
  123. def __getitem__(self, item):
  124. if self._cache_complete:
  125. return self._cache[item]
  126. elif isinstance(item, slice):
  127. if item.step and item.step < 0:
  128. return list(iter(self))[item]
  129. else:
  130. return list(itertools.islice(self,
  131. item.start or 0,
  132. item.stop or sys.maxsize,
  133. item.step or 1))
  134. elif item >= 0:
  135. gen = iter(self)
  136. try:
  137. for i in range(item+1):
  138. res = advance_iterator(gen)
  139. except StopIteration:
  140. raise IndexError
  141. return res
  142. else:
  143. return list(iter(self))[item]
  144. def __contains__(self, item):
  145. if self._cache_complete:
  146. return item in self._cache
  147. else:
  148. for i in self:
  149. if i == item:
  150. return True
  151. elif i > item:
  152. return False
  153. return False
  154. # __len__() introduces a large performance penality.
  155. def count(self):
  156. """ Returns the number of recurrences in this set. It will have go
  157. trough the whole recurrence, if this hasn't been done before. """
  158. if self._len is None:
  159. for x in self:
  160. pass
  161. return self._len
  162. def before(self, dt, inc=False):
  163. """ Returns the last recurrence before the given datetime instance. The
  164. inc keyword defines what happens if dt is an occurrence. With
  165. inc=True, if dt itself is an occurrence, it will be returned. """
  166. if self._cache_complete:
  167. gen = self._cache
  168. else:
  169. gen = self
  170. last = None
  171. if inc:
  172. for i in gen:
  173. if i > dt:
  174. break
  175. last = i
  176. else:
  177. for i in gen:
  178. if i >= dt:
  179. break
  180. last = i
  181. return last
  182. def after(self, dt, inc=False):
  183. """ Returns the first recurrence after the given datetime instance. The
  184. inc keyword defines what happens if dt is an occurrence. With
  185. inc=True, if dt itself is an occurrence, it will be returned. """
  186. if self._cache_complete:
  187. gen = self._cache
  188. else:
  189. gen = self
  190. if inc:
  191. for i in gen:
  192. if i >= dt:
  193. return i
  194. else:
  195. for i in gen:
  196. if i > dt:
  197. return i
  198. return None
  199. def xafter(self, dt, count=None, inc=False):
  200. """
  201. Generator which yields up to `count` recurrences after the given
  202. datetime instance, equivalent to `after`.
  203. :param dt:
  204. The datetime at which to start generating recurrences.
  205. :param count:
  206. The maximum number of recurrences to generate. If `None` (default),
  207. dates are generated until the recurrence rule is exhausted.
  208. :param inc:
  209. If `dt` is an instance of the rule and `inc` is `True`, it is
  210. included in the output.
  211. :yields: Yields a sequence of `datetime` objects.
  212. """
  213. if self._cache_complete:
  214. gen = self._cache
  215. else:
  216. gen = self
  217. # Select the comparison function
  218. if inc:
  219. comp = lambda dc, dtc: dc >= dtc
  220. else:
  221. comp = lambda dc, dtc: dc > dtc
  222. # Generate dates
  223. n = 0
  224. for d in gen:
  225. if comp(d, dt):
  226. if count is not None:
  227. n += 1
  228. if n > count:
  229. break
  230. yield d
  231. def between(self, after, before, inc=False, count=1):
  232. """ Returns all the occurrences of the rrule between after and before.
  233. The inc keyword defines what happens if after and/or before are
  234. themselves occurrences. With inc=True, they will be included in the
  235. list, if they are found in the recurrence set. """
  236. if self._cache_complete:
  237. gen = self._cache
  238. else:
  239. gen = self
  240. started = False
  241. l = []
  242. if inc:
  243. for i in gen:
  244. if i > before:
  245. break
  246. elif not started:
  247. if i >= after:
  248. started = True
  249. l.append(i)
  250. else:
  251. l.append(i)
  252. else:
  253. for i in gen:
  254. if i >= before:
  255. break
  256. elif not started:
  257. if i > after:
  258. started = True
  259. l.append(i)
  260. else:
  261. l.append(i)
  262. return l
  263. class rrule(rrulebase):
  264. """
  265. That's the base of the rrule operation. It accepts all the keywords
  266. defined in the RFC as its constructor parameters (except byday,
  267. which was renamed to byweekday) and more. The constructor prototype is::
  268. rrule(freq)
  269. Where freq must be one of YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY,
  270. or SECONDLY.
  271. .. note::
  272. Per RFC section 3.3.10, recurrence instances falling on invalid dates
  273. and times are ignored rather than coerced:
  274. Recurrence rules may generate recurrence instances with an invalid
  275. date (e.g., February 30) or nonexistent local time (e.g., 1:30 AM
  276. on a day where the local time is moved forward by an hour at 1:00
  277. AM). Such recurrence instances MUST be ignored and MUST NOT be
  278. counted as part of the recurrence set.
  279. This can lead to possibly surprising behavior when, for example, the
  280. start date occurs at the end of the month:
  281. >>> from dateutil.rrule import rrule, MONTHLY
  282. >>> from datetime import datetime
  283. >>> start_date = datetime(2014, 12, 31)
  284. >>> list(rrule(freq=MONTHLY, count=4, dtstart=start_date))
  285. ... # doctest: +NORMALIZE_WHITESPACE
  286. [datetime.datetime(2014, 12, 31, 0, 0),
  287. datetime.datetime(2015, 1, 31, 0, 0),
  288. datetime.datetime(2015, 3, 31, 0, 0),
  289. datetime.datetime(2015, 5, 31, 0, 0)]
  290. Additionally, it supports the following keyword arguments:
  291. :param dtstart:
  292. The recurrence start. Besides being the base for the recurrence,
  293. missing parameters in the final recurrence instances will also be
  294. extracted from this date. If not given, datetime.now() will be used
  295. instead.
  296. :param interval:
  297. The interval between each freq iteration. For example, when using
  298. YEARLY, an interval of 2 means once every two years, but with HOURLY,
  299. it means once every two hours. The default interval is 1.
  300. :param wkst:
  301. The week start day. Must be one of the MO, TU, WE constants, or an
  302. integer, specifying the first day of the week. This will affect
  303. recurrences based on weekly periods. The default week start is got
  304. from calendar.firstweekday(), and may be modified by
  305. calendar.setfirstweekday().
  306. :param count:
  307. How many occurrences will be generated.
  308. .. note::
  309. As of version 2.5.0, the use of the ``until`` keyword together
  310. with the ``count`` keyword is deprecated per RFC-5545 Sec. 3.3.10.
  311. :param until:
  312. If given, this must be a datetime instance, that will specify the
  313. limit of the recurrence. The last recurrence in the rule is the greatest
  314. datetime that is less than or equal to the value specified in the
  315. ``until`` parameter.
  316. .. note::
  317. As of version 2.5.0, the use of the ``until`` keyword together
  318. with the ``count`` keyword is deprecated per RFC-5545 Sec. 3.3.10.
  319. :param bysetpos:
  320. If given, it must be either an integer, or a sequence of integers,
  321. positive or negative. Each given integer will specify an occurrence
  322. number, corresponding to the nth occurrence of the rule inside the
  323. frequency period. For example, a bysetpos of -1 if combined with a
  324. MONTHLY frequency, and a byweekday of (MO, TU, WE, TH, FR), will
  325. result in the last work day of every month.
  326. :param bymonth:
  327. If given, it must be either an integer, or a sequence of integers,
  328. meaning the months to apply the recurrence to.
  329. :param bymonthday:
  330. If given, it must be either an integer, or a sequence of integers,
  331. meaning the month days to apply the recurrence to.
  332. :param byyearday:
  333. If given, it must be either an integer, or a sequence of integers,
  334. meaning the year days to apply the recurrence to.
  335. :param byeaster:
  336. If given, it must be either an integer, or a sequence of integers,
  337. positive or negative. Each integer will define an offset from the
  338. Easter Sunday. Passing the offset 0 to byeaster will yield the Easter
  339. Sunday itself. This is an extension to the RFC specification.
  340. :param byweekno:
  341. If given, it must be either an integer, or a sequence of integers,
  342. meaning the week numbers to apply the recurrence to. Week numbers
  343. have the meaning described in ISO8601, that is, the first week of
  344. the year is that containing at least four days of the new year.
  345. :param byweekday:
  346. If given, it must be either an integer (0 == MO), a sequence of
  347. integers, one of the weekday constants (MO, TU, etc), or a sequence
  348. of these constants. When given, these variables will define the
  349. weekdays where the recurrence will be applied. It's also possible to
  350. use an argument n for the weekday instances, which will mean the nth
  351. occurrence of this weekday in the period. For example, with MONTHLY,
  352. or with YEARLY and BYMONTH, using FR(+1) in byweekday will specify the
  353. first friday of the month where the recurrence happens. Notice that in
  354. the RFC documentation, this is specified as BYDAY, but was renamed to
  355. avoid the ambiguity of that keyword.
  356. :param byhour:
  357. If given, it must be either an integer, or a sequence of integers,
  358. meaning the hours to apply the recurrence to.
  359. :param byminute:
  360. If given, it must be either an integer, or a sequence of integers,
  361. meaning the minutes to apply the recurrence to.
  362. :param bysecond:
  363. If given, it must be either an integer, or a sequence of integers,
  364. meaning the seconds to apply the recurrence to.
  365. :param cache:
  366. If given, it must be a boolean value specifying to enable or disable
  367. caching of results. If you will use the same rrule instance multiple
  368. times, enabling caching will improve the performance considerably.
  369. """
  370. def __init__(self, freq, dtstart=None,
  371. interval=1, wkst=None, count=None, until=None, bysetpos=None,
  372. bymonth=None, bymonthday=None, byyearday=None, byeaster=None,
  373. byweekno=None, byweekday=None,
  374. byhour=None, byminute=None, bysecond=None,
  375. cache=False):
  376. super(rrule, self).__init__(cache)
  377. global easter
  378. if not dtstart:
  379. if until and until.tzinfo:
  380. dtstart = datetime.datetime.now(tz=until.tzinfo).replace(microsecond=0)
  381. else:
  382. dtstart = datetime.datetime.now().replace(microsecond=0)
  383. elif not isinstance(dtstart, datetime.datetime):
  384. dtstart = datetime.datetime.fromordinal(dtstart.toordinal())
  385. else:
  386. dtstart = dtstart.replace(microsecond=0)
  387. self._dtstart = dtstart
  388. self._tzinfo = dtstart.tzinfo
  389. self._freq = freq
  390. self._interval = interval
  391. self._count = count
  392. # Cache the original byxxx rules, if they are provided, as the _byxxx
  393. # attributes do not necessarily map to the inputs, and this can be
  394. # a problem in generating the strings. Only store things if they've
  395. # been supplied (the string retrieval will just use .get())
  396. self._original_rule = {}
  397. if until and not isinstance(until, datetime.datetime):
  398. until = datetime.datetime.fromordinal(until.toordinal())
  399. self._until = until
  400. if self._dtstart and self._until:
  401. if (self._dtstart.tzinfo is not None) != (self._until.tzinfo is not None):
  402. # According to RFC5545 Section 3.3.10:
  403. # https://tools.ietf.org/html/rfc5545#section-3.3.10
  404. #
  405. # > If the "DTSTART" property is specified as a date with UTC
  406. # > time or a date with local time and time zone reference,
  407. # > then the UNTIL rule part MUST be specified as a date with
  408. # > UTC time.
  409. raise ValueError(
  410. 'RRULE UNTIL values must be specified in UTC when DTSTART '
  411. 'is timezone-aware'
  412. )
  413. if count is not None and until:
  414. warn("Using both 'count' and 'until' is inconsistent with RFC 5545"
  415. " and has been deprecated in dateutil. Future versions will "
  416. "raise an error.", DeprecationWarning)
  417. if wkst is None:
  418. self._wkst = calendar.firstweekday()
  419. elif isinstance(wkst, integer_types):
  420. self._wkst = wkst
  421. else:
  422. self._wkst = wkst.weekday
  423. if bysetpos is None:
  424. self._bysetpos = None
  425. elif isinstance(bysetpos, integer_types):
  426. if bysetpos == 0 or not (-366 <= bysetpos <= 366):
  427. raise ValueError("bysetpos must be between 1 and 366, "
  428. "or between -366 and -1")
  429. self._bysetpos = (bysetpos,)
  430. else:
  431. self._bysetpos = tuple(bysetpos)
  432. for pos in self._bysetpos:
  433. if pos == 0 or not (-366 <= pos <= 366):
  434. raise ValueError("bysetpos must be between 1 and 366, "
  435. "or between -366 and -1")
  436. if self._bysetpos:
  437. self._original_rule['bysetpos'] = self._bysetpos
  438. if (byweekno is None and byyearday is None and bymonthday is None and
  439. byweekday is None and byeaster is None):
  440. if freq == YEARLY:
  441. if bymonth is None:
  442. bymonth = dtstart.month
  443. self._original_rule['bymonth'] = None
  444. bymonthday = dtstart.day
  445. self._original_rule['bymonthday'] = None
  446. elif freq == MONTHLY:
  447. bymonthday = dtstart.day
  448. self._original_rule['bymonthday'] = None
  449. elif freq == WEEKLY:
  450. byweekday = dtstart.weekday()
  451. self._original_rule['byweekday'] = None
  452. # bymonth
  453. if bymonth is None:
  454. self._bymonth = None
  455. else:
  456. if isinstance(bymonth, integer_types):
  457. bymonth = (bymonth,)
  458. self._bymonth = tuple(sorted(set(bymonth)))
  459. if 'bymonth' not in self._original_rule:
  460. self._original_rule['bymonth'] = self._bymonth
  461. # byyearday
  462. if byyearday is None:
  463. self._byyearday = None
  464. else:
  465. if isinstance(byyearday, integer_types):
  466. byyearday = (byyearday,)
  467. self._byyearday = tuple(sorted(set(byyearday)))
  468. self._original_rule['byyearday'] = self._byyearday
  469. # byeaster
  470. if byeaster is not None:
  471. if not easter:
  472. from dateutil import easter
  473. if isinstance(byeaster, integer_types):
  474. self._byeaster = (byeaster,)
  475. else:
  476. self._byeaster = tuple(sorted(byeaster))
  477. self._original_rule['byeaster'] = self._byeaster
  478. else:
  479. self._byeaster = None
  480. # bymonthday
  481. if bymonthday is None:
  482. self._bymonthday = ()
  483. self._bynmonthday = ()
  484. else:
  485. if isinstance(bymonthday, integer_types):
  486. bymonthday = (bymonthday,)
  487. bymonthday = set(bymonthday) # Ensure it's unique
  488. self._bymonthday = tuple(sorted(x for x in bymonthday if x > 0))
  489. self._bynmonthday = tuple(sorted(x for x in bymonthday if x < 0))
  490. # Storing positive numbers first, then negative numbers
  491. if 'bymonthday' not in self._original_rule:
  492. self._original_rule['bymonthday'] = tuple(
  493. itertools.chain(self._bymonthday, self._bynmonthday))
  494. # byweekno
  495. if byweekno is None:
  496. self._byweekno = None
  497. else:
  498. if isinstance(byweekno, integer_types):
  499. byweekno = (byweekno,)
  500. self._byweekno = tuple(sorted(set(byweekno)))
  501. self._original_rule['byweekno'] = self._byweekno
  502. # byweekday / bynweekday
  503. if byweekday is None:
  504. self._byweekday = None
  505. self._bynweekday = None
  506. else:
  507. # If it's one of the valid non-sequence types, convert to a
  508. # single-element sequence before the iterator that builds the
  509. # byweekday set.
  510. if isinstance(byweekday, integer_types) or hasattr(byweekday, "n"):
  511. byweekday = (byweekday,)
  512. self._byweekday = set()
  513. self._bynweekday = set()
  514. for wday in byweekday:
  515. if isinstance(wday, integer_types):
  516. self._byweekday.add(wday)
  517. elif not wday.n or freq > MONTHLY:
  518. self._byweekday.add(wday.weekday)
  519. else:
  520. self._bynweekday.add((wday.weekday, wday.n))
  521. if not self._byweekday:
  522. self._byweekday = None
  523. elif not self._bynweekday:
  524. self._bynweekday = None
  525. if self._byweekday is not None:
  526. self._byweekday = tuple(sorted(self._byweekday))
  527. orig_byweekday = [weekday(x) for x in self._byweekday]
  528. else:
  529. orig_byweekday = ()
  530. if self._bynweekday is not None:
  531. self._bynweekday = tuple(sorted(self._bynweekday))
  532. orig_bynweekday = [weekday(*x) for x in self._bynweekday]
  533. else:
  534. orig_bynweekday = ()
  535. if 'byweekday' not in self._original_rule:
  536. self._original_rule['byweekday'] = tuple(itertools.chain(
  537. orig_byweekday, orig_bynweekday))
  538. # byhour
  539. if byhour is None:
  540. if freq < HOURLY:
  541. self._byhour = {dtstart.hour}
  542. else:
  543. self._byhour = None
  544. else:
  545. if isinstance(byhour, integer_types):
  546. byhour = (byhour,)
  547. if freq == HOURLY:
  548. self._byhour = self.__construct_byset(start=dtstart.hour,
  549. byxxx=byhour,
  550. base=24)
  551. else:
  552. self._byhour = set(byhour)
  553. self._byhour = tuple(sorted(self._byhour))
  554. self._original_rule['byhour'] = self._byhour
  555. # byminute
  556. if byminute is None:
  557. if freq < MINUTELY:
  558. self._byminute = {dtstart.minute}
  559. else:
  560. self._byminute = None
  561. else:
  562. if isinstance(byminute, integer_types):
  563. byminute = (byminute,)
  564. if freq == MINUTELY:
  565. self._byminute = self.__construct_byset(start=dtstart.minute,
  566. byxxx=byminute,
  567. base=60)
  568. else:
  569. self._byminute = set(byminute)
  570. self._byminute = tuple(sorted(self._byminute))
  571. self._original_rule['byminute'] = self._byminute
  572. # bysecond
  573. if bysecond is None:
  574. if freq < SECONDLY:
  575. self._bysecond = ((dtstart.second,))
  576. else:
  577. self._bysecond = None
  578. else:
  579. if isinstance(bysecond, integer_types):
  580. bysecond = (bysecond,)
  581. self._bysecond = set(bysecond)
  582. if freq == SECONDLY:
  583. self._bysecond = self.__construct_byset(start=dtstart.second,
  584. byxxx=bysecond,
  585. base=60)
  586. else:
  587. self._bysecond = set(bysecond)
  588. self._bysecond = tuple(sorted(self._bysecond))
  589. self._original_rule['bysecond'] = self._bysecond
  590. if self._freq >= HOURLY:
  591. self._timeset = None
  592. else:
  593. self._timeset = []
  594. for hour in self._byhour:
  595. for minute in self._byminute:
  596. for second in self._bysecond:
  597. self._timeset.append(
  598. datetime.time(hour, minute, second,
  599. tzinfo=self._tzinfo))
  600. self._timeset.sort()
  601. self._timeset = tuple(self._timeset)
  602. def __str__(self):
  603. """
  604. Output a string that would generate this RRULE if passed to rrulestr.
  605. This is mostly compatible with RFC5545, except for the
  606. dateutil-specific extension BYEASTER.
  607. """
  608. output = []
  609. h, m, s = [None] * 3
  610. if self._dtstart:
  611. output.append(self._dtstart.strftime('DTSTART:%Y%m%dT%H%M%S'))
  612. h, m, s = self._dtstart.timetuple()[3:6]
  613. parts = ['FREQ=' + FREQNAMES[self._freq]]
  614. if self._interval != 1:
  615. parts.append('INTERVAL=' + str(self._interval))
  616. if self._wkst:
  617. parts.append('WKST=' + repr(weekday(self._wkst))[0:2])
  618. if self._count is not None:
  619. parts.append('COUNT=' + str(self._count))
  620. if self._until:
  621. parts.append(self._until.strftime('UNTIL=%Y%m%dT%H%M%S'))
  622. if self._original_rule.get('byweekday') is not None:
  623. # The str() method on weekday objects doesn't generate
  624. # RFC5545-compliant strings, so we should modify that.
  625. original_rule = dict(self._original_rule)
  626. wday_strings = []
  627. for wday in original_rule['byweekday']:
  628. if wday.n:
  629. wday_strings.append('{n:+d}{wday}'.format(
  630. n=wday.n,
  631. wday=repr(wday)[0:2]))
  632. else:
  633. wday_strings.append(repr(wday))
  634. original_rule['byweekday'] = wday_strings
  635. else:
  636. original_rule = self._original_rule
  637. partfmt = '{name}={vals}'
  638. for name, key in [('BYSETPOS', 'bysetpos'),
  639. ('BYMONTH', 'bymonth'),
  640. ('BYMONTHDAY', 'bymonthday'),
  641. ('BYYEARDAY', 'byyearday'),
  642. ('BYWEEKNO', 'byweekno'),
  643. ('BYDAY', 'byweekday'),
  644. ('BYHOUR', 'byhour'),
  645. ('BYMINUTE', 'byminute'),
  646. ('BYSECOND', 'bysecond'),
  647. ('BYEASTER', 'byeaster')]:
  648. value = original_rule.get(key)
  649. if value:
  650. parts.append(partfmt.format(name=name, vals=(','.join(str(v)
  651. for v in value))))
  652. output.append('RRULE:' + ';'.join(parts))
  653. return '\n'.join(output)
  654. def replace(self, **kwargs):
  655. """Return new rrule with same attributes except for those attributes given new
  656. values by whichever keyword arguments are specified."""
  657. new_kwargs = {"interval": self._interval,
  658. "count": self._count,
  659. "dtstart": self._dtstart,
  660. "freq": self._freq,
  661. "until": self._until,
  662. "wkst": self._wkst,
  663. "cache": False if self._cache is None else True }
  664. new_kwargs.update(self._original_rule)
  665. new_kwargs.update(kwargs)
  666. return rrule(**new_kwargs)
  667. def _iter(self):
  668. year, month, day, hour, minute, second, weekday, yearday, _ = \
  669. self._dtstart.timetuple()
  670. # Some local variables to speed things up a bit
  671. freq = self._freq
  672. interval = self._interval
  673. wkst = self._wkst
  674. until = self._until
  675. bymonth = self._bymonth
  676. byweekno = self._byweekno
  677. byyearday = self._byyearday
  678. byweekday = self._byweekday
  679. byeaster = self._byeaster
  680. bymonthday = self._bymonthday
  681. bynmonthday = self._bynmonthday
  682. bysetpos = self._bysetpos
  683. byhour = self._byhour
  684. byminute = self._byminute
  685. bysecond = self._bysecond
  686. ii = _iterinfo(self)
  687. ii.rebuild(year, month)
  688. getdayset = {YEARLY: ii.ydayset,
  689. MONTHLY: ii.mdayset,
  690. WEEKLY: ii.wdayset,
  691. DAILY: ii.ddayset,
  692. HOURLY: ii.ddayset,
  693. MINUTELY: ii.ddayset,
  694. SECONDLY: ii.ddayset}[freq]
  695. if freq < HOURLY:
  696. timeset = self._timeset
  697. else:
  698. gettimeset = {HOURLY: ii.htimeset,
  699. MINUTELY: ii.mtimeset,
  700. SECONDLY: ii.stimeset}[freq]
  701. if ((freq >= HOURLY and
  702. self._byhour and hour not in self._byhour) or
  703. (freq >= MINUTELY and
  704. self._byminute and minute not in self._byminute) or
  705. (freq >= SECONDLY and
  706. self._bysecond and second not in self._bysecond)):
  707. timeset = ()
  708. else:
  709. timeset = gettimeset(hour, minute, second)
  710. total = 0
  711. count = self._count
  712. while True:
  713. # Get dayset with the right frequency
  714. dayset, start, end = getdayset(year, month, day)
  715. # Do the "hard" work ;-)
  716. filtered = False
  717. for i in dayset[start:end]:
  718. if ((bymonth and ii.mmask[i] not in bymonth) or
  719. (byweekno and not ii.wnomask[i]) or
  720. (byweekday and ii.wdaymask[i] not in byweekday) or
  721. (ii.nwdaymask and not ii.nwdaymask[i]) or
  722. (byeaster and not ii.eastermask[i]) or
  723. ((bymonthday or bynmonthday) and
  724. ii.mdaymask[i] not in bymonthday and
  725. ii.nmdaymask[i] not in bynmonthday) or
  726. (byyearday and
  727. ((i < ii.yearlen and i+1 not in byyearday and
  728. -ii.yearlen+i not in byyearday) or
  729. (i >= ii.yearlen and i+1-ii.yearlen not in byyearday and
  730. -ii.nextyearlen+i-ii.yearlen not in byyearday)))):
  731. dayset[i] = None
  732. filtered = True
  733. # Output results
  734. if bysetpos and timeset:
  735. poslist = []
  736. for pos in bysetpos:
  737. if pos < 0:
  738. daypos, timepos = divmod(pos, len(timeset))
  739. else:
  740. daypos, timepos = divmod(pos-1, len(timeset))
  741. try:
  742. i = [x for x in dayset[start:end]
  743. if x is not None][daypos]
  744. time = timeset[timepos]
  745. except IndexError:
  746. pass
  747. else:
  748. date = datetime.date.fromordinal(ii.yearordinal+i)
  749. res = datetime.datetime.combine(date, time)
  750. if res not in poslist:
  751. poslist.append(res)
  752. poslist.sort()
  753. for res in poslist:
  754. if until and res > until:
  755. self._len = total
  756. return
  757. elif res >= self._dtstart:
  758. if count is not None:
  759. count -= 1
  760. if count < 0:
  761. self._len = total
  762. return
  763. total += 1
  764. yield res
  765. else:
  766. for i in dayset[start:end]:
  767. if i is not None:
  768. date = datetime.date.fromordinal(ii.yearordinal + i)
  769. for time in timeset:
  770. res = datetime.datetime.combine(date, time)
  771. if until and res > until:
  772. self._len = total
  773. return
  774. elif res >= self._dtstart:
  775. if count is not None:
  776. count -= 1
  777. if count < 0:
  778. self._len = total
  779. return
  780. total += 1
  781. yield res
  782. # Handle frequency and interval
  783. fixday = False
  784. if freq == YEARLY:
  785. year += interval
  786. if year > datetime.MAXYEAR:
  787. self._len = total
  788. return
  789. ii.rebuild(year, month)
  790. elif freq == MONTHLY:
  791. month += interval
  792. if month > 12:
  793. div, mod = divmod(month, 12)
  794. month = mod
  795. year += div
  796. if month == 0:
  797. month = 12
  798. year -= 1
  799. if year > datetime.MAXYEAR:
  800. self._len = total
  801. return
  802. ii.rebuild(year, month)
  803. elif freq == WEEKLY:
  804. if wkst > weekday:
  805. day += -(weekday+1+(6-wkst))+self._interval*7
  806. else:
  807. day += -(weekday-wkst)+self._interval*7
  808. weekday = wkst
  809. fixday = True
  810. elif freq == DAILY:
  811. day += interval
  812. fixday = True
  813. elif freq == HOURLY:
  814. if filtered:
  815. # Jump to one iteration before next day
  816. hour += ((23-hour)//interval)*interval
  817. if byhour:
  818. ndays, hour = self.__mod_distance(value=hour,
  819. byxxx=self._byhour,
  820. base=24)
  821. else:
  822. ndays, hour = divmod(hour+interval, 24)
  823. if ndays:
  824. day += ndays
  825. fixday = True
  826. timeset = gettimeset(hour, minute, second)
  827. elif freq == MINUTELY:
  828. if filtered:
  829. # Jump to one iteration before next day
  830. minute += ((1439-(hour*60+minute))//interval)*interval
  831. valid = False
  832. rep_rate = (24*60)
  833. for j in range(rep_rate // gcd(interval, rep_rate)):
  834. if byminute:
  835. nhours, minute = \
  836. self.__mod_distance(value=minute,
  837. byxxx=self._byminute,
  838. base=60)
  839. else:
  840. nhours, minute = divmod(minute+interval, 60)
  841. div, hour = divmod(hour+nhours, 24)
  842. if div:
  843. day += div
  844. fixday = True
  845. filtered = False
  846. if not byhour or hour in byhour:
  847. valid = True
  848. break
  849. if not valid:
  850. raise ValueError('Invalid combination of interval and ' +
  851. 'byhour resulting in empty rule.')
  852. timeset = gettimeset(hour, minute, second)
  853. elif freq == SECONDLY:
  854. if filtered:
  855. # Jump to one iteration before next day
  856. second += (((86399 - (hour * 3600 + minute * 60 + second))
  857. // interval) * interval)
  858. rep_rate = (24 * 3600)
  859. valid = False
  860. for j in range(0, rep_rate // gcd(interval, rep_rate)):
  861. if bysecond:
  862. nminutes, second = \
  863. self.__mod_distance(value=second,
  864. byxxx=self._bysecond,
  865. base=60)
  866. else:
  867. nminutes, second = divmod(second+interval, 60)
  868. div, minute = divmod(minute+nminutes, 60)
  869. if div:
  870. hour += div
  871. div, hour = divmod(hour, 24)
  872. if div:
  873. day += div
  874. fixday = True
  875. if ((not byhour or hour in byhour) and
  876. (not byminute or minute in byminute) and
  877. (not bysecond or second in bysecond)):
  878. valid = True
  879. break
  880. if not valid:
  881. raise ValueError('Invalid combination of interval, ' +
  882. 'byhour and byminute resulting in empty' +
  883. ' rule.')
  884. timeset = gettimeset(hour, minute, second)
  885. if fixday and day > 28:
  886. daysinmonth = calendar.monthrange(year, month)[1]
  887. if day > daysinmonth:
  888. while day > daysinmonth:
  889. day -= daysinmonth
  890. month += 1
  891. if month == 13:
  892. month = 1
  893. year += 1
  894. if year > datetime.MAXYEAR:
  895. self._len = total
  896. return
  897. daysinmonth = calendar.monthrange(year, month)[1]
  898. ii.rebuild(year, month)
  899. def __construct_byset(self, start, byxxx, base):
  900. """
  901. If a `BYXXX` sequence is passed to the constructor at the same level as
  902. `FREQ` (e.g. `FREQ=HOURLY,BYHOUR={2,4,7},INTERVAL=3`), there are some
  903. specifications which cannot be reached given some starting conditions.
  904. This occurs whenever the interval is not coprime with the base of a
  905. given unit and the difference between the starting position and the
  906. ending position is not coprime with the greatest common denominator
  907. between the interval and the base. For example, with a FREQ of hourly
  908. starting at 17:00 and an interval of 4, the only valid values for
  909. BYHOUR would be {21, 1, 5, 9, 13, 17}, because 4 and 24 are not
  910. coprime.
  911. :param start:
  912. Specifies the starting position.
  913. :param byxxx:
  914. An iterable containing the list of allowed values.
  915. :param base:
  916. The largest allowable value for the specified frequency (e.g.
  917. 24 hours, 60 minutes).
  918. This does not preserve the type of the iterable, returning a set, since
  919. the values should be unique and the order is irrelevant, this will
  920. speed up later lookups.
  921. In the event of an empty set, raises a :exception:`ValueError`, as this
  922. results in an empty rrule.
  923. """
  924. cset = set()
  925. # Support a single byxxx value.
  926. if isinstance(byxxx, integer_types):
  927. byxxx = (byxxx, )
  928. for num in byxxx:
  929. i_gcd = gcd(self._interval, base)
  930. # Use divmod rather than % because we need to wrap negative nums.
  931. if i_gcd == 1 or divmod(num - start, i_gcd)[1] == 0:
  932. cset.add(num)
  933. if len(cset) == 0:
  934. raise ValueError("Invalid rrule byxxx generates an empty set.")
  935. return cset
  936. def __mod_distance(self, value, byxxx, base):
  937. """
  938. Calculates the next value in a sequence where the `FREQ` parameter is
  939. specified along with a `BYXXX` parameter at the same "level"
  940. (e.g. `HOURLY` specified with `BYHOUR`).
  941. :param value:
  942. The old value of the component.
  943. :param byxxx:
  944. The `BYXXX` set, which should have been generated by
  945. `rrule._construct_byset`, or something else which checks that a
  946. valid rule is present.
  947. :param base:
  948. The largest allowable value for the specified frequency (e.g.
  949. 24 hours, 60 minutes).
  950. If a valid value is not found after `base` iterations (the maximum
  951. number before the sequence would start to repeat), this raises a
  952. :exception:`ValueError`, as no valid values were found.
  953. This returns a tuple of `divmod(n*interval, base)`, where `n` is the
  954. smallest number of `interval` repetitions until the next specified
  955. value in `byxxx` is found.
  956. """
  957. accumulator = 0
  958. for ii in range(1, base + 1):
  959. # Using divmod() over % to account for negative intervals
  960. div, value = divmod(value + self._interval, base)
  961. accumulator += div
  962. if value in byxxx:
  963. return (accumulator, value)
  964. class _iterinfo(object):
  965. __slots__ = ["rrule", "lastyear", "lastmonth",
  966. "yearlen", "nextyearlen", "yearordinal", "yearweekday",
  967. "mmask", "mrange", "mdaymask", "nmdaymask",
  968. "wdaymask", "wnomask", "nwdaymask", "eastermask"]
  969. def __init__(self, rrule):
  970. for attr in self.__slots__:
  971. setattr(self, attr, None)
  972. self.rrule = rrule
  973. def rebuild(self, year, month):
  974. # Every mask is 7 days longer to handle cross-year weekly periods.
  975. rr = self.rrule
  976. if year != self.lastyear:
  977. self.yearlen = 365 + calendar.isleap(year)
  978. self.nextyearlen = 365 + calendar.isleap(year + 1)
  979. firstyday = datetime.date(year, 1, 1)
  980. self.yearordinal = firstyday.toordinal()
  981. self.yearweekday = firstyday.weekday()
  982. wday = datetime.date(year, 1, 1).weekday()
  983. if self.yearlen == 365:
  984. self.mmask = M365MASK
  985. self.mdaymask = MDAY365MASK
  986. self.nmdaymask = NMDAY365MASK
  987. self.wdaymask = WDAYMASK[wday:]
  988. self.mrange = M365RANGE
  989. else:
  990. self.mmask = M366MASK
  991. self.mdaymask = MDAY366MASK
  992. self.nmdaymask = NMDAY366MASK
  993. self.wdaymask = WDAYMASK[wday:]
  994. self.mrange = M366RANGE
  995. if not rr._byweekno:
  996. self.wnomask = None
  997. else:
  998. self.wnomask = [0]*(self.yearlen+7)
  999. # no1wkst = firstwkst = self.wdaymask.index(rr._wkst)
  1000. no1wkst = firstwkst = (7-self.yearweekday+rr._wkst) % 7
  1001. if no1wkst >= 4:
  1002. no1wkst = 0
  1003. # Number of days in the year, plus the days we got
  1004. # from last year.
  1005. wyearlen = self.yearlen+(self.yearweekday-rr._wkst) % 7
  1006. else:
  1007. # Number of days in the year, minus the days we
  1008. # left in last year.
  1009. wyearlen = self.yearlen-no1wkst
  1010. div, mod = divmod(wyearlen, 7)
  1011. numweeks = div+mod//4
  1012. for n in rr._byweekno:
  1013. if n < 0:
  1014. n += numweeks+1
  1015. if not (0 < n <= numweeks):
  1016. continue
  1017. if n > 1:
  1018. i = no1wkst+(n-1)*7
  1019. if no1wkst != firstwkst:
  1020. i -= 7-firstwkst
  1021. else:
  1022. i = no1wkst
  1023. for j in range(7):
  1024. self.wnomask[i] = 1
  1025. i += 1
  1026. if self.wdaymask[i] == rr._wkst:
  1027. break
  1028. if 1 in rr._byweekno:
  1029. # Check week number 1 of next year as well
  1030. # TODO: Check -numweeks for next year.
  1031. i = no1wkst+numweeks*7
  1032. if no1wkst != firstwkst:
  1033. i -= 7-firstwkst
  1034. if i < self.yearlen:
  1035. # If week starts in next year, we
  1036. # don't care about it.
  1037. for j in range(7):
  1038. self.wnomask[i] = 1
  1039. i += 1
  1040. if self.wdaymask[i] == rr._wkst:
  1041. break
  1042. if no1wkst:
  1043. # Check last week number of last year as
  1044. # well. If no1wkst is 0, either the year
  1045. # started on week start, or week number 1
  1046. # got days from last year, so there are no
  1047. # days from last year's last week number in
  1048. # this year.
  1049. if -1 not in rr._byweekno:
  1050. lyearweekday = datetime.date(year-1, 1, 1).weekday()
  1051. lno1wkst = (7-lyearweekday+rr._wkst) % 7
  1052. lyearlen = 365+calendar.isleap(year-1)
  1053. if lno1wkst >= 4:
  1054. lno1wkst = 0
  1055. lnumweeks = 52+(lyearlen +
  1056. (lyearweekday-rr._wkst) % 7) % 7//4
  1057. else:
  1058. lnumweeks = 52+(self.yearlen-no1wkst) % 7//4
  1059. else:
  1060. lnumweeks = -1
  1061. if lnumweeks in rr._byweekno:
  1062. for i in range(no1wkst):
  1063. self.wnomask[i] = 1
  1064. if (rr._bynweekday and (month != self.lastmonth or
  1065. year != self.lastyear)):
  1066. ranges = []
  1067. if rr._freq == YEARLY:
  1068. if rr._bymonth:
  1069. for month in rr._bymonth:
  1070. ranges.append(self.mrange[month-1:month+1])
  1071. else:
  1072. ranges = [(0, self.yearlen)]
  1073. elif rr._freq == MONTHLY:
  1074. ranges = [self.mrange[month-1:month+1]]
  1075. if ranges:
  1076. # Weekly frequency won't get here, so we may not
  1077. # care about cross-year weekly periods.
  1078. self.nwdaymask = [0]*self.yearlen
  1079. for first, last in ranges:
  1080. last -= 1
  1081. for wday, n in rr._bynweekday:
  1082. if n < 0:
  1083. i = last+(n+1)*7
  1084. i -= (self.wdaymask[i]-wday) % 7
  1085. else:
  1086. i = first+(n-1)*7
  1087. i += (7-self.wdaymask[i]+wday) % 7
  1088. if first <= i <= last:
  1089. self.nwdaymask[i] = 1
  1090. if rr._byeaster:
  1091. self.eastermask = [0]*(self.yearlen+7)
  1092. eyday = easter.easter(year).toordinal()-self.yearordinal
  1093. for offset in rr._byeaster:
  1094. self.eastermask[eyday+offset] = 1
  1095. self.lastyear = year
  1096. self.lastmonth = month
  1097. def ydayset(self, year, month, day):
  1098. return list(range(self.yearlen)), 0, self.yearlen
  1099. def mdayset(self, year, month, day):
  1100. dset = [None]*self.yearlen
  1101. start, end = self.mrange[month-1:month+1]
  1102. for i in range(start, end):
  1103. dset[i] = i
  1104. return dset, start, end
  1105. def wdayset(self, year, month, day):
  1106. # We need to handle cross-year weeks here.
  1107. dset = [None]*(self.yearlen+7)
  1108. i = datetime.date(year, month, day).toordinal()-self.yearordinal
  1109. start = i
  1110. for j in range(7):
  1111. dset[i] = i
  1112. i += 1
  1113. # if (not (0 <= i < self.yearlen) or
  1114. # self.wdaymask[i] == self.rrule._wkst):
  1115. # This will cross the year boundary, if necessary.
  1116. if self.wdaymask[i] == self.rrule._wkst:
  1117. break
  1118. return dset, start, i
  1119. def ddayset(self, year, month, day):
  1120. dset = [None] * self.yearlen
  1121. i = datetime.date(year, month, day).toordinal() - self.yearordinal
  1122. dset[i] = i
  1123. return dset, i, i + 1
  1124. def htimeset(self, hour, minute, second):
  1125. tset = []
  1126. rr = self.rrule
  1127. for minute in rr._byminute:
  1128. for second in rr._bysecond:
  1129. tset.append(datetime.time(hour, minute, second,
  1130. tzinfo=rr._tzinfo))
  1131. tset.sort()
  1132. return tset
  1133. def mtimeset(self, hour, minute, second):
  1134. tset = []
  1135. rr = self.rrule
  1136. for second in rr._bysecond:
  1137. tset.append(datetime.time(hour, minute, second, tzinfo=rr._tzinfo))
  1138. tset.sort()
  1139. return tset
  1140. def stimeset(self, hour, minute, second):
  1141. return (datetime.time(hour, minute, second,
  1142. tzinfo=self.rrule._tzinfo),)
  1143. class rruleset(rrulebase):
  1144. """ The rruleset type allows more complex recurrence setups, mixing
  1145. multiple rules, dates, exclusion rules, and exclusion dates. The type
  1146. constructor takes the following keyword arguments:
  1147. :param cache: If True, caching of results will be enabled, improving
  1148. performance of multiple queries considerably. """
  1149. class _genitem(object):
  1150. def __init__(self, genlist, gen):
  1151. try:
  1152. self.dt = advance_iterator(gen)
  1153. genlist.append(self)
  1154. except StopIteration:
  1155. pass
  1156. self.genlist = genlist
  1157. self.gen = gen
  1158. def __next__(self):
  1159. try:
  1160. self.dt = advance_iterator(self.gen)
  1161. except StopIteration:
  1162. if self.genlist[0] is self:
  1163. heapq.heappop(self.genlist)
  1164. else:
  1165. self.genlist.remove(self)
  1166. heapq.heapify(self.genlist)
  1167. next = __next__
  1168. def __lt__(self, other):
  1169. return self.dt < other.dt
  1170. def __gt__(self, other):
  1171. return self.dt > other.dt
  1172. def __eq__(self, other):
  1173. return self.dt == other.dt
  1174. def __ne__(self, other):
  1175. return self.dt != other.dt
  1176. def __init__(self, cache=False):
  1177. super(rruleset, self).__init__(cache)
  1178. self._rrule = []
  1179. self._rdate = []
  1180. self._exrule = []
  1181. self._exdate = []
  1182. @_invalidates_cache
  1183. def rrule(self, rrule):
  1184. """ Include the given :py:class:`rrule` instance in the recurrence set
  1185. generation. """
  1186. self._rrule.append(rrule)
  1187. @_invalidates_cache
  1188. def rdate(self, rdate):
  1189. """ Include the given :py:class:`datetime` instance in the recurrence
  1190. set generation. """
  1191. self._rdate.append(rdate)
  1192. @_invalidates_cache
  1193. def exrule(self, exrule):
  1194. """ Include the given rrule instance in the recurrence set exclusion
  1195. list. Dates which are part of the given recurrence rules will not
  1196. be generated, even if some inclusive rrule or rdate matches them.
  1197. """
  1198. self._exrule.append(exrule)
  1199. @_invalidates_cache
  1200. def exdate(self, exdate):
  1201. """ Include the given datetime instance in the recurrence set
  1202. exclusion list. Dates included that way will not be generated,
  1203. even if some inclusive rrule or rdate matches them. """
  1204. self._exdate.append(exdate)
  1205. def _iter(self):
  1206. rlist = []
  1207. self._rdate.sort()
  1208. self._genitem(rlist, iter(self._rdate))
  1209. for gen in [iter(x) for x in self._rrule]:
  1210. self._genitem(rlist, gen)
  1211. exlist = []
  1212. self._exdate.sort()
  1213. self._genitem(exlist, iter(self._exdate))
  1214. for gen in [iter(x) for x in self._exrule]:
  1215. self._genitem(exlist, gen)
  1216. lastdt = None
  1217. total = 0
  1218. heapq.heapify(rlist)
  1219. heapq.heapify(exlist)
  1220. while rlist:
  1221. ritem = rlist[0]
  1222. if not lastdt or lastdt != ritem.dt:
  1223. while exlist and exlist[0] < ritem:
  1224. exitem = exlist[0]
  1225. advance_iterator(exitem)
  1226. if exlist and exlist[0] is exitem:
  1227. heapq.heapreplace(exlist, exitem)
  1228. if not exlist or ritem != exlist[0]:
  1229. total += 1
  1230. yield ritem.dt
  1231. lastdt = ritem.dt
  1232. advance_iterator(ritem)
  1233. if rlist and rlist[0] is ritem:
  1234. heapq.heapreplace(rlist, ritem)
  1235. self._len = total
  1236. class _rrulestr(object):
  1237. _freq_map = {"YEARLY": YEARLY,
  1238. "MONTHLY": MONTHLY,
  1239. "WEEKLY": WEEKLY,
  1240. "DAILY": DAILY,
  1241. "HOURLY": HOURLY,
  1242. "MINUTELY": MINUTELY,
  1243. "SECONDLY": SECONDLY}
  1244. _weekday_map = {"MO": 0, "TU": 1, "WE": 2, "TH": 3,
  1245. "FR": 4, "SA": 5, "SU": 6}
  1246. def _handle_int(self, rrkwargs, name, value, **kwargs):
  1247. rrkwargs[name.lower()] = int(value)
  1248. def _handle_int_list(self, rrkwargs, name, value, **kwargs):
  1249. rrkwargs[name.lower()] = [int(x) for x in value.split(',')]
  1250. _handle_INTERVAL = _handle_int
  1251. _handle_COUNT = _handle_int
  1252. _handle_BYSETPOS = _handle_int_list
  1253. _handle_BYMONTH = _handle_int_list
  1254. _handle_BYMONTHDAY = _handle_int_list
  1255. _handle_BYYEARDAY = _handle_int_list
  1256. _handle_BYEASTER = _handle_int_list
  1257. _handle_BYWEEKNO = _handle_int_list
  1258. _handle_BYHOUR = _handle_int_list
  1259. _handle_BYMINUTE = _handle_int_list
  1260. _handle_BYSECOND = _handle_int_list
  1261. def _handle_FREQ(self, rrkwargs, name, value, **kwargs):
  1262. rrkwargs["freq"] = self._freq_map[value]
  1263. def _handle_UNTIL(self, rrkwargs, name, value, **kwargs):
  1264. global parser
  1265. if not parser:
  1266. from dateutil import parser
  1267. try:
  1268. rrkwargs["until"] = parser.parse(value,
  1269. ignoretz=kwargs.get("ignoretz"),
  1270. tzinfos=kwargs.get("tzinfos"))
  1271. except ValueError:
  1272. raise ValueError("invalid until date")
  1273. def _handle_WKST(self, rrkwargs, name, value, **kwargs):
  1274. rrkwargs["wkst"] = self._weekday_map[value]
  1275. def _handle_BYWEEKDAY(self, rrkwargs, name, value, **kwargs):
  1276. """
  1277. Two ways to specify this: +1MO or MO(+1)
  1278. """
  1279. l = []
  1280. for wday in value.split(','):
  1281. if '(' in wday:
  1282. # If it's of the form TH(+1), etc.
  1283. splt = wday.split('(')
  1284. w = splt[0]
  1285. n = int(splt[1][:-1])
  1286. elif len(wday):
  1287. # If it's of the form +1MO
  1288. for i in range(len(wday)):
  1289. if wday[i] not in '+-0123456789':
  1290. break
  1291. n = wday[:i] or None
  1292. w = wday[i:]
  1293. if n:
  1294. n = int(n)
  1295. else:
  1296. raise ValueError("Invalid (empty) BYDAY specification.")
  1297. l.append(weekdays[self._weekday_map[w]](n))
  1298. rrkwargs["byweekday"] = l
  1299. _handle_BYDAY = _handle_BYWEEKDAY
  1300. def _parse_rfc_rrule(self, line,
  1301. dtstart=None,
  1302. cache=False,
  1303. ignoretz=False,
  1304. tzinfos=None):
  1305. if line.find(':') != -1:
  1306. name, value = line.split(':')
  1307. if name != "RRULE":
  1308. raise ValueError("unknown parameter name")
  1309. else:
  1310. value = line
  1311. rrkwargs = {}
  1312. for pair in value.split(';'):
  1313. name, value = pair.split('=')
  1314. name = name.upper()
  1315. value = value.upper()
  1316. try:
  1317. getattr(self, "_handle_"+name)(rrkwargs, name, value,
  1318. ignoretz=ignoretz,
  1319. tzinfos=tzinfos)
  1320. except AttributeError:
  1321. raise ValueError("unknown parameter '%s'" % name)
  1322. except (KeyError, ValueError):
  1323. raise ValueError("invalid '%s': %s" % (name, value))
  1324. return rrule(dtstart=dtstart, cache=cache, **rrkwargs)
  1325. def _parse_rfc(self, s,
  1326. dtstart=None,
  1327. cache=False,
  1328. unfold=False,
  1329. forceset=False,
  1330. compatible=False,
  1331. ignoretz=False,
  1332. tzids=None,
  1333. tzinfos=None):
  1334. global parser
  1335. if compatible:
  1336. forceset = True
  1337. unfold = True
  1338. TZID_NAMES = dict(map(
  1339. lambda x: (x.upper(), x),
  1340. re.findall('TZID=(?P<name>[^:]+):', s)
  1341. ))
  1342. s = s.upper()
  1343. if not s.strip():
  1344. raise ValueError("empty string")
  1345. if unfold:
  1346. lines = s.splitlines()
  1347. i = 0
  1348. while i < len(lines):
  1349. line = lines[i].rstrip()
  1350. if not line:
  1351. del lines[i]
  1352. elif i > 0 and line[0] == " ":
  1353. lines[i-1] += line[1:]
  1354. del lines[i]
  1355. else:
  1356. i += 1
  1357. else:
  1358. lines = s.split()
  1359. if (not forceset and len(lines) == 1 and (s.find(':') == -1 or
  1360. s.startswith('RRULE:'))):
  1361. return self._parse_rfc_rrule(lines[0], cache=cache,
  1362. dtstart=dtstart, ignoretz=ignoretz,
  1363. tzinfos=tzinfos)
  1364. else:
  1365. rrulevals = []
  1366. rdatevals = []
  1367. exrulevals = []
  1368. exdatevals = []
  1369. for line in lines:
  1370. if not line:
  1371. continue
  1372. if line.find(':') == -1:
  1373. name = "RRULE"
  1374. value = line
  1375. else:
  1376. name, value = line.split(':', 1)
  1377. parms = name.split(';')
  1378. if not parms:
  1379. raise ValueError("empty property name")
  1380. name = parms[0]
  1381. parms = parms[1:]
  1382. if name == "RRULE":
  1383. for parm in parms:
  1384. raise ValueError("unsupported RRULE parm: "+parm)
  1385. rrulevals.append(value)
  1386. elif name == "RDATE":
  1387. for parm in parms:
  1388. if parm != "VALUE=DATE-TIME":
  1389. raise ValueError("unsupported RDATE parm: "+parm)
  1390. rdatevals.append(value)
  1391. elif name == "EXRULE":
  1392. for parm in parms:
  1393. raise ValueError("unsupported EXRULE parm: "+parm)
  1394. exrulevals.append(value)
  1395. elif name == "EXDATE":
  1396. for parm in parms:
  1397. if parm != "VALUE=DATE-TIME":
  1398. raise ValueError("unsupported EXDATE parm: "+parm)
  1399. exdatevals.append(value)
  1400. elif name == "DTSTART":
  1401. # RFC 5445 3.8.2.4: The VALUE parameter is optional, but
  1402. # may be found only once.
  1403. value_found = False
  1404. TZID = None
  1405. valid_values = {"VALUE=DATE-TIME", "VALUE=DATE"}
  1406. for parm in parms:
  1407. if parm.startswith("TZID="):
  1408. try:
  1409. tzkey = TZID_NAMES[parm.split('TZID=')[-1]]
  1410. except KeyError:
  1411. continue
  1412. if tzids is None:
  1413. from . import tz
  1414. tzlookup = tz.gettz
  1415. elif callable(tzids):
  1416. tzlookup = tzids
  1417. else:
  1418. tzlookup = getattr(tzids, 'get', None)
  1419. if tzlookup is None:
  1420. msg = ('tzids must be a callable, ' +
  1421. 'mapping, or None, ' +
  1422. 'not %s' % tzids)
  1423. raise ValueError(msg)
  1424. TZID = tzlookup(tzkey)
  1425. continue
  1426. if parm not in valid_values:
  1427. raise ValueError("unsupported DTSTART parm: "+parm)
  1428. else:
  1429. if value_found:
  1430. msg = ("Duplicate value parameter found in " +
  1431. "DTSTART: " + parm)
  1432. raise ValueError(msg)
  1433. value_found = True
  1434. if not parser:
  1435. from dateutil import parser
  1436. dtstart = parser.parse(value, ignoretz=ignoretz,
  1437. tzinfos=tzinfos)
  1438. if TZID is not None:
  1439. if dtstart.tzinfo is None:
  1440. dtstart = dtstart.replace(tzinfo=TZID)
  1441. else:
  1442. raise ValueError('DTSTART specifies multiple timezones')
  1443. else:
  1444. raise ValueError("unsupported property: "+name)
  1445. if (forceset or len(rrulevals) > 1 or rdatevals
  1446. or exrulevals or exdatevals):
  1447. if not parser and (rdatevals or exdatevals):
  1448. from dateutil import parser
  1449. rset = rruleset(cache=cache)
  1450. for value in rrulevals:
  1451. rset.rrule(self._parse_rfc_rrule(value, dtstart=dtstart,
  1452. ignoretz=ignoretz,
  1453. tzinfos=tzinfos))
  1454. for value in rdatevals:
  1455. for datestr in value.split(','):
  1456. rset.rdate(parser.parse(datestr,
  1457. ignoretz=ignoretz,
  1458. tzinfos=tzinfos))
  1459. for value in exrulevals:
  1460. rset.exrule(self._parse_rfc_rrule(value, dtstart=dtstart,
  1461. ignoretz=ignoretz,
  1462. tzinfos=tzinfos))
  1463. for value in exdatevals:
  1464. for datestr in value.split(','):
  1465. rset.exdate(parser.parse(datestr,
  1466. ignoretz=ignoretz,
  1467. tzinfos=tzinfos))
  1468. if compatible and dtstart:
  1469. rset.rdate(dtstart)
  1470. return rset
  1471. else:
  1472. return self._parse_rfc_rrule(rrulevals[0],
  1473. dtstart=dtstart,
  1474. cache=cache,
  1475. ignoretz=ignoretz,
  1476. tzinfos=tzinfos)
  1477. def __call__(self, s, **kwargs):
  1478. return self._parse_rfc(s, **kwargs)
  1479. rrulestr = _rrulestr()
  1480. # vim:ts=4:sw=4:et