__init__.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. # This file is part of Radicale Server - Calendar 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. Storage backends.
  20. This module loads the storage backend, according to the storage configuration.
  21. Default storage uses one folder per collection and one file per collection
  22. entry.
  23. """
  24. import json
  25. from contextlib import contextmanager
  26. from hashlib import md5
  27. from importlib import import_module
  28. import pkg_resources
  29. import vobject
  30. from radicale.log import logger
  31. INTERNAL_TYPES = ("multifilesystem",)
  32. CACHE_DEPS = ("radicale", "vobject", "python-dateutil",)
  33. CACHE_VERSION = (";".join(pkg_resources.get_distribution(pkg).version
  34. for pkg in CACHE_DEPS) + ";").encode()
  35. def load(configuration):
  36. """Load the storage manager chosen in configuration."""
  37. storage_type = configuration.get("storage", "type")
  38. if storage_type in INTERNAL_TYPES:
  39. module = "radicale.storage.%s" % storage_type
  40. else:
  41. module = storage_type
  42. try:
  43. class_ = import_module(module).Collection
  44. except Exception as e:
  45. raise RuntimeError("Failed to load storage module %r: %s" %
  46. (storage_type, e)) from e
  47. logger.info("Storage type is %r", storage_type)
  48. class CollectionCopy(class_):
  49. """Collection copy, avoids overriding the original class attributes."""
  50. CollectionCopy.configuration = configuration
  51. CollectionCopy.static_init()
  52. return CollectionCopy
  53. class ComponentExistsError(ValueError):
  54. def __init__(self, path):
  55. message = "Component already exists: %r" % path
  56. super().__init__(message)
  57. class ComponentNotFoundError(ValueError):
  58. def __init__(self, path):
  59. message = "Component doesn't exist: %r" % path
  60. super().__init__(message)
  61. class BaseCollection:
  62. # Overriden on copy by the "load" function
  63. configuration = None
  64. # Properties of instance
  65. """The sanitized path of the collection without leading or trailing ``/``.
  66. """
  67. path = ""
  68. @classmethod
  69. def static_init():
  70. """init collection copy"""
  71. pass
  72. @property
  73. def owner(self):
  74. """The owner of the collection."""
  75. return self.path.split("/", maxsplit=1)[0]
  76. @property
  77. def is_principal(self):
  78. """Collection is a principal."""
  79. return bool(self.path) and "/" not in self.path
  80. @classmethod
  81. def discover(cls, path, depth="0"):
  82. """Discover a list of collections under the given ``path``.
  83. ``path`` is sanitized.
  84. If ``depth`` is "0", only the actual object under ``path`` is
  85. returned.
  86. If ``depth`` is anything but "0", it is considered as "1" and direct
  87. children are included in the result.
  88. The root collection "/" must always exist.
  89. """
  90. raise NotImplementedError
  91. @classmethod
  92. def move(cls, item, to_collection, to_href):
  93. """Move an object.
  94. ``item`` is the item to move.
  95. ``to_collection`` is the target collection.
  96. ``to_href`` is the target name in ``to_collection``. An item with the
  97. same name might already exist.
  98. """
  99. if item.collection.path == to_collection.path and item.href == to_href:
  100. return
  101. to_collection.upload(to_href, item)
  102. item.collection.delete(item.href)
  103. @property
  104. def etag(self):
  105. """Encoded as quoted-string (see RFC 2616)."""
  106. etag = md5()
  107. for item in self.get_all():
  108. etag.update((item.href + "/" + item.etag).encode("utf-8"))
  109. etag.update(json.dumps(self.get_meta(), sort_keys=True).encode())
  110. return '"%s"' % etag.hexdigest()
  111. @classmethod
  112. def create_collection(cls, href, items=None, props=None):
  113. """Create a collection.
  114. ``href`` is the sanitized path.
  115. If the collection already exists and neither ``collection`` nor
  116. ``props`` are set, this method shouldn't do anything. Otherwise the
  117. existing collection must be replaced.
  118. ``collection`` is a list of vobject components.
  119. ``props`` are metadata values for the collection.
  120. ``props["tag"]`` is the type of collection (VCALENDAR or
  121. VADDRESSBOOK). If the key ``tag`` is missing, it is guessed from the
  122. collection.
  123. """
  124. raise NotImplementedError
  125. def sync(self, old_token=None):
  126. """Get the current sync token and changed items for synchronization.
  127. ``old_token`` an old sync token which is used as the base of the
  128. delta update. If sync token is missing, all items are returned.
  129. ValueError is raised for invalid or old tokens.
  130. WARNING: This simple default implementation treats all sync-token as
  131. invalid. It adheres to the specification but some clients
  132. (e.g. InfCloud) don't like it. Subclasses should provide a
  133. more sophisticated implementation.
  134. """
  135. token = "http://radicale.org/ns/sync/%s" % self.etag.strip("\"")
  136. if old_token:
  137. raise ValueError("Sync token are not supported")
  138. return token, self.list()
  139. def list(self):
  140. """List collection items."""
  141. raise NotImplementedError
  142. def get(self, href):
  143. """Fetch a single item."""
  144. raise NotImplementedError
  145. def get_multi(self, hrefs):
  146. """Fetch multiple items.
  147. Functionally similar to ``get``, but might bring performance benefits
  148. on some storages when used cleverly. It's not required to return the
  149. requested items in the correct order. Duplicated hrefs can be ignored.
  150. Returns tuples with the href and the item or None if the item doesn't
  151. exist.
  152. """
  153. return ((href, self.get(href)) for href in hrefs)
  154. def get_all(self):
  155. """Fetch all items.
  156. Functionally similar to ``get``, but might bring performance benefits
  157. on some storages when used cleverly.
  158. """
  159. return map(self.get, self.list())
  160. def get_all_filtered(self, filters):
  161. """Fetch all items with optional filtering.
  162. This can largely improve performance of reports depending on
  163. the filters and this implementation.
  164. Returns tuples in the form ``(item, filters_matched)``.
  165. ``filters_matched`` is a bool that indicates if ``filters`` are fully
  166. matched.
  167. This returns all events by default
  168. """
  169. return ((item, False) for item in self.get_all())
  170. def has(self, href):
  171. """Check if an item exists by its href.
  172. Functionally similar to ``get``, but might bring performance benefits
  173. on some storages when used cleverly.
  174. """
  175. return self.get(href) is not None
  176. def has_uid(self, uid):
  177. """Check if a UID exists in the collection."""
  178. for item in self.get_all():
  179. if item.uid == uid:
  180. return True
  181. return False
  182. def upload(self, href, item):
  183. """Upload a new or replace an existing item."""
  184. raise NotImplementedError
  185. def delete(self, href=None):
  186. """Delete an item.
  187. When ``href`` is ``None``, delete the collection.
  188. """
  189. raise NotImplementedError
  190. def get_meta(self, key=None):
  191. """Get metadata value for collection.
  192. Return the value of the property ``key``. If ``key`` is ``None`` return
  193. a dict with all properties
  194. """
  195. raise NotImplementedError
  196. def set_meta(self, props):
  197. """Set metadata values for collection.
  198. ``props`` a dict with values for properties.
  199. """
  200. raise NotImplementedError
  201. @property
  202. def last_modified(self):
  203. """Get the HTTP-datetime of when the collection was modified."""
  204. raise NotImplementedError
  205. def serialize(self):
  206. """Get the unicode string representing the whole collection."""
  207. if self.get_meta("tag") == "VCALENDAR":
  208. in_vcalendar = False
  209. vtimezones = ""
  210. included_tzids = set()
  211. vtimezone = []
  212. tzid = None
  213. components = ""
  214. # Concatenate all child elements of VCALENDAR from all items
  215. # together, while preventing duplicated VTIMEZONE entries.
  216. # VTIMEZONEs are only distinguished by their TZID, if different
  217. # timezones share the same TZID this produces errornous ouput.
  218. # VObject fails at this too.
  219. for item in self.get_all():
  220. depth = 0
  221. for line in item.serialize().split("\r\n"):
  222. if line.startswith("BEGIN:"):
  223. depth += 1
  224. if depth == 1 and line == "BEGIN:VCALENDAR":
  225. in_vcalendar = True
  226. elif in_vcalendar:
  227. if depth == 1 and line.startswith("END:"):
  228. in_vcalendar = False
  229. if depth == 2 and line == "BEGIN:VTIMEZONE":
  230. vtimezone.append(line + "\r\n")
  231. elif vtimezone:
  232. vtimezone.append(line + "\r\n")
  233. if depth == 2 and line.startswith("TZID:"):
  234. tzid = line[len("TZID:"):]
  235. elif depth == 2 and line.startswith("END:"):
  236. if tzid is None or tzid not in included_tzids:
  237. vtimezones += "".join(vtimezone)
  238. included_tzids.add(tzid)
  239. vtimezone.clear()
  240. tzid = None
  241. elif depth >= 2:
  242. components += line + "\r\n"
  243. if line.startswith("END:"):
  244. depth -= 1
  245. template = vobject.iCalendar()
  246. displayname = self.get_meta("D:displayname")
  247. if displayname:
  248. template.add("X-WR-CALNAME")
  249. template.x_wr_calname.value_param = "TEXT"
  250. template.x_wr_calname.value = displayname
  251. description = self.get_meta("C:calendar-description")
  252. if description:
  253. template.add("X-WR-CALDESC")
  254. template.x_wr_caldesc.value_param = "TEXT"
  255. template.x_wr_caldesc.value = description
  256. template = template.serialize()
  257. template_insert_pos = template.find("\r\nEND:VCALENDAR\r\n") + 2
  258. assert template_insert_pos != -1
  259. return (template[:template_insert_pos] +
  260. vtimezones + components +
  261. template[template_insert_pos:])
  262. elif self.get_meta("tag") == "VADDRESSBOOK":
  263. return "".join((item.serialize() for item in self.get_all()))
  264. return ""
  265. @classmethod
  266. @contextmanager
  267. def acquire_lock(cls, mode, user=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. @classmethod
  275. def verify(cls):
  276. """Check the storage for errors."""
  277. return True