__init__.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. # This file is part of Radicale - CalDAV and CardDAV server
  2. # Copyright © 2014 Jean-Marc Martins
  3. # Copyright © 2012-2017 Guillaume Ayoub
  4. # Copyright © 2017-2018 Unrud <unrud@outlook.com>
  5. #
  6. # This library is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This library is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  18. """
  19. The storage module that stores calendars and address books.
  20. Take a look at the class ``BaseCollection`` if you want to implement your own.
  21. """
  22. import json
  23. import xml.etree.ElementTree as ET
  24. from hashlib import sha256
  25. from typing import (Callable, ContextManager, Iterable, Iterator, Mapping,
  26. Optional, Sequence, Set, Tuple, Union, overload)
  27. import vobject
  28. from radicale import config
  29. from radicale import item as radicale_item
  30. from radicale import types, utils
  31. from radicale.item import filter as radicale_filter
  32. INTERNAL_TYPES: Sequence[str] = ("multifilesystem", "multifilesystem_nolock",)
  33. CACHE_DEPS: Sequence[str] = ("radicale", "vobject", "python-dateutil",)
  34. CACHE_VERSION: bytes = "".join(
  35. "%s=%s;" % (pkg, utils.package_version(pkg))
  36. for pkg in CACHE_DEPS).encode()
  37. def load(configuration: "config.Configuration") -> "BaseStorage":
  38. """Load the storage module chosen in configuration."""
  39. return utils.load_plugin(INTERNAL_TYPES, "storage", "Storage", BaseStorage,
  40. configuration)
  41. class ComponentExistsError(ValueError):
  42. def __init__(self, path: str) -> None:
  43. message = "Component already exists: %r" % path
  44. super().__init__(message)
  45. class ComponentNotFoundError(ValueError):
  46. def __init__(self, path: str) -> None:
  47. message = "Component doesn't exist: %r" % path
  48. super().__init__(message)
  49. class BaseCollection:
  50. @property
  51. def path(self) -> str:
  52. """The sanitized path of the collection without leading or
  53. trailing ``/``."""
  54. raise NotImplementedError
  55. @property
  56. def owner(self) -> str:
  57. """The owner of the collection."""
  58. return self.path.split("/", maxsplit=1)[0]
  59. @property
  60. def is_principal(self) -> bool:
  61. """Collection is a principal."""
  62. return bool(self.path) and "/" not in self.path
  63. @property
  64. def etag(self) -> str:
  65. """Encoded as quoted-string (see RFC 2616)."""
  66. etag = sha256()
  67. for item in self.get_all():
  68. assert item.href
  69. etag.update((item.href + "/" + item.etag).encode())
  70. etag.update(json.dumps(self.get_meta(), sort_keys=True).encode())
  71. return '"%s"' % etag.hexdigest()
  72. @property
  73. def tag(self) -> str:
  74. """The tag of the collection."""
  75. return self.get_meta("tag") or ""
  76. def sync(self, old_token: str = "") -> Tuple[str, Iterable[str]]:
  77. """Get the current sync token and changed items for synchronization.
  78. ``old_token`` an old sync token which is used as the base of the
  79. delta update. If sync token is empty, all items are returned.
  80. ValueError is raised for invalid or old tokens.
  81. WARNING: This simple default implementation treats all sync-token as
  82. invalid.
  83. """
  84. def hrefs_iter() -> Iterator[str]:
  85. for item in self.get_all():
  86. assert item.href
  87. yield item.href
  88. token = "http://radicale.org/ns/sync/%s" % self.etag.strip("\"")
  89. if old_token:
  90. raise ValueError("Sync token are not supported")
  91. return token, hrefs_iter()
  92. def get_multi(self, hrefs: Iterable[str]
  93. ) -> Iterable[Tuple[str, Optional["radicale_item.Item"]]]:
  94. """Fetch multiple items.
  95. It's not required to return the requested items in the correct order.
  96. Duplicated hrefs can be ignored.
  97. Returns tuples with the href and the item or None if the item doesn't
  98. exist.
  99. """
  100. raise NotImplementedError
  101. def get_all(self) -> Iterable["radicale_item.Item"]:
  102. """Fetch all items."""
  103. raise NotImplementedError
  104. def get_filtered(self, filters: Iterable[ET.Element]
  105. ) -> Iterable[Tuple["radicale_item.Item", bool]]:
  106. """Fetch all items with optional filtering.
  107. This can largely improve performance of reports depending on
  108. the filters and this implementation.
  109. Returns tuples in the form ``(item, filters_matched)``.
  110. ``filters_matched`` is a bool that indicates if ``filters`` are fully
  111. matched.
  112. """
  113. if not self.tag:
  114. return
  115. tag, start, end, simple = radicale_filter.simplify_prefilters(
  116. filters, self.tag)
  117. for item in self.get_all():
  118. if tag is not None and tag != item.component_name:
  119. continue
  120. istart, iend = item.time_range
  121. if istart >= end or iend <= start:
  122. continue
  123. yield item, simple and (start <= istart or iend <= end)
  124. def has_uid(self, uid: str) -> bool:
  125. """Check if a UID exists in the collection."""
  126. for item in self.get_all():
  127. if item.uid == uid:
  128. return True
  129. return False
  130. def upload(self, href: str, item: "radicale_item.Item") -> (
  131. "radicale_item.Item"):
  132. """Upload a new or replace an existing item."""
  133. raise NotImplementedError
  134. def delete(self, href: Optional[str] = None) -> None:
  135. """Delete an item.
  136. When ``href`` is ``None``, delete the collection.
  137. """
  138. raise NotImplementedError
  139. @overload
  140. def get_meta(self, key: None = None) -> Mapping[str, str]: ...
  141. @overload
  142. def get_meta(self, key: str) -> Optional[str]: ...
  143. def get_meta(self, key: Optional[str] = None
  144. ) -> Union[Mapping[str, str], Optional[str]]:
  145. """Get metadata value for collection.
  146. Return the value of the property ``key``. If ``key`` is ``None`` return
  147. a dict with all properties
  148. """
  149. raise NotImplementedError
  150. def set_meta(self, props: Mapping[str, str]) -> None:
  151. """Set metadata values for collection.
  152. ``props`` a dict with values for properties.
  153. """
  154. raise NotImplementedError
  155. @property
  156. def last_modified(self) -> str:
  157. """Get the HTTP-datetime of when the collection was modified."""
  158. raise NotImplementedError
  159. def serialize(self) -> str:
  160. """Get the unicode string representing the whole collection."""
  161. if self.tag == "VCALENDAR":
  162. in_vcalendar = False
  163. vtimezones = ""
  164. included_tzids: Set[str] = set()
  165. vtimezone = []
  166. tzid = None
  167. components = ""
  168. # Concatenate all child elements of VCALENDAR from all items
  169. # together, while preventing duplicated VTIMEZONE entries.
  170. # VTIMEZONEs are only distinguished by their TZID, if different
  171. # timezones share the same TZID this produces erroneous output.
  172. # VObject fails at this too.
  173. for item in self.get_all():
  174. depth = 0
  175. for line in item.serialize().split("\r\n"):
  176. if line.startswith("BEGIN:"):
  177. depth += 1
  178. if depth == 1 and line == "BEGIN:VCALENDAR":
  179. in_vcalendar = True
  180. elif in_vcalendar:
  181. if depth == 1 and line.startswith("END:"):
  182. in_vcalendar = False
  183. if depth == 2 and line == "BEGIN:VTIMEZONE":
  184. vtimezone.append(line + "\r\n")
  185. elif vtimezone:
  186. vtimezone.append(line + "\r\n")
  187. if depth == 2 and line.startswith("TZID:"):
  188. tzid = line[len("TZID:"):]
  189. elif depth == 2 and line.startswith("END:"):
  190. if tzid is None or tzid not in included_tzids:
  191. vtimezones += "".join(vtimezone)
  192. if tzid is not None:
  193. included_tzids.add(tzid)
  194. vtimezone.clear()
  195. tzid = None
  196. elif depth >= 2:
  197. components += line + "\r\n"
  198. if line.startswith("END:"):
  199. depth -= 1
  200. template = vobject.iCalendar()
  201. displayname = self.get_meta("D:displayname")
  202. if displayname:
  203. template.add("X-WR-CALNAME")
  204. template.x_wr_calname.value_param = "TEXT"
  205. template.x_wr_calname.value = displayname
  206. description = self.get_meta("C:calendar-description")
  207. if description:
  208. template.add("X-WR-CALDESC")
  209. template.x_wr_caldesc.value_param = "TEXT"
  210. template.x_wr_caldesc.value = description
  211. template = template.serialize()
  212. template_insert_pos = template.find("\r\nEND:VCALENDAR\r\n") + 2
  213. assert template_insert_pos != -1
  214. return (template[:template_insert_pos] +
  215. vtimezones + components +
  216. template[template_insert_pos:])
  217. if self.tag == "VADDRESSBOOK":
  218. return "".join((item.serialize() for item in self.get_all()))
  219. return ""
  220. class BaseStorage:
  221. def __init__(self, configuration: "config.Configuration") -> None:
  222. """Initialize BaseStorage.
  223. ``configuration`` see ``radicale.config`` module.
  224. The ``configuration`` must not change during the lifetime of
  225. this object, it is kept as an internal reference.
  226. """
  227. self.configuration = configuration
  228. def discover(
  229. self, path: str, depth: str = "0",
  230. child_context_manager: Optional[
  231. Callable[[str, Optional[str]], ContextManager[None]]] = None,
  232. user_groups: Set[str] = set([])) -> Iterable["types.CollectionOrItem"]:
  233. """Discover a list of collections under the given ``path``.
  234. ``path`` is sanitized.
  235. If ``depth`` is "0", only the actual object under ``path`` is
  236. returned.
  237. If ``depth`` is anything but "0", it is considered as "1" and direct
  238. children are included in the result.
  239. The root collection "/" must always exist.
  240. """
  241. raise NotImplementedError
  242. def move(self, item: "radicale_item.Item", to_collection: BaseCollection,
  243. to_href: str) -> None:
  244. """Move an object.
  245. ``item`` is the item to move.
  246. ``to_collection`` is the target collection.
  247. ``to_href`` is the target name in ``to_collection``. An item with the
  248. same name might already exist.
  249. """
  250. raise NotImplementedError
  251. def create_collection(
  252. self, href: str,
  253. items: Optional[Iterable["radicale_item.Item"]] = None,
  254. props: Optional[Mapping[str, str]] = None) -> BaseCollection:
  255. """Create a collection.
  256. ``href`` is the sanitized path.
  257. If the collection already exists and neither ``collection`` nor
  258. ``props`` are set, this method shouldn't do anything. Otherwise the
  259. existing collection must be replaced.
  260. ``collection`` is a list of vobject components.
  261. ``props`` are metadata values for the collection.
  262. ``props["tag"]`` is the type of collection (VCALENDAR or VADDRESSBOOK).
  263. If the key ``tag`` is missing, ``items`` is ignored.
  264. """
  265. raise NotImplementedError
  266. @types.contextmanager
  267. def acquire_lock(self, mode: str, user: str = "") -> Iterator[None]:
  268. """Set a context manager to lock the whole storage.
  269. ``mode`` must either be "r" for shared access or "w" for exclusive
  270. access.
  271. ``user`` is the name of the logged in user or empty.
  272. """
  273. raise NotImplementedError
  274. def verify(self) -> bool:
  275. """Check the storage for errors."""
  276. raise NotImplementedError