__init__.py 18 KB

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