__init__.py 11 KB

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