__init__.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import json
  2. from enum import Enum
  3. from typing import Sequence
  4. from radicale import pathutils, utils
  5. from radicale.log import logger
  6. INTERNAL_TYPES: Sequence[str] = ("none", "rabbitmq")
  7. def load(configuration):
  8. """Load the storage module chosen in configuration."""
  9. try:
  10. return utils.load_plugin(
  11. INTERNAL_TYPES, "hook", "Hook", BaseHook, configuration)
  12. except Exception as e:
  13. logger.warning(e)
  14. logger.warning("Hook \"%s\" failed to load, falling back to \"none\"." % configuration.get("hook", "type"))
  15. configuration = configuration.copy()
  16. configuration.update({"hook": {"type": "none"}}, "hook", privileged=True)
  17. return utils.load_plugin(
  18. INTERNAL_TYPES, "hook", "Hook", BaseHook, configuration)
  19. class BaseHook:
  20. def __init__(self, configuration):
  21. """Initialize BaseHook.
  22. ``configuration`` see ``radicale.config`` module.
  23. The ``configuration`` must not change during the lifetime of
  24. this object, it is kept as an internal reference.
  25. """
  26. self.configuration = configuration
  27. def notify(self, notification_item):
  28. """Upload a new or replace an existing item."""
  29. raise NotImplementedError
  30. class HookNotificationItemTypes(Enum):
  31. CPATCH = "cpatch"
  32. UPSERT = "upsert"
  33. DELETE = "delete"
  34. def _cleanup(path):
  35. sane_path = pathutils.strip_path(path)
  36. attributes = sane_path.split("/") if sane_path else []
  37. if len(attributes) < 2:
  38. return ""
  39. return attributes[0] + "/" + attributes[1]
  40. class HookNotificationItem:
  41. def __init__(self, notification_item_type, path, content):
  42. self.type = notification_item_type.value
  43. self.point = _cleanup(path)
  44. self.content = content
  45. def to_json(self):
  46. return json.dumps(
  47. self,
  48. default=lambda o: o.__dict__,
  49. sort_keys=True,
  50. indent=4
  51. )