__init__.py 13 KB

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