2015-12-22 16:19:34 +01:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
# Copyright 2015 OpenMarket Ltd
|
|
|
|
#
|
|
|
|
# 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.
|
|
|
|
|
|
|
|
import logging
|
|
|
|
|
|
|
|
from twisted.internet import defer
|
|
|
|
|
2016-03-08 12:45:50 +01:00
|
|
|
from .push_rule_evaluator import PushRuleEvaluatorForEvent
|
2016-01-18 15:09:47 +01:00
|
|
|
|
2017-05-08 14:07:41 +02:00
|
|
|
from synapse.visibility import filter_events_for_clients_context
|
2017-05-02 11:46:01 +02:00
|
|
|
from synapse.api.constants import EventTypes, Membership
|
|
|
|
from synapse.util.caches.descriptors import cached
|
|
|
|
from synapse.util.async import Linearizer
|
2015-12-22 16:19:34 +01:00
|
|
|
|
2016-01-06 12:38:09 +01:00
|
|
|
|
2015-12-22 16:19:34 +01:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
2017-05-02 11:46:01 +02:00
|
|
|
rules_by_room = {}
|
2015-12-22 16:19:34 +01: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
|
|
|
|
|
|
|
def __init__(self, hs):
|
|
|
|
self.hs = hs
|
|
|
|
self.store = hs.get_datastore()
|
|
|
|
|
|
|
|
@defer.inlineCallbacks
|
|
|
|
def _get_rules_for_event(self, event, context):
|
|
|
|
"""This gets the rules for all users in the room at the time of the event,
|
|
|
|
as well as the push rules for the invitee if the event is an invite.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
dict of user_id -> push_rules
|
|
|
|
"""
|
|
|
|
room_id = event.room_id
|
|
|
|
rules_for_room = self._get_rules_for_room(room_id)
|
|
|
|
|
|
|
|
rules_by_user = yield rules_for_room.get_rules(context)
|
|
|
|
|
|
|
|
# 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
|
|
|
|
if event.type == 'm.room.member' and event.content['membership'] == 'invite':
|
|
|
|
invited = event.state_key
|
|
|
|
if invited and self.hs.is_mine_id(invited):
|
|
|
|
has_pusher = yield self.store.user_has_pusher(invited)
|
|
|
|
if has_pusher:
|
|
|
|
rules_by_user = dict(rules_by_user)
|
|
|
|
rules_by_user[invited] = yield self.store.get_push_rules_for_user(
|
|
|
|
invited
|
|
|
|
)
|
|
|
|
|
|
|
|
defer.returnValue(rules_by_user)
|
|
|
|
|
|
|
|
@cached(max_entries=10000)
|
|
|
|
def _get_rules_for_room(self, room_id):
|
|
|
|
"""Get the current RulesForRoom object for the given room id
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
RulesForRoom
|
|
|
|
"""
|
2017-05-18 12:45:56 +02:00
|
|
|
# It's important that RulesForRoom gets added to self._get_rules_for_room.cache
|
|
|
|
# before any lookup methods get called on it as otherwise there may be
|
|
|
|
# a race if invalidate_all gets called (which assumes its in the cache)
|
2017-05-02 11:46:01 +02:00
|
|
|
return RulesForRoom(self.hs, room_id, self._get_rules_for_room.cache)
|
2015-12-22 16:19:34 +01:00
|
|
|
|
2016-01-06 12:38:09 +01:00
|
|
|
@defer.inlineCallbacks
|
2016-08-25 18:32:22 +02:00
|
|
|
def action_for_event_by_user(self, event, context):
|
2017-05-02 11:46:01 +02:00
|
|
|
"""Given an event and context, evaluate the push rules and return
|
|
|
|
the results
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
dict of user_id -> action
|
|
|
|
"""
|
|
|
|
rules_by_user = yield self._get_rules_for_event(event, context)
|
2015-12-22 16:19:34 +01:00
|
|
|
actions_by_user = {}
|
|
|
|
|
2017-05-08 14:07:41 +02:00
|
|
|
# None of these users can be peeking since this list of users comes
|
|
|
|
# from the set of users in the room, so we know for sure they're all
|
|
|
|
# actually in the room.
|
2017-05-02 11:46:01 +02:00
|
|
|
user_tuples = [(u, False) for u in rules_by_user]
|
2017-05-08 14:07:41 +02:00
|
|
|
|
|
|
|
filtered_by_user = yield filter_events_for_clients_context(
|
|
|
|
self.store, user_tuples, [event], {event.event_id: context}
|
|
|
|
)
|
|
|
|
|
2016-08-25 18:32:22 +02:00
|
|
|
room_members = yield self.store.get_joined_users_from_context(
|
2016-08-31 14:55:02 +02:00
|
|
|
event, context
|
2016-06-01 12:08:45 +02:00
|
|
|
)
|
2016-03-22 14:52:45 +01:00
|
|
|
|
|
|
|
evaluator = PushRuleEvaluatorForEvent(event, len(room_members))
|
2016-01-18 15:09:47 +01:00
|
|
|
|
|
|
|
condition_cache = {}
|
|
|
|
|
2017-05-02 11:46:01 +02:00
|
|
|
for uid, rules in rules_by_user.iteritems():
|
2017-04-25 15:38:51 +02:00
|
|
|
display_name = None
|
2017-04-25 16:22:59 +02:00
|
|
|
profile_info = room_members.get(uid)
|
2017-04-25 15:38:51 +02:00
|
|
|
if profile_info:
|
|
|
|
display_name = profile_info.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)
|
2016-01-18 15:09:47 +01:00
|
|
|
|
2017-05-08 14:07:41 +02:00
|
|
|
filtered = filtered_by_user[uid]
|
|
|
|
if len(filtered) == 0:
|
|
|
|
continue
|
|
|
|
|
|
|
|
if filtered[0].sender == uid:
|
|
|
|
continue
|
|
|
|
|
2015-12-22 16:19:34 +01:00
|
|
|
for rule in rules:
|
|
|
|
if 'enabled' in rule and not rule['enabled']:
|
|
|
|
continue
|
|
|
|
|
2016-01-18 15:09:47 +01:00
|
|
|
matches = _condition_checker(
|
2016-01-18 11:09:14 +01:00
|
|
|
evaluator, rule['conditions'], uid, display_name, condition_cache
|
2016-01-18 15:09:47 +01:00
|
|
|
)
|
|
|
|
if matches:
|
2015-12-22 16:19:34 +01:00
|
|
|
actions = [x for x in rule['actions'] if x != 'dont_notify']
|
2016-01-22 18:21:58 +01:00
|
|
|
if actions and 'notify' in actions:
|
2015-12-22 16:19:34 +01:00
|
|
|
actions_by_user[uid] = actions
|
|
|
|
break
|
2016-01-06 12:38:09 +01:00
|
|
|
defer.returnValue(actions_by_user)
|
2015-12-22 16:19:34 +01:00
|
|
|
|
2016-01-18 15:09:47 +01:00
|
|
|
|
2016-01-18 11:09:14 +01:00
|
|
|
def _condition_checker(evaluator, conditions, uid, display_name, cache):
|
2016-01-18 15:09:47 +01:00
|
|
|
for cond in conditions:
|
|
|
|
_id = cond.get("_id", None)
|
|
|
|
if _id:
|
|
|
|
res = cache.get(_id, None)
|
|
|
|
if res is False:
|
2016-01-19 15:24:59 +01:00
|
|
|
return False
|
2016-01-18 15:09:47 +01:00
|
|
|
elif res is True:
|
|
|
|
continue
|
|
|
|
|
2016-02-18 17:05:13 +01:00
|
|
|
res = evaluator.matches(cond, uid, display_name)
|
2016-01-18 15:09:47 +01:00
|
|
|
if _id:
|
2016-01-19 17:01:05 +01:00
|
|
|
cache[_id] = bool(res)
|
2016-01-18 15:09:47 +01:00
|
|
|
|
2016-01-19 15:22:02 +01:00
|
|
|
if not res:
|
2016-01-18 15:09:47 +01:00
|
|
|
return False
|
|
|
|
|
|
|
|
return True
|
2017-05-02 11:46:01 +02:00
|
|
|
|
|
|
|
|
|
|
|
class RulesForRoom(object):
|
|
|
|
"""Caches push rules for users in a room.
|
|
|
|
|
|
|
|
This efficiently handles users joining/leaving the room by not invalidating
|
|
|
|
the entire cache for the room.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, hs, room_id, rules_for_room_cache):
|
|
|
|
"""
|
|
|
|
Args:
|
|
|
|
hs (HomeServer)
|
|
|
|
room_id (str)
|
|
|
|
rules_for_room_cache(Cache): The cache object that caches these
|
|
|
|
RoomsForUser objects.
|
|
|
|
"""
|
|
|
|
self.room_id = room_id
|
|
|
|
self.is_mine_id = hs.is_mine_id
|
|
|
|
self.store = hs.get_datastore()
|
|
|
|
|
|
|
|
self.linearizer = Linearizer(name="rules_for_room")
|
|
|
|
|
|
|
|
self.member_map = {} # event_id -> (user_id, state)
|
|
|
|
self.rules_by_user = {} # user_id -> rules
|
|
|
|
|
|
|
|
# The last state group we updated the caches for. If the state_group of
|
|
|
|
# a new event comes along, we know that we can just return the cached
|
|
|
|
# result.
|
|
|
|
# On invalidation of the rules themselves (if the user changes them),
|
|
|
|
# we invalidate everything and set state_group to `object()`
|
|
|
|
self.state_group = object()
|
|
|
|
|
|
|
|
# A sequence number to keep track of when we're allowed to update the
|
|
|
|
# cache. We bump the sequence number when we invalidate the cache. If
|
|
|
|
# the sequence number changes while we're calculating stuff we should
|
|
|
|
# not update the cache with it.
|
|
|
|
self.sequence = 0
|
|
|
|
|
|
|
|
# We need to be clever on the invalidating caches callbacks, as
|
|
|
|
# otherwise the invalidation callback holds a reference to the object,
|
|
|
|
# potentially causing it to leak.
|
|
|
|
# To get around this we pass a function that on invalidations looks ups
|
|
|
|
# the RoomsForUser entry in the cache, rather than keeping a reference
|
|
|
|
# to self around in the callback.
|
|
|
|
def invalidate_all_cb():
|
|
|
|
rules = rules_for_room_cache.get(room_id, update_metrics=False)
|
|
|
|
if rules:
|
|
|
|
rules.invalidate_all()
|
|
|
|
|
|
|
|
self.invalidate_all_cb = invalidate_all_cb
|
|
|
|
|
|
|
|
@defer.inlineCallbacks
|
|
|
|
def get_rules(self, context):
|
|
|
|
"""Given an event context return the rules for all users who are
|
|
|
|
currently in the room.
|
|
|
|
"""
|
|
|
|
state_group = context.state_group
|
|
|
|
|
|
|
|
with (yield self.linearizer.queue(())):
|
|
|
|
if state_group and self.state_group == state_group:
|
|
|
|
defer.returnValue(self.rules_by_user)
|
|
|
|
|
|
|
|
ret_rules_by_user = {}
|
|
|
|
missing_member_event_ids = {}
|
|
|
|
if state_group and self.state_group == context.prev_group:
|
|
|
|
# If we have a simple delta then we can reuse most of the previous
|
|
|
|
# results.
|
|
|
|
ret_rules_by_user = self.rules_by_user
|
|
|
|
current_state_ids = context.delta_ids
|
|
|
|
else:
|
|
|
|
current_state_ids = context.current_state_ids
|
|
|
|
|
|
|
|
# Loop through to see which member events we've seen and have rules
|
|
|
|
# for and which we need to fetch
|
|
|
|
for key, event_id in current_state_ids.iteritems():
|
|
|
|
if key[0] != EventTypes.Member:
|
|
|
|
continue
|
|
|
|
|
|
|
|
res = self.member_map.get(event_id, None)
|
|
|
|
if res:
|
|
|
|
user_id, state = res
|
|
|
|
if state == Membership.JOIN:
|
|
|
|
rules = self.rules_by_user.get(user_id, None)
|
|
|
|
if rules:
|
|
|
|
ret_rules_by_user[user_id] = rules
|
|
|
|
continue
|
|
|
|
|
|
|
|
user_id = key[1]
|
|
|
|
if not self.is_mine_id(user_id):
|
|
|
|
continue
|
|
|
|
|
|
|
|
if self.store.get_if_app_services_interested_in_user(
|
|
|
|
user_id, exclusive=True
|
|
|
|
):
|
|
|
|
continue
|
|
|
|
|
|
|
|
# If a user has left a room we remove their push rule. If they
|
|
|
|
# joined then we readd it later in _update_rules_with_member_event_ids
|
|
|
|
ret_rules_by_user.pop(user_id, None)
|
|
|
|
missing_member_event_ids[user_id] = event_id
|
|
|
|
|
|
|
|
if missing_member_event_ids:
|
|
|
|
# If we have some memebr events we haven't seen, look them up
|
|
|
|
# and fetch push rules for them if appropriate.
|
|
|
|
yield self._update_rules_with_member_event_ids(
|
|
|
|
ret_rules_by_user, missing_member_event_ids, state_group
|
|
|
|
)
|
|
|
|
|
|
|
|
defer.returnValue(ret_rules_by_user)
|
|
|
|
|
|
|
|
@defer.inlineCallbacks
|
|
|
|
def _update_rules_with_member_event_ids(self, ret_rules_by_user, member_event_ids,
|
|
|
|
state_group):
|
|
|
|
"""Update the partially filled rules_by_user dict by fetching rules for
|
|
|
|
any newly joined users in the `member_event_ids` list.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
ret_rules_by_user (dict): Partiallly filled dict of push rules. Gets
|
|
|
|
updated with any new rules.
|
|
|
|
member_event_ids (list): List of event ids for membership events that
|
|
|
|
have happened since the last time we filled rules_by_user
|
|
|
|
state_group: The state group we are currently computing push rules
|
|
|
|
for. Used when updating the cache.
|
|
|
|
"""
|
|
|
|
sequence = self.sequence
|
|
|
|
|
|
|
|
rows = yield self.store._simple_select_many_batch(
|
|
|
|
table="room_memberships",
|
|
|
|
column="event_id",
|
|
|
|
iterable=member_event_ids.values(),
|
|
|
|
retcols=('user_id', 'membership', 'event_id'),
|
|
|
|
keyvalues={},
|
|
|
|
batch_size=500,
|
|
|
|
desc="_get_rules_for_member_event_ids",
|
|
|
|
)
|
|
|
|
|
|
|
|
members = {
|
|
|
|
row["event_id"]: (row["user_id"], row["membership"])
|
|
|
|
for row in rows
|
|
|
|
}
|
|
|
|
|
|
|
|
interested_in_user_ids = set(user_id for user_id, _ in members.itervalues())
|
|
|
|
|
|
|
|
if_users_with_pushers = yield self.store.get_if_users_have_pushers(
|
|
|
|
interested_in_user_ids,
|
|
|
|
on_invalidate=self.invalidate_all_cb,
|
|
|
|
)
|
|
|
|
|
|
|
|
user_ids = set(
|
|
|
|
uid for uid, have_pusher in if_users_with_pushers.iteritems() if have_pusher
|
|
|
|
)
|
|
|
|
|
|
|
|
users_with_receipts = yield self.store.get_users_with_read_receipts_in_room(
|
|
|
|
self.room_id, on_invalidate=self.invalidate_all_cb,
|
|
|
|
)
|
|
|
|
|
|
|
|
# any users with pushers must be ours: they have pushers
|
|
|
|
for uid in users_with_receipts:
|
|
|
|
if uid in interested_in_user_ids:
|
|
|
|
user_ids.add(uid)
|
|
|
|
|
|
|
|
rules_by_user = yield self.store.bulk_get_push_rules(
|
|
|
|
user_ids, on_invalidate=self.invalidate_all_cb,
|
|
|
|
)
|
|
|
|
|
|
|
|
ret_rules_by_user.update(
|
|
|
|
item for item in rules_by_user.iteritems() if item[0] is not None
|
|
|
|
)
|
|
|
|
|
|
|
|
self.update_cache(sequence, members, ret_rules_by_user, state_group)
|
|
|
|
|
|
|
|
def invalidate_all(self):
|
|
|
|
# Note: Don't hand this function directly to an invalidation callback
|
|
|
|
# as it keeps a reference to self and will stop this instance from being
|
|
|
|
# GC'd if it gets dropped from the rules_to_user cache. Instead use
|
|
|
|
# `self.invalidate_all_cb`
|
|
|
|
self.sequence += 1
|
|
|
|
self.state_group = object()
|
|
|
|
self.member_map = {}
|
|
|
|
self.rules_by_user = {}
|
|
|
|
|
|
|
|
def update_cache(self, sequence, members, rules_by_user, state_group):
|
|
|
|
if sequence == self.sequence:
|
|
|
|
self.member_map.update(members)
|
|
|
|
self.rules_by_user = rules_by_user
|
|
|
|
self.state_group = state_group
|