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