No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 
 
 

551 líneas
21 KiB

  1. # Copyright 2015 OpenMarket Ltd
  2. # Copyright 2017 New Vector Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import logging
  16. from typing import (
  17. TYPE_CHECKING,
  18. Any,
  19. Collection,
  20. Dict,
  21. List,
  22. Mapping,
  23. Optional,
  24. Sequence,
  25. Tuple,
  26. Union,
  27. )
  28. from prometheus_client import Counter
  29. from synapse.api.constants import (
  30. MAIN_TIMELINE,
  31. EventContentFields,
  32. EventTypes,
  33. Membership,
  34. RelationTypes,
  35. )
  36. from synapse.api.room_versions import PushRuleRoomFlag
  37. from synapse.event_auth import auth_types_for_event, get_user_power_level
  38. from synapse.events import EventBase, relation_from_event
  39. from synapse.events.snapshot import EventContext
  40. from synapse.state import POWER_KEY
  41. from synapse.storage.databases.main.roommember import EventIdMembership
  42. from synapse.synapse_rust.push import FilteredPushRules, PushRuleEvaluator
  43. from synapse.types import JsonValue
  44. from synapse.types.state import StateFilter
  45. from synapse.util.caches import register_cache
  46. from synapse.util.metrics import measure_func
  47. from synapse.visibility import filter_event_for_clients_with_state
  48. if TYPE_CHECKING:
  49. from synapse.server import HomeServer
  50. logger = logging.getLogger(__name__)
  51. push_rules_invalidation_counter = Counter(
  52. "synapse_push_bulk_push_rule_evaluator_push_rules_invalidation_counter", ""
  53. )
  54. push_rules_state_size_counter = Counter(
  55. "synapse_push_bulk_push_rule_evaluator_push_rules_state_size_counter", ""
  56. )
  57. STATE_EVENT_TYPES_TO_MARK_UNREAD = {
  58. EventTypes.Topic,
  59. EventTypes.Name,
  60. EventTypes.RoomAvatar,
  61. EventTypes.Tombstone,
  62. }
  63. SENTINEL = object()
  64. def _should_count_as_unread(event: EventBase, context: EventContext) -> bool:
  65. # Exclude rejected and soft-failed events.
  66. if context.rejected or event.internal_metadata.is_soft_failed():
  67. return False
  68. # Exclude notices.
  69. if (
  70. not event.is_state()
  71. and event.type == EventTypes.Message
  72. and event.content.get("msgtype") == "m.notice"
  73. ):
  74. return False
  75. # Exclude edits.
  76. relates_to = relation_from_event(event)
  77. if relates_to and relates_to.rel_type == RelationTypes.REPLACE:
  78. return False
  79. # Mark events that have a non-empty string body as unread.
  80. body = event.content.get("body")
  81. if isinstance(body, str) and body:
  82. return True
  83. # Mark some state events as unread.
  84. if event.is_state() and event.type in STATE_EVENT_TYPES_TO_MARK_UNREAD:
  85. return True
  86. # Mark encrypted events as unread.
  87. if not event.is_state() and event.type == EventTypes.Encrypted:
  88. return True
  89. return False
  90. class BulkPushRuleEvaluator:
  91. """Calculates the outcome of push rules for an event for all users in the
  92. room at once.
  93. """
  94. def __init__(self, hs: "HomeServer"):
  95. self.hs = hs
  96. self.store = hs.get_datastores().main
  97. self.clock = hs.get_clock()
  98. self._event_auth_handler = hs.get_event_auth_handler()
  99. self.should_calculate_push_rules = self.hs.config.push.enable_push
  100. self._related_event_match_enabled = self.hs.config.experimental.msc3664_enabled
  101. self.room_push_rule_cache_metrics = register_cache(
  102. "cache",
  103. "room_push_rule_cache",
  104. cache=[], # Meaningless size, as this isn't a cache that stores values,
  105. resizable=False,
  106. )
  107. async def _get_rules_for_event(
  108. self,
  109. event: EventBase,
  110. ) -> Dict[str, FilteredPushRules]:
  111. """Get the push rules for all users who may need to be notified about
  112. the event.
  113. Note: this does not check if the user is allowed to see the event.
  114. Returns:
  115. Mapping of user ID to their push rules.
  116. """
  117. # If this is a membership event, only calculate push rules for the target.
  118. # While it's possible for users to configure push rules to respond to such an
  119. # event, in practise nobody does this. At the cost of violating the spec a
  120. # little, we can skip fetching a huge number of push rules in large rooms.
  121. # This helps make joins and leaves faster.
  122. if event.type == EventTypes.Member:
  123. local_users: Sequence[str] = []
  124. # We never notify a user about their own actions. This is enforced in
  125. # `_action_for_event_by_user` in the loop over `rules_by_user`, but we
  126. # do the same check here to avoid unnecessary DB queries.
  127. if event.sender != event.state_key and self.hs.is_mine_id(event.state_key):
  128. # Check the target is in the room, to avoid notifying them of
  129. # e.g. a pre-emptive ban.
  130. target_already_in_room = await self.store.check_local_user_in_room(
  131. event.state_key, event.room_id
  132. )
  133. if target_already_in_room:
  134. local_users = [event.state_key]
  135. else:
  136. # We get the users who may need to be notified by first fetching the
  137. # local users currently in the room, finding those that have push rules,
  138. # and *then* checking which users are actually allowed to see the event.
  139. #
  140. # The alternative is to first fetch all users that were joined at the
  141. # event, but that requires fetching the full state at the event, which
  142. # may be expensive for large rooms with few local users.
  143. local_users = await self.store.get_local_users_in_room(event.room_id)
  144. # Filter out appservice users.
  145. local_users = [
  146. u
  147. for u in local_users
  148. if not self.store.get_if_app_services_interested_in_user(u)
  149. ]
  150. # if this event is an invite event, we may need to run rules for the user
  151. # who's been invited, otherwise they won't get told they've been invited
  152. if event.type == EventTypes.Member and event.membership == Membership.INVITE:
  153. invited = event.state_key
  154. if invited and self.hs.is_mine_id(invited) and invited not in local_users:
  155. local_users.append(invited)
  156. if not local_users:
  157. return {}
  158. rules_by_user = await self.store.bulk_get_push_rules(local_users)
  159. logger.debug("Users in room: %s", local_users)
  160. if logger.isEnabledFor(logging.DEBUG):
  161. logger.debug(
  162. "Returning push rules for %r %r",
  163. event.room_id,
  164. list(rules_by_user.keys()),
  165. )
  166. return rules_by_user
  167. async def _get_power_levels_and_sender_level(
  168. self,
  169. event: EventBase,
  170. context: EventContext,
  171. event_id_to_event: Mapping[str, EventBase],
  172. ) -> Tuple[dict, Optional[int]]:
  173. """
  174. Given an event and an event context, get the power level event relevant to the event
  175. and the power level of the sender of the event.
  176. Args:
  177. event: event to check
  178. context: context of event to check
  179. event_id_to_event: a mapping of event_id to event for a set of events being
  180. batch persisted. This is needed as the sought-after power level event may
  181. be in this batch rather than the DB
  182. """
  183. # There are no power levels and sender levels possible to get from outlier
  184. if event.internal_metadata.is_outlier():
  185. return {}, None
  186. event_types = auth_types_for_event(event.room_version, event)
  187. prev_state_ids = await context.get_prev_state_ids(
  188. StateFilter.from_types(event_types)
  189. )
  190. pl_event_id = prev_state_ids.get(POWER_KEY)
  191. # fastpath: if there's a power level event, that's all we need, and
  192. # not having a power level event is an extreme edge case
  193. if pl_event_id:
  194. # Get the power level event from the batch, or fall back to the database.
  195. pl_event = event_id_to_event.get(pl_event_id)
  196. if pl_event:
  197. auth_events = {POWER_KEY: pl_event}
  198. else:
  199. auth_events = {POWER_KEY: await self.store.get_event(pl_event_id)}
  200. else:
  201. auth_events_ids = self._event_auth_handler.compute_auth_events(
  202. event, prev_state_ids, for_verification=False
  203. )
  204. auth_events_dict = await self.store.get_events(auth_events_ids)
  205. # Some needed auth events might be in the batch, combine them with those
  206. # fetched from the database.
  207. for auth_event_id in auth_events_ids:
  208. auth_event = event_id_to_event.get(auth_event_id)
  209. if auth_event:
  210. auth_events_dict[auth_event_id] = auth_event
  211. auth_events = {(e.type, e.state_key): e for e in auth_events_dict.values()}
  212. sender_level = get_user_power_level(event.sender, auth_events)
  213. pl_event = auth_events.get(POWER_KEY)
  214. return pl_event.content if pl_event else {}, sender_level
  215. async def _related_events(
  216. self, event: EventBase
  217. ) -> Dict[str, Dict[str, JsonValue]]:
  218. """Fetches the related events for 'event'. Sets the im.vector.is_falling_back key if the event is from a fallback relation
  219. Returns:
  220. Mapping of relation type to flattened events.
  221. """
  222. related_events: Dict[str, Dict[str, JsonValue]] = {}
  223. if self._related_event_match_enabled:
  224. related_event_id = event.content.get("m.relates_to", {}).get("event_id")
  225. relation_type = event.content.get("m.relates_to", {}).get("rel_type")
  226. if related_event_id is not None and relation_type is not None:
  227. related_event = await self.store.get_event(
  228. related_event_id, allow_none=True
  229. )
  230. if related_event is not None:
  231. related_events[relation_type] = _flatten_dict(related_event)
  232. reply_event_id = (
  233. event.content.get("m.relates_to", {})
  234. .get("m.in_reply_to", {})
  235. .get("event_id")
  236. )
  237. # convert replies to pseudo relations
  238. if reply_event_id is not None:
  239. related_event = await self.store.get_event(
  240. reply_event_id, allow_none=True
  241. )
  242. if related_event is not None:
  243. related_events["m.in_reply_to"] = _flatten_dict(related_event)
  244. # indicate that this is from a fallback relation.
  245. if relation_type == "m.thread" and event.content.get(
  246. "m.relates_to", {}
  247. ).get("is_falling_back", False):
  248. related_events["m.in_reply_to"][
  249. "im.vector.is_falling_back"
  250. ] = ""
  251. return related_events
  252. async def action_for_events_by_user(
  253. self, events_and_context: List[Tuple[EventBase, EventContext]]
  254. ) -> None:
  255. """Given a list of events and their associated contexts, evaluate the push rules
  256. for each event, check if the message should increment the unread count, and
  257. insert the results into the event_push_actions_staging table.
  258. """
  259. if not self.should_calculate_push_rules:
  260. return
  261. # For batched events the power level events may not have been persisted yet,
  262. # so we pass in the batched events. Thus if the event cannot be found in the
  263. # database we can check in the batch.
  264. event_id_to_event = {e.event_id: e for e, _ in events_and_context}
  265. for event, context in events_and_context:
  266. await self._action_for_event_by_user(event, context, event_id_to_event)
  267. @measure_func("action_for_event_by_user")
  268. async def _action_for_event_by_user(
  269. self,
  270. event: EventBase,
  271. context: EventContext,
  272. event_id_to_event: Mapping[str, EventBase],
  273. ) -> None:
  274. if (
  275. not event.internal_metadata.is_notifiable()
  276. or event.room_id in self.hs.config.server.rooms_to_exclude_from_sync
  277. ):
  278. # Push rules for events that aren't notifiable can't be processed by this and
  279. # we want to skip push notification actions for historical messages
  280. # because we don't want to notify people about old history back in time.
  281. # The historical messages also do not have the proper `context.current_state_ids`
  282. # and `state_groups` because they have `prev_events` that aren't persisted yet
  283. # (historical messages persisted in reverse-chronological order).
  284. return
  285. # Disable counting as unread unless the experimental configuration is
  286. # enabled, as it can cause additional (unwanted) rows to be added to the
  287. # event_push_actions table.
  288. count_as_unread = False
  289. if self.hs.config.experimental.msc2654_enabled:
  290. count_as_unread = _should_count_as_unread(event, context)
  291. rules_by_user = await self._get_rules_for_event(event)
  292. actions_by_user: Dict[str, Collection[Union[Mapping, str]]] = {}
  293. room_member_count = await self.store.get_number_joined_users_in_room(
  294. event.room_id
  295. )
  296. (
  297. power_levels,
  298. sender_power_level,
  299. ) = await self._get_power_levels_and_sender_level(
  300. event, context, event_id_to_event
  301. )
  302. # Find the event's thread ID.
  303. relation = relation_from_event(event)
  304. # If the event does not have a relation, then it cannot have a thread ID.
  305. thread_id = MAIN_TIMELINE
  306. if relation:
  307. # Recursively attempt to find the thread this event relates to.
  308. if relation.rel_type == RelationTypes.THREAD:
  309. thread_id = relation.parent_id
  310. else:
  311. # Since the event has not yet been persisted we check whether
  312. # the parent is part of a thread.
  313. thread_id = await self.store.get_thread_id(relation.parent_id)
  314. related_events = await self._related_events(event)
  315. # It's possible that old room versions have non-integer power levels (floats or
  316. # strings; even the occasional `null`). For old rooms, we interpret these as if
  317. # they were integers. Do this here for the `@room` power level threshold.
  318. # Note that this is done automatically for the sender's power level by
  319. # _get_power_levels_and_sender_level in its call to get_user_power_level
  320. # (even for room V10.)
  321. notification_levels = power_levels.get("notifications", {})
  322. if not event.room_version.enforce_int_power_levels:
  323. keys = list(notification_levels.keys())
  324. for key in keys:
  325. level = notification_levels.get(key, SENTINEL)
  326. if level is not SENTINEL and type(level) is not int: # noqa: E721
  327. try:
  328. notification_levels[key] = int(level)
  329. except (TypeError, ValueError):
  330. del notification_levels[key]
  331. # Pull out any user and room mentions.
  332. has_mentions = EventContentFields.MENTIONS in event.content
  333. evaluator = PushRuleEvaluator(
  334. _flatten_dict(event),
  335. has_mentions,
  336. room_member_count,
  337. sender_power_level,
  338. notification_levels,
  339. related_events,
  340. self._related_event_match_enabled,
  341. event.room_version.msc3931_push_features,
  342. self.hs.config.experimental.msc1767_enabled, # MSC3931 flag
  343. )
  344. users = rules_by_user.keys()
  345. profiles = await self.store.get_subset_users_in_room_with_profiles(
  346. event.room_id, users
  347. )
  348. for uid, rules in rules_by_user.items():
  349. if event.sender == uid:
  350. continue
  351. display_name = None
  352. profile = profiles.get(uid)
  353. if profile:
  354. display_name = profile.display_name
  355. if not display_name:
  356. # Handle the case where we are pushing a membership event to
  357. # that user, as they might not be already joined.
  358. if event.type == EventTypes.Member and event.state_key == uid:
  359. display_name = event.content.get("displayname", None)
  360. if not isinstance(display_name, str):
  361. display_name = None
  362. if count_as_unread:
  363. # Add an element for the current user if the event needs to be marked as
  364. # unread, so that add_push_actions_to_staging iterates over it.
  365. # If the event shouldn't be marked as unread but should notify the
  366. # current user, it'll be added to the dict later.
  367. actions_by_user[uid] = []
  368. actions = evaluator.run(rules, uid, display_name)
  369. if "notify" in actions:
  370. # Push rules say we should notify the user of this event
  371. actions_by_user[uid] = actions
  372. # If there aren't any actions then we can skip the rest of the
  373. # processing.
  374. if not actions_by_user:
  375. return
  376. # This is a check for the case where user joins a room without being
  377. # allowed to see history, and then the server receives a delayed event
  378. # from before the user joined, which they should not be pushed for
  379. #
  380. # We do this *after* calculating the push actions as a) its unlikely
  381. # that we'll filter anyone out and b) for large rooms its likely that
  382. # most users will have push disabled and so the set of users to check is
  383. # much smaller.
  384. uids_with_visibility = await filter_event_for_clients_with_state(
  385. self.store, actions_by_user.keys(), event, context
  386. )
  387. for user_id in set(actions_by_user).difference(uids_with_visibility):
  388. actions_by_user.pop(user_id, None)
  389. # Mark in the DB staging area the push actions for users who should be
  390. # notified for this event. (This will then get handled when we persist
  391. # the event)
  392. await self.store.add_push_actions_to_staging(
  393. event.event_id,
  394. actions_by_user,
  395. count_as_unread,
  396. thread_id,
  397. )
  398. MemberMap = Dict[str, Optional[EventIdMembership]]
  399. Rule = Dict[str, dict]
  400. RulesByUser = Dict[str, List[Rule]]
  401. StateGroup = Union[object, int]
  402. def _is_simple_value(value: Any) -> bool:
  403. return (
  404. isinstance(value, (bool, str))
  405. or type(value) is int # noqa: E721
  406. or value is None
  407. )
  408. def _flatten_dict(
  409. d: Union[EventBase, Mapping[str, Any]],
  410. prefix: Optional[List[str]] = None,
  411. result: Optional[Dict[str, JsonValue]] = None,
  412. ) -> Dict[str, JsonValue]:
  413. """
  414. Given a JSON dictionary (or event) which might contain sub dictionaries,
  415. flatten it into a single layer dictionary by combining the keys & sub-keys.
  416. String, integer, boolean, null or lists of those values are kept. All others are dropped.
  417. Transforms:
  418. {"foo": {"bar": "test"}}
  419. To:
  420. {"foo.bar": "test"}
  421. Args:
  422. d: The event or content to continue flattening.
  423. prefix: The key prefix (from outer dictionaries).
  424. result: The result to mutate.
  425. Returns:
  426. The resulting dictionary.
  427. """
  428. if prefix is None:
  429. prefix = []
  430. if result is None:
  431. result = {}
  432. for key, value in d.items():
  433. # Escape periods in the key with a backslash (and backslashes with an
  434. # extra backslash). This is since a period is used as a separator between
  435. # nested fields.
  436. key = key.replace("\\", "\\\\").replace(".", "\\.")
  437. if _is_simple_value(value):
  438. result[".".join(prefix + [key])] = value
  439. elif isinstance(value, (list, tuple)):
  440. result[".".join(prefix + [key])] = [v for v in value if _is_simple_value(v)]
  441. elif isinstance(value, Mapping):
  442. # do not set `room_version` due to recursion considerations below
  443. _flatten_dict(value, prefix=(prefix + [key]), result=result)
  444. # `room_version` should only ever be set when looking at the top level of an event
  445. if (
  446. isinstance(d, EventBase)
  447. and PushRuleRoomFlag.EXTENSIBLE_EVENTS in d.room_version.msc3931_push_features
  448. ):
  449. # Room supports extensible events: replace `content.body` with the plain text
  450. # representation from `m.markup`, as per MSC1767.
  451. markup = d.get("content").get("m.markup")
  452. if d.room_version.identifier.startswith("org.matrix.msc1767."):
  453. markup = d.get("content").get("org.matrix.msc1767.markup")
  454. if markup is not None and isinstance(markup, list):
  455. text = ""
  456. for rep in markup:
  457. if not isinstance(rep, dict):
  458. # invalid markup - skip all processing
  459. break
  460. if rep.get("mimetype", "text/plain") == "text/plain":
  461. rep_text = rep.get("body")
  462. if rep_text is not None and isinstance(rep_text, str):
  463. text = rep_text.lower()
  464. break
  465. result["content.body"] = text
  466. return result