__init__.py 14 KB

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