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.
 
 
 
 

2086 regels
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 (VERSION, 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 %s//EN" % VERSION
  32. WEEKDAYS = "MO", "TU", "WE", "TH", "FR", "SA", "SU"
  33. FREQUENCIES = ('YEARLY', 'MONTHLY', 'WEEKLY', 'DAILY', 'HOURLY', 'MINUTELY',
  34. 'SECONDLY')
  35. ZERO_DELTA = 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))
  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(cls, tzinfo):
  99. """
  100. Register tzinfo if it's not already registered, return its tzid.
  101. """
  102. tzid = cls.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 UTC, we don't need a TZID
  290. if tzinfo is None or (not allowUTC and tzinfo_eq(tzinfo, utc)):
  291. return None
  292. # Try pytz 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. if hasattr(tzinfo, '_tzid'):
  300. return toUnicode(tzinfo._tzid)
  301. # Return tzname for standard (non-DST) time
  302. for month in range(1, 13):
  303. dt = datetime.datetime(2000, month, 1)
  304. if tzinfo.dst(dt) == ZERO_DELTA:
  305. return toUnicode(tzinfo.tzname(dt))
  306. # There was no standard time in 2000!
  307. raise VObjectError("Unable to guess TZID for tzinfo {0!s}"
  308. .format(tzinfo))
  309. def __str__(self):
  310. return "<VTIMEZONE | {0}>".format(getattr(self, 'tzid', 'No TZID'))
  311. def __repr__(self):
  312. return self.__str__()
  313. def prettyPrint(self, level, tabwidth):
  314. pre = ' ' * level * tabwidth
  315. print(pre, self.name)
  316. print(pre, "TZID:", self.tzid)
  317. print('')
  318. class RecurringComponent(Component):
  319. """
  320. A vCalendar component like VEVENT or VTODO which may recur.
  321. Any recurring component can have one or multiple RRULE, RDATE,
  322. EXRULE, or EXDATE lines, and one or zero DTSTART lines. It can also have a
  323. variety of children that don't have any recurrence information.
  324. In the example below, note that dtstart is included in the rruleset.
  325. This is not the default behavior for dateutil's rrule implementation unless
  326. dtstart would already have been a member of the recurrence rule, and as a
  327. result, COUNT is wrong. This can be worked around when getting rruleset by
  328. adjusting count down by one if an rrule has a count and dtstart isn't in its
  329. result set, but by default, the rruleset property doesn't do this work
  330. around, to access it getrruleset must be called with addRDate set True.
  331. @ivar rruleset:
  332. A U{rruleset<https://moin.conectiva.com.br/DateUtil>}.
  333. """
  334. def __init__(self, *args, **kwds):
  335. super(RecurringComponent, self).__init__(*args, **kwds)
  336. self.isNative = True
  337. def getrruleset(self, addRDate=False):
  338. """
  339. Get an rruleset created from self.
  340. If addRDate is True, add an RDATE for dtstart if it's not included in
  341. an RRULE or RDATE, and count is decremented if it exists.
  342. Note that for rules which don't match DTSTART, DTSTART may not appear
  343. in list(rruleset), although it should. By default, an RDATE is not
  344. created in these cases, and count isn't updated, so dateutil may list
  345. a spurious occurrence.
  346. """
  347. rruleset = None
  348. for name in DATESANDRULES:
  349. addfunc = None
  350. for line in self.contents.get(name, ()):
  351. # don't bother creating a rruleset unless there's a rule
  352. if rruleset is None:
  353. rruleset = rrule.rruleset()
  354. if addfunc is None:
  355. addfunc = getattr(rruleset, name)
  356. try:
  357. dtstart = self.dtstart.value
  358. except (AttributeError, KeyError):
  359. # Special for VTODO - try DUE property instead
  360. try:
  361. if self.name == "VTODO":
  362. dtstart = self.due.value
  363. else:
  364. # if there's no dtstart, just return None
  365. logging.error('failed to get dtstart with VTODO')
  366. return None
  367. except (AttributeError, KeyError):
  368. # if there's no due, just return None
  369. logging.error('failed to find DUE at all.')
  370. return None
  371. if name in DATENAMES:
  372. if type(line.value[0]) == datetime.datetime:
  373. list(map(addfunc, line.value))
  374. elif type(line.value[0]) == datetime.date:
  375. for dt in line.value:
  376. addfunc(datetime.datetime(dt.year, dt.month, dt.day))
  377. else:
  378. # ignore RDATEs with PERIOD values for now
  379. pass
  380. elif name in RULENAMES:
  381. # a Ruby iCalendar library escapes semi-colons in rrules,
  382. # so also remove any backslashes
  383. value = line.value.replace('\\', '')
  384. # If dtstart has no time zone, `until`
  385. # shouldn't get one, either:
  386. ignoretz = (not isinstance(dtstart, datetime.datetime) or
  387. dtstart.tzinfo is None)
  388. try:
  389. until = rrule.rrulestr(value, ignoretz=ignoretz)._until
  390. except ValueError:
  391. # WORKAROUND: dateutil<=2.7.2 doesn't set the time zone
  392. # of dtstart
  393. if ignoretz:
  394. raise
  395. utc_now = datetime.datetime.now(datetime.timezone.utc)
  396. until = rrule.rrulestr(value, dtstart=utc_now)._until
  397. if until is not None and isinstance(dtstart,
  398. datetime.datetime) and \
  399. (until.tzinfo != dtstart.tzinfo):
  400. # dateutil converts the UNTIL date to a datetime,
  401. # check to see if the UNTIL parameter value was a date
  402. vals = dict(pair.split('=') for pair in
  403. value.upper().split(';'))
  404. if len(vals.get('UNTIL', '')) == 8:
  405. until = datetime.datetime.combine(until.date(),
  406. dtstart.time())
  407. # While RFC2445 says UNTIL MUST be UTC, Chandler allows
  408. # floating recurring events, and uses floating UNTIL
  409. # values. Also, some odd floating UNTIL but timezoned
  410. # DTSTART values have shown up in the wild, so put
  411. # floating UNTIL values DTSTART's timezone
  412. if until.tzinfo is None:
  413. until = until.replace(tzinfo=dtstart.tzinfo)
  414. if dtstart.tzinfo is not None:
  415. until = until.astimezone(dtstart.tzinfo)
  416. # RFC2445 actually states that UNTIL must be a UTC
  417. # value. Whilst the changes above work OK, one problem
  418. # case is if DTSTART is floating but UNTIL is properly
  419. # specified as UTC (or with a TZID). In that case
  420. # dateutil will fail datetime comparisons. There is no
  421. # easy solution to this as there is no obvious timezone
  422. # (at this point) to do proper floating time offset
  423. # comparisons. The best we can do is treat the UNTIL
  424. # value as floating. This could mean incorrect
  425. # determination of the last instance. The better
  426. # solution here is to encourage clients to use COUNT
  427. # rather than UNTIL when DTSTART is floating.
  428. if dtstart.tzinfo is None:
  429. until = until.replace(tzinfo=None)
  430. value_without_until = ';'.join(
  431. pair for pair in value.split(';')
  432. if pair.split('=')[0].upper() != 'UNTIL')
  433. rule = rrule.rrulestr(value_without_until,
  434. dtstart=dtstart, ignoretz=ignoretz)
  435. rule._until = until
  436. # add the rrule or exrule to the rruleset
  437. addfunc(rule)
  438. if (name == 'rrule' or name == 'rdate') and addRDate:
  439. # rlist = rruleset._rrule if name == 'rrule' else rruleset._rdate
  440. try:
  441. # dateutils does not work with all-day
  442. # (datetime.date) items so we need to convert to a
  443. # datetime.datetime (which is what dateutils
  444. # does internally)
  445. if not isinstance(dtstart, datetime.datetime):
  446. adddtstart = datetime.datetime.fromordinal(dtstart.toordinal())
  447. else:
  448. adddtstart = dtstart
  449. if name == 'rrule':
  450. if rruleset._rrule[-1][0] != adddtstart:
  451. rruleset.rdate(adddtstart)
  452. added = True
  453. if rruleset._rrule[-1]._count is not None:
  454. rruleset._rrule[-1]._count -= 1
  455. else:
  456. added = False
  457. elif name == 'rdate':
  458. if rruleset._rdate[0] != adddtstart:
  459. rruleset.rdate(adddtstart)
  460. added = True
  461. else:
  462. added = False
  463. except IndexError:
  464. # it's conceivable that an rrule has 0 datetimes
  465. added = False
  466. return rruleset
  467. def setrruleset(self, rruleset):
  468. # Get DTSTART from component (or DUE if no DTSTART in a VTODO)
  469. try:
  470. dtstart = self.dtstart.value
  471. except (AttributeError, KeyError):
  472. if self.name == "VTODO":
  473. dtstart = self.due.value
  474. else:
  475. raise
  476. isDate = datetime.date == type(dtstart)
  477. if isDate:
  478. dtstart = datetime.datetime(dtstart.year, dtstart.month, dtstart.day)
  479. untilSerialize = dateToString
  480. else:
  481. # make sure to convert time zones to UTC
  482. untilSerialize = lambda x: dateTimeToString(x, True)
  483. for name in DATESANDRULES:
  484. if name in self.contents:
  485. del self.contents[name]
  486. setlist = getattr(rruleset, '_' + name)
  487. if name in DATENAMES:
  488. setlist = list(setlist) # make a copy of the list
  489. if name == 'rdate' and dtstart in setlist:
  490. setlist.remove(dtstart)
  491. if isDate:
  492. setlist = [dt.date() for dt in setlist]
  493. if len(setlist) > 0:
  494. self.add(name).value = setlist
  495. elif name in RULENAMES:
  496. for rule in setlist:
  497. buf = six.StringIO()
  498. buf.write('FREQ=')
  499. buf.write(FREQUENCIES[rule._freq])
  500. values = {}
  501. if rule._interval != 1:
  502. values['INTERVAL'] = [str(rule._interval)]
  503. if rule._wkst != 0: # wkst defaults to Monday
  504. values['WKST'] = [WEEKDAYS[rule._wkst]]
  505. if rule._bysetpos is not None:
  506. values['BYSETPOS'] = [str(i) for i in rule._bysetpos]
  507. if rule._count is not None:
  508. values['COUNT'] = [str(rule._count)]
  509. elif rule._until is not None:
  510. values['UNTIL'] = [untilSerialize(rule._until)]
  511. days = []
  512. if (rule._byweekday is not None and (
  513. rrule.WEEKLY != rule._freq or
  514. len(rule._byweekday) != 1 or
  515. rule._dtstart.weekday() != rule._byweekday[0])):
  516. # ignore byweekday if freq is WEEKLY and day correlates
  517. # with dtstart because it was automatically set by dateutil
  518. days.extend(WEEKDAYS[n] for n in rule._byweekday)
  519. if rule._bynweekday is not None:
  520. days.extend(n + WEEKDAYS[day] for day, n in rule._bynweekday)
  521. if len(days) > 0:
  522. values['BYDAY'] = days
  523. if (rule._bymonthday is not None and
  524. len(rule._bymonthday) > 0 and
  525. not (rule._freq <= rrule.MONTHLY and
  526. len(rule._bymonthday) == 1 and
  527. rule._bymonthday[0] == rule._dtstart.day)):
  528. # ignore bymonthday if it's generated by dateutil
  529. values['BYMONTHDAY'] = [str(n) for n in rule._bymonthday]
  530. if rule._bynmonthday is not None and len(rule._bynmonthday) > 0:
  531. values.setdefault('BYMONTHDAY', []).extend(str(n) for n in rule._bynmonthday)
  532. if (rule._bymonth is not None and
  533. len(rule._bymonth) > 0 and
  534. (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' and
  699. 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[-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. minutes = int(absDelta.seconds / 60) % 60
  1480. minutesString = numToDigits(minutes, 2)
  1481. if absDelta == delta:
  1482. signString = "+"
  1483. else:
  1484. signString = "-"
  1485. return signString + hoursString + minutesString
  1486. def periodToString(period, convertToUTC=False):
  1487. txtstart = dateTimeToString(period[0], convertToUTC)
  1488. if isinstance(period[1], datetime.timedelta):
  1489. txtend = timedeltaToString(period[1])
  1490. else:
  1491. txtend = dateTimeToString(period[1], convertToUTC)
  1492. return txtstart + "/" + txtend
  1493. # ----------------------- Parsing functions ------------------------------------
  1494. def isDuration(s):
  1495. s = s.upper()
  1496. return (s.find("P") != -1) and (s.find("P") < 2)
  1497. def stringToDate(s):
  1498. year = int(s[0:4])
  1499. month = int(s[4:6])
  1500. day = int(s[6:8])
  1501. return datetime.date(year, month, day)
  1502. def stringToDateTime(s, tzinfo=None, strict=False):
  1503. """
  1504. Returns datetime.datetime object.
  1505. """
  1506. if not strict:
  1507. s = s.strip()
  1508. try:
  1509. year = int(s[0:4])
  1510. month = int(s[4:6])
  1511. day = int(s[6:8])
  1512. hour = int(s[9:11])
  1513. minute = int(s[11:13])
  1514. second = int(s[13:15])
  1515. if len(s) > 15 and s[15] == 'Z':
  1516. tzinfo = getTzid('UTC')
  1517. except:
  1518. raise ParseError("'{0!s}' is not a valid DATE-TIME".format(s))
  1519. year = year if year else 2000
  1520. if tzinfo is not None and hasattr(tzinfo,'localize'): # Cater for pytz tzinfo instanes
  1521. return tzinfo.localize(datetime.datetime(year, month, day, hour, minute, second))
  1522. return datetime.datetime(year, month, day, hour, minute, second, 0, tzinfo)
  1523. # DQUOTE included to work around iCal's penchant for backslash escaping it,
  1524. # although it isn't actually supposed to be escaped according to rfc2445 TEXT
  1525. escapableCharList = '\\;,Nn"'
  1526. def stringToTextValues(s, listSeparator=',', charList=None, strict=False):
  1527. """
  1528. Returns list of strings.
  1529. """
  1530. if charList is None:
  1531. charList = escapableCharList
  1532. def escapableChar(c):
  1533. return c in charList
  1534. def error(msg):
  1535. if strict:
  1536. raise ParseError(msg)
  1537. else:
  1538. logging.error(msg)
  1539. # vars which control state machine
  1540. charIterator = enumerate(s)
  1541. state = "read normal"
  1542. current = []
  1543. results = []
  1544. while True:
  1545. try:
  1546. charIndex, char = next(charIterator)
  1547. except:
  1548. char = "eof"
  1549. if state == "read normal":
  1550. if char == '\\':
  1551. state = "read escaped char"
  1552. elif char == listSeparator:
  1553. state = "read normal"
  1554. current = "".join(current)
  1555. results.append(current)
  1556. current = []
  1557. elif char == "eof":
  1558. state = "end"
  1559. else:
  1560. state = "read normal"
  1561. current.append(char)
  1562. elif state == "read escaped char":
  1563. if escapableChar(char):
  1564. state = "read normal"
  1565. if char in 'nN':
  1566. current.append('\n')
  1567. else:
  1568. current.append(char)
  1569. else:
  1570. state = "read normal"
  1571. # leave unrecognized escaped characters for later passes
  1572. current.append('\\' + char)
  1573. elif state == "end": # an end state
  1574. if len(current) or len(results) == 0:
  1575. current = "".join(current)
  1576. results.append(current)
  1577. return results
  1578. elif state == "error": # an end state
  1579. return results
  1580. else:
  1581. state = "error"
  1582. error("unknown state: '{0!s}' reached in {1!s}".format(state, s))
  1583. def stringToDurations(s, strict=False):
  1584. """
  1585. Returns list of timedelta objects.
  1586. """
  1587. def makeTimedelta(sign, week, day, hour, minute, sec):
  1588. if sign == "-":
  1589. sign = -1
  1590. else:
  1591. sign = 1
  1592. week = int(week)
  1593. day = int(day)
  1594. hour = int(hour)
  1595. minute = int(minute)
  1596. sec = int(sec)
  1597. return sign * datetime.timedelta(weeks=week, days=day, hours=hour,
  1598. minutes=minute, seconds=sec)
  1599. def error(msg):
  1600. if strict:
  1601. raise ParseError(msg)
  1602. else:
  1603. raise ParseError(msg)
  1604. # vars which control state machine
  1605. charIterator = enumerate(s)
  1606. state = "start"
  1607. durations = []
  1608. current = ""
  1609. sign = None
  1610. week = 0
  1611. day = 0
  1612. hour = 0
  1613. minute = 0
  1614. sec = 0
  1615. while True:
  1616. try:
  1617. charIndex, char = next(charIterator)
  1618. except:
  1619. char = "eof"
  1620. if state == "start":
  1621. if char == '+':
  1622. state = "start"
  1623. sign = char
  1624. elif char == '-':
  1625. state = "start"
  1626. sign = char
  1627. elif char.upper() == 'P':
  1628. state = "read field"
  1629. elif char == "eof":
  1630. state = "error"
  1631. error("got end-of-line while reading in duration: " + s)
  1632. elif char in string.digits:
  1633. state = "read field"
  1634. current = current + char # update this part when updating "read field"
  1635. else:
  1636. state = "error"
  1637. error("got unexpected character {0} reading in duration: {1}"
  1638. .format(char, s))
  1639. elif state == "read field":
  1640. if (char in string.digits):
  1641. state = "read field"
  1642. current = current + char # update part above when updating "read field"
  1643. elif char.upper() == 'T':
  1644. state = "read field"
  1645. elif char.upper() == 'W':
  1646. state = "read field"
  1647. week = current
  1648. current = ""
  1649. elif char.upper() == 'D':
  1650. state = "read field"
  1651. day = current
  1652. current = ""
  1653. elif char.upper() == 'H':
  1654. state = "read field"
  1655. hour = current
  1656. current = ""
  1657. elif char.upper() == 'M':
  1658. state = "read field"
  1659. minute = current
  1660. current = ""
  1661. elif char.upper() == 'S':
  1662. state = "read field"
  1663. sec = current
  1664. current = ""
  1665. elif char == ",":
  1666. state = "start"
  1667. durations.append(makeTimedelta(sign, week, day, hour, minute,
  1668. sec))
  1669. current = ""
  1670. sign = None
  1671. week = None
  1672. day = None
  1673. hour = None
  1674. minute = None
  1675. sec = None
  1676. elif char == "eof":
  1677. state = "end"
  1678. else:
  1679. state = "error"
  1680. error("got unexpected character reading in duration: " + s)
  1681. elif state == "end": # an end state
  1682. if (sign or week or day or hour or minute or sec):
  1683. durations.append(makeTimedelta(sign, week, day, hour, minute,
  1684. sec))
  1685. return durations
  1686. elif state == "error": # an end state
  1687. error("in error state")
  1688. return durations
  1689. else:
  1690. state = "error"
  1691. error("unknown state: '{0!s}' reached in {1!s}".format(state, s))
  1692. def parseDtstart(contentline, allowSignatureMismatch=False):
  1693. """
  1694. Convert a contentline's value into a date or date-time.
  1695. A variety of clients don't serialize dates with the appropriate VALUE
  1696. parameter, so rather than failing on these (technically invalid) lines,
  1697. if allowSignatureMismatch is True, try to parse both varieties.
  1698. """
  1699. tzinfo = getTzid(getattr(contentline, 'tzid_param', None))
  1700. valueParam = getattr(contentline, 'value_param', 'DATE-TIME').upper()
  1701. if valueParam == "DATE":
  1702. return stringToDate(contentline.value)
  1703. elif valueParam == "DATE-TIME":
  1704. try:
  1705. return stringToDateTime(contentline.value, tzinfo)
  1706. except:
  1707. if allowSignatureMismatch:
  1708. return stringToDate(contentline.value)
  1709. else:
  1710. raise
  1711. def stringToPeriod(s, tzinfo=None):
  1712. values = s.split("/")
  1713. start = stringToDateTime(values[0], tzinfo)
  1714. valEnd = values[1]
  1715. if isDuration(valEnd): # period-start = date-time "/" dur-value
  1716. delta = stringToDurations(valEnd)[0]
  1717. return (start, delta)
  1718. else:
  1719. return (start, stringToDateTime(valEnd, tzinfo))
  1720. def getTransition(transitionTo, year, tzinfo):
  1721. """
  1722. Return the datetime of the transition to/from DST, or None.
  1723. """
  1724. def firstTransition(iterDates, test):
  1725. """
  1726. Return the last date not matching test, or None if all tests matched.
  1727. """
  1728. success = None
  1729. for dt in iterDates:
  1730. if not test(dt):
  1731. success = dt
  1732. else:
  1733. if success is not None:
  1734. return success
  1735. return success # may be None
  1736. def generateDates(year, month=None, day=None):
  1737. """
  1738. Iterate over possible dates with unspecified values.
  1739. """
  1740. months = range(1, 13)
  1741. days = range(1, 32)
  1742. hours = range(0, 24)
  1743. if month is None:
  1744. for month in months:
  1745. yield datetime.datetime(year, month, 1)
  1746. elif day is None:
  1747. for day in days:
  1748. try:
  1749. yield datetime.datetime(year, month, day)
  1750. except ValueError:
  1751. pass
  1752. else:
  1753. for hour in hours:
  1754. yield datetime.datetime(year, month, day, hour)
  1755. assert transitionTo in ('daylight', 'standard')
  1756. if transitionTo == 'daylight':
  1757. def test(dt):
  1758. try:
  1759. return tzinfo.dst(dt) != ZERO_DELTA
  1760. except pytz.NonExistentTimeError:
  1761. return True # entering daylight time
  1762. except pytz.AmbiguousTimeError:
  1763. return False # entering standard time
  1764. elif transitionTo == 'standard':
  1765. def test(dt):
  1766. try:
  1767. return tzinfo.dst(dt) == ZERO_DELTA
  1768. except pytz.NonExistentTimeError:
  1769. return False # entering daylight time
  1770. except pytz.AmbiguousTimeError:
  1771. return True # entering standard time
  1772. newyear = datetime.datetime(year, 1, 1)
  1773. monthDt = firstTransition(generateDates(year), test)
  1774. if monthDt is None:
  1775. return newyear
  1776. elif monthDt.month == 12:
  1777. return None
  1778. else:
  1779. # there was a good transition somewhere in a non-December month
  1780. month = monthDt.month
  1781. day = firstTransition(generateDates(year, month), test).day
  1782. uncorrected = firstTransition(generateDates(year, month, day), test)
  1783. if transitionTo == 'standard':
  1784. # assuming tzinfo.dst returns a new offset for the first
  1785. # possible hour, we need to add one hour for the offset change
  1786. # and another hour because firstTransition returns the hour
  1787. # before the transition
  1788. return uncorrected + datetime.timedelta(hours=2)
  1789. else:
  1790. return uncorrected + datetime.timedelta(hours=1)
  1791. def tzinfo_eq(tzinfo1, tzinfo2, startYear=2000, endYear=2020):
  1792. """
  1793. Compare offsets and DST transitions from startYear to endYear.
  1794. """
  1795. if tzinfo1 == tzinfo2:
  1796. return True
  1797. elif tzinfo1 is None or tzinfo2 is None:
  1798. return False
  1799. def dt_test(dt):
  1800. if dt is None:
  1801. return True
  1802. return tzinfo1.utcoffset(dt) == tzinfo2.utcoffset(dt)
  1803. if not dt_test(datetime.datetime(startYear, 1, 1)):
  1804. return False
  1805. for year in range(startYear, endYear):
  1806. for transitionTo in 'daylight', 'standard':
  1807. t1 = getTransition(transitionTo, year, tzinfo1)
  1808. t2 = getTransition(transitionTo, year, tzinfo2)
  1809. if t1 != t2 or not dt_test(t1):
  1810. return False
  1811. return True
  1812. # ------------------- Testing and running functions ----------------------------
  1813. if __name__ == '__main__':
  1814. import tests
  1815. tests._test()