meta.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. import json
  19. import os
  20. from typing import Mapping, Optional, TextIO, Union, cast, overload
  21. import radicale.item as radicale_item
  22. from radicale.storage import multifilesystem
  23. from radicale.storage.multifilesystem.base import CollectionBase
  24. class CollectionPartMeta(CollectionBase):
  25. _meta_cache: Optional[Mapping[str, str]]
  26. _props_path: str
  27. def __init__(self, storage_: "multifilesystem.Storage", path: str,
  28. filesystem_path: Optional[str] = None) -> None:
  29. super().__init__(storage_, path, filesystem_path)
  30. self._meta_cache = None
  31. self._props_path = os.path.join(
  32. self._filesystem_path, ".Radicale.props")
  33. @overload
  34. def get_meta(self, key: None = None) -> Mapping[str, str]: ...
  35. @overload
  36. def get_meta(self, key: str) -> Optional[str]: ...
  37. def get_meta(self, key: Optional[str] = None) -> Union[Mapping[str, str],
  38. Optional[str]]:
  39. # reuse cached value if the storage is read-only
  40. if self._storage._lock.locked == "w" or self._meta_cache is None:
  41. try:
  42. try:
  43. with open(self._props_path, encoding=self._encoding) as f:
  44. temp_meta = json.load(f)
  45. except FileNotFoundError:
  46. temp_meta = {}
  47. self._meta_cache = radicale_item.check_and_sanitize_props(
  48. temp_meta)
  49. except ValueError as e:
  50. raise RuntimeError("Failed to load properties of collection "
  51. "%r: %s" % (self.path, e)) from e
  52. return self._meta_cache if key is None else self._meta_cache.get(key)
  53. def set_meta(self, props: Mapping[str, str]) -> None:
  54. # TODO: better fix for "mypy"
  55. with self._atomic_write(self._props_path, "w") as fo: # type: ignore
  56. f = cast(TextIO, fo)
  57. json.dump(props, f, sort_keys=True)