icalendar.py 73 KB

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