選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 
 
 

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