Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 
 
 

120 строки
4.1 KiB

  1. # Copyright 2016 OpenMarket Ltd
  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. import copy
  15. from typing import Any, Dict, List, Optional
  16. from synapse.push.rulekinds import PRIORITY_CLASS_INVERSE_MAP, PRIORITY_CLASS_MAP
  17. from synapse.synapse_rust.push import FilteredPushRules, PushRule
  18. from synapse.types import UserID
  19. def format_push_rules_for_user(
  20. user: UserID, ruleslist: FilteredPushRules
  21. ) -> Dict[str, Dict[str, List[Dict[str, Any]]]]:
  22. """Converts a list of rawrules and a enabled map into nested dictionaries
  23. to match the Matrix client-server format for push rules"""
  24. rules: Dict[str, Dict[str, List[Dict[str, Any]]]] = {"global": {}}
  25. rules["global"] = _add_empty_priority_class_arrays(rules["global"])
  26. for r, enabled in ruleslist.rules():
  27. template_name = _priority_class_to_template_name(r.priority_class)
  28. rulearray = rules["global"][template_name]
  29. template_rule = _rule_to_template(r)
  30. if not template_rule:
  31. continue
  32. rulearray.append(template_rule)
  33. _convert_type_to_value(template_rule, user)
  34. template_rule["enabled"] = enabled
  35. if "conditions" not in template_rule:
  36. # Not all formatted rules have explicit conditions, e.g. "room"
  37. # rules omit them as they can be derived from the kind and rule ID.
  38. #
  39. # If the formatted rule has no conditions then we can skip the
  40. # formatting of conditions.
  41. continue
  42. # Remove internal stuff.
  43. template_rule["conditions"] = copy.deepcopy(template_rule["conditions"])
  44. for c in template_rule["conditions"]:
  45. c.pop("_cache_key", None)
  46. _convert_type_to_value(c, user)
  47. return rules
  48. def _convert_type_to_value(rule_or_cond: Dict[str, Any], user: UserID) -> None:
  49. for type_key in ("pattern", "value"):
  50. type_value = rule_or_cond.pop(f"{type_key}_type", None)
  51. if type_value == "user_id":
  52. rule_or_cond[type_key] = user.to_string()
  53. elif type_value == "user_localpart":
  54. rule_or_cond[type_key] = user.localpart
  55. def _add_empty_priority_class_arrays(d: Dict[str, list]) -> Dict[str, list]:
  56. for pc in PRIORITY_CLASS_MAP.keys():
  57. d[pc] = []
  58. return d
  59. def _rule_to_template(rule: PushRule) -> Optional[Dict[str, Any]]:
  60. templaterule: Dict[str, Any]
  61. unscoped_rule_id = _rule_id_from_namespaced(rule.rule_id)
  62. template_name = _priority_class_to_template_name(rule.priority_class)
  63. if template_name in ["override", "underride"]:
  64. templaterule = {"conditions": rule.conditions, "actions": rule.actions}
  65. elif template_name in ["sender", "room"]:
  66. templaterule = {"actions": rule.actions}
  67. unscoped_rule_id = rule.conditions[0]["pattern"]
  68. elif template_name == "content":
  69. if len(rule.conditions) != 1:
  70. return None
  71. thecond = rule.conditions[0]
  72. templaterule = {"actions": rule.actions}
  73. if "pattern" in thecond:
  74. templaterule["pattern"] = thecond["pattern"]
  75. elif "pattern_type" in thecond:
  76. templaterule["pattern_type"] = thecond["pattern_type"]
  77. else:
  78. return None
  79. else:
  80. # This should not be reached unless this function is not kept in sync
  81. # with PRIORITY_CLASS_INVERSE_MAP.
  82. raise ValueError("Unexpected template_name: %s" % (template_name,))
  83. templaterule["rule_id"] = unscoped_rule_id
  84. templaterule["default"] = rule.default
  85. return templaterule
  86. def _rule_id_from_namespaced(in_rule_id: str) -> str:
  87. return in_rule_id.split("/")[-1]
  88. def _priority_class_to_template_name(pc: int) -> str:
  89. return PRIORITY_CLASS_INVERSE_MAP[pc]