rrule.py 65 KB

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