clientformat.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  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.types import UserID
  18. def format_push_rules_for_user(
  19. user: UserID, ruleslist: List
  20. ) -> Dict[str, Dict[str, list]]:
  21. """Converts a list of rawrules and a enabled map into nested dictionaries
  22. to match the Matrix client-server format for push rules"""
  23. # We're going to be mutating this a lot, so do a deep copy
  24. ruleslist = copy.deepcopy(ruleslist)
  25. rules: Dict[str, Dict[str, List[Dict[str, Any]]]] = {
  26. "global": {},
  27. "device": {},
  28. }
  29. rules["global"] = _add_empty_priority_class_arrays(rules["global"])
  30. for r in ruleslist:
  31. template_name = _priority_class_to_template_name(r["priority_class"])
  32. # Remove internal stuff.
  33. for c in r["conditions"]:
  34. c.pop("_cache_key", None)
  35. pattern_type = c.pop("pattern_type", None)
  36. if pattern_type == "user_id":
  37. c["pattern"] = user.to_string()
  38. elif pattern_type == "user_localpart":
  39. c["pattern"] = user.localpart
  40. sender_type = c.pop("sender_type", None)
  41. if sender_type == "user_id":
  42. c["sender"] = user.to_string()
  43. rulearray = rules["global"][template_name]
  44. template_rule = _rule_to_template(r)
  45. if template_rule:
  46. if "enabled" in r:
  47. template_rule["enabled"] = r["enabled"]
  48. else:
  49. template_rule["enabled"] = True
  50. rulearray.append(template_rule)
  51. return rules
  52. def _add_empty_priority_class_arrays(d: Dict[str, list]) -> Dict[str, list]:
  53. for pc in PRIORITY_CLASS_MAP.keys():
  54. d[pc] = []
  55. return d
  56. def _rule_to_template(rule: Dict[str, Any]) -> Optional[Dict[str, Any]]:
  57. unscoped_rule_id = None
  58. if "rule_id" in rule:
  59. unscoped_rule_id = _rule_id_from_namespaced(rule["rule_id"])
  60. template_name = _priority_class_to_template_name(rule["priority_class"])
  61. if template_name in ["override", "underride"]:
  62. templaterule = {k: rule[k] for k in ["conditions", "actions"]}
  63. elif template_name in ["sender", "room"]:
  64. templaterule = {"actions": rule["actions"]}
  65. unscoped_rule_id = rule["conditions"][0]["pattern"]
  66. elif template_name == "content":
  67. if len(rule["conditions"]) != 1:
  68. return None
  69. thecond = rule["conditions"][0]
  70. if "pattern" not in thecond:
  71. return None
  72. templaterule = {"actions": rule["actions"]}
  73. templaterule["pattern"] = thecond["pattern"]
  74. else:
  75. # This should not be reached unless this function is not kept in sync
  76. # with PRIORITY_CLASS_INVERSE_MAP.
  77. raise ValueError("Unexpected template_name: %s" % (template_name,))
  78. if unscoped_rule_id:
  79. templaterule["rule_id"] = unscoped_rule_id
  80. if "default" in rule:
  81. templaterule["default"] = rule["default"]
  82. return templaterule
  83. def _rule_id_from_namespaced(in_rule_id: str) -> str:
  84. return in_rule_id.split("/")[-1]
  85. def _priority_class_to_template_name(pc: int) -> str:
  86. return PRIORITY_CLASS_INVERSE_MAP[pc]