2015-12-22 16:19:34 +01:00
|
|
|
# Copyright 2015 OpenMarket Ltd
|
2017-10-10 12:47:10 +02:00
|
|
|
# Copyright 2017 New Vector Ltd
|
2015-12-22 16:19:34 +01:00
|
|
|
#
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
# you may not use this file except in compliance with the License.
|
|
|
|
# You may obtain a copy of the License at
|
|
|
|
#
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
#
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
# limitations under the License.
|
|
|
|
|
2022-05-24 15:23:23 +02:00
|
|
|
import itertools
|
2015-12-22 16:19:34 +01:00
|
|
|
import logging
|
2022-05-24 15:23:23 +02:00
|
|
|
from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Set, Tuple, Union
|
2015-12-22 16:19:34 +01:00
|
|
|
|
2018-07-09 08:09:20 +02:00
|
|
|
from prometheus_client import Counter
|
|
|
|
|
2020-09-02 18:19:37 +02:00
|
|
|
from synapse.api.constants import EventTypes, Membership, RelationTypes
|
2022-05-20 10:54:12 +02:00
|
|
|
from synapse.event_auth import auth_types_for_event, get_user_power_level
|
2022-05-16 14:42:45 +02:00
|
|
|
from synapse.events import EventBase, relation_from_event
|
2020-09-02 18:19:37 +02:00
|
|
|
from synapse.events.snapshot import EventContext
|
2018-07-09 08:09:20 +02:00
|
|
|
from synapse.state import POWER_KEY
|
2022-03-25 15:58:56 +01:00
|
|
|
from synapse.storage.databases.main.roommember import EventIdMembership
|
2022-07-11 22:08:39 +02:00
|
|
|
from synapse.storage.state import StateFilter
|
|
|
|
from synapse.util.caches import register_cache
|
2022-05-11 13:15:21 +02:00
|
|
|
from synapse.util.metrics import measure_func
|
2022-07-11 22:08:39 +02:00
|
|
|
from synapse.visibility import filter_event_for_clients_with_state
|
2015-12-22 16:19:34 +01:00
|
|
|
|
2018-07-09 08:09:20 +02:00
|
|
|
from .push_rule_evaluator import PushRuleEvaluatorForEvent
|
2016-01-06 12:38:09 +01:00
|
|
|
|
2020-12-11 17:43:53 +01:00
|
|
|
if TYPE_CHECKING:
|
2021-03-23 12:12:48 +01:00
|
|
|
from synapse.server import HomeServer
|
2015-12-22 16:19:34 +01:00
|
|
|
|
2020-12-11 17:43:53 +01:00
|
|
|
logger = logging.getLogger(__name__)
|
2015-12-22 16:19:34 +01:00
|
|
|
|
2017-07-13 12:37:09 +02:00
|
|
|
|
2018-05-23 00:32:57 +02:00
|
|
|
push_rules_invalidation_counter = Counter(
|
2019-06-20 11:32:02 +02:00
|
|
|
"synapse_push_bulk_push_rule_evaluator_push_rules_invalidation_counter", ""
|
|
|
|
)
|
2018-05-23 00:32:57 +02:00
|
|
|
push_rules_state_size_counter = Counter(
|
2019-06-20 11:32:02 +02:00
|
|
|
"synapse_push_bulk_push_rule_evaluator_push_rules_state_size_counter", ""
|
|
|
|
)
|
2017-07-13 12:37:09 +02:00
|
|
|
|
2015-12-22 16:19:34 +01:00
|
|
|
|
2020-09-02 18:19:37 +02:00
|
|
|
STATE_EVENT_TYPES_TO_MARK_UNREAD = {
|
|
|
|
EventTypes.Topic,
|
|
|
|
EventTypes.Name,
|
|
|
|
EventTypes.RoomAvatar,
|
|
|
|
EventTypes.Tombstone,
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
def _should_count_as_unread(event: EventBase, context: EventContext) -> bool:
|
|
|
|
# Exclude rejected and soft-failed events.
|
|
|
|
if context.rejected or event.internal_metadata.is_soft_failed():
|
|
|
|
return False
|
|
|
|
|
|
|
|
# Exclude notices.
|
|
|
|
if (
|
|
|
|
not event.is_state()
|
|
|
|
and event.type == EventTypes.Message
|
|
|
|
and event.content.get("msgtype") == "m.notice"
|
|
|
|
):
|
|
|
|
return False
|
|
|
|
|
|
|
|
# Exclude edits.
|
2022-05-16 14:42:45 +02:00
|
|
|
relates_to = relation_from_event(event)
|
|
|
|
if relates_to and relates_to.rel_type == RelationTypes.REPLACE:
|
2020-09-02 18:19:37 +02:00
|
|
|
return False
|
|
|
|
|
|
|
|
# Mark events that have a non-empty string body as unread.
|
|
|
|
body = event.content.get("body")
|
|
|
|
if isinstance(body, str) and body:
|
|
|
|
return True
|
|
|
|
|
|
|
|
# Mark some state events as unread.
|
|
|
|
if event.is_state() and event.type in STATE_EVENT_TYPES_TO_MARK_UNREAD:
|
|
|
|
return True
|
|
|
|
|
|
|
|
# Mark encrypted events as unread.
|
|
|
|
if not event.is_state() and event.type == EventTypes.Encrypted:
|
|
|
|
return True
|
|
|
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
2020-09-04 12:54:56 +02:00
|
|
|
class BulkPushRuleEvaluator:
|
2017-05-02 11:46:01 +02:00
|
|
|
"""Calculates the outcome of push rules for an event for all users in the
|
|
|
|
room at once.
|
2015-12-22 18:19:22 +01:00
|
|
|
"""
|
2017-05-02 11:46:01 +02:00
|
|
|
|
2020-12-11 17:43:53 +01:00
|
|
|
def __init__(self, hs: "HomeServer"):
|
2017-05-02 11:46:01 +02:00
|
|
|
self.hs = hs
|
2022-02-23 12:04:02 +01:00
|
|
|
self.store = hs.get_datastores().main
|
2022-05-11 13:15:21 +02:00
|
|
|
self.clock = hs.get_clock()
|
2021-07-01 20:25:37 +02:00
|
|
|
self._event_auth_handler = hs.get_event_auth_handler()
|
2017-05-02 11:46:01 +02:00
|
|
|
|
2018-05-22 02:48:57 +02:00
|
|
|
self.room_push_rule_cache_metrics = register_cache(
|
2017-07-13 12:37:09 +02:00
|
|
|
"cache",
|
2018-05-22 02:48:57 +02:00
|
|
|
"room_push_rule_cache",
|
2020-05-11 19:45:23 +02:00
|
|
|
cache=[], # Meaningless size, as this isn't a cache that stores values,
|
|
|
|
resizable=False,
|
2017-07-13 12:37:09 +02:00
|
|
|
)
|
|
|
|
|
2022-05-24 15:23:23 +02:00
|
|
|
# Whether to support MSC3772 is supported.
|
|
|
|
self._relations_match_enabled = self.hs.config.experimental.msc3772_enabled
|
|
|
|
|
2020-12-11 17:43:53 +01:00
|
|
|
async def _get_rules_for_event(
|
2022-07-11 22:08:39 +02:00
|
|
|
self,
|
|
|
|
event: EventBase,
|
2020-12-11 17:43:53 +01:00
|
|
|
) -> Dict[str, List[Dict[str, Any]]]:
|
2022-07-11 22:08:39 +02:00
|
|
|
"""Get the push rules for all users who may need to be notified about
|
|
|
|
the event.
|
|
|
|
|
|
|
|
Note: this does not check if the user is allowed to see the event.
|
2017-05-02 11:46:01 +02:00
|
|
|
|
|
|
|
Returns:
|
2022-07-11 22:08:39 +02:00
|
|
|
Mapping of user ID to their push rules.
|
2017-05-02 11:46:01 +02:00
|
|
|
"""
|
2022-07-11 22:08:39 +02:00
|
|
|
# We get the users who may need to be notified by first fetching the
|
|
|
|
# local users currently in the room, finding those that have push rules,
|
|
|
|
# and *then* checking which users are actually allowed to see the event.
|
|
|
|
#
|
|
|
|
# The alternative is to first fetch all users that were joined at the
|
|
|
|
# event, but that requires fetching the full state at the event, which
|
|
|
|
# may be expensive for large rooms with few local users.
|
2017-05-02 11:46:01 +02:00
|
|
|
|
2022-07-11 22:08:39 +02:00
|
|
|
local_users = await self.store.get_local_users_in_room(event.room_id)
|
2017-05-02 11:46:01 +02:00
|
|
|
|
2022-07-20 13:06:13 +02:00
|
|
|
# Filter out appservice users.
|
|
|
|
local_users = [
|
|
|
|
u
|
|
|
|
for u in local_users
|
|
|
|
if not self.store.get_if_app_services_interested_in_user(u)
|
|
|
|
]
|
|
|
|
|
2017-05-02 11:46:01 +02:00
|
|
|
# if this event is an invite event, we may need to run rules for the user
|
|
|
|
# who's been invited, otherwise they won't get told they've been invited
|
2022-07-11 22:08:39 +02:00
|
|
|
if event.type == EventTypes.Member and event.membership == Membership.INVITE:
|
2017-05-02 11:46:01 +02:00
|
|
|
invited = event.state_key
|
2022-07-11 22:08:39 +02:00
|
|
|
if invited and self.hs.is_mine_id(invited) and invited not in local_users:
|
|
|
|
local_users = list(local_users)
|
|
|
|
local_users.append(invited)
|
2017-05-02 11:46:01 +02:00
|
|
|
|
2022-07-11 22:08:39 +02:00
|
|
|
rules_by_user = await self.store.bulk_get_push_rules(local_users)
|
2017-05-02 11:46:01 +02:00
|
|
|
|
2022-07-11 22:08:39 +02:00
|
|
|
logger.debug("Users in room: %s", local_users)
|
|
|
|
|
|
|
|
if logger.isEnabledFor(logging.DEBUG):
|
|
|
|
logger.debug(
|
|
|
|
"Returning push rules for %r %r",
|
|
|
|
event.room_id,
|
|
|
|
list(rules_by_user.keys()),
|
|
|
|
)
|
|
|
|
|
|
|
|
return rules_by_user
|
2015-12-22 16:19:34 +01:00
|
|
|
|
2020-12-11 17:43:53 +01:00
|
|
|
async def _get_power_levels_and_sender_level(
|
|
|
|
self, event: EventBase, context: EventContext
|
|
|
|
) -> Tuple[dict, int]:
|
2022-05-20 10:54:12 +02:00
|
|
|
event_types = auth_types_for_event(event.room_version, event)
|
|
|
|
prev_state_ids = await context.get_prev_state_ids(
|
|
|
|
StateFilter.from_types(event_types)
|
|
|
|
)
|
2018-07-23 14:00:22 +02:00
|
|
|
pl_event_id = prev_state_ids.get(POWER_KEY)
|
2022-05-20 10:54:12 +02:00
|
|
|
|
2017-10-05 14:27:12 +02:00
|
|
|
if pl_event_id:
|
2017-10-05 14:20:22 +02:00
|
|
|
# fastpath: if there's a power level event, that's all we need, and
|
|
|
|
# not having a power level event is an extreme edge case
|
2020-12-11 17:43:53 +01:00
|
|
|
auth_events = {POWER_KEY: await self.store.get_event(pl_event_id)}
|
2017-10-05 14:20:22 +02:00
|
|
|
else:
|
2021-07-01 20:25:37 +02:00
|
|
|
auth_events_ids = self._event_auth_handler.compute_auth_events(
|
2019-06-20 11:32:02 +02:00
|
|
|
event, prev_state_ids, for_verification=False
|
2017-10-05 14:20:22 +02:00
|
|
|
)
|
2020-12-11 17:43:53 +01:00
|
|
|
auth_events_dict = await self.store.get_events(auth_events_ids)
|
|
|
|
auth_events = {(e.type, e.state_key): e for e in auth_events_dict.values()}
|
2017-10-10 12:38:31 +02:00
|
|
|
|
2017-10-10 16:23:00 +02:00
|
|
|
sender_level = get_user_power_level(event.sender, auth_events)
|
|
|
|
|
2017-10-10 16:34:05 +02:00
|
|
|
pl_event = auth_events.get(POWER_KEY)
|
|
|
|
|
2019-08-30 17:28:26 +02:00
|
|
|
return pl_event.content if pl_event else {}, sender_level
|
2017-10-05 13:39:18 +02:00
|
|
|
|
2022-05-24 15:23:23 +02:00
|
|
|
async def _get_mutual_relations(
|
|
|
|
self, event: EventBase, rules: Iterable[Dict[str, Any]]
|
|
|
|
) -> Dict[str, Set[Tuple[str, str]]]:
|
|
|
|
"""
|
|
|
|
Fetch event metadata for events which related to the same event as the given event.
|
|
|
|
|
|
|
|
If the given event has no relation information, returns an empty dictionary.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
event_id: The event ID which is targeted by relations.
|
|
|
|
rules: The push rules which will be processed for this event.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
A dictionary of relation type to:
|
|
|
|
A set of tuples of:
|
|
|
|
The sender
|
|
|
|
The event type
|
|
|
|
"""
|
|
|
|
|
|
|
|
# If the experimental feature is not enabled, skip fetching relations.
|
|
|
|
if not self._relations_match_enabled:
|
|
|
|
return {}
|
|
|
|
|
|
|
|
# If the event does not have a relation, then cannot have any mutual
|
|
|
|
# relations.
|
|
|
|
relation = relation_from_event(event)
|
|
|
|
if not relation:
|
|
|
|
return {}
|
|
|
|
|
|
|
|
# Pre-filter to figure out which relation types are interesting.
|
|
|
|
rel_types = set()
|
|
|
|
for rule in rules:
|
|
|
|
# Skip disabled rules.
|
|
|
|
if "enabled" in rule and not rule["enabled"]:
|
|
|
|
continue
|
|
|
|
|
|
|
|
for condition in rule["conditions"]:
|
|
|
|
if condition["kind"] != "org.matrix.msc3772.relation_match":
|
|
|
|
continue
|
|
|
|
|
|
|
|
# rel_type is required.
|
|
|
|
rel_type = condition.get("rel_type")
|
|
|
|
if rel_type:
|
|
|
|
rel_types.add(rel_type)
|
|
|
|
|
|
|
|
# If no valid rules were found, no mutual relations.
|
|
|
|
if not rel_types:
|
|
|
|
return {}
|
|
|
|
|
|
|
|
# If any valid rules were found, fetch the mutual relations.
|
|
|
|
return await self.store.get_mutual_event_relations(
|
|
|
|
relation.parent_id, rel_types
|
|
|
|
)
|
|
|
|
|
2022-05-11 13:15:21 +02:00
|
|
|
@measure_func("action_for_event_by_user")
|
2020-12-11 17:43:53 +01:00
|
|
|
async def action_for_event_by_user(
|
|
|
|
self, event: EventBase, context: EventContext
|
|
|
|
) -> None:
|
2020-09-02 18:19:37 +02:00
|
|
|
"""Given an event and context, evaluate the push rules, check if the message
|
|
|
|
should increment the unread count, and insert the results into the
|
|
|
|
event_push_actions_staging table.
|
2017-05-02 11:46:01 +02:00
|
|
|
"""
|
2022-05-11 13:15:21 +02:00
|
|
|
if event.internal_metadata.is_outlier():
|
|
|
|
# This can happen due to out of band memberships
|
|
|
|
return
|
|
|
|
|
2020-09-02 18:19:37 +02:00
|
|
|
count_as_unread = _should_count_as_unread(event, context)
|
|
|
|
|
2022-07-11 22:08:39 +02:00
|
|
|
rules_by_user = await self._get_rules_for_event(event)
|
2021-07-15 12:02:43 +02:00
|
|
|
actions_by_user: Dict[str, List[Union[dict, str]]] = {}
|
2015-12-22 16:19:34 +01:00
|
|
|
|
2022-07-11 22:08:39 +02:00
|
|
|
room_member_count = await self.store.get_number_joined_users_in_room(
|
|
|
|
event.room_id
|
|
|
|
)
|
2016-03-22 14:52:45 +01:00
|
|
|
|
2019-10-31 16:43:24 +01:00
|
|
|
(
|
|
|
|
power_levels,
|
|
|
|
sender_power_level,
|
2020-07-27 18:21:34 +02:00
|
|
|
) = await self._get_power_levels_and_sender_level(event, context)
|
2017-10-05 13:39:18 +02:00
|
|
|
|
2022-05-24 15:23:23 +02:00
|
|
|
relations = await self._get_mutual_relations(
|
|
|
|
event, itertools.chain(*rules_by_user.values())
|
|
|
|
)
|
|
|
|
|
2017-10-05 13:39:18 +02:00
|
|
|
evaluator = PushRuleEvaluatorForEvent(
|
2022-05-24 15:23:23 +02:00
|
|
|
event,
|
2022-07-11 22:08:39 +02:00
|
|
|
room_member_count,
|
2022-05-24 15:23:23 +02:00
|
|
|
sender_power_level,
|
|
|
|
power_levels,
|
|
|
|
relations,
|
|
|
|
self._relations_match_enabled,
|
2017-10-05 13:39:18 +02:00
|
|
|
)
|
2016-01-18 15:09:47 +01:00
|
|
|
|
2022-07-11 22:08:39 +02:00
|
|
|
users = rules_by_user.keys()
|
|
|
|
profiles = await self.store.get_subset_users_in_room_with_profiles(
|
|
|
|
event.room_id, users
|
|
|
|
)
|
|
|
|
|
|
|
|
# This is a check for the case where user joins a room without being
|
|
|
|
# allowed to see history, and then the server receives a delayed event
|
|
|
|
# from before the user joined, which they should not be pushed for
|
|
|
|
uids_with_visibility = await filter_event_for_clients_with_state(
|
|
|
|
self.store, users, event, context
|
|
|
|
)
|
2021-01-07 14:03:38 +01:00
|
|
|
|
2020-06-15 13:03:36 +02:00
|
|
|
for uid, rules in rules_by_user.items():
|
2017-07-07 15:04:40 +02:00
|
|
|
if event.sender == uid:
|
|
|
|
continue
|
|
|
|
|
2022-07-11 22:08:39 +02:00
|
|
|
if uid not in uids_with_visibility:
|
2021-01-07 14:03:38 +01:00
|
|
|
continue
|
2017-07-07 15:04:40 +02:00
|
|
|
|
2017-04-25 15:38:51 +02:00
|
|
|
display_name = None
|
2022-07-11 22:08:39 +02:00
|
|
|
profile = profiles.get(uid)
|
|
|
|
if profile:
|
|
|
|
display_name = profile.display_name
|
2017-04-25 16:39:19 +02:00
|
|
|
|
|
|
|
if not display_name:
|
2016-12-08 14:32:05 +01:00
|
|
|
# Handle the case where we are pushing a membership event to
|
|
|
|
# that user, as they might not be already joined.
|
|
|
|
if event.type == EventTypes.Member and event.state_key == uid:
|
|
|
|
display_name = event.content.get("displayname", None)
|
2021-11-02 14:55:52 +01:00
|
|
|
if not isinstance(display_name, str):
|
|
|
|
display_name = None
|
2016-01-18 15:09:47 +01:00
|
|
|
|
2020-09-07 17:56:27 +02:00
|
|
|
if count_as_unread:
|
|
|
|
# Add an element for the current user if the event needs to be marked as
|
|
|
|
# unread, so that add_push_actions_to_staging iterates over it.
|
|
|
|
# If the event shouldn't be marked as unread but should notify the
|
|
|
|
# current user, it'll be added to the dict later.
|
|
|
|
actions_by_user[uid] = []
|
2020-09-02 18:19:37 +02:00
|
|
|
|
2015-12-22 16:19:34 +01:00
|
|
|
for rule in rules:
|
2019-06-20 11:32:02 +02:00
|
|
|
if "enabled" in rule and not rule["enabled"]:
|
2015-12-22 16:19:34 +01:00
|
|
|
continue
|
|
|
|
|
2022-05-10 13:54:30 +02:00
|
|
|
matches = evaluator.check_conditions(
|
|
|
|
rule["conditions"], uid, display_name
|
2016-01-18 15:09:47 +01:00
|
|
|
)
|
|
|
|
if matches:
|
2019-06-20 11:32:02 +02:00
|
|
|
actions = [x for x in rule["actions"] if x != "dont_notify"]
|
2020-07-01 12:08:25 +02:00
|
|
|
if actions and "notify" in actions:
|
|
|
|
# Push rules say we should notify the user of this event
|
2020-06-12 16:11:01 +02:00
|
|
|
actions_by_user[uid] = actions
|
2015-12-22 16:19:34 +01:00
|
|
|
break
|
|
|
|
|
2018-02-21 12:29:49 +01:00
|
|
|
# Mark in the DB staging area the push actions for users who should be
|
|
|
|
# notified for this event. (This will then get handled when we persist
|
|
|
|
# the event)
|
2020-09-02 18:19:37 +02:00
|
|
|
await self.store.add_push_actions_to_staging(
|
2021-02-16 23:32:34 +01:00
|
|
|
event.event_id,
|
|
|
|
actions_by_user,
|
|
|
|
count_as_unread,
|
2020-09-02 18:19:37 +02:00
|
|
|
)
|
2018-02-20 12:30:54 +01:00
|
|
|
|
2016-01-18 15:09:47 +01:00
|
|
|
|
2022-03-25 15:58:56 +01:00
|
|
|
MemberMap = Dict[str, Optional[EventIdMembership]]
|
2021-10-11 18:42:10 +02:00
|
|
|
Rule = Dict[str, dict]
|
|
|
|
RulesByUser = Dict[str, List[Rule]]
|
|
|
|
StateGroup = Union[object, int]
|