rrule.py 65 KB

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