__init__.py 11 KB

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