__init__.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. # This file is part of Radicale Server - Calendar 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. import math
  21. import sys
  22. from hashlib import md5
  23. from random import getrandbits
  24. import vobject
  25. from radicale import pathutils
  26. from radicale.item import filter as radicale_filter
  27. def predict_tag_of_parent_collection(vobject_items):
  28. if len(vobject_items) != 1:
  29. return ""
  30. if vobject_items[0].name == "VCALENDAR":
  31. return "VCALENDAR"
  32. if vobject_items[0].name in ("VCARD", "VLIST"):
  33. return "VADDRESSBOOK"
  34. return ""
  35. def predict_tag_of_whole_collection(vobject_items, fallback_tag=None):
  36. if vobject_items and vobject_items[0].name == "VCALENDAR":
  37. return "VCALENDAR"
  38. if vobject_items and vobject_items[0].name in ("VCARD", "VLIST"):
  39. return "VADDRESSBOOK"
  40. if not fallback_tag and not vobject_items:
  41. # Maybe an empty address book
  42. return "VADDRESSBOOK"
  43. return fallback_tag
  44. def check_and_sanitize_items(vobject_items, is_collection=False, tag=None):
  45. """Check vobject items for common errors and add missing UIDs.
  46. ``is_collection`` indicates that vobject_item contains unrelated
  47. components.
  48. The ``tag`` of the collection.
  49. """
  50. if tag and tag not in ("VCALENDAR", "VADDRESSBOOK"):
  51. raise ValueError("Unsupported collection tag: %r" % tag)
  52. if not is_collection and len(vobject_items) != 1:
  53. raise ValueError("Item contains %d components" % len(vobject_items))
  54. if tag == "VCALENDAR":
  55. if len(vobject_items) > 1:
  56. raise RuntimeError("VCALENDAR collection contains %d "
  57. "components" % len(vobject_items))
  58. vobject_item = vobject_items[0]
  59. if vobject_item.name != "VCALENDAR":
  60. raise ValueError("Item type %r not supported in %r "
  61. "collection" % (vobject_item.name, tag))
  62. component_uids = set()
  63. for component in vobject_item.components():
  64. if component.name in ("VTODO", "VEVENT", "VJOURNAL"):
  65. component_uid = get_uid(component)
  66. if component_uid:
  67. component_uids.add(component_uid)
  68. component_name = None
  69. object_uid = None
  70. object_uid_set = False
  71. for component in vobject_item.components():
  72. # https://tools.ietf.org/html/rfc4791#section-4.1
  73. if component.name == "VTIMEZONE":
  74. continue
  75. if component_name is None or is_collection:
  76. component_name = component.name
  77. elif component_name != component.name:
  78. raise ValueError("Multiple component types in object: %r, %r" %
  79. (component_name, component.name))
  80. if component_name not in ("VTODO", "VEVENT", "VJOURNAL"):
  81. continue
  82. component_uid = get_uid(component)
  83. if not object_uid_set or is_collection:
  84. object_uid_set = True
  85. object_uid = component_uid
  86. if not component_uid:
  87. if not is_collection:
  88. raise ValueError("%s component without UID in object" %
  89. component_name)
  90. component_uid = find_available_uid(
  91. component_uids.__contains__)
  92. component_uids.add(component_uid)
  93. if hasattr(component, "uid"):
  94. component.uid.value = component_uid
  95. else:
  96. component.add("UID").value = component_uid
  97. elif not object_uid or not component_uid:
  98. raise ValueError("Multiple %s components without UID in "
  99. "object" % component_name)
  100. elif object_uid != component_uid:
  101. raise ValueError(
  102. "Multiple %s components with different UIDs in object: "
  103. "%r, %r" % (component_name, object_uid, component_uid))
  104. # vobject interprets recurrence rules on demand
  105. try:
  106. component.rruleset
  107. except Exception as e:
  108. raise ValueError("invalid recurrence rules in %s" %
  109. component.name) from e
  110. elif tag == "VADDRESSBOOK":
  111. # https://tools.ietf.org/html/rfc6352#section-5.1
  112. object_uids = set()
  113. for vobject_item in vobject_items:
  114. if vobject_item.name == "VCARD":
  115. object_uid = get_uid(vobject_item)
  116. if object_uid:
  117. object_uids.add(object_uid)
  118. for vobject_item in vobject_items:
  119. if vobject_item.name == "VLIST":
  120. # Custom format used by SOGo Connector to store lists of
  121. # contacts
  122. continue
  123. if vobject_item.name != "VCARD":
  124. raise ValueError("Item type %r not supported in %r "
  125. "collection" % (vobject_item.name, tag))
  126. object_uid = get_uid(vobject_item)
  127. if not object_uid:
  128. if not is_collection:
  129. raise ValueError("%s object without UID" %
  130. vobject_item.name)
  131. object_uid = find_available_uid(object_uids.__contains__)
  132. object_uids.add(object_uid)
  133. if hasattr(vobject_item, "uid"):
  134. vobject_item.uid.value = object_uid
  135. else:
  136. vobject_item.add("UID").value = object_uid
  137. else:
  138. for i in vobject_items:
  139. raise ValueError("Item type %r not supported in %s collection" %
  140. (i.name, repr(tag) if tag else "generic"))
  141. def check_and_sanitize_props(props):
  142. """Check collection properties for common errors."""
  143. tag = props.get("tag")
  144. if tag and tag not in ("VCALENDAR", "VADDRESSBOOK"):
  145. raise ValueError("Unsupported collection tag: %r" % tag)
  146. def find_available_uid(exists_fn, suffix=""):
  147. """Generate a pseudo-random UID"""
  148. # Prevent infinite loop
  149. for _ in range(1000):
  150. r = "%016x" % getrandbits(128)
  151. name = "%s-%s-%s-%s-%s%s" % (
  152. r[:8], r[8:12], r[12:16], r[16:20], r[20:], suffix)
  153. if not exists_fn(name):
  154. return name
  155. # something is wrong with the PRNG
  156. raise RuntimeError("No unique random sequence found")
  157. def get_etag(text):
  158. """Etag from collection or item.
  159. Encoded as quoted-string (see RFC 2616).
  160. """
  161. etag = md5()
  162. etag.update(text.encode("utf-8"))
  163. return '"%s"' % etag.hexdigest()
  164. def get_uid(vobject_component):
  165. """UID value of an item if defined."""
  166. return (vobject_component.uid.value
  167. if hasattr(vobject_component, "uid") else None)
  168. def get_uid_from_object(vobject_item):
  169. """UID value of an calendar/addressbook object."""
  170. if vobject_item.name == "VCALENDAR":
  171. if hasattr(vobject_item, "vevent"):
  172. return get_uid(vobject_item.vevent)
  173. if hasattr(vobject_item, "vjournal"):
  174. return get_uid(vobject_item.vjournal)
  175. if hasattr(vobject_item, "vtodo"):
  176. return get_uid(vobject_item.vtodo)
  177. elif vobject_item.name == "VCARD":
  178. return get_uid(vobject_item)
  179. return None
  180. def find_tag(vobject_item):
  181. """Find component name from ``vobject_item``."""
  182. if vobject_item.name == "VCALENDAR":
  183. for component in vobject_item.components():
  184. if component.name != "VTIMEZONE":
  185. return component.name or ""
  186. return ""
  187. def find_tag_and_time_range(vobject_item):
  188. """Find component name and enclosing time range from ``vobject item``.
  189. Returns a tuple (``tag``, ``start``, ``end``) where ``tag`` is a string
  190. and ``start`` and ``end`` are POSIX timestamps (as int).
  191. This is intened to be used for matching against simplified prefilters.
  192. """
  193. tag = find_tag(vobject_item)
  194. if not tag:
  195. return (
  196. tag, radicale_filter.TIMESTAMP_MIN, radicale_filter.TIMESTAMP_MAX)
  197. start = end = None
  198. def range_fn(range_start, range_end, is_recurrence):
  199. nonlocal start, end
  200. if start is None or range_start < start:
  201. start = range_start
  202. if end is None or end < range_end:
  203. end = range_end
  204. return False
  205. def infinity_fn(range_start):
  206. nonlocal start, end
  207. if start is None or range_start < start:
  208. start = range_start
  209. end = radicale_filter.DATETIME_MAX
  210. return True
  211. radicale_filter.visit_time_ranges(vobject_item, tag, range_fn, infinity_fn)
  212. if start is None:
  213. start = radicale_filter.DATETIME_MIN
  214. if end is None:
  215. end = radicale_filter.DATETIME_MAX
  216. try:
  217. return tag, math.floor(start.timestamp()), math.ceil(end.timestamp())
  218. except ValueError as e:
  219. if str(e) == ("offset must be a timedelta representing a whole "
  220. "number of minutes") and sys.version_info < (3, 6):
  221. raise RuntimeError("Unsupported in Python < 3.6: %s" % e) from e
  222. raise
  223. class Item:
  224. def __init__(self, collection_path=None, collection=None,
  225. vobject_item=None, href=None, last_modified=None, text=None,
  226. etag=None, uid=None, name=None, component_name=None,
  227. time_range=None):
  228. """Initialize an item.
  229. ``collection_path`` the path of the parent collection (optional if
  230. ``collection`` is set).
  231. ``collection`` the parent collection (optional).
  232. ``href`` the href of the item.
  233. ``last_modified`` the HTTP-datetime of when the item was modified.
  234. ``text`` the text representation of the item (optional if
  235. ``vobject_item`` is set).
  236. ``vobject_item`` the vobject item (optional if ``text`` is set).
  237. ``etag`` the etag of the item (optional). See ``get_etag``.
  238. ``uid`` the UID of the object (optional). See ``get_uid_from_object``.
  239. ``name`` the name of the item (optional). See ``vobject_item.name``.
  240. ``component_name`` the name of the primary component (optional).
  241. See ``find_tag``.
  242. ``time_range`` the enclosing time range.
  243. See ``find_tag_and_time_range``.
  244. """
  245. if text is None and vobject_item is None:
  246. raise ValueError(
  247. "at least one of 'text' or 'vobject_item' must be set")
  248. if collection_path is None:
  249. if collection is None:
  250. raise ValueError("at least one of 'collection_path' or "
  251. "'collection' must be set")
  252. collection_path = collection.path
  253. assert collection_path == pathutils.strip_path(
  254. pathutils.sanitize_path(collection_path))
  255. self._collection_path = collection_path
  256. self.collection = collection
  257. self.href = href
  258. self.last_modified = last_modified
  259. self._text = text
  260. self._vobject_item = vobject_item
  261. self._etag = etag
  262. self._uid = uid
  263. self._name = name
  264. self._component_name = component_name
  265. self._time_range = time_range
  266. def serialize(self):
  267. if self._text is None:
  268. try:
  269. self._text = self.vobject_item.serialize()
  270. except Exception as e:
  271. raise RuntimeError("Failed to serialize item %r from %r: %s" %
  272. (self.href, self._collection_path,
  273. e)) from e
  274. return self._text
  275. @property
  276. def vobject_item(self):
  277. if self._vobject_item is None:
  278. try:
  279. self._vobject_item = vobject.readOne(self._text)
  280. except Exception as e:
  281. raise RuntimeError("Failed to parse item %r from %r: %s" %
  282. (self.href, self._collection_path,
  283. e)) from e
  284. return self._vobject_item
  285. @property
  286. def etag(self):
  287. """Encoded as quoted-string (see RFC 2616)."""
  288. if self._etag is None:
  289. self._etag = get_etag(self.serialize())
  290. return self._etag
  291. @property
  292. def uid(self):
  293. if self._uid is None:
  294. self._uid = get_uid_from_object(self.vobject_item)
  295. return self._uid
  296. @property
  297. def name(self):
  298. if self._name is None:
  299. self._name = self.vobject_item.name or ""
  300. return self._name
  301. @property
  302. def component_name(self):
  303. if self._component_name is not None:
  304. return self._component_name
  305. return find_tag(self.vobject_item)
  306. @property
  307. def time_range(self):
  308. if self._time_range is None:
  309. self._component_name, *self._time_range = (
  310. find_tag_and_time_range(self.vobject_item))
  311. return self._time_range
  312. def prepare(self):
  313. """Fill cache with values."""
  314. orig_vobject_item = self._vobject_item
  315. self.serialize()
  316. self.etag
  317. self.uid
  318. self.name
  319. self.time_range
  320. self.component_name
  321. self._vobject_item = orig_vobject_item