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

2079 lines
74 KiB

  1. """Definitions and behavior for iCalendar, also known as vCalendar 2.0"""
  2. from __future__ import print_function
  3. import datetime
  4. import logging
  5. import random # for generating a UID
  6. import socket
  7. import string
  8. import base64
  9. from dateutil import rrule, tz
  10. import six
  11. try:
  12. import pytz
  13. except ImportError:
  14. class Pytz:
  15. """fake pytz module (pytz is not required)"""
  16. class AmbiguousTimeError(Exception):
  17. """pytz error for ambiguous times
  18. during transition daylight->standard"""
  19. class NonExistentTimeError(Exception):
  20. """pytz error for non-existent times
  21. during transition standard->daylight"""
  22. pytz = Pytz # keeps quantifiedcode happy
  23. from . import behavior
  24. from .base import (VObjectError, NativeError, ValidateError, ParseError,
  25. Component, ContentLine, logger, registerBehavior,
  26. backslashEscape, foldOneLine)
  27. # ------------------------------- Constants ------------------------------------
  28. DATENAMES = ("rdate", "exdate")
  29. RULENAMES = ("exrule", "rrule")
  30. DATESANDRULES = ("exrule", "rrule", "rdate", "exdate")
  31. PRODID = u"-//PYVOBJECT//NONSGML Version 1//EN"
  32. WEEKDAYS = "MO", "TU", "WE", "TH", "FR", "SA", "SU"
  33. FREQUENCIES = ('YEARLY', 'MONTHLY', 'WEEKLY', 'DAILY', 'HOURLY', 'MINUTELY',
  34. 'SECONDLY')
  35. zeroDelta = datetime.timedelta(0)
  36. twoHours = datetime.timedelta(hours=2)
  37. # ---------------------------- TZID registry -----------------------------------
  38. __tzidMap = {}
  39. def toUnicode(s):
  40. """
  41. Take a string or unicode, turn it into unicode, decoding as utf-8
  42. """
  43. if isinstance(s, six.binary_type):
  44. s = s.decode('utf-8')
  45. return s
  46. def registerTzid(tzid, tzinfo):
  47. """
  48. Register a tzid -> tzinfo mapping.
  49. """
  50. __tzidMap[toUnicode(tzid)] = tzinfo
  51. def getTzid(tzid, smart=True):
  52. """
  53. Return the tzid if it exists, or None.
  54. """
  55. tz = __tzidMap.get(toUnicode(tzid), None)
  56. if smart and tzid and not tz:
  57. try:
  58. from pytz import timezone, UnknownTimeZoneError
  59. try:
  60. tz = timezone(tzid)
  61. registerTzid(toUnicode(tzid), tz)
  62. except UnknownTimeZoneError as e:
  63. logging.error(e)
  64. except ImportError as e:
  65. logging.error(e)
  66. return tz
  67. utc = tz.tzutc()
  68. registerTzid("UTC", utc)
  69. # -------------------- Helper subclasses ---------------------------------------
  70. class TimezoneComponent(Component):
  71. """
  72. A VTIMEZONE object.
  73. VTIMEZONEs are parsed by tz.tzical, the resulting datetime.tzinfo
  74. subclass is stored in self.tzinfo, self.tzid stores the TZID associated
  75. with this timezone.
  76. @ivar name:
  77. The uppercased name of the object, in this case always 'VTIMEZONE'.
  78. @ivar tzinfo:
  79. A datetime.tzinfo subclass representing this timezone.
  80. @ivar tzid:
  81. The string used to refer to this timezone.
  82. """
  83. def __init__(self, tzinfo=None, *args, **kwds):
  84. """
  85. Accept an existing Component or a tzinfo class.
  86. """
  87. super(TimezoneComponent, self).__init__(*args, **kwds)
  88. self.isNative = True
  89. # hack to make sure a behavior is assigned
  90. if self.behavior is None:
  91. self.behavior = VTimezone
  92. if tzinfo is not None:
  93. self.tzinfo = tzinfo
  94. if not hasattr(self, 'name') or self.name == '':
  95. self.name = 'VTIMEZONE'
  96. self.useBegin = True
  97. @classmethod
  98. def registerTzinfo(obj, tzinfo):
  99. """
  100. Register tzinfo if it's not already registered, return its tzid.
  101. """
  102. tzid = obj.pickTzid(tzinfo)
  103. if tzid and not getTzid(tzid, False):
  104. registerTzid(tzid, tzinfo)
  105. return tzid
  106. def gettzinfo(self):
  107. # workaround for dateutil failing to parse some experimental properties
  108. good_lines = ('rdate', 'rrule', 'dtstart', 'tzname', 'tzoffsetfrom',
  109. 'tzoffsetto', 'tzid')
  110. # serialize encodes as utf-8, cStringIO will leave utf-8 alone
  111. buffer = six.StringIO()
  112. # allow empty VTIMEZONEs
  113. if len(self.contents) == 0:
  114. return None
  115. def customSerialize(obj):
  116. if isinstance(obj, Component):
  117. foldOneLine(buffer, u"BEGIN:" + obj.name)
  118. for child in obj.lines():
  119. if child.name.lower() in good_lines:
  120. child.serialize(buffer, 75, validate=False)
  121. for comp in obj.components():
  122. customSerialize(comp)
  123. foldOneLine(buffer, u"END:" + obj.name)
  124. customSerialize(self)
  125. buffer.seek(0) # tzical wants to read a stream
  126. return tz.tzical(buffer).get()
  127. def settzinfo(self, tzinfo, start=2000, end=2030):
  128. """
  129. Create appropriate objects in self to represent tzinfo.
  130. Collapse DST transitions to rrules as much as possible.
  131. Assumptions:
  132. - DST <-> Standard transitions occur on the hour
  133. - never within a month of one another
  134. - twice or fewer times a year
  135. - never in the month of December
  136. - DST always moves offset exactly one hour later
  137. - tzinfo classes dst method always treats times that could be in either
  138. offset as being in the later regime
  139. """
  140. def fromLastWeek(dt):
  141. """
  142. How many weeks from the end of the month dt is, starting from 1.
  143. """
  144. weekDelta = datetime.timedelta(weeks=1)
  145. n = 1
  146. current = dt + weekDelta
  147. while current.month == dt.month:
  148. n += 1
  149. current += weekDelta
  150. return n
  151. # lists of dictionaries defining rules which are no longer in effect
  152. completed = {'daylight': [], 'standard': []}
  153. # dictionary defining rules which are currently in effect
  154. working = {'daylight': None, 'standard': None}
  155. # rule may be based on nth week of the month or the nth from the last
  156. for year in range(start, end + 1):
  157. newyear = datetime.datetime(year, 1, 1)
  158. for transitionTo in 'daylight', 'standard':
  159. transition = getTransition(transitionTo, year, tzinfo)
  160. oldrule = working[transitionTo]
  161. if transition == newyear:
  162. # transitionTo is in effect for the whole year
  163. rule = {'end' : None,
  164. 'start' : newyear,
  165. 'month' : 1,
  166. 'weekday' : None,
  167. 'hour' : None,
  168. 'plus' : None,
  169. 'minus' : None,
  170. 'name' : tzinfo.tzname(newyear),
  171. 'offset' : tzinfo.utcoffset(newyear),
  172. 'offsetfrom' : tzinfo.utcoffset(newyear)}
  173. if oldrule is None:
  174. # transitionTo was not yet in effect
  175. working[transitionTo] = rule
  176. else:
  177. # transitionTo was already in effect
  178. if (oldrule['offset'] != tzinfo.utcoffset(newyear)):
  179. # old rule was different, it shouldn't continue
  180. oldrule['end'] = year - 1
  181. completed[transitionTo].append(oldrule)
  182. working[transitionTo] = rule
  183. elif transition is None:
  184. # transitionTo is not in effect
  185. if oldrule is not None:
  186. # transitionTo used to be in effect
  187. oldrule['end'] = year - 1
  188. completed[transitionTo].append(oldrule)
  189. working[transitionTo] = None
  190. else:
  191. # an offset transition was found
  192. try:
  193. old_offset = tzinfo.utcoffset(transition - twoHours)
  194. name = tzinfo.tzname(transition)
  195. offset = tzinfo.utcoffset(transition)
  196. except (pytz.AmbiguousTimeError, pytz.NonExistentTimeError):
  197. # guaranteed that tzinfo is a pytz timezone
  198. is_dst = (transitionTo == "daylight")
  199. old_offset = tzinfo.utcoffset(transition - twoHours, is_dst=is_dst)
  200. name = tzinfo.tzname(transition, is_dst=is_dst)
  201. offset = tzinfo.utcoffset(transition, is_dst=is_dst)
  202. rule = {'end' : None, # None, or an integer year
  203. 'start' : transition, # the datetime of transition
  204. 'month' : transition.month,
  205. 'weekday' : transition.weekday(),
  206. 'hour' : transition.hour,
  207. 'name' : name,
  208. 'plus' : int(
  209. (transition.day - 1)/ 7 + 1), # nth week of the month
  210. 'minus' : fromLastWeek(transition), # nth from last week
  211. 'offset' : offset,
  212. 'offsetfrom' : old_offset}
  213. if oldrule is None:
  214. working[transitionTo] = rule
  215. else:
  216. plusMatch = rule['plus'] == oldrule['plus']
  217. minusMatch = rule['minus'] == oldrule['minus']
  218. truth = plusMatch or minusMatch
  219. for key in 'month', 'weekday', 'hour', 'offset':
  220. truth = truth and rule[key] == oldrule[key]
  221. if truth:
  222. # the old rule is still true, limit to plus or minus
  223. if not plusMatch:
  224. oldrule['plus'] = None
  225. if not minusMatch:
  226. oldrule['minus'] = None
  227. else:
  228. # the new rule did not match the old
  229. oldrule['end'] = year - 1
  230. completed[transitionTo].append(oldrule)
  231. working[transitionTo] = rule
  232. for transitionTo in 'daylight', 'standard':
  233. if working[transitionTo] is not None:
  234. completed[transitionTo].append(working[transitionTo])
  235. self.tzid = []
  236. self.daylight = []
  237. self.standard = []
  238. self.add('tzid').value = self.pickTzid(tzinfo, True)
  239. # old = None # unused?
  240. for transitionTo in 'daylight', 'standard':
  241. for rule in completed[transitionTo]:
  242. comp = self.add(transitionTo)
  243. dtstart = comp.add('dtstart')
  244. dtstart.value = rule['start']
  245. if rule['name'] is not None:
  246. comp.add('tzname').value = rule['name']
  247. line = comp.add('tzoffsetto')
  248. line.value = deltaToOffset(rule['offset'])
  249. line = comp.add('tzoffsetfrom')
  250. line.value = deltaToOffset(rule['offsetfrom'])
  251. if rule['plus'] is not None:
  252. num = rule['plus']
  253. elif rule['minus'] is not None:
  254. num = -1 * rule['minus']
  255. else:
  256. num = None
  257. if num is not None:
  258. dayString = ";BYDAY=" + str(num) + WEEKDAYS[rule['weekday']]
  259. else:
  260. dayString = ""
  261. if rule['end'] is not None:
  262. if rule['hour'] is None:
  263. # all year offset, with no rule
  264. endDate = datetime.datetime(rule['end'], 1, 1)
  265. else:
  266. weekday = rrule.weekday(rule['weekday'], num)
  267. du_rule = rrule.rrule(rrule.YEARLY,
  268. bymonth=rule['month'], byweekday=weekday,
  269. dtstart=datetime.datetime(
  270. rule['end'], 1, 1, rule['hour']
  271. )
  272. )
  273. endDate = du_rule[0]
  274. endDate = endDate.replace(tzinfo=utc) - rule['offsetfrom']
  275. endString = ";UNTIL=" + dateTimeToString(endDate)
  276. else:
  277. endString = ''
  278. new_rule = "FREQ=YEARLY{0!s};BYMONTH={1!s}{2!s}"\
  279. .format(dayString, rule['month'], endString)
  280. comp.add('rrule').value = new_rule
  281. tzinfo = property(gettzinfo, settzinfo)
  282. # prevent Component's __setattr__ from overriding the tzinfo property
  283. normal_attributes = Component.normal_attributes + ['tzinfo']
  284. @staticmethod
  285. def pickTzid(tzinfo, allowUTC=False):
  286. """
  287. Given a tzinfo class, use known APIs to determine TZID, or use tzname.
  288. """
  289. if tzinfo is None or (not allowUTC and tzinfo_eq(tzinfo, utc)):
  290. # If tzinfo is UTC, we don't need a TZID
  291. return None
  292. # try PyICU's tzid key
  293. if hasattr(tzinfo, 'tzid'):
  294. return toUnicode(tzinfo.tzid)
  295. # try pytz zone key
  296. if hasattr(tzinfo, 'zone'):
  297. return toUnicode(tzinfo.zone)
  298. # try tzical's tzid key
  299. elif hasattr(tzinfo, '_tzid'):
  300. return toUnicode(tzinfo._tzid)
  301. else:
  302. # return tzname for standard (non-DST) time
  303. notDST = datetime.timedelta(0)
  304. for month in range(1, 13):
  305. dt = datetime.datetime(2000, month, 1)
  306. if tzinfo.dst(dt) == notDST:
  307. return toUnicode(tzinfo.tzname(dt))
  308. # there was no standard time in 2000!
  309. raise VObjectError("Unable to guess TZID for tzinfo {0!s}"
  310. .format(tzinfo))
  311. def __str__(self):
  312. return "<VTIMEZONE | {0}>".format(getattr(self, 'tzid', 'No TZID'))
  313. def __repr__(self):
  314. return self.__str__()
  315. def prettyPrint(self, level, tabwidth):
  316. pre = ' ' * level * tabwidth
  317. print(pre, self.name)
  318. print(pre, "TZID:", self.tzid)
  319. print('')
  320. class RecurringComponent(Component):
  321. """
  322. A vCalendar component like VEVENT or VTODO which may recur.
  323. Any recurring component can have one or multiple RRULE, RDATE,
  324. EXRULE, or EXDATE lines, and one or zero DTSTART lines. It can also have a
  325. variety of children that don't have any recurrence information.
  326. In the example below, note that dtstart is included in the rruleset.
  327. This is not the default behavior for dateutil's rrule implementation unless
  328. dtstart would already have been a member of the recurrence rule, and as a
  329. result, COUNT is wrong. This can be worked around when getting rruleset by
  330. adjusting count down by one if an rrule has a count and dtstart isn't in its
  331. result set, but by default, the rruleset property doesn't do this work
  332. around, to access it getrruleset must be called with addRDate set True.
  333. @ivar rruleset:
  334. A U{rruleset<https://moin.conectiva.com.br/DateUtil>}.
  335. """
  336. def __init__(self, *args, **kwds):
  337. super(RecurringComponent, self).__init__(*args, **kwds)
  338. self.isNative = True
  339. def getrruleset(self, addRDate=False):
  340. """
  341. Get an rruleset created from self.
  342. If addRDate is True, add an RDATE for dtstart if it's not included in
  343. an RRULE or RDATE, and count is decremented if it exists.
  344. Note that for rules which don't match DTSTART, DTSTART may not appear
  345. in list(rruleset), although it should. By default, an RDATE is not
  346. created in these cases, and count isn't updated, so dateutil may list
  347. a spurious occurrence.
  348. """
  349. rruleset = None
  350. for name in DATESANDRULES:
  351. addfunc = None
  352. for line in self.contents.get(name, ()):
  353. # don't bother creating a rruleset unless there's a rule
  354. if rruleset is None:
  355. rruleset = rrule.rruleset()
  356. if addfunc is None:
  357. addfunc = getattr(rruleset, name)
  358. try:
  359. dtstart = self.dtstart.value
  360. except (AttributeError, KeyError):
  361. # Special for VTODO - try DUE property instead
  362. try:
  363. if self.name == "VTODO":
  364. dtstart = self.due.value
  365. else:
  366. # if there's no dtstart, just return None
  367. logging.error('failed to get dtstart with VTODO')
  368. return None
  369. except (AttributeError, KeyError):
  370. # if there's no due, just return None
  371. logging.error('failed to find DUE at all.')
  372. return None
  373. if name in DATENAMES:
  374. if type(line.value[0]) == datetime.datetime:
  375. list(map(addfunc, line.value))
  376. elif type(line.value[0]) == datetime.date:
  377. for dt in line.value:
  378. addfunc(datetime.datetime(dt.year, dt.month, dt.day))
  379. else:
  380. # ignore RDATEs with PERIOD values for now
  381. pass
  382. elif name in RULENAMES:
  383. # a Ruby iCalendar library escapes semi-colons in rrules,
  384. # so also remove any backslashes
  385. value = line.value.replace('\\', '')
  386. # If dtstart has no time zone, `until`
  387. # shouldn't get one, either:
  388. ignoretz = (not isinstance(dtstart, datetime.datetime) or
  389. dtstart.tzinfo is None)
  390. try:
  391. until = rrule.rrulestr(value, ignoretz=ignoretz)._until
  392. except ValueError:
  393. # WORKAROUND: dateutil<=2.7.2 doesn't set the time zone
  394. # of dtstart
  395. if ignoretz:
  396. raise
  397. utc_now = datetime.datetime.now(datetime.timezone.utc)
  398. until = rrule.rrulestr(value, dtstart=utc_now)._until
  399. if until is not None and isinstance(dtstart,
  400. datetime.datetime) and \
  401. (until.tzinfo != dtstart.tzinfo):
  402. # dateutil converts the UNTIL date to a datetime,
  403. # check to see if the UNTIL parameter value was a date
  404. vals = dict(pair.split('=') for pair in
  405. value.upper().split(';'))
  406. if len(vals.get('UNTIL', '')) == 8:
  407. until = datetime.datetime.combine(until.date(),
  408. dtstart.time())
  409. # While RFC2445 says UNTIL MUST be UTC, Chandler allows
  410. # floating recurring events, and uses floating UNTIL
  411. # values. Also, some odd floating UNTIL but timezoned
  412. # DTSTART values have shown up in the wild, so put
  413. # floating UNTIL values DTSTART's timezone
  414. if until.tzinfo is None:
  415. until = until.replace(tzinfo=dtstart.tzinfo)
  416. if dtstart.tzinfo is not None:
  417. until = until.astimezone(dtstart.tzinfo)
  418. # RFC2445 actually states that UNTIL must be a UTC
  419. # value. Whilst the changes above work OK, one problem
  420. # case is if DTSTART is floating but UNTIL is properly
  421. # specified as UTC (or with a TZID). In that case
  422. # dateutil will fail datetime comparisons. There is no
  423. # easy solution to this as there is no obvious timezone
  424. # (at this point) to do proper floating time offset
  425. # comparisons. The best we can do is treat the UNTIL
  426. # value as floating. This could mean incorrect
  427. # determination of the last instance. The better
  428. # solution here is to encourage clients to use COUNT
  429. # rather than UNTIL when DTSTART is floating.
  430. if dtstart.tzinfo is None:
  431. until = until.replace(tzinfo=None)
  432. value_without_until = ';'.join(
  433. pair for pair in value.split(';')
  434. if pair.split('=')[0].upper() != 'UNTIL')
  435. rule = rrule.rrulestr(value_without_until,
  436. dtstart=dtstart, ignoretz=ignoretz)
  437. rule._until = until
  438. # add the rrule or exrule to the rruleset
  439. addfunc(rule)
  440. if (name == 'rrule' or name == 'rdate') and addRDate:
  441. # rlist = rruleset._rrule if name == 'rrule' else rruleset._rdate
  442. try:
  443. # dateutils does not work with all-day
  444. # (datetime.date) items so we need to convert to a
  445. # datetime.datetime (which is what dateutils
  446. # does internally)
  447. if not isinstance(dtstart, datetime.datetime):
  448. adddtstart = datetime.datetime.fromordinal(dtstart.toordinal())
  449. else:
  450. adddtstart = dtstart
  451. if name == 'rrule':
  452. if rruleset._rrule[-1][0] != adddtstart:
  453. rruleset.rdate(adddtstart)
  454. added = True
  455. if rruleset._rrule[-1]._count is not None:
  456. rruleset._rrule[-1]._count -= 1
  457. else:
  458. added = False
  459. elif name == 'rdate':
  460. if rruleset._rdate[0] != adddtstart:
  461. rruleset.rdate(adddtstart)
  462. added = True
  463. else:
  464. added = False
  465. except IndexError:
  466. # it's conceivable that an rrule has 0 datetimes
  467. added = False
  468. return rruleset
  469. def setrruleset(self, rruleset):
  470. # Get DTSTART from component (or DUE if no DTSTART in a VTODO)
  471. try:
  472. dtstart = self.dtstart.value
  473. except (AttributeError, KeyError):
  474. if self.name == "VTODO":
  475. dtstart = self.due.value
  476. else:
  477. raise
  478. isDate = datetime.date == type(dtstart)
  479. if isDate:
  480. dtstart = datetime.datetime(dtstart.year, dtstart.month, dtstart.day)
  481. untilSerialize = dateToString
  482. else:
  483. # make sure to convert time zones to UTC
  484. untilSerialize = lambda x: dateTimeToString(x, True)
  485. for name in DATESANDRULES:
  486. if name in self.contents:
  487. del self.contents[name]
  488. setlist = getattr(rruleset, '_' + name)
  489. if name in DATENAMES:
  490. setlist = list(setlist) # make a copy of the list
  491. if name == 'rdate' and dtstart in setlist:
  492. setlist.remove(dtstart)
  493. if isDate:
  494. setlist = [dt.date() for dt in setlist]
  495. if len(setlist) > 0:
  496. self.add(name).value = setlist
  497. elif name in RULENAMES:
  498. for rule in setlist:
  499. buf = six.StringIO()
  500. buf.write('FREQ=')
  501. buf.write(FREQUENCIES[rule._freq])
  502. values = {}
  503. if rule._interval != 1:
  504. values['INTERVAL'] = [str(rule._interval)]
  505. if rule._wkst != 0: # wkst defaults to Monday
  506. values['WKST'] = [WEEKDAYS[rule._wkst]]
  507. if rule._bysetpos is not None:
  508. values['BYSETPOS'] = [str(i) for i in rule._bysetpos]
  509. if rule._count is not None:
  510. values['COUNT'] = [str(rule._count)]
  511. elif rule._until is not None:
  512. values['UNTIL'] = [untilSerialize(rule._until)]
  513. days = []
  514. if (rule._byweekday is not None and (
  515. rrule.WEEKLY != rule._freq or
  516. len(rule._byweekday) != 1 or
  517. rule._dtstart.weekday() != rule._byweekday[0])):
  518. # ignore byweekday if freq is WEEKLY and day correlates
  519. # with dtstart because it was automatically set by dateutil
  520. days.extend(WEEKDAYS[n] for n in rule._byweekday)
  521. if rule._bynweekday is not None:
  522. days.extend(n + WEEKDAYS[day] for day, n in rule._bynweekday)
  523. if len(days) > 0:
  524. values['BYDAY'] = days
  525. if rule._bymonthday is not None and len(rule._bymonthday) > 0:
  526. if not (rule._freq <= rrule.MONTHLY and
  527. len(rule._bymonthday) == 1 and
  528. rule._bymonthday[0] == rule._dtstart.day):
  529. # ignore bymonthday if it's generated by dateutil
  530. values['BYMONTHDAY'] = [str(n) for n in rule._bymonthday]
  531. if rule._bynmonthday is not None and len(rule._bynmonthday) > 0:
  532. values.setdefault('BYMONTHDAY', []).extend(str(n) for n in rule._bynmonthday)
  533. if rule._bymonth is not None and len(rule._bymonth) > 0:
  534. if (rule._byweekday is not None or
  535. len(rule._bynweekday or ()) > 0 or
  536. not (rule._freq == rrule.YEARLY and
  537. len(rule._bymonth) == 1 and
  538. rule._bymonth[0] == rule._dtstart.month)):
  539. # ignore bymonth if it's generated by dateutil
  540. values['BYMONTH'] = [str(n) for n in rule._bymonth]
  541. if rule._byyearday is not None:
  542. values['BYYEARDAY'] = [str(n) for n in rule._byyearday]
  543. if rule._byweekno is not None:
  544. values['BYWEEKNO'] = [str(n) for n in rule._byweekno]
  545. # byhour, byminute, bysecond are always ignored for now
  546. for key, paramvals in values.items():
  547. buf.write(';')
  548. buf.write(key)
  549. buf.write('=')
  550. buf.write(','.join(paramvals))
  551. self.add(name).value = buf.getvalue()
  552. rruleset = property(getrruleset, setrruleset)
  553. def __setattr__(self, name, value):
  554. """
  555. For convenience, make self.contents directly accessible.
  556. """
  557. if name == 'rruleset':
  558. self.setrruleset(value)
  559. else:
  560. super(RecurringComponent, self).__setattr__(name, value)
  561. class TextBehavior(behavior.Behavior):
  562. """
  563. Provide backslash escape encoding/decoding for single valued properties.
  564. TextBehavior also deals with base64 encoding if the ENCODING parameter is
  565. explicitly set to BASE64.
  566. """
  567. base64string = 'BASE64' # vCard uses B
  568. @classmethod
  569. def decode(cls, line):
  570. """
  571. Remove backslash escaping from line.value.
  572. """
  573. if line.encoded:
  574. encoding = getattr(line, 'encoding_param', None)
  575. if encoding and encoding.upper() == cls.base64string:
  576. line.value = base64.b64decode(line.value)
  577. else:
  578. line.value = stringToTextValues(line.value)[0]
  579. line.encoded = False
  580. @classmethod
  581. def encode(cls, line):
  582. """
  583. Backslash escape line.value.
  584. """
  585. if not line.encoded:
  586. encoding = getattr(line, 'encoding_param', None)
  587. if encoding and encoding.upper() == cls.base64string:
  588. line.value = base64.b64encode(line.value.encode('utf-8')).decode('utf-8').replace('\n', '')
  589. else:
  590. line.value = backslashEscape(line.value)
  591. line.encoded = True
  592. class VCalendarComponentBehavior(behavior.Behavior):
  593. defaultBehavior = TextBehavior
  594. isComponent = True
  595. class RecurringBehavior(VCalendarComponentBehavior):
  596. """
  597. Parent Behavior for components which should be RecurringComponents.
  598. """
  599. hasNative = True
  600. @staticmethod
  601. def transformToNative(obj):
  602. """
  603. Turn a recurring Component into a RecurringComponent.
  604. """
  605. if not obj.isNative:
  606. object.__setattr__(obj, '__class__', RecurringComponent)
  607. obj.isNative = True
  608. return obj
  609. @staticmethod
  610. def transformFromNative(obj):
  611. if obj.isNative:
  612. object.__setattr__(obj, '__class__', Component)
  613. obj.isNative = False
  614. return obj
  615. @staticmethod
  616. def generateImplicitParameters(obj):
  617. """
  618. Generate a UID and DTSTAMP if one does not exist.
  619. This is just a dummy implementation, for now.
  620. """
  621. if not hasattr(obj, 'uid'):
  622. rand = int(random.random() * 100000)
  623. now = datetime.datetime.now(utc)
  624. now = dateTimeToString(now)
  625. host = socket.gethostname()
  626. obj.add(ContentLine('UID', [], "{0} - {1}@{2}".format(now, rand,
  627. host)))
  628. if not hasattr(obj, 'dtstamp'):
  629. now = datetime.datetime.now(utc)
  630. obj.add('dtstamp').value = now
  631. class DateTimeBehavior(behavior.Behavior):
  632. """
  633. Parent Behavior for ContentLines containing one DATE-TIME.
  634. """
  635. hasNative = True
  636. @staticmethod
  637. def transformToNative(obj):
  638. """
  639. Turn obj.value into a datetime.
  640. RFC2445 allows times without time zone information, "floating times"
  641. in some properties. Mostly, this isn't what you want, but when parsing
  642. a file, real floating times are noted by setting to 'TRUE' the
  643. X-VOBJ-FLOATINGTIME-ALLOWED parameter.
  644. """
  645. if obj.isNative:
  646. return obj
  647. obj.isNative = True
  648. if obj.value == '':
  649. return obj
  650. obj.value = obj.value
  651. # we're cheating a little here, parseDtstart allows DATE
  652. obj.value = parseDtstart(obj)
  653. if obj.value.tzinfo is None:
  654. obj.params['X-VOBJ-FLOATINGTIME-ALLOWED'] = ['TRUE']
  655. if obj.params.get('TZID'):
  656. # Keep a copy of the original TZID around
  657. obj.params['X-VOBJ-ORIGINAL-TZID'] = [obj.params['TZID']]
  658. del obj.params['TZID']
  659. return obj
  660. @classmethod
  661. def transformFromNative(cls, obj):
  662. """
  663. Replace the datetime in obj.value with an ISO 8601 string.
  664. """
  665. if obj.isNative:
  666. obj.isNative = False
  667. tzid = TimezoneComponent.registerTzinfo(obj.value.tzinfo)
  668. obj.value = dateTimeToString(obj.value, cls.forceUTC)
  669. if not cls.forceUTC and tzid is not None:
  670. obj.tzid_param = tzid
  671. if obj.params.get('X-VOBJ-ORIGINAL-TZID'):
  672. if not hasattr(obj, 'tzid_param'):
  673. obj.tzid_param = obj.x_vobj_original_tzid_param
  674. del obj.params['X-VOBJ-ORIGINAL-TZID']
  675. return obj
  676. class UTCDateTimeBehavior(DateTimeBehavior):
  677. """
  678. A value which must be specified in UTC.
  679. """
  680. forceUTC = True
  681. class DateOrDateTimeBehavior(behavior.Behavior):
  682. """
  683. Parent Behavior for ContentLines containing one DATE or DATE-TIME.
  684. """
  685. hasNative = True
  686. @staticmethod
  687. def transformToNative(obj):
  688. """
  689. Turn obj.value into a date or datetime.
  690. """
  691. if obj.isNative:
  692. return obj
  693. obj.isNative = True
  694. if obj.value == '':
  695. return obj
  696. obj.value = obj.value
  697. obj.value = parseDtstart(obj, allowSignatureMismatch=True)
  698. if getattr(obj, 'value_param', 'DATE-TIME').upper() == 'DATE-TIME':
  699. if hasattr(obj, 'tzid_param'):
  700. # Keep a copy of the original TZID around
  701. obj.params['X-VOBJ-ORIGINAL-TZID'] = [obj.tzid_param]
  702. del obj.tzid_param
  703. return obj
  704. @staticmethod
  705. def transformFromNative(obj):
  706. """
  707. Replace the date or datetime in obj.value with an ISO 8601 string.
  708. """
  709. if type(obj.value) == datetime.date:
  710. obj.isNative = False
  711. obj.value_param = 'DATE'
  712. obj.value = dateToString(obj.value)
  713. return obj
  714. else:
  715. return DateTimeBehavior.transformFromNative(obj)
  716. class MultiDateBehavior(behavior.Behavior):
  717. """
  718. Parent Behavior for ContentLines containing one or more DATE, DATE-TIME, or
  719. PERIOD.
  720. """
  721. hasNative = True
  722. @staticmethod
  723. def transformToNative(obj):
  724. """
  725. Turn obj.value into a list of dates, datetimes, or
  726. (datetime, timedelta) tuples.
  727. """
  728. if obj.isNative:
  729. return obj
  730. obj.isNative = True
  731. if obj.value == '':
  732. obj.value = []
  733. return obj
  734. tzinfo = getTzid(getattr(obj, 'tzid_param', None))
  735. valueParam = getattr(obj, 'value_param', "DATE-TIME").upper()
  736. valTexts = obj.value.split(",")
  737. if valueParam == "DATE":
  738. obj.value = [stringToDate(x) for x in valTexts]
  739. elif valueParam == "DATE-TIME":
  740. obj.value = [stringToDateTime(x, tzinfo) for x in valTexts]
  741. elif valueParam == "PERIOD":
  742. obj.value = [stringToPeriod(x, tzinfo) for x in valTexts]
  743. return obj
  744. @staticmethod
  745. def transformFromNative(obj):
  746. """
  747. Replace the date, datetime or period tuples in obj.value with
  748. appropriate strings.
  749. """
  750. if obj.value and type(obj.value[0]) == datetime.date:
  751. obj.isNative = False
  752. obj.value_param = 'DATE'
  753. obj.value = ','.join([dateToString(val) for val in obj.value])
  754. return obj
  755. # Fixme: handle PERIOD case
  756. else:
  757. if obj.isNative:
  758. obj.isNative = False
  759. transformed = []
  760. tzid = None
  761. for val in obj.value:
  762. if tzid is None and type(val) == datetime.datetime:
  763. tzid = TimezoneComponent.registerTzinfo(val.tzinfo)
  764. if tzid is not None:
  765. obj.tzid_param = tzid
  766. transformed.append(dateTimeToString(val))
  767. obj.value = ','.join(transformed)
  768. return obj
  769. class MultiTextBehavior(behavior.Behavior):
  770. """
  771. Provide backslash escape encoding/decoding of each of several values.
  772. After transformation, value is a list of strings.
  773. """
  774. listSeparator = ","
  775. @classmethod
  776. def decode(cls, line):
  777. """
  778. Remove backslash escaping from line.value, then split on commas.
  779. """
  780. if line.encoded:
  781. line.value = stringToTextValues(line.value,
  782. listSeparator=cls.listSeparator)
  783. line.encoded = False
  784. @classmethod
  785. def encode(cls, line):
  786. """
  787. Backslash escape line.value.
  788. """
  789. if not line.encoded:
  790. line.value = cls.listSeparator.join(backslashEscape(val)
  791. for val in line.value)
  792. line.encoded = True
  793. class SemicolonMultiTextBehavior(MultiTextBehavior):
  794. listSeparator = ";"
  795. # ------------------------ Registered Behavior subclasses ----------------------
  796. class VCalendar2_0(VCalendarComponentBehavior):
  797. """
  798. vCalendar 2.0 behavior. With added VAVAILABILITY support.
  799. """
  800. name = 'VCALENDAR'
  801. description = 'vCalendar 2.0, also known as iCalendar.'
  802. versionString = '2.0'
  803. sortFirst = ('version', 'calscale', 'method', 'prodid', 'vtimezone')
  804. knownChildren = {
  805. 'CALSCALE': (0, 1, None), # min, max, behaviorRegistry id
  806. 'METHOD': (0, 1, None),
  807. 'VERSION': (0, 1, None), # required, but auto-generated
  808. 'PRODID': (1, 1, None),
  809. 'VTIMEZONE': (0, None, None),
  810. 'VEVENT': (0, None, None),
  811. 'VTODO': (0, None, None),
  812. 'VJOURNAL': (0, None, None),
  813. 'VFREEBUSY': (0, None, None),
  814. 'VAVAILABILITY': (0, None, None),
  815. }
  816. @classmethod
  817. def generateImplicitParameters(cls, obj):
  818. """
  819. Create PRODID, VERSION and VTIMEZONEs if needed.
  820. VTIMEZONEs will need to exist whenever TZID parameters exist or when
  821. datetimes with tzinfo exist.
  822. """
  823. for comp in obj.components():
  824. if comp.behavior is not None:
  825. comp.behavior.generateImplicitParameters(comp)
  826. if not hasattr(obj, 'prodid'):
  827. obj.add(ContentLine('PRODID', [], PRODID))
  828. if not hasattr(obj, 'version'):
  829. obj.add(ContentLine('VERSION', [], cls.versionString))
  830. tzidsUsed = {}
  831. def findTzids(obj, table):
  832. if isinstance(obj, ContentLine) and (obj.behavior is None or
  833. not obj.behavior.forceUTC):
  834. if getattr(obj, 'tzid_param', None):
  835. table[obj.tzid_param] = 1
  836. else:
  837. if type(obj.value) == list:
  838. for item in obj.value:
  839. tzinfo = getattr(obj.value, 'tzinfo', None)
  840. tzid = TimezoneComponent.registerTzinfo(tzinfo)
  841. if tzid:
  842. table[tzid] = 1
  843. else:
  844. tzinfo = getattr(obj.value, 'tzinfo', None)
  845. tzid = TimezoneComponent.registerTzinfo(tzinfo)
  846. if tzid:
  847. table[tzid] = 1
  848. for child in obj.getChildren():
  849. if obj.name != 'VTIMEZONE':
  850. findTzids(child, table)
  851. findTzids(obj, tzidsUsed)
  852. oldtzids = [toUnicode(x.tzid.value) for x in getattr(obj, 'vtimezone_list', [])]
  853. for tzid in tzidsUsed.keys():
  854. tzid = toUnicode(tzid)
  855. if tzid != u'UTC' and tzid not in oldtzids:
  856. obj.add(TimezoneComponent(tzinfo=getTzid(tzid)))
  857. @classmethod
  858. def serialize(cls, obj, buf, lineLength, validate=True):
  859. """
  860. Set implicit parameters, do encoding, return unicode string.
  861. If validate is True, raise VObjectError if the line doesn't validate
  862. after implicit parameters are generated.
  863. Default is to call base.defaultSerialize.
  864. """
  865. cls.generateImplicitParameters(obj)
  866. if validate:
  867. cls.validate(obj, raiseException=True)
  868. if obj.isNative:
  869. transformed = obj.transformFromNative()
  870. undoTransform = True
  871. else:
  872. transformed = obj
  873. undoTransform = False
  874. out = None
  875. outbuf = buf or six.StringIO()
  876. if obj.group is None:
  877. groupString = ''
  878. else:
  879. groupString = obj.group + '.'
  880. if obj.useBegin:
  881. foldOneLine(outbuf, "{0}BEGIN:{1}".format(groupString, obj.name),
  882. lineLength)
  883. try:
  884. first_props = [s for s in cls.sortFirst if s in obj.contents \
  885. and not isinstance(obj.contents[s][0], Component)]
  886. first_components = [s for s in cls.sortFirst if s in obj.contents \
  887. and isinstance(obj.contents[s][0], Component)]
  888. except Exception:
  889. first_props = first_components = []
  890. # first_components = []
  891. prop_keys = sorted(list(k for k in obj.contents.keys() if k not in first_props \
  892. and not isinstance(obj.contents[k][0], Component)))
  893. comp_keys = sorted(list(k for k in obj.contents.keys() if k not in first_components \
  894. and isinstance(obj.contents[k][0], Component)))
  895. sorted_keys = first_props + prop_keys + first_components + comp_keys
  896. children = [o for k in sorted_keys for o in obj.contents[k]]
  897. for child in children:
  898. # validate is recursive, we only need to validate once
  899. child.serialize(outbuf, lineLength, validate=False)
  900. if obj.useBegin:
  901. foldOneLine(outbuf, "{0}END:{1}".format(groupString, obj.name),
  902. lineLength)
  903. out = buf or outbuf.getvalue()
  904. if undoTransform:
  905. obj.transformToNative()
  906. return out
  907. registerBehavior(VCalendar2_0)
  908. class VTimezone(VCalendarComponentBehavior):
  909. """
  910. Timezone behavior.
  911. """
  912. name = 'VTIMEZONE'
  913. hasNative = True
  914. description = 'A grouping of component properties that defines a time zone.'
  915. sortFirst = ('tzid', 'last-modified', 'tzurl', 'standard', 'daylight')
  916. knownChildren = {
  917. 'TZID': (1, 1, None), # min, max, behaviorRegistry id
  918. 'LAST-MODIFIED': (0, 1, None),
  919. 'TZURL': (0, 1, None),
  920. 'STANDARD': (0, None, None), # NOTE: One of Standard or
  921. 'DAYLIGHT': (0, None, None) # Daylight must appear
  922. }
  923. @classmethod
  924. def validate(cls, obj, raiseException, *args):
  925. if not hasattr(obj, 'tzid') or obj.tzid.value is None:
  926. if raiseException:
  927. m = "VTIMEZONE components must contain a valid TZID"
  928. raise ValidateError(m)
  929. return False
  930. if 'standard' in obj.contents or 'daylight' in obj.contents:
  931. return super(VTimezone, cls).validate(obj, raiseException, *args)
  932. else:
  933. if raiseException:
  934. m = "VTIMEZONE components must contain a STANDARD or a DAYLIGHT\
  935. component"
  936. raise ValidateError(m)
  937. return False
  938. @staticmethod
  939. def transformToNative(obj):
  940. if not obj.isNative:
  941. object.__setattr__(obj, '__class__', TimezoneComponent)
  942. obj.isNative = True
  943. obj.registerTzinfo(obj.tzinfo)
  944. return obj
  945. @staticmethod
  946. def transformFromNative(obj):
  947. return obj
  948. registerBehavior(VTimezone)
  949. class TZID(behavior.Behavior):
  950. """
  951. Don't use TextBehavior for TZID.
  952. RFC2445 only allows TZID lines to be paramtext, so they shouldn't need any
  953. encoding or decoding. Unfortunately, some Microsoft products use commas
  954. in TZIDs which should NOT be treated as a multi-valued text property, nor
  955. do we want to escape them. Leaving them alone works for Microsoft's breakage,
  956. and doesn't affect compliant iCalendar streams.
  957. """
  958. registerBehavior(TZID)
  959. class DaylightOrStandard(VCalendarComponentBehavior):
  960. hasNative = False
  961. knownChildren = {'DTSTART': (1, 1, None), # min, max, behaviorRegistry id
  962. 'RRULE': (0, 1, None)}
  963. registerBehavior(DaylightOrStandard, 'STANDARD')
  964. registerBehavior(DaylightOrStandard, 'DAYLIGHT')
  965. class VEvent(RecurringBehavior):
  966. """
  967. Event behavior.
  968. """
  969. name = 'VEVENT'
  970. sortFirst = ('uid', 'recurrence-id', 'dtstart', 'duration', 'dtend')
  971. description = 'A grouping of component properties, and possibly including \
  972. "VALARM" calendar components, that represents a scheduled \
  973. amount of time on a calendar.'
  974. knownChildren = {
  975. 'DTSTART': (0, 1, None), # min, max, behaviorRegistry id
  976. 'CLASS': (0, 1, None),
  977. 'CREATED': (0, 1, None),
  978. 'DESCRIPTION': (0, 1, None),
  979. 'GEO': (0, 1, None),
  980. 'LAST-MODIFIED': (0, 1, None),
  981. 'LOCATION': (0, 1, None),
  982. 'ORGANIZER': (0, 1, None),
  983. 'PRIORITY': (0, 1, None),
  984. 'DTSTAMP': (1, 1, None), # required
  985. 'SEQUENCE': (0, 1, None),
  986. 'STATUS': (0, 1, None),
  987. 'SUMMARY': (0, 1, None),
  988. 'TRANSP': (0, 1, None),
  989. 'UID': (1, 1, None),
  990. 'URL': (0, 1, None),
  991. 'RECURRENCE-ID': (0, 1, None),
  992. 'DTEND': (0, 1, None), # NOTE: Only one of DtEnd or
  993. 'DURATION': (0, 1, None), # Duration can appear
  994. 'ATTACH': (0, None, None),
  995. 'ATTENDEE': (0, None, None),
  996. 'CATEGORIES': (0, None, None),
  997. 'COMMENT': (0, None, None),
  998. 'CONTACT': (0, None, None),
  999. 'EXDATE': (0, None, None),
  1000. 'EXRULE': (0, None, None),
  1001. 'REQUEST-STATUS': (0, None, None),
  1002. 'RELATED-TO': (0, None, None),
  1003. 'RESOURCES': (0, None, None),
  1004. 'RDATE': (0, None, None),
  1005. 'RRULE': (0, None, None),
  1006. 'VALARM': (0, None, None)
  1007. }
  1008. @classmethod
  1009. def validate(cls, obj, raiseException, *args):
  1010. if 'dtend' in obj.contents and 'duration' in obj.contents:
  1011. if raiseException:
  1012. m = "VEVENT components cannot contain both DTEND and DURATION\
  1013. components"
  1014. raise ValidateError(m)
  1015. return False
  1016. else:
  1017. return super(VEvent, cls).validate(obj, raiseException, *args)
  1018. registerBehavior(VEvent)
  1019. class VTodo(RecurringBehavior):
  1020. """
  1021. To-do behavior.
  1022. """
  1023. name = 'VTODO'
  1024. description = 'A grouping of component properties and possibly "VALARM" \
  1025. calendar components that represent an action-item or \
  1026. assignment.'
  1027. knownChildren = {
  1028. 'DTSTART': (0, 1, None), # min, max, behaviorRegistry id
  1029. 'CLASS': (0, 1, None),
  1030. 'COMPLETED': (0, 1, None),
  1031. 'CREATED': (0, 1, None),
  1032. 'DESCRIPTION': (0, 1, None),
  1033. 'GEO': (0, 1, None),
  1034. 'LAST-MODIFIED': (0, 1, None),
  1035. 'LOCATION': (0, 1, None),
  1036. 'ORGANIZER': (0, 1, None),
  1037. 'PERCENT': (0, 1, None),
  1038. 'PRIORITY': (0, 1, None),
  1039. 'DTSTAMP': (1, 1, None),
  1040. 'SEQUENCE': (0, 1, None),
  1041. 'STATUS': (0, 1, None),
  1042. 'SUMMARY': (0, 1, None),
  1043. 'UID': (0, 1, None),
  1044. 'URL': (0, 1, None),
  1045. 'RECURRENCE-ID': (0, 1, None),
  1046. 'DUE': (0, 1, None), # NOTE: Only one of Due or
  1047. 'DURATION': (0, 1, None), # Duration can appear
  1048. 'ATTACH': (0, None, None),
  1049. 'ATTENDEE': (0, None, None),
  1050. 'CATEGORIES': (0, None, None),
  1051. 'COMMENT': (0, None, None),
  1052. 'CONTACT': (0, None, None),
  1053. 'EXDATE': (0, None, None),
  1054. 'EXRULE': (0, None, None),
  1055. 'REQUEST-STATUS': (0, None, None),
  1056. 'RELATED-TO': (0, None, None),
  1057. 'RESOURCES': (0, None, None),
  1058. 'RDATE': (0, None, None),
  1059. 'RRULE': (0, None, None),
  1060. 'VALARM': (0, None, None)
  1061. }
  1062. @classmethod
  1063. def validate(cls, obj, raiseException, *args):
  1064. if 'due' in obj.contents and 'duration' in obj.contents:
  1065. if raiseException:
  1066. m = "VTODO components cannot contain both DUE and DURATION\
  1067. components"
  1068. raise ValidateError(m)
  1069. return False
  1070. else:
  1071. return super(VTodo, cls).validate(obj, raiseException, *args)
  1072. registerBehavior(VTodo)
  1073. class VJournal(RecurringBehavior):
  1074. """
  1075. Journal entry behavior.
  1076. """
  1077. name = 'VJOURNAL'
  1078. knownChildren = {
  1079. 'DTSTART': (0, 1, None), # min, max, behaviorRegistry id
  1080. 'CLASS': (0, 1, None),
  1081. 'CREATED': (0, 1, None),
  1082. 'DESCRIPTION': (0, 1, None),
  1083. 'LAST-MODIFIED': (0, 1, None),
  1084. 'ORGANIZER': (0, 1, None),
  1085. 'DTSTAMP': (1, 1, None),
  1086. 'SEQUENCE': (0, 1, None),
  1087. 'STATUS': (0, 1, None),
  1088. 'SUMMARY': (0, 1, None),
  1089. 'UID': (0, 1, None),
  1090. 'URL': (0, 1, None),
  1091. 'RECURRENCE-ID': (0, 1, None),
  1092. 'ATTACH': (0, None, None),
  1093. 'ATTENDEE': (0, None, None),
  1094. 'CATEGORIES': (0, None, None),
  1095. 'COMMENT': (0, None, None),
  1096. 'CONTACT': (0, None, None),
  1097. 'EXDATE': (0, None, None),
  1098. 'EXRULE': (0, None, None),
  1099. 'REQUEST-STATUS': (0, None, None),
  1100. 'RELATED-TO': (0, None, None),
  1101. 'RDATE': (0, None, None),
  1102. 'RRULE': (0, None, None)
  1103. }
  1104. registerBehavior(VJournal)
  1105. class VFreeBusy(VCalendarComponentBehavior):
  1106. """
  1107. Free/busy state behavior.
  1108. """
  1109. name = 'VFREEBUSY'
  1110. description = 'A grouping of component properties that describe either a \
  1111. request for free/busy time, describe a response to a request \
  1112. for free/busy time or describe a published set of busy time.'
  1113. sortFirst = ('uid', 'dtstart', 'duration', 'dtend')
  1114. knownChildren = {
  1115. 'DTSTART': (0, 1, None), # min, max, behaviorRegistry id
  1116. 'CONTACT': (0, 1, None),
  1117. 'DTEND': (0, 1, None),
  1118. 'DURATION': (0, 1, None),
  1119. 'ORGANIZER': (0, 1, None),
  1120. 'DTSTAMP': (1, 1, None),
  1121. 'UID': (0, 1, None),
  1122. 'URL': (0, 1, None),
  1123. 'ATTENDEE': (0, None, None),
  1124. 'COMMENT': (0, None, None),
  1125. 'FREEBUSY': (0, None, None),
  1126. 'REQUEST-STATUS': (0, None, None)
  1127. }
  1128. registerBehavior(VFreeBusy)
  1129. class VAlarm(VCalendarComponentBehavior):
  1130. """
  1131. Alarm behavior.
  1132. """
  1133. name = 'VALARM'
  1134. description = 'Alarms describe when and how to provide alerts about events \
  1135. and to-dos.'
  1136. knownChildren = {
  1137. 'ACTION': (1, 1, None), # min, max, behaviorRegistry id
  1138. 'TRIGGER': (1, 1, None),
  1139. 'DURATION': (0, 1, None),
  1140. 'REPEAT': (0, 1, None),
  1141. 'DESCRIPTION': (0, 1, None)
  1142. }
  1143. @staticmethod
  1144. def generateImplicitParameters(obj):
  1145. """
  1146. Create default ACTION and TRIGGER if they're not set.
  1147. """
  1148. try:
  1149. obj.action
  1150. except AttributeError:
  1151. obj.add('action').value = 'AUDIO'
  1152. try:
  1153. obj.trigger
  1154. except AttributeError:
  1155. obj.add('trigger').value = datetime.timedelta(0)
  1156. @classmethod
  1157. def validate(cls, obj, raiseException, *args):
  1158. """
  1159. # TODO
  1160. if obj.contents.has_key('dtend') and obj.contents.has_key('duration'):
  1161. if raiseException:
  1162. m = "VEVENT components cannot contain both DTEND and DURATION\
  1163. components"
  1164. raise ValidateError(m)
  1165. return False
  1166. else:
  1167. return super(VEvent, cls).validate(obj, raiseException, *args)
  1168. """
  1169. return True
  1170. registerBehavior(VAlarm)
  1171. class VAvailability(VCalendarComponentBehavior):
  1172. """
  1173. Availability state behavior.
  1174. Used to represent user's available time slots.
  1175. """
  1176. name = 'VAVAILABILITY'
  1177. description = 'A component used to represent a user\'s available time slots.'
  1178. sortFirst = ('uid', 'dtstart', 'duration', 'dtend')
  1179. knownChildren = {
  1180. 'UID': (1, 1, None), # min, max, behaviorRegistry id
  1181. 'DTSTAMP': (1, 1, None),
  1182. 'BUSYTYPE': (0, 1, None),
  1183. 'CREATED': (0, 1, None),
  1184. 'DTSTART': (0, 1, None),
  1185. 'LAST-MODIFIED': (0, 1, None),
  1186. 'ORGANIZER': (0, 1, None),
  1187. 'SEQUENCE': (0, 1, None),
  1188. 'SUMMARY': (0, 1, None),
  1189. 'URL': (0, 1, None),
  1190. 'DTEND': (0, 1, None),
  1191. 'DURATION': (0, 1, None),
  1192. 'CATEGORIES': (0, None, None),
  1193. 'COMMENT': (0, None, None),
  1194. 'CONTACT': (0, None, None),
  1195. 'AVAILABLE': (0, None, None),
  1196. }
  1197. @classmethod
  1198. def validate(cls, obj, raiseException, *args):
  1199. if 'dtend' in obj.contents and 'duration' in obj.contents:
  1200. if raiseException:
  1201. m = "VAVAILABILITY components cannot contain both DTEND and DURATION components"
  1202. raise ValidateError(m)
  1203. return False
  1204. else:
  1205. return super(VAvailability, cls).validate(obj, raiseException, *args)
  1206. registerBehavior(VAvailability)
  1207. class Available(RecurringBehavior):
  1208. """
  1209. Event behavior.
  1210. """
  1211. name = 'AVAILABLE'
  1212. sortFirst = ('uid', 'recurrence-id', 'dtstart', 'duration', 'dtend')
  1213. description = 'Defines a period of time in which a user is normally available.'
  1214. knownChildren = {
  1215. 'DTSTAMP': (1, 1, None), # min, max, behaviorRegistry id
  1216. 'DTSTART': (1, 1, None),
  1217. 'UID': (1, 1, None),
  1218. 'DTEND': (0, 1, None), # NOTE: One of DtEnd or
  1219. 'DURATION': (0, 1, None), # Duration must appear, but not both
  1220. 'CREATED': (0, 1, None),
  1221. 'LAST-MODIFIED': (0, 1, None),
  1222. 'RECURRENCE-ID': (0, 1, None),
  1223. 'RRULE': (0, 1, None),
  1224. 'SUMMARY': (0, 1, None),
  1225. 'CATEGORIES': (0, None, None),
  1226. 'COMMENT': (0, None, None),
  1227. 'CONTACT': (0, None, None),
  1228. 'EXDATE': (0, None, None),
  1229. 'RDATE': (0, None, None),
  1230. }
  1231. @classmethod
  1232. def validate(cls, obj, raiseException, *args):
  1233. has_dtend = 'dtend' in obj.contents
  1234. has_duration = 'duration' in obj.contents
  1235. if has_dtend and has_duration:
  1236. if raiseException:
  1237. m = "AVAILABLE components cannot contain both DTEND and DURATION\
  1238. properties"
  1239. raise ValidateError(m)
  1240. return False
  1241. elif not (has_dtend or has_duration):
  1242. if raiseException:
  1243. m = "AVAILABLE components must contain one of DTEND or DURATION\
  1244. properties"
  1245. raise ValidateError(m)
  1246. return False
  1247. else:
  1248. return super(Available, cls).validate(obj, raiseException, *args)
  1249. registerBehavior(Available)
  1250. class Duration(behavior.Behavior):
  1251. """
  1252. Behavior for Duration ContentLines. Transform to datetime.timedelta.
  1253. """
  1254. name = 'DURATION'
  1255. hasNative = True
  1256. @staticmethod
  1257. def transformToNative(obj):
  1258. """
  1259. Turn obj.value into a datetime.timedelta.
  1260. """
  1261. if obj.isNative:
  1262. return obj
  1263. obj.isNative = True
  1264. obj.value = obj.value
  1265. if obj.value == '':
  1266. return obj
  1267. else:
  1268. deltalist = stringToDurations(obj.value)
  1269. # When can DURATION have multiple durations? For now:
  1270. if len(deltalist) == 1:
  1271. obj.value = deltalist[0]
  1272. return obj
  1273. else:
  1274. raise ParseError("DURATION must have a single duration string.")
  1275. @staticmethod
  1276. def transformFromNative(obj):
  1277. """
  1278. Replace the datetime.timedelta in obj.value with an RFC2445 string.
  1279. """
  1280. if not obj.isNative:
  1281. return obj
  1282. obj.isNative = False
  1283. obj.value = timedeltaToString(obj.value)
  1284. return obj
  1285. registerBehavior(Duration)
  1286. class Trigger(behavior.Behavior):
  1287. """
  1288. DATE-TIME or DURATION
  1289. """
  1290. name = 'TRIGGER'
  1291. description = 'This property specifies when an alarm will trigger.'
  1292. hasNative = True
  1293. forceUTC = True
  1294. @staticmethod
  1295. def transformToNative(obj):
  1296. """
  1297. Turn obj.value into a timedelta or datetime.
  1298. """
  1299. if obj.isNative:
  1300. return obj
  1301. value = getattr(obj, 'value_param', 'DURATION').upper()
  1302. if hasattr(obj, 'value_param'):
  1303. del obj.value_param
  1304. if obj.value == '':
  1305. obj.isNative = True
  1306. return obj
  1307. elif value == 'DURATION':
  1308. try:
  1309. return Duration.transformToNative(obj)
  1310. except ParseError:
  1311. logger.warning("TRIGGER not recognized as DURATION, trying "
  1312. "DATE-TIME, because iCal sometimes exports "
  1313. "DATE-TIMEs without setting VALUE=DATE-TIME")
  1314. try:
  1315. obj.isNative = False
  1316. dt = DateTimeBehavior.transformToNative(obj)
  1317. return dt
  1318. except:
  1319. msg = "TRIGGER with no VALUE not recognized as DURATION " \
  1320. "or as DATE-TIME"
  1321. raise ParseError(msg)
  1322. elif value == 'DATE-TIME':
  1323. # TRIGGERs with DATE-TIME values must be in UTC, we could validate
  1324. # that fact, for now we take it on faith.
  1325. return DateTimeBehavior.transformToNative(obj)
  1326. else:
  1327. raise ParseError("VALUE must be DURATION or DATE-TIME")
  1328. @staticmethod
  1329. def transformFromNative(obj):
  1330. if type(obj.value) == datetime.datetime:
  1331. obj.value_param = 'DATE-TIME'
  1332. return UTCDateTimeBehavior.transformFromNative(obj)
  1333. elif type(obj.value) == datetime.timedelta:
  1334. return Duration.transformFromNative(obj)
  1335. else:
  1336. raise NativeError("Native TRIGGER values must be timedelta or "
  1337. "datetime")
  1338. registerBehavior(Trigger)
  1339. class PeriodBehavior(behavior.Behavior):
  1340. """
  1341. A list of (date-time, timedelta) tuples.
  1342. """
  1343. hasNative = True
  1344. @staticmethod
  1345. def transformToNative(obj):
  1346. """
  1347. Convert comma separated periods into tuples.
  1348. """
  1349. if obj.isNative:
  1350. return obj
  1351. obj.isNative = True
  1352. if obj.value == '':
  1353. obj.value = []
  1354. return obj
  1355. tzinfo = getTzid(getattr(obj, 'tzid_param', None))
  1356. obj.value = [stringToPeriod(x, tzinfo) for x in obj.value.split(",")]
  1357. return obj
  1358. @classmethod
  1359. def transformFromNative(cls, obj):
  1360. """
  1361. Convert the list of tuples in obj.value to strings.
  1362. """
  1363. if obj.isNative:
  1364. obj.isNative = False
  1365. transformed = []
  1366. for tup in obj.value:
  1367. transformed.append(periodToString(tup, cls.forceUTC))
  1368. if len(transformed) > 0:
  1369. tzid = TimezoneComponent.registerTzinfo(tup[0].tzinfo)
  1370. if not cls.forceUTC and tzid is not None:
  1371. obj.tzid_param = tzid
  1372. obj.value = ','.join(transformed)
  1373. return obj
  1374. class FreeBusy(PeriodBehavior):
  1375. """
  1376. Free or busy period of time, must be specified in UTC.
  1377. """
  1378. name = 'FREEBUSY'
  1379. forceUTC = True
  1380. registerBehavior(FreeBusy, 'FREEBUSY')
  1381. class RRule(behavior.Behavior):
  1382. """
  1383. Dummy behavior to avoid having RRULEs being treated as text lines (and thus
  1384. having semi-colons inaccurately escaped).
  1385. """
  1386. registerBehavior(RRule, 'RRULE')
  1387. registerBehavior(RRule, 'EXRULE')
  1388. # ------------------------ Registration of common classes ----------------------
  1389. utcDateTimeList = ['LAST-MODIFIED', 'CREATED', 'COMPLETED', 'DTSTAMP']
  1390. list(map(lambda x: registerBehavior(UTCDateTimeBehavior, x), utcDateTimeList))
  1391. dateTimeOrDateList = ['DTEND', 'DTSTART', 'DUE', 'RECURRENCE-ID']
  1392. list(map(lambda x: registerBehavior(DateOrDateTimeBehavior, x),
  1393. dateTimeOrDateList))
  1394. registerBehavior(MultiDateBehavior, 'RDATE')
  1395. registerBehavior(MultiDateBehavior, 'EXDATE')
  1396. textList = ['CALSCALE', 'METHOD', 'PRODID', 'CLASS', 'COMMENT', 'DESCRIPTION',
  1397. 'LOCATION', 'STATUS', 'SUMMARY', 'TRANSP', 'CONTACT', 'RELATED-TO',
  1398. 'UID', 'ACTION', 'BUSYTYPE']
  1399. list(map(lambda x: registerBehavior(TextBehavior, x), textList))
  1400. list(map(lambda x: registerBehavior(MultiTextBehavior, x), ['CATEGORIES',
  1401. 'RESOURCES']))
  1402. registerBehavior(SemicolonMultiTextBehavior, 'REQUEST-STATUS')
  1403. # ------------------------ Serializing helper functions ------------------------
  1404. def numToDigits(num, places):
  1405. """
  1406. Helper, for converting numbers to textual digits.
  1407. """
  1408. s = str(num)
  1409. if len(s) < places:
  1410. return ("0" * (places - len(s))) + s
  1411. elif len(s) > places:
  1412. return s[len(s)-places:]
  1413. else:
  1414. return s
  1415. def timedeltaToString(delta):
  1416. """
  1417. Convert timedelta to an ical DURATION.
  1418. """
  1419. if delta.days == 0:
  1420. sign = 1
  1421. else:
  1422. sign = delta.days / abs(delta.days)
  1423. delta = abs(delta)
  1424. days = delta.days
  1425. hours = int(delta.seconds / 3600)
  1426. minutes = int((delta.seconds % 3600) / 60)
  1427. seconds = int(delta.seconds % 60)
  1428. output = ''
  1429. if sign == -1:
  1430. output += '-'
  1431. output += 'P'
  1432. if days:
  1433. output += '{}D'.format(days)
  1434. if hours or minutes or seconds:
  1435. output += 'T'
  1436. elif not days: # Deal with zero duration
  1437. output += 'T0S'
  1438. if hours:
  1439. output += '{}H'.format(hours)
  1440. if minutes:
  1441. output += '{}M'.format(minutes)
  1442. if seconds:
  1443. output += '{}S'.format(seconds)
  1444. return output
  1445. def timeToString(dateOrDateTime):
  1446. """
  1447. Wraps dateToString and dateTimeToString, returning the results
  1448. of either based on the type of the argument
  1449. """
  1450. if hasattr(dateOrDateTime, 'hour'):
  1451. return dateTimeToString(dateOrDateTime)
  1452. return dateToString(dateOrDateTime)
  1453. def dateToString(date):
  1454. year = numToDigits(date.year, 4)
  1455. month = numToDigits(date.month, 2)
  1456. day = numToDigits(date.day, 2)
  1457. return year + month + day
  1458. def dateTimeToString(dateTime, convertToUTC=False):
  1459. """
  1460. Ignore tzinfo unless convertToUTC. Output string.
  1461. """
  1462. if dateTime.tzinfo and convertToUTC:
  1463. dateTime = dateTime.astimezone(utc)
  1464. datestr = "{0}{1}{2}T{3}{4}{5}".format(
  1465. numToDigits(dateTime.year, 4),
  1466. numToDigits(dateTime.month, 2),
  1467. numToDigits(dateTime.day, 2),
  1468. numToDigits(dateTime.hour, 2),
  1469. numToDigits(dateTime.minute, 2),
  1470. numToDigits(dateTime.second, 2),
  1471. )
  1472. if tzinfo_eq(dateTime.tzinfo, utc):
  1473. datestr += "Z"
  1474. return datestr
  1475. def deltaToOffset(delta):
  1476. absDelta = abs(delta)
  1477. hours = int(absDelta.seconds / 3600)
  1478. hoursString = numToDigits(hours, 2)
  1479. minutesString = '00'
  1480. if absDelta == delta:
  1481. signString = "+"
  1482. else:
  1483. signString = "-"
  1484. return signString + hoursString + minutesString
  1485. def periodToString(period, convertToUTC=False):
  1486. txtstart = dateTimeToString(period[0], convertToUTC)
  1487. if isinstance(period[1], datetime.timedelta):
  1488. txtend = timedeltaToString(period[1])
  1489. else:
  1490. txtend = dateTimeToString(period[1], convertToUTC)
  1491. return txtstart + "/" + txtend
  1492. # ----------------------- Parsing functions ------------------------------------
  1493. def isDuration(s):
  1494. s = s.upper()
  1495. return (s.find("P") != -1) and (s.find("P") < 2)
  1496. def stringToDate(s):
  1497. year = int(s[0:4])
  1498. month = int(s[4:6])
  1499. day = int(s[6:8])
  1500. return datetime.date(year, month, day)
  1501. def stringToDateTime(s, tzinfo=None):
  1502. """
  1503. Returns datetime.datetime object.
  1504. """
  1505. try:
  1506. year = int(s[0:4])
  1507. month = int(s[4:6])
  1508. day = int(s[6:8])
  1509. hour = int(s[9:11])
  1510. minute = int(s[11:13])
  1511. second = int(s[13:15])
  1512. if len(s) > 15:
  1513. if s[15] == 'Z':
  1514. tzinfo = getTzid('UTC')
  1515. except:
  1516. raise ParseError("'{0!s}' is not a valid DATE-TIME".format(s))
  1517. year = year and year or 2000
  1518. if tzinfo is not None and hasattr(tzinfo,'localize'): # PyTZ case
  1519. return tzinfo.localize(datetime.datetime(year, month, day, hour, minute, second))
  1520. return datetime.datetime(year, month, day, hour, minute, second, 0, tzinfo)
  1521. # DQUOTE included to work around iCal's penchant for backslash escaping it,
  1522. # although it isn't actually supposed to be escaped according to rfc2445 TEXT
  1523. escapableCharList = '\\;,Nn"'
  1524. def stringToTextValues(s, listSeparator=',', charList=None, strict=False):
  1525. """
  1526. Returns list of strings.
  1527. """
  1528. if charList is None:
  1529. charList = escapableCharList
  1530. def escapableChar(c):
  1531. return c in charList
  1532. def error(msg):
  1533. if strict:
  1534. raise ParseError(msg)
  1535. else:
  1536. logging.error(msg)
  1537. # vars which control state machine
  1538. charIterator = enumerate(s)
  1539. state = "read normal"
  1540. current = []
  1541. results = []
  1542. while True:
  1543. try:
  1544. charIndex, char = next(charIterator)
  1545. except:
  1546. char = "eof"
  1547. if state == "read normal":
  1548. if char == '\\':
  1549. state = "read escaped char"
  1550. elif char == listSeparator:
  1551. state = "read normal"
  1552. current = "".join(current)
  1553. results.append(current)
  1554. current = []
  1555. elif char == "eof":
  1556. state = "end"
  1557. else:
  1558. state = "read normal"
  1559. current.append(char)
  1560. elif state == "read escaped char":
  1561. if escapableChar(char):
  1562. state = "read normal"
  1563. if char in 'nN':
  1564. current.append('\n')
  1565. else:
  1566. current.append(char)
  1567. else:
  1568. state = "read normal"
  1569. # leave unrecognized escaped characters for later passes
  1570. current.append('\\' + char)
  1571. elif state == "end": # an end state
  1572. if len(current) or len(results) == 0:
  1573. current = "".join(current)
  1574. results.append(current)
  1575. return results
  1576. elif state == "error": # an end state
  1577. return results
  1578. else:
  1579. state = "error"
  1580. error("unknown state: '{0!s}' reached in {1!s}".format(state, s))
  1581. def stringToDurations(s, strict=False):
  1582. """
  1583. Returns list of timedelta objects.
  1584. """
  1585. def makeTimedelta(sign, week, day, hour, minute, sec):
  1586. if sign == "-":
  1587. sign = -1
  1588. else:
  1589. sign = 1
  1590. week = int(week)
  1591. day = int(day)
  1592. hour = int(hour)
  1593. minute = int(minute)
  1594. sec = int(sec)
  1595. return sign * datetime.timedelta(weeks=week, days=day, hours=hour,
  1596. minutes=minute, seconds=sec)
  1597. def error(msg):
  1598. if strict:
  1599. raise ParseError(msg)
  1600. else:
  1601. raise ParseError(msg)
  1602. # vars which control state machine
  1603. charIterator = enumerate(s)
  1604. state = "start"
  1605. durations = []
  1606. current = ""
  1607. sign = None
  1608. week = 0
  1609. day = 0
  1610. hour = 0
  1611. minute = 0
  1612. sec = 0
  1613. while True:
  1614. try:
  1615. charIndex, char = next(charIterator)
  1616. except:
  1617. char = "eof"
  1618. if state == "start":
  1619. if char == '+':
  1620. state = "start"
  1621. sign = char
  1622. elif char == '-':
  1623. state = "start"
  1624. sign = char
  1625. elif char.upper() == 'P':
  1626. state = "read field"
  1627. elif char == "eof":
  1628. state = "error"
  1629. error("got end-of-line while reading in duration: " + s)
  1630. elif char in string.digits:
  1631. state = "read field"
  1632. current = current + char # update this part when updating "read field"
  1633. else:
  1634. state = "error"
  1635. error("got unexpected character {0} reading in duration: {1}"
  1636. .format(char, s))
  1637. elif state == "read field":
  1638. if (char in string.digits):
  1639. state = "read field"
  1640. current = current + char # update part above when updating "read field"
  1641. elif char.upper() == 'T':
  1642. state = "read field"
  1643. elif char.upper() == 'W':
  1644. state = "read field"
  1645. week = current
  1646. current = ""
  1647. elif char.upper() == 'D':
  1648. state = "read field"
  1649. day = current
  1650. current = ""
  1651. elif char.upper() == 'H':
  1652. state = "read field"
  1653. hour = current
  1654. current = ""
  1655. elif char.upper() == 'M':
  1656. state = "read field"
  1657. minute = current
  1658. current = ""
  1659. elif char.upper() == 'S':
  1660. state = "read field"
  1661. sec = current
  1662. current = ""
  1663. elif char == ",":
  1664. state = "start"
  1665. durations.append(makeTimedelta(sign, week, day, hour, minute,
  1666. sec))
  1667. current = ""
  1668. sign = None
  1669. week = None
  1670. day = None
  1671. hour = None
  1672. minute = None
  1673. sec = None
  1674. elif char == "eof":
  1675. state = "end"
  1676. else:
  1677. state = "error"
  1678. error("got unexpected character reading in duration: " + s)
  1679. elif state == "end": # an end state
  1680. if (sign or week or day or hour or minute or sec):
  1681. durations.append(makeTimedelta(sign, week, day, hour, minute,
  1682. sec))
  1683. return durations
  1684. elif state == "error": # an end state
  1685. error("in error state")
  1686. return durations
  1687. else:
  1688. state = "error"
  1689. error("unknown state: '{0!s}' reached in {1!s}".format(state, s))
  1690. def parseDtstart(contentline, allowSignatureMismatch=False):
  1691. """
  1692. Convert a contentline's value into a date or date-time.
  1693. A variety of clients don't serialize dates with the appropriate VALUE
  1694. parameter, so rather than failing on these (technically invalid) lines,
  1695. if allowSignatureMismatch is True, try to parse both varieties.
  1696. """
  1697. tzinfo = getTzid(getattr(contentline, 'tzid_param', None))
  1698. valueParam = getattr(contentline, 'value_param', 'DATE-TIME').upper()
  1699. if valueParam == "DATE":
  1700. return stringToDate(contentline.value)
  1701. elif valueParam == "DATE-TIME":
  1702. try:
  1703. return stringToDateTime(contentline.value, tzinfo)
  1704. except:
  1705. if allowSignatureMismatch:
  1706. return stringToDate(contentline.value)
  1707. else:
  1708. raise
  1709. def stringToPeriod(s, tzinfo=None):
  1710. values = s.split("/")
  1711. start = stringToDateTime(values[0], tzinfo)
  1712. valEnd = values[1]
  1713. if isDuration(valEnd): # period-start = date-time "/" dur-value
  1714. delta = stringToDurations(valEnd)[0]
  1715. return (start, delta)
  1716. else:
  1717. return (start, stringToDateTime(valEnd, tzinfo))
  1718. def getTransition(transitionTo, year, tzinfo):
  1719. """
  1720. Return the datetime of the transition to/from DST, or None.
  1721. """
  1722. def firstTransition(iterDates, test):
  1723. """
  1724. Return the last date not matching test, or None if all tests matched.
  1725. """
  1726. success = None
  1727. for dt in iterDates:
  1728. if not test(dt):
  1729. success = dt
  1730. else:
  1731. if success is not None:
  1732. return success
  1733. return success # may be None
  1734. def generateDates(year, month=None, day=None):
  1735. """
  1736. Iterate over possible dates with unspecified values.
  1737. """
  1738. months = range(1, 13)
  1739. days = range(1, 32)
  1740. hours = range(0, 24)
  1741. if month is None:
  1742. for month in months:
  1743. yield datetime.datetime(year, month, 1)
  1744. elif day is None:
  1745. for day in days:
  1746. try:
  1747. yield datetime.datetime(year, month, day)
  1748. except ValueError:
  1749. pass
  1750. else:
  1751. for hour in hours:
  1752. yield datetime.datetime(year, month, day, hour)
  1753. assert transitionTo in ('daylight', 'standard')
  1754. if transitionTo == 'daylight':
  1755. def test(dt):
  1756. try:
  1757. return tzinfo.dst(dt) != zeroDelta
  1758. except pytz.NonExistentTimeError:
  1759. return True # entering daylight time
  1760. except pytz.AmbiguousTimeError:
  1761. return False # entering standard time
  1762. elif transitionTo == 'standard':
  1763. def test(dt):
  1764. try:
  1765. return tzinfo.dst(dt) == zeroDelta
  1766. except pytz.NonExistentTimeError:
  1767. return False # entering daylight time
  1768. except pytz.AmbiguousTimeError:
  1769. return True # entering standard time
  1770. newyear = datetime.datetime(year, 1, 1)
  1771. monthDt = firstTransition(generateDates(year), test)
  1772. if monthDt is None:
  1773. return newyear
  1774. elif monthDt.month == 12:
  1775. return None
  1776. else:
  1777. # there was a good transition somewhere in a non-December month
  1778. month = monthDt.month
  1779. day = firstTransition(generateDates(year, month), test).day
  1780. uncorrected = firstTransition(generateDates(year, month, day), test)
  1781. if transitionTo == 'standard':
  1782. # assuming tzinfo.dst returns a new offset for the first
  1783. # possible hour, we need to add one hour for the offset change
  1784. # and another hour because firstTransition returns the hour
  1785. # before the transition
  1786. return uncorrected + datetime.timedelta(hours=2)
  1787. else:
  1788. return uncorrected + datetime.timedelta(hours=1)
  1789. def tzinfo_eq(tzinfo1, tzinfo2, startYear=2000, endYear=2020):
  1790. """
  1791. Compare offsets and DST transitions from startYear to endYear.
  1792. """
  1793. if tzinfo1 == tzinfo2:
  1794. return True
  1795. elif tzinfo1 is None or tzinfo2 is None:
  1796. return False
  1797. def dt_test(dt):
  1798. if dt is None:
  1799. return True
  1800. return tzinfo1.utcoffset(dt) == tzinfo2.utcoffset(dt)
  1801. if not dt_test(datetime.datetime(startYear, 1, 1)):
  1802. return False
  1803. for year in range(startYear, endYear):
  1804. for transitionTo in 'daylight', 'standard':
  1805. t1 = getTransition(transitionTo, year, tzinfo1)
  1806. t2 = getTransition(transitionTo, year, tzinfo2)
  1807. if t1 != t2 or not dt_test(t1):
  1808. return False
  1809. return True
  1810. # ------------------- Testing and running functions ----------------------------
  1811. if __name__ == '__main__':
  1812. import tests
  1813. tests._test()