You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

142 lines
5.1 KiB

  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.storage.push_rule import RuleNotFoundException
  18. from synapse.synapse_rust.push import get_base_rule_ids
  19. from synapse.types import JsonDict
  20. if TYPE_CHECKING:
  21. from synapse.server import HomeServer
  22. BASE_RULE_IDS = get_base_rule_ids()
  23. @attr.s(slots=True, frozen=True, auto_attribs=True)
  24. class RuleSpec:
  25. scope: str
  26. template: str
  27. rule_id: str
  28. attr: Optional[str]
  29. class PushRulesHandler:
  30. """A class to handle changes in push rules for users."""
  31. def __init__(self, hs: "HomeServer"):
  32. self._notifier = hs.get_notifier()
  33. self._main_store = hs.get_datastores().main
  34. async def set_rule_attr(
  35. self, user_id: str, spec: RuleSpec, val: Union[bool, JsonDict]
  36. ) -> None:
  37. """Set an attribute (enabled or actions) on an existing push rule.
  38. Notifies listeners (e.g. sync handler) of the change.
  39. Args:
  40. user_id: the user for which to modify the push rule.
  41. spec: the spec of the push rule to modify.
  42. val: the value to change the attribute to.
  43. Raises:
  44. RuleNotFoundException if the rule being modified doesn't exist.
  45. SynapseError(400) if the value is malformed.
  46. UnrecognizedRequestError if the attribute to change is unknown.
  47. InvalidRuleException if we're trying to change the actions on a rule but
  48. the provided actions aren't compliant with the spec.
  49. """
  50. if spec.attr not in ("enabled", "actions"):
  51. # for the sake of potential future expansion, shouldn't report
  52. # 404 in the case of an unknown request so check it corresponds to
  53. # a known attribute first.
  54. raise UnrecognizedRequestError()
  55. namespaced_rule_id = f"global/{spec.template}/{spec.rule_id}"
  56. rule_id = spec.rule_id
  57. is_default_rule = rule_id.startswith(".")
  58. if is_default_rule:
  59. if namespaced_rule_id not in BASE_RULE_IDS:
  60. raise RuleNotFoundException("Unknown rule %r" % (namespaced_rule_id,))
  61. if spec.attr == "enabled":
  62. if isinstance(val, dict) and "enabled" in val:
  63. val = val["enabled"]
  64. if not isinstance(val, bool):
  65. # Legacy fallback
  66. # This should *actually* take a dict, but many clients pass
  67. # bools directly, so let's not break them.
  68. raise SynapseError(400, "Value for 'enabled' must be boolean")
  69. await self._main_store.set_push_rule_enabled(
  70. user_id, namespaced_rule_id, val, is_default_rule
  71. )
  72. elif spec.attr == "actions":
  73. if not isinstance(val, dict):
  74. raise SynapseError(400, "Value must be a dict")
  75. actions = val.get("actions")
  76. if not isinstance(actions, list):
  77. raise SynapseError(400, "Value for 'actions' must be dict")
  78. check_actions(actions)
  79. rule_id = spec.rule_id
  80. is_default_rule = rule_id.startswith(".")
  81. if is_default_rule:
  82. if namespaced_rule_id not in BASE_RULE_IDS:
  83. raise RuleNotFoundException(
  84. "Unknown rule %r" % (namespaced_rule_id,)
  85. )
  86. await self._main_store.set_push_rule_actions(
  87. user_id, namespaced_rule_id, actions, is_default_rule
  88. )
  89. else:
  90. raise UnrecognizedRequestError()
  91. self.notify_user(user_id)
  92. def notify_user(self, user_id: str) -> None:
  93. """Notify listeners about a push rule change.
  94. Args:
  95. user_id: the user ID the change is for.
  96. """
  97. stream_id = self._main_store.get_max_push_rules_stream_id()
  98. self._notifier.on_new_event("push_rules_key", stream_id, users=[user_id])
  99. def check_actions(actions: List[Union[str, JsonDict]]) -> None:
  100. """Check if the given actions are spec compliant.
  101. Args:
  102. actions: the actions to check.
  103. Raises:
  104. InvalidRuleException if the rules aren't compliant with the spec.
  105. """
  106. if not isinstance(actions, list):
  107. raise InvalidRuleException("No actions found")
  108. for a in actions:
  109. if a in ["notify", "dont_notify", "coalesce"]:
  110. pass
  111. elif isinstance(a, dict) and "set_tweak" in a:
  112. pass
  113. else:
  114. raise InvalidRuleException("Unrecognised action %s" % a)
  115. class InvalidRuleException(Exception):
  116. pass