__init__.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. # This file is part of Radicale - CalDAV and CardDAV server
  2. # Copyright © 2008 Nicolas Kandel
  3. # Copyright © 2008 Pascal Halter
  4. # Copyright © 2014 Jean-Marc Martins
  5. # Copyright © 2008-2017 Guillaume Ayoub
  6. # Copyright © 2017-2018 Unrud <unrud@outlook.com>
  7. #
  8. # This library is free software: you can redistribute it and/or modify
  9. # it under the terms of the GNU General Public License as published by
  10. # the Free Software Foundation, either version 3 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # This library is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License
  19. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  20. """
  21. Module for address books and calendar entries (see ``Item``).
  22. """
  23. import binascii
  24. import contextlib
  25. import math
  26. import os
  27. import sys
  28. from datetime import datetime, timedelta
  29. from hashlib import sha256
  30. from itertools import chain
  31. from typing import (Any, Callable, List, MutableMapping, Optional, Sequence,
  32. Tuple)
  33. import vobject
  34. from radicale import storage # noqa:F401
  35. from radicale import pathutils
  36. from radicale.item import filter as radicale_filter
  37. from radicale.log import logger
  38. def predict_tag_of_parent_collection(
  39. vobject_items: Sequence[vobject.base.Component]) -> Optional[str]:
  40. """Returns the predicted tag or `None`"""
  41. if len(vobject_items) != 1:
  42. return None
  43. if vobject_items[0].name == "VCALENDAR":
  44. return "VCALENDAR"
  45. if vobject_items[0].name in ("VCARD", "VLIST"):
  46. return "VADDRESSBOOK"
  47. return None
  48. def predict_tag_of_whole_collection(
  49. vobject_items: Sequence[vobject.base.Component],
  50. fallback_tag: Optional[str] = None) -> Optional[str]:
  51. """Returns the predicted tag or `fallback_tag`"""
  52. if vobject_items and vobject_items[0].name == "VCALENDAR":
  53. return "VCALENDAR"
  54. if vobject_items and vobject_items[0].name in ("VCARD", "VLIST"):
  55. return "VADDRESSBOOK"
  56. if not fallback_tag and not vobject_items:
  57. # Maybe an empty address book
  58. return "VADDRESSBOOK"
  59. return fallback_tag
  60. def check_and_sanitize_items(
  61. vobject_items: List[vobject.base.Component],
  62. is_collection: bool = False, tag: str = "") -> None:
  63. """Check vobject items for common errors and add missing UIDs.
  64. Modifies the list `vobject_items`.
  65. ``is_collection`` indicates that vobject_item contains unrelated
  66. components.
  67. The ``tag`` of the collection.
  68. """
  69. if tag and tag not in ("VCALENDAR", "VADDRESSBOOK"):
  70. raise ValueError("Unsupported collection tag: %r" % tag)
  71. if not is_collection and len(vobject_items) != 1:
  72. raise ValueError("Item contains %d components" % len(vobject_items))
  73. if tag == "VCALENDAR":
  74. if len(vobject_items) > 1:
  75. raise RuntimeError("VCALENDAR collection contains %d "
  76. "components" % len(vobject_items))
  77. vobject_item = vobject_items[0]
  78. if vobject_item.name != "VCALENDAR":
  79. raise ValueError("Item type %r not supported in %r "
  80. "collection" % (vobject_item.name, tag))
  81. component_uids = set()
  82. for component in vobject_item.components():
  83. if component.name in ("VTODO", "VEVENT", "VJOURNAL"):
  84. component_uid = get_uid(component)
  85. if component_uid:
  86. component_uids.add(component_uid)
  87. component_name = None
  88. object_uid = None
  89. object_uid_set = False
  90. for component in vobject_item.components():
  91. # https://tools.ietf.org/html/rfc4791#section-4.1
  92. if component.name == "VTIMEZONE":
  93. continue
  94. if component_name is None or is_collection:
  95. component_name = component.name
  96. elif component_name != component.name:
  97. raise ValueError("Multiple component types in object: %r, %r" %
  98. (component_name, component.name))
  99. if component_name not in ("VTODO", "VEVENT", "VJOURNAL"):
  100. continue
  101. component_uid = get_uid(component)
  102. if not object_uid_set or is_collection:
  103. object_uid_set = True
  104. object_uid = component_uid
  105. if not component_uid:
  106. if not is_collection:
  107. raise ValueError("%s component without UID in object" %
  108. component_name)
  109. component_uid = find_available_uid(
  110. component_uids.__contains__)
  111. component_uids.add(component_uid)
  112. if hasattr(component, "uid"):
  113. component.uid.value = component_uid
  114. else:
  115. component.add("UID").value = component_uid
  116. elif not object_uid or not component_uid:
  117. raise ValueError("Multiple %s components without UID in "
  118. "object" % component_name)
  119. elif object_uid != component_uid:
  120. raise ValueError(
  121. "Multiple %s components with different UIDs in object: "
  122. "%r, %r" % (component_name, object_uid, component_uid))
  123. # Workaround for bug in Lightning (Thunderbird)
  124. # Rescheduling a single occurrence from a repeating event creates
  125. # an event with DTEND and DURATION:PT0S
  126. if (hasattr(component, "dtend") and
  127. hasattr(component, "duration") and
  128. component.duration.value == timedelta(0)):
  129. logger.debug("Quirks: Removing zero duration from %s in "
  130. "object %r", component_name, component_uid)
  131. del component.duration
  132. # Workaround for Evolution
  133. # EXDATE has value DATE even if DTSTART/DTEND is DATE-TIME.
  134. # The RFC is vaguely formulated on the issue.
  135. # To resolve the issue convert EXDATE and RDATE to
  136. # the same type as DTDSTART
  137. if hasattr(component, "dtstart"):
  138. ref_date = component.dtstart.value
  139. ref_value_param = component.dtstart.params.get("VALUE")
  140. for dates in chain(component.contents.get("exdate", []),
  141. component.contents.get("rdate", [])):
  142. replace_value_param = False
  143. for i, date in enumerate(dates.value):
  144. if type(date) != type(ref_date):
  145. replace_value_param = True
  146. dates.value[i] = ref_date.replace(
  147. date.year, date.month, date.day)
  148. if replace_value_param:
  149. if ref_value_param is None:
  150. with contextlib.suppress(KeyError):
  151. del dates.params["VALUE"]
  152. else:
  153. dates.params["VALUE"] = ref_value_param
  154. # vobject interprets recurrence rules on demand
  155. try:
  156. component.rruleset
  157. except Exception as e:
  158. raise ValueError("Invalid recurrence rules in %s in object %r"
  159. % (component.name, component_uid)) from e
  160. elif tag == "VADDRESSBOOK":
  161. # https://tools.ietf.org/html/rfc6352#section-5.1
  162. object_uids = set()
  163. for vobject_item in vobject_items:
  164. if vobject_item.name == "VCARD":
  165. object_uid = get_uid(vobject_item)
  166. if object_uid:
  167. object_uids.add(object_uid)
  168. for vobject_item in vobject_items:
  169. if vobject_item.name == "VLIST":
  170. # Custom format used by SOGo Connector to store lists of
  171. # contacts
  172. continue
  173. if vobject_item.name != "VCARD":
  174. raise ValueError("Item type %r not supported in %r "
  175. "collection" % (vobject_item.name, tag))
  176. object_uid = get_uid(vobject_item)
  177. if not object_uid:
  178. if not is_collection:
  179. raise ValueError("%s object without UID" %
  180. vobject_item.name)
  181. object_uid = find_available_uid(object_uids.__contains__)
  182. object_uids.add(object_uid)
  183. if hasattr(vobject_item, "uid"):
  184. vobject_item.uid.value = object_uid
  185. else:
  186. vobject_item.add("UID").value = object_uid
  187. else:
  188. for item in vobject_items:
  189. raise ValueError("Item type %r not supported in %s collection" %
  190. (item.name, repr(tag) if tag else "generic"))
  191. def check_and_sanitize_props(props: MutableMapping[Any, Any]
  192. ) -> MutableMapping[str, str]:
  193. """Check collection properties for common errors.
  194. Modifies the dict `props`.
  195. """
  196. for k, v in list(props.items()): # Make copy to be able to delete items
  197. if not isinstance(k, str):
  198. raise ValueError("Key must be %r not %r: %r" % (
  199. str.__name__, type(k).__name__, k))
  200. if not isinstance(v, str):
  201. if v is None:
  202. del props[k]
  203. continue
  204. raise ValueError("Value of %r must be %r not %r: %r" % (
  205. k, str.__name__, type(v).__name__, v))
  206. if k == "tag":
  207. if v not in ("", "VCALENDAR", "VADDRESSBOOK"):
  208. raise ValueError("Unsupported collection tag: %r" % v)
  209. return props
  210. def find_available_uid(exists_fn: Callable[[str], bool], suffix: str = ""
  211. ) -> str:
  212. """Generate a pseudo-random UID"""
  213. # Prevent infinite loop
  214. for _ in range(1000):
  215. r = binascii.hexlify(os.urandom(16)).decode("ascii")
  216. name = "%s-%s-%s-%s-%s%s" % (
  217. r[:8], r[8:12], r[12:16], r[16:20], r[20:], suffix)
  218. if not exists_fn(name):
  219. return name
  220. # something is wrong with the PRNG
  221. raise RuntimeError("No unique random sequence found")
  222. def get_etag(text: str) -> str:
  223. """Etag from collection or item.
  224. Encoded as quoted-string (see RFC 2616).
  225. """
  226. etag = sha256()
  227. etag.update(text.encode())
  228. return '"%s"' % etag.hexdigest()
  229. def get_uid(vobject_component: vobject.base.Component) -> str:
  230. """UID value of an item if defined."""
  231. return (vobject_component.uid.value or ""
  232. if hasattr(vobject_component, "uid") else "")
  233. def get_uid_from_object(vobject_item: vobject.base.Component) -> str:
  234. """UID value of an calendar/addressbook object."""
  235. if vobject_item.name == "VCALENDAR":
  236. if hasattr(vobject_item, "vevent"):
  237. return get_uid(vobject_item.vevent)
  238. if hasattr(vobject_item, "vjournal"):
  239. return get_uid(vobject_item.vjournal)
  240. if hasattr(vobject_item, "vtodo"):
  241. return get_uid(vobject_item.vtodo)
  242. elif vobject_item.name == "VCARD":
  243. return get_uid(vobject_item)
  244. return ""
  245. def find_tag(vobject_item: vobject.base.Component) -> str:
  246. """Find component name from ``vobject_item``."""
  247. if vobject_item.name == "VCALENDAR":
  248. for component in vobject_item.components():
  249. if component.name != "VTIMEZONE":
  250. return component.name or ""
  251. return ""
  252. def find_time_range(vobject_item: vobject.base.Component, tag: str
  253. ) -> Tuple[int, int]:
  254. """Find enclosing time range from ``vobject item``.
  255. ``tag`` must be set to the return value of ``find_tag``.
  256. Returns a tuple (``start``, ``end``) where ``start`` and ``end`` are
  257. POSIX timestamps.
  258. This is intened to be used for matching against simplified prefilters.
  259. """
  260. if not tag:
  261. return radicale_filter.TIMESTAMP_MIN, radicale_filter.TIMESTAMP_MAX
  262. start = end = None
  263. def range_fn(range_start: datetime, range_end: datetime,
  264. is_recurrence: bool) -> bool:
  265. nonlocal start, end
  266. if start is None or range_start < start:
  267. start = range_start
  268. if end is None or end < range_end:
  269. end = range_end
  270. return False
  271. def infinity_fn(range_start: datetime) -> bool:
  272. nonlocal start, end
  273. if start is None or range_start < start:
  274. start = range_start
  275. end = radicale_filter.DATETIME_MAX
  276. return True
  277. radicale_filter.visit_time_ranges(vobject_item, tag, range_fn, infinity_fn)
  278. if start is None:
  279. start = radicale_filter.DATETIME_MIN
  280. if end is None:
  281. end = radicale_filter.DATETIME_MAX
  282. try:
  283. return math.floor(start.timestamp()), math.ceil(end.timestamp())
  284. except ValueError as e:
  285. if str(e) == ("offset must be a timedelta representing a whole "
  286. "number of minutes") and sys.version_info < (3, 6):
  287. raise RuntimeError("Unsupported in Python < 3.6: %s" % e) from e
  288. raise
  289. class Item:
  290. """Class for address book and calendar entries."""
  291. collection: Optional["storage.BaseCollection"]
  292. href: Optional[str]
  293. last_modified: Optional[str]
  294. _collection_path: str
  295. _text: Optional[str]
  296. _vobject_item: Optional[vobject.base.Component]
  297. _etag: Optional[str]
  298. _uid: Optional[str]
  299. _name: Optional[str]
  300. _component_name: Optional[str]
  301. _time_range: Optional[Tuple[int, int]]
  302. def __init__(self,
  303. collection_path: Optional[str] = None,
  304. collection: Optional["storage.BaseCollection"] = None,
  305. vobject_item: Optional[vobject.base.Component] = None,
  306. href: Optional[str] = None,
  307. last_modified: Optional[str] = None,
  308. text: Optional[str] = None,
  309. etag: Optional[str] = None,
  310. uid: Optional[str] = None,
  311. name: Optional[str] = None,
  312. component_name: Optional[str] = None,
  313. time_range: Optional[Tuple[int, int]] = None):
  314. """Initialize an item.
  315. ``collection_path`` the path of the parent collection (optional if
  316. ``collection`` is set).
  317. ``collection`` the parent collection (optional).
  318. ``href`` the href of the item.
  319. ``last_modified`` the HTTP-datetime of when the item was modified.
  320. ``text`` the text representation of the item (optional if
  321. ``vobject_item`` is set).
  322. ``vobject_item`` the vobject item (optional if ``text`` is set).
  323. ``etag`` the etag of the item (optional). See ``get_etag``.
  324. ``uid`` the UID of the object (optional). See ``get_uid_from_object``.
  325. ``name`` the name of the item (optional). See ``vobject_item.name``.
  326. ``component_name`` the name of the primary component (optional).
  327. See ``find_tag``.
  328. ``time_range`` the enclosing time range. See ``find_time_range``.
  329. """
  330. if text is None and vobject_item is None:
  331. raise ValueError(
  332. "At least one of 'text' or 'vobject_item' must be set")
  333. if collection_path is None:
  334. if collection is None:
  335. raise ValueError("At least one of 'collection_path' or "
  336. "'collection' must be set")
  337. collection_path = collection.path
  338. assert collection_path == pathutils.strip_path(
  339. pathutils.sanitize_path(collection_path))
  340. self._collection_path = collection_path
  341. self.collection = collection
  342. self.href = href
  343. self.last_modified = last_modified
  344. self._text = text
  345. self._vobject_item = vobject_item
  346. self._etag = etag
  347. self._uid = uid
  348. self._name = name
  349. self._component_name = component_name
  350. self._time_range = time_range
  351. def serialize(self) -> str:
  352. if self._text is None:
  353. try:
  354. self._text = self.vobject_item.serialize()
  355. except Exception as e:
  356. raise RuntimeError("Failed to serialize item %r from %r: %s" %
  357. (self.href, self._collection_path,
  358. e)) from e
  359. return self._text
  360. @property
  361. def vobject_item(self):
  362. if self._vobject_item is None:
  363. try:
  364. self._vobject_item = vobject.readOne(self._text)
  365. except Exception as e:
  366. raise RuntimeError("Failed to parse item %r from %r: %s" %
  367. (self.href, self._collection_path,
  368. e)) from e
  369. return self._vobject_item
  370. @property
  371. def etag(self) -> str:
  372. """Encoded as quoted-string (see RFC 2616)."""
  373. if self._etag is None:
  374. self._etag = get_etag(self.serialize())
  375. return self._etag
  376. @property
  377. def uid(self) -> str:
  378. if self._uid is None:
  379. self._uid = get_uid_from_object(self.vobject_item)
  380. return self._uid
  381. @property
  382. def name(self) -> str:
  383. if self._name is None:
  384. self._name = self.vobject_item.name or ""
  385. return self._name
  386. @property
  387. def component_name(self) -> str:
  388. if self._component_name is None:
  389. self._component_name = find_tag(self.vobject_item)
  390. return self._component_name
  391. @property
  392. def time_range(self) -> Tuple[int, int]:
  393. if self._time_range is None:
  394. self._time_range = find_time_range(
  395. self.vobject_item, self.component_name)
  396. return self._time_range
  397. def prepare(self) -> None:
  398. """Fill cache with values."""
  399. orig_vobject_item = self._vobject_item
  400. self.serialize()
  401. self.etag
  402. self.uid
  403. self.name
  404. self.time_range
  405. self.component_name
  406. self._vobject_item = orig_vobject_item