__init__.py 11 KB

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