__init__.py 13 KB

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