push_rules.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. # Copyright 2022 The Matrix.org Foundation C.I.C.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from typing import TYPE_CHECKING, List, Optional, Union
  15. import attr
  16. from synapse.api.errors import SynapseError, UnrecognizedRequestError
  17. from synapse.push.baserules import BASE_RULE_IDS
  18. from synapse.storage.push_rule import RuleNotFoundException
  19. from synapse.types import JsonDict
  20. if TYPE_CHECKING:
  21. from synapse.server import HomeServer
  22. @attr.s(slots=True, frozen=True, auto_attribs=True)
  23. class RuleSpec:
  24. scope: str
  25. template: str
  26. rule_id: str
  27. attr: Optional[str]
  28. class PushRulesHandler:
  29. """A class to handle changes in push rules for users."""
  30. def __init__(self, hs: "HomeServer"):
  31. self._notifier = hs.get_notifier()
  32. self._main_store = hs.get_datastores().main
  33. async def set_rule_attr(
  34. self, user_id: str, spec: RuleSpec, val: Union[bool, JsonDict]
  35. ) -> None:
  36. """Set an attribute (enabled or actions) on an existing push rule.
  37. Notifies listeners (e.g. sync handler) of the change.
  38. Args:
  39. user_id: the user for which to modify the push rule.
  40. spec: the spec of the push rule to modify.
  41. val: the value to change the attribute to.
  42. Raises:
  43. RuleNotFoundException if the rule being modified doesn't exist.
  44. SynapseError(400) if the value is malformed.
  45. UnrecognizedRequestError if the attribute to change is unknown.
  46. InvalidRuleException if we're trying to change the actions on a rule but
  47. the provided actions aren't compliant with the spec.
  48. """
  49. if spec.attr not in ("enabled", "actions"):
  50. # for the sake of potential future expansion, shouldn't report
  51. # 404 in the case of an unknown request so check it corresponds to
  52. # a known attribute first.
  53. raise UnrecognizedRequestError()
  54. namespaced_rule_id = f"global/{spec.template}/{spec.rule_id}"
  55. rule_id = spec.rule_id
  56. is_default_rule = rule_id.startswith(".")
  57. if is_default_rule:
  58. if namespaced_rule_id not in BASE_RULE_IDS:
  59. raise RuleNotFoundException("Unknown rule %r" % (namespaced_rule_id,))
  60. if spec.attr == "enabled":
  61. if isinstance(val, dict) and "enabled" in val:
  62. val = val["enabled"]
  63. if not isinstance(val, bool):
  64. # Legacy fallback
  65. # This should *actually* take a dict, but many clients pass
  66. # bools directly, so let's not break them.
  67. raise SynapseError(400, "Value for 'enabled' must be boolean")
  68. await self._main_store.set_push_rule_enabled(
  69. user_id, namespaced_rule_id, val, is_default_rule
  70. )
  71. elif spec.attr == "actions":
  72. if not isinstance(val, dict):
  73. raise SynapseError(400, "Value must be a dict")
  74. actions = val.get("actions")
  75. if not isinstance(actions, list):
  76. raise SynapseError(400, "Value for 'actions' must be dict")
  77. check_actions(actions)
  78. rule_id = spec.rule_id
  79. is_default_rule = rule_id.startswith(".")
  80. if is_default_rule:
  81. if namespaced_rule_id not in BASE_RULE_IDS:
  82. raise RuleNotFoundException(
  83. "Unknown rule %r" % (namespaced_rule_id,)
  84. )
  85. await self._main_store.set_push_rule_actions(
  86. user_id, namespaced_rule_id, actions, is_default_rule
  87. )
  88. else:
  89. raise UnrecognizedRequestError()
  90. self.notify_user(user_id)
  91. def notify_user(self, user_id: str) -> None:
  92. """Notify listeners about a push rule change.
  93. Args:
  94. user_id: the user ID the change is for.
  95. """
  96. stream_id = self._main_store.get_max_push_rules_stream_id()
  97. self._notifier.on_new_event("push_rules_key", stream_id, users=[user_id])
  98. def check_actions(actions: List[Union[str, JsonDict]]) -> None:
  99. """Check if the given actions are spec compliant.
  100. Args:
  101. actions: the actions to check.
  102. Raises:
  103. InvalidRuleException if the rules aren't compliant with the spec.
  104. """
  105. if not isinstance(actions, list):
  106. raise InvalidRuleException("No actions found")
  107. for a in actions:
  108. if a in ["notify", "dont_notify", "coalesce"]:
  109. pass
  110. elif isinstance(a, dict) and "set_tweak" in a:
  111. pass
  112. else:
  113. raise InvalidRuleException("Unrecognised action %s" % a)
  114. class InvalidRuleException(Exception):
  115. pass