__init__.py 12 KB

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