rrule.py 62 KB

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