2019-10-21 07:56:42 -04:00
|
|
|
#
|
2023-11-21 15:29:58 -05:00
|
|
|
# This file is licensed under the Affero General Public License (AGPL) version 3.
|
|
|
|
#
|
|
|
|
# Copyright (C) 2023 New Vector, Ltd
|
|
|
|
#
|
|
|
|
# This program is free software: you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU Affero General Public License as
|
|
|
|
# published by the Free Software Foundation, either version 3 of the
|
|
|
|
# License, or (at your option) any later version.
|
|
|
|
#
|
|
|
|
# See the GNU Affero General Public License for more details:
|
|
|
|
# <https://www.gnu.org/licenses/agpl-3.0.html>.
|
|
|
|
#
|
|
|
|
# Originally licensed under the Apache License, Version 2.0:
|
|
|
|
# <http://www.apache.org/licenses/LICENSE-2.0>.
|
|
|
|
#
|
|
|
|
# [This file includes modifications made by New Vector Limited]
|
2019-10-21 07:56:42 -04:00
|
|
|
#
|
|
|
|
#
|
|
|
|
import logging
|
2022-08-16 07:22:17 -04:00
|
|
|
from typing import (
|
|
|
|
TYPE_CHECKING,
|
|
|
|
Any,
|
|
|
|
Collection,
|
|
|
|
Dict,
|
2022-11-11 05:51:49 -05:00
|
|
|
Iterable,
|
2022-08-16 07:22:17 -04:00
|
|
|
List,
|
|
|
|
Mapping,
|
|
|
|
Optional,
|
|
|
|
Sequence,
|
|
|
|
Tuple,
|
|
|
|
Union,
|
|
|
|
cast,
|
|
|
|
)
|
2019-10-21 07:56:42 -04:00
|
|
|
|
2023-11-06 15:41:57 -05:00
|
|
|
from twisted.internet import defer
|
|
|
|
|
2022-04-27 09:55:33 -04:00
|
|
|
from synapse.api.errors import StoreError
|
2022-10-25 09:38:01 -04:00
|
|
|
from synapse.config.homeserver import ExperimentalConfig
|
2023-11-06 15:41:57 -05:00
|
|
|
from synapse.logging.context import make_deferred_yieldable, run_in_background
|
2022-11-11 05:51:49 -05:00
|
|
|
from synapse.replication.tcp.streams import PushRulesStream
|
2022-09-20 07:10:31 -04:00
|
|
|
from synapse.storage._base import SQLBaseStore
|
2022-05-17 10:29:06 -04:00
|
|
|
from synapse.storage.database import (
|
|
|
|
DatabasePool,
|
|
|
|
LoggingDatabaseConnection,
|
|
|
|
LoggingTransaction,
|
|
|
|
)
|
2020-08-05 16:38:57 -04:00
|
|
|
from synapse.storage.databases.main.appservice import ApplicationServiceWorkerStore
|
|
|
|
from synapse.storage.databases.main.events_worker import EventsWorkerStore
|
|
|
|
from synapse.storage.databases.main.pusher import PusherWorkerStore
|
|
|
|
from synapse.storage.databases.main.receipts import ReceiptsWorkerStore
|
|
|
|
from synapse.storage.databases.main.roommember import RoomMemberWorkerStore
|
2020-09-09 06:39:39 -04:00
|
|
|
from synapse.storage.engines import PostgresEngine, Sqlite3Engine
|
2019-10-21 07:56:42 -04:00
|
|
|
from synapse.storage.push_rule import InconsistentRuleException, RuleNotFoundException
|
2021-11-26 13:41:31 -05:00
|
|
|
from synapse.storage.util.id_generators import (
|
2022-05-17 10:29:06 -04:00
|
|
|
AbstractStreamIdGenerator,
|
|
|
|
IdGenerator,
|
2021-11-26 13:41:31 -05:00
|
|
|
StreamIdGenerator,
|
|
|
|
)
|
2022-09-20 07:10:31 -04:00
|
|
|
from synapse.synapse_rust.push import FilteredPushRules, PushRule, PushRules
|
2022-05-17 10:29:06 -04:00
|
|
|
from synapse.types import JsonDict
|
2023-11-06 15:41:57 -05:00
|
|
|
from synapse.util import json_encoder, unwrapFirstError
|
|
|
|
from synapse.util.async_helpers import gather_results
|
2020-08-14 10:30:16 -04:00
|
|
|
from synapse.util.caches.descriptors import cached, cachedList
|
2019-10-21 07:56:42 -04:00
|
|
|
from synapse.util.caches.stream_change_cache import StreamChangeCache
|
|
|
|
|
2021-10-22 13:15:41 -04:00
|
|
|
if TYPE_CHECKING:
|
|
|
|
from synapse.server import HomeServer
|
|
|
|
|
2019-10-21 07:56:42 -04:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
2022-05-17 10:29:06 -04:00
|
|
|
def _load_rules(
|
2023-10-11 13:24:56 -04:00
|
|
|
rawrules: List[Tuple[str, int, str, str]],
|
2022-10-25 09:38:01 -04:00
|
|
|
enabled_map: Dict[str, bool],
|
|
|
|
experimental_config: ExperimentalConfig,
|
2022-08-16 07:22:17 -04:00
|
|
|
) -> FilteredPushRules:
|
|
|
|
"""Take the DB rows returned from the DB and convert them into a full
|
|
|
|
`FilteredPushRules` object.
|
2023-10-11 13:24:56 -04:00
|
|
|
|
|
|
|
Args:
|
|
|
|
rawrules: List of tuples of:
|
|
|
|
* rule ID
|
|
|
|
* Priority lass
|
|
|
|
* Conditions (as serialized JSON)
|
|
|
|
* Actions (as serialized JSON)
|
|
|
|
enabled_map: A dictionary of rule ID to a boolean of whether the rule is
|
|
|
|
enabled. This might not include all rule IDs from rawrules.
|
|
|
|
experimental_config: The `experimental_features` section of the Synapse
|
|
|
|
config. (Used to check if various features are enabled.)
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
A new FilteredPushRules object.
|
2022-08-16 07:22:17 -04:00
|
|
|
"""
|
2019-10-21 07:56:42 -04:00
|
|
|
|
2022-08-16 07:22:17 -04:00
|
|
|
ruleslist = [
|
2022-09-20 07:10:31 -04:00
|
|
|
PushRule.from_db(
|
2023-10-11 13:24:56 -04:00
|
|
|
rule_id=rawrule[0],
|
|
|
|
priority_class=rawrule[1],
|
|
|
|
conditions=rawrule[2],
|
|
|
|
actions=rawrule[3],
|
2022-08-16 07:22:17 -04:00
|
|
|
)
|
|
|
|
for rawrule in rawrules
|
|
|
|
]
|
2022-05-10 03:57:36 -04:00
|
|
|
|
2022-10-04 07:08:27 -04:00
|
|
|
push_rules = PushRules(ruleslist)
|
2022-05-10 03:57:36 -04:00
|
|
|
|
2022-10-25 09:38:01 -04:00
|
|
|
filtered_rules = FilteredPushRules(
|
2022-11-28 20:02:41 -05:00
|
|
|
push_rules,
|
|
|
|
enabled_map,
|
|
|
|
msc1767_enabled=experimental_config.msc1767_enabled,
|
2023-01-19 07:47:10 -05:00
|
|
|
msc3664_enabled=experimental_config.msc3664_enabled,
|
|
|
|
msc3381_polls_enabled=experimental_config.msc3381_polls_enabled,
|
2023-09-26 11:52:19 -04:00
|
|
|
msc4028_push_encrypted_events=experimental_config.msc4028_push_encrypted_events,
|
2022-10-25 09:38:01 -04:00
|
|
|
)
|
2019-10-21 07:56:42 -04:00
|
|
|
|
2022-08-16 07:22:17 -04:00
|
|
|
return filtered_rules
|
2019-10-21 07:56:42 -04:00
|
|
|
|
|
|
|
|
|
|
|
class PushRulesWorkerStore(
|
|
|
|
ApplicationServiceWorkerStore,
|
|
|
|
PusherWorkerStore,
|
|
|
|
RoomMemberWorkerStore,
|
2022-06-15 11:17:14 -04:00
|
|
|
ReceiptsWorkerStore,
|
2020-05-15 11:43:59 -04:00
|
|
|
EventsWorkerStore,
|
2019-10-21 07:56:42 -04:00
|
|
|
SQLBaseStore,
|
|
|
|
):
|
|
|
|
"""This is an abstract base class where subclasses must implement
|
|
|
|
`get_max_push_rules_stream_id` which can be called in the initializer.
|
|
|
|
"""
|
|
|
|
|
2021-12-13 12:05:00 -05:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
database: DatabasePool,
|
|
|
|
db_conn: LoggingDatabaseConnection,
|
|
|
|
hs: "HomeServer",
|
|
|
|
):
|
2020-09-18 09:56:44 -04:00
|
|
|
super().__init__(database, db_conn, hs)
|
2019-10-21 07:56:42 -04:00
|
|
|
|
2022-11-16 17:16:46 -05:00
|
|
|
# In the worker store this is an ID tracker which we overwrite in the non-worker
|
|
|
|
# class below that is used on the main process.
|
2023-03-03 08:13:37 -05:00
|
|
|
self._push_rules_stream_id_gen = StreamIdGenerator(
|
2022-11-16 17:16:46 -05:00
|
|
|
db_conn,
|
2023-01-20 13:02:18 -05:00
|
|
|
hs.get_replication_notifier(),
|
2022-11-16 17:16:46 -05:00
|
|
|
"push_rules_stream",
|
|
|
|
"stream_id",
|
|
|
|
is_writer=hs.config.worker.worker_app is None,
|
|
|
|
)
|
2020-05-15 11:43:59 -04:00
|
|
|
|
2020-08-05 16:38:57 -04:00
|
|
|
push_rules_prefill, push_rules_id = self.db_pool.get_cache_dict(
|
2019-10-21 07:56:42 -04:00
|
|
|
db_conn,
|
|
|
|
"push_rules_stream",
|
|
|
|
entity_column="user_id",
|
|
|
|
stream_column="stream_id",
|
|
|
|
max_value=self.get_max_push_rules_stream_id(),
|
|
|
|
)
|
|
|
|
|
|
|
|
self.push_rules_stream_cache = StreamChangeCache(
|
|
|
|
"PushRulesStreamChangeCache",
|
|
|
|
push_rules_id,
|
|
|
|
prefilled_cache=push_rules_prefill,
|
|
|
|
)
|
|
|
|
|
2022-05-17 10:29:06 -04:00
|
|
|
def get_max_push_rules_stream_id(self) -> int:
|
2019-10-21 07:56:42 -04:00
|
|
|
"""Get the position of the push rules stream.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
int
|
|
|
|
"""
|
2022-11-11 05:51:49 -05:00
|
|
|
return self._push_rules_stream_id_gen.get_current_token()
|
|
|
|
|
|
|
|
def process_replication_rows(
|
|
|
|
self, stream_name: str, instance_name: str, token: int, rows: Iterable[Any]
|
|
|
|
) -> None:
|
|
|
|
if stream_name == PushRulesStream.NAME:
|
|
|
|
self._push_rules_stream_id_gen.advance(instance_name, token)
|
|
|
|
for row in rows:
|
|
|
|
self.get_push_rules_for_user.invalidate((row.user_id,))
|
|
|
|
self.push_rules_stream_cache.entity_has_changed(row.user_id, token)
|
|
|
|
return super().process_replication_rows(stream_name, instance_name, token, rows)
|
2019-10-21 07:56:42 -04:00
|
|
|
|
2023-01-04 06:49:26 -05:00
|
|
|
def process_replication_position(
|
|
|
|
self, stream_name: str, instance_name: str, token: int
|
|
|
|
) -> None:
|
|
|
|
if stream_name == PushRulesStream.NAME:
|
|
|
|
self._push_rules_stream_id_gen.advance(instance_name, token)
|
|
|
|
super().process_replication_position(stream_name, instance_name, token)
|
|
|
|
|
2020-08-14 10:30:16 -04:00
|
|
|
@cached(max_entries=5000)
|
2022-08-16 07:22:17 -04:00
|
|
|
async def get_push_rules_for_user(self, user_id: str) -> FilteredPushRules:
|
2023-10-26 13:01:36 -04:00
|
|
|
rows = cast(
|
|
|
|
List[Tuple[str, int, int, str, str]],
|
|
|
|
await self.db_pool.simple_select_list(
|
|
|
|
table="push_rules",
|
|
|
|
keyvalues={"user_name": user_id},
|
|
|
|
retcols=(
|
|
|
|
"rule_id",
|
|
|
|
"priority_class",
|
|
|
|
"priority",
|
|
|
|
"conditions",
|
|
|
|
"actions",
|
|
|
|
),
|
|
|
|
desc="get_push_rules_for_user",
|
2019-10-21 07:56:42 -04:00
|
|
|
),
|
|
|
|
)
|
|
|
|
|
2023-10-26 13:01:36 -04:00
|
|
|
# Sort by highest priority_class, then highest priority.
|
|
|
|
rows.sort(key=lambda row: (-int(row[1]), -int(row[2])))
|
2019-10-21 07:56:42 -04:00
|
|
|
|
2020-08-14 10:30:16 -04:00
|
|
|
enabled_map = await self.get_push_rules_enabled_for_user(user_id)
|
2019-10-21 07:56:42 -04:00
|
|
|
|
2023-10-11 13:24:56 -04:00
|
|
|
return _load_rules(
|
2023-10-26 13:01:36 -04:00
|
|
|
[(row[0], row[1], row[3], row[4]) for row in rows],
|
2023-10-11 13:24:56 -04:00
|
|
|
enabled_map,
|
|
|
|
self.hs.config.experimental,
|
|
|
|
)
|
2019-10-21 07:56:42 -04:00
|
|
|
|
2022-05-17 10:29:06 -04:00
|
|
|
async def get_push_rules_enabled_for_user(self, user_id: str) -> Dict[str, bool]:
|
2023-10-26 13:01:36 -04:00
|
|
|
results = cast(
|
|
|
|
List[Tuple[str, Optional[Union[int, bool]]]],
|
|
|
|
await self.db_pool.simple_select_list(
|
|
|
|
table="push_rules_enable",
|
|
|
|
keyvalues={"user_name": user_id},
|
|
|
|
retcols=("rule_id", "enabled"),
|
|
|
|
desc="get_push_rules_enabled_for_user",
|
|
|
|
),
|
2019-10-21 07:56:42 -04:00
|
|
|
)
|
2023-10-26 13:01:36 -04:00
|
|
|
return {r[0]: bool(r[1]) for r in results}
|
2019-10-21 07:56:42 -04:00
|
|
|
|
2020-09-01 08:39:04 -04:00
|
|
|
async def have_push_rules_changed_for_user(
|
|
|
|
self, user_id: str, last_id: int
|
|
|
|
) -> bool:
|
2019-10-21 07:56:42 -04:00
|
|
|
if not self.push_rules_stream_cache.has_entity_changed(user_id, last_id):
|
2020-09-01 08:39:04 -04:00
|
|
|
return False
|
2019-10-21 07:56:42 -04:00
|
|
|
else:
|
|
|
|
|
2022-05-17 10:29:06 -04:00
|
|
|
def have_push_rules_changed_txn(txn: LoggingTransaction) -> bool:
|
2019-10-21 07:56:42 -04:00
|
|
|
sql = (
|
|
|
|
"SELECT COUNT(stream_id) FROM push_rules_stream"
|
|
|
|
" WHERE user_id = ? AND ? < stream_id"
|
|
|
|
)
|
|
|
|
txn.execute(sql, (user_id, last_id))
|
2022-05-17 10:29:06 -04:00
|
|
|
(count,) = cast(Tuple[int], txn.fetchone())
|
2019-10-21 07:56:42 -04:00
|
|
|
return bool(count)
|
|
|
|
|
2020-09-01 08:39:04 -04:00
|
|
|
return await self.db_pool.runInteraction(
|
2019-10-21 07:56:42 -04:00
|
|
|
"have_push_rules_changed", have_push_rules_changed_txn
|
|
|
|
)
|
|
|
|
|
2022-05-25 07:49:12 -04:00
|
|
|
@cachedList(cached_method_name="get_push_rules_for_user", list_name="user_ids")
|
2022-05-17 10:29:06 -04:00
|
|
|
async def bulk_get_push_rules(
|
|
|
|
self, user_ids: Collection[str]
|
2023-09-19 15:26:44 -04:00
|
|
|
) -> Mapping[str, FilteredPushRules]:
|
2019-10-21 07:56:42 -04:00
|
|
|
if not user_ids:
|
|
|
|
return {}
|
|
|
|
|
2023-10-11 13:24:56 -04:00
|
|
|
raw_rules: Dict[str, List[Tuple[str, int, str, str]]] = {
|
|
|
|
user_id: [] for user_id in user_ids
|
|
|
|
}
|
|
|
|
|
2023-11-06 15:41:57 -05:00
|
|
|
# gatherResults loses all type information.
|
|
|
|
rows, enabled_map_by_user = await make_deferred_yieldable(
|
|
|
|
gather_results(
|
|
|
|
(
|
|
|
|
cast(
|
|
|
|
"defer.Deferred[List[Tuple[str, str, int, int, str, str]]]",
|
|
|
|
run_in_background(
|
|
|
|
self.db_pool.simple_select_many_batch,
|
|
|
|
table="push_rules",
|
|
|
|
column="user_name",
|
|
|
|
iterable=user_ids,
|
|
|
|
retcols=(
|
|
|
|
"user_name",
|
|
|
|
"rule_id",
|
|
|
|
"priority_class",
|
|
|
|
"priority",
|
|
|
|
"conditions",
|
|
|
|
"actions",
|
|
|
|
),
|
|
|
|
desc="bulk_get_push_rules",
|
|
|
|
batch_size=1000,
|
|
|
|
),
|
|
|
|
),
|
|
|
|
run_in_background(self.bulk_get_push_rules_enabled, user_ids),
|
2023-10-11 13:24:56 -04:00
|
|
|
),
|
2023-11-06 15:41:57 -05:00
|
|
|
consumeErrors=True,
|
|
|
|
).addErrback(unwrapFirstError)
|
2019-10-21 07:56:42 -04:00
|
|
|
)
|
|
|
|
|
2023-10-11 13:24:56 -04:00
|
|
|
# Sort by highest priority_class, then highest priority.
|
|
|
|
rows.sort(key=lambda row: (-int(row[2]), -int(row[3])))
|
2019-10-21 07:56:42 -04:00
|
|
|
|
2023-10-11 13:24:56 -04:00
|
|
|
for user_name, rule_id, priority_class, _, conditions, actions in rows:
|
|
|
|
raw_rules.setdefault(user_name, []).append(
|
|
|
|
(rule_id, priority_class, conditions, actions)
|
|
|
|
)
|
2019-10-21 07:56:42 -04:00
|
|
|
|
2022-08-16 07:22:17 -04:00
|
|
|
results: Dict[str, FilteredPushRules] = {}
|
|
|
|
|
|
|
|
for user_id, rules in raw_rules.items():
|
2022-10-25 09:38:01 -04:00
|
|
|
results[user_id] = _load_rules(
|
|
|
|
rules, enabled_map_by_user.get(user_id, {}), self.hs.config.experimental
|
|
|
|
)
|
2019-10-21 07:56:42 -04:00
|
|
|
|
|
|
|
return results
|
|
|
|
|
2022-05-17 10:29:06 -04:00
|
|
|
async def bulk_get_push_rules_enabled(
|
|
|
|
self, user_ids: Collection[str]
|
|
|
|
) -> Dict[str, Dict[str, bool]]:
|
2019-10-21 07:56:42 -04:00
|
|
|
if not user_ids:
|
|
|
|
return {}
|
|
|
|
|
2022-05-17 10:29:06 -04:00
|
|
|
results: Dict[str, Dict[str, bool]] = {user_id: {} for user_id in user_ids}
|
2019-10-21 07:56:42 -04:00
|
|
|
|
2023-10-11 13:24:56 -04:00
|
|
|
rows = cast(
|
|
|
|
List[Tuple[str, str, Optional[int]]],
|
|
|
|
await self.db_pool.simple_select_many_batch(
|
|
|
|
table="push_rules_enable",
|
|
|
|
column="user_name",
|
|
|
|
iterable=user_ids,
|
|
|
|
retcols=("user_name", "rule_id", "enabled"),
|
|
|
|
desc="bulk_get_push_rules_enabled",
|
|
|
|
batch_size=1000,
|
|
|
|
),
|
2019-10-21 07:56:42 -04:00
|
|
|
)
|
2023-10-11 13:24:56 -04:00
|
|
|
for user_name, rule_id, enabled in rows:
|
|
|
|
results.setdefault(user_name, {})[rule_id] = bool(enabled)
|
2019-10-21 07:56:42 -04:00
|
|
|
return results
|
|
|
|
|
2020-06-16 12:10:28 -04:00
|
|
|
async def get_all_push_rule_updates(
|
|
|
|
self, instance_name: str, last_id: int, current_id: int, limit: int
|
2022-05-17 10:29:06 -04:00
|
|
|
) -> Tuple[List[Tuple[int, Tuple[str]]], int, bool]:
|
2020-06-16 12:10:28 -04:00
|
|
|
"""Get updates for push_rules replication stream.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
instance_name: The writer we want to fetch updates from. Unused
|
|
|
|
here since there is only ever one writer.
|
|
|
|
last_id: The token to fetch updates from. Exclusive.
|
|
|
|
current_id: The token to fetch updates up to. Inclusive.
|
|
|
|
limit: The requested limit for the number of rows to return. The
|
|
|
|
function may return more or fewer rows.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
A tuple consisting of: the updates, a token to use to fetch
|
|
|
|
subsequent updates, and whether we returned fewer rows than exists
|
|
|
|
between the requested tokens due to the limit.
|
|
|
|
|
|
|
|
The token returned can be used in a subsequent call to this
|
|
|
|
function to get further updatees.
|
|
|
|
|
|
|
|
The updates are a list of 2-tuples of stream ID and the row data
|
|
|
|
"""
|
|
|
|
|
2020-04-07 06:01:04 -04:00
|
|
|
if last_id == current_id:
|
2020-06-16 12:10:28 -04:00
|
|
|
return [], current_id, False
|
2020-04-07 06:01:04 -04:00
|
|
|
|
2022-05-17 10:29:06 -04:00
|
|
|
def get_all_push_rule_updates_txn(
|
|
|
|
txn: LoggingTransaction,
|
|
|
|
) -> Tuple[List[Tuple[int, Tuple[str]]], int, bool]:
|
2020-06-16 12:10:28 -04:00
|
|
|
sql = """
|
|
|
|
SELECT stream_id, user_id
|
|
|
|
FROM push_rules_stream
|
|
|
|
WHERE ? < stream_id AND stream_id <= ?
|
|
|
|
ORDER BY stream_id ASC
|
|
|
|
LIMIT ?
|
|
|
|
"""
|
2020-04-07 06:01:04 -04:00
|
|
|
txn.execute(sql, (last_id, current_id, limit))
|
2022-05-17 10:29:06 -04:00
|
|
|
updates = cast(
|
|
|
|
List[Tuple[int, Tuple[str]]],
|
|
|
|
[(stream_id, (user_id,)) for stream_id, user_id in txn],
|
|
|
|
)
|
2020-06-16 12:10:28 -04:00
|
|
|
|
|
|
|
limited = False
|
|
|
|
upper_bound = current_id
|
|
|
|
if len(updates) == limit:
|
|
|
|
limited = True
|
|
|
|
upper_bound = updates[-1][0]
|
|
|
|
|
|
|
|
return updates, upper_bound, limited
|
2020-04-07 06:01:04 -04:00
|
|
|
|
2020-08-05 16:38:57 -04:00
|
|
|
return await self.db_pool.runInteraction(
|
2020-04-07 06:01:04 -04:00
|
|
|
"get_all_push_rule_updates", get_all_push_rule_updates_txn
|
|
|
|
)
|
|
|
|
|
2019-10-21 07:56:42 -04:00
|
|
|
|
|
|
|
class PushRuleStore(PushRulesWorkerStore):
|
2022-05-17 10:29:06 -04:00
|
|
|
# Because we have write access, this will be a StreamIdGenerator
|
|
|
|
# (see PushRulesWorkerStore.__init__)
|
|
|
|
_push_rules_stream_id_gen: AbstractStreamIdGenerator
|
|
|
|
|
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
database: DatabasePool,
|
|
|
|
db_conn: LoggingDatabaseConnection,
|
|
|
|
hs: "HomeServer",
|
|
|
|
):
|
|
|
|
super().__init__(database, db_conn, hs)
|
|
|
|
|
|
|
|
self._push_rule_id_gen = IdGenerator(db_conn, "push_rules", "id")
|
|
|
|
self._push_rules_enable_id_gen = IdGenerator(db_conn, "push_rules_enable", "id")
|
|
|
|
|
2020-08-14 10:30:16 -04:00
|
|
|
async def add_push_rule(
|
2019-10-21 07:56:42 -04:00
|
|
|
self,
|
2022-05-17 10:29:06 -04:00
|
|
|
user_id: str,
|
|
|
|
rule_id: str,
|
|
|
|
priority_class: int,
|
2022-08-16 07:22:17 -04:00
|
|
|
conditions: Sequence[Mapping[str, str]],
|
|
|
|
actions: Sequence[Union[Mapping[str, Any], str]],
|
2022-05-17 10:29:06 -04:00
|
|
|
before: Optional[str] = None,
|
|
|
|
after: Optional[str] = None,
|
2020-08-14 10:30:16 -04:00
|
|
|
) -> None:
|
2020-08-07 08:02:55 -04:00
|
|
|
conditions_json = json_encoder.encode(conditions)
|
|
|
|
actions_json = json_encoder.encode(actions)
|
2020-09-23 11:11:18 -04:00
|
|
|
async with self._push_rules_stream_id_gen.get_next() as stream_id:
|
2020-08-19 08:41:51 -04:00
|
|
|
event_stream_ordering = self._stream_id_gen.get_current_token()
|
|
|
|
|
2019-10-21 07:56:42 -04:00
|
|
|
if before or after:
|
2020-08-14 10:30:16 -04:00
|
|
|
await self.db_pool.runInteraction(
|
2019-10-21 07:56:42 -04:00
|
|
|
"_add_push_rule_relative_txn",
|
|
|
|
self._add_push_rule_relative_txn,
|
|
|
|
stream_id,
|
|
|
|
event_stream_ordering,
|
|
|
|
user_id,
|
|
|
|
rule_id,
|
|
|
|
priority_class,
|
|
|
|
conditions_json,
|
|
|
|
actions_json,
|
|
|
|
before,
|
|
|
|
after,
|
|
|
|
)
|
|
|
|
else:
|
2020-08-14 10:30:16 -04:00
|
|
|
await self.db_pool.runInteraction(
|
2019-10-21 07:56:42 -04:00
|
|
|
"_add_push_rule_highest_priority_txn",
|
|
|
|
self._add_push_rule_highest_priority_txn,
|
|
|
|
stream_id,
|
|
|
|
event_stream_ordering,
|
|
|
|
user_id,
|
|
|
|
rule_id,
|
|
|
|
priority_class,
|
|
|
|
conditions_json,
|
|
|
|
actions_json,
|
|
|
|
)
|
|
|
|
|
|
|
|
def _add_push_rule_relative_txn(
|
|
|
|
self,
|
2022-05-17 10:29:06 -04:00
|
|
|
txn: LoggingTransaction,
|
|
|
|
stream_id: int,
|
|
|
|
event_stream_ordering: int,
|
|
|
|
user_id: str,
|
|
|
|
rule_id: str,
|
|
|
|
priority_class: int,
|
|
|
|
conditions_json: str,
|
|
|
|
actions_json: str,
|
|
|
|
before: str,
|
|
|
|
after: str,
|
|
|
|
) -> None:
|
2019-10-21 07:56:42 -04:00
|
|
|
relative_to_rule = before or after
|
|
|
|
|
2023-11-13 11:57:44 -05:00
|
|
|
sql = """
|
|
|
|
SELECT priority, priority_class FROM push_rules
|
|
|
|
WHERE user_name = ? AND rule_id = ?
|
|
|
|
"""
|
|
|
|
|
|
|
|
if isinstance(self.database_engine, PostgresEngine):
|
|
|
|
sql += " FOR UPDATE"
|
|
|
|
else:
|
|
|
|
# Annoyingly SQLite doesn't support row level locking, so lock the whole table
|
|
|
|
self.database_engine.lock_table(txn, "push_rules")
|
|
|
|
|
|
|
|
txn.execute(sql, (user_id, relative_to_rule))
|
|
|
|
row = txn.fetchone()
|
2019-10-21 07:56:42 -04:00
|
|
|
|
2023-11-13 11:57:44 -05:00
|
|
|
if row is None:
|
2019-10-21 07:56:42 -04:00
|
|
|
raise RuleNotFoundException(
|
|
|
|
"before/after rule not found: %s" % (relative_to_rule,)
|
|
|
|
)
|
|
|
|
|
2023-11-13 11:57:44 -05:00
|
|
|
base_rule_priority, base_priority_class = row
|
2019-10-21 07:56:42 -04:00
|
|
|
|
|
|
|
if base_priority_class != priority_class:
|
|
|
|
raise InconsistentRuleException(
|
|
|
|
"Given priority class does not match class of relative rule"
|
|
|
|
)
|
|
|
|
|
|
|
|
if before:
|
|
|
|
# Higher priority rules are executed first, So adding a rule before
|
|
|
|
# a rule means giving it a higher priority than that rule.
|
|
|
|
new_rule_priority = base_rule_priority + 1
|
|
|
|
else:
|
|
|
|
# We increment the priority of the existing rules to make space for
|
|
|
|
# the new rule. Therefore if we want this rule to appear after
|
|
|
|
# an existing rule we give it the priority of the existing rule,
|
|
|
|
# and then increment the priority of the existing rule.
|
|
|
|
new_rule_priority = base_rule_priority
|
|
|
|
|
|
|
|
sql = (
|
|
|
|
"UPDATE push_rules SET priority = priority + 1"
|
|
|
|
" WHERE user_name = ? AND priority_class = ? AND priority >= ?"
|
|
|
|
)
|
|
|
|
|
|
|
|
txn.execute(sql, (user_id, priority_class, new_rule_priority))
|
|
|
|
|
|
|
|
self._upsert_push_rule_txn(
|
|
|
|
txn,
|
|
|
|
stream_id,
|
|
|
|
event_stream_ordering,
|
|
|
|
user_id,
|
|
|
|
rule_id,
|
|
|
|
priority_class,
|
|
|
|
new_rule_priority,
|
|
|
|
conditions_json,
|
|
|
|
actions_json,
|
|
|
|
)
|
|
|
|
|
|
|
|
def _add_push_rule_highest_priority_txn(
|
|
|
|
self,
|
2022-05-17 10:29:06 -04:00
|
|
|
txn: LoggingTransaction,
|
|
|
|
stream_id: int,
|
|
|
|
event_stream_ordering: int,
|
|
|
|
user_id: str,
|
|
|
|
rule_id: str,
|
|
|
|
priority_class: int,
|
|
|
|
conditions_json: str,
|
|
|
|
actions_json: str,
|
|
|
|
) -> None:
|
2023-11-13 11:57:44 -05:00
|
|
|
if isinstance(self.database_engine, PostgresEngine):
|
|
|
|
# Postgres doesn't do FOR UPDATE on aggregate functions, so select the rows first
|
|
|
|
# then re-select the count/max below.
|
|
|
|
sql = """
|
|
|
|
SELECT * FROM push_rules
|
|
|
|
WHERE user_name = ? and priority_class = ?
|
|
|
|
FOR UPDATE
|
|
|
|
"""
|
|
|
|
txn.execute(sql, (user_id, priority_class))
|
|
|
|
else:
|
|
|
|
# Annoyingly SQLite doesn't support row level locking, so lock the whole table
|
|
|
|
self.database_engine.lock_table(txn, "push_rules")
|
2019-10-21 07:56:42 -04:00
|
|
|
|
|
|
|
# find the highest priority rule in that class
|
|
|
|
sql = (
|
|
|
|
"SELECT COUNT(*), MAX(priority) FROM push_rules"
|
|
|
|
" WHERE user_name = ? and priority_class = ?"
|
|
|
|
)
|
|
|
|
txn.execute(sql, (user_id, priority_class))
|
|
|
|
res = txn.fetchall()
|
|
|
|
(how_many, highest_prio) = res[0]
|
|
|
|
|
|
|
|
new_prio = 0
|
|
|
|
if how_many > 0:
|
|
|
|
new_prio = highest_prio + 1
|
|
|
|
|
|
|
|
self._upsert_push_rule_txn(
|
|
|
|
txn,
|
|
|
|
stream_id,
|
|
|
|
event_stream_ordering,
|
|
|
|
user_id,
|
|
|
|
rule_id,
|
|
|
|
priority_class,
|
|
|
|
new_prio,
|
|
|
|
conditions_json,
|
|
|
|
actions_json,
|
|
|
|
)
|
|
|
|
|
|
|
|
def _upsert_push_rule_txn(
|
|
|
|
self,
|
2022-05-17 10:29:06 -04:00
|
|
|
txn: LoggingTransaction,
|
|
|
|
stream_id: int,
|
|
|
|
event_stream_ordering: int,
|
|
|
|
user_id: str,
|
|
|
|
rule_id: str,
|
|
|
|
priority_class: int,
|
|
|
|
priority: int,
|
|
|
|
conditions_json: str,
|
|
|
|
actions_json: str,
|
|
|
|
update_stream: bool = True,
|
|
|
|
) -> None:
|
2019-12-04 05:15:55 -05:00
|
|
|
"""Specialised version of simple_upsert_txn that picks a push_rule_id
|
2019-10-21 07:56:42 -04:00
|
|
|
using the _push_rule_id_gen if it needs to insert the rule. It assumes
|
|
|
|
that the "push_rules" table is locked"""
|
|
|
|
|
|
|
|
sql = (
|
|
|
|
"UPDATE push_rules"
|
|
|
|
" SET priority_class = ?, priority = ?, conditions = ?, actions = ?"
|
|
|
|
" WHERE user_name = ? AND rule_id = ?"
|
|
|
|
)
|
|
|
|
|
|
|
|
txn.execute(
|
|
|
|
sql,
|
|
|
|
(priority_class, priority, conditions_json, actions_json, user_id, rule_id),
|
|
|
|
)
|
|
|
|
|
|
|
|
if txn.rowcount == 0:
|
|
|
|
# We didn't update a row with the given rule_id so insert one
|
|
|
|
push_rule_id = self._push_rule_id_gen.get_next()
|
|
|
|
|
2020-08-05 16:38:57 -04:00
|
|
|
self.db_pool.simple_insert_txn(
|
2019-10-21 07:56:42 -04:00
|
|
|
txn,
|
|
|
|
table="push_rules",
|
|
|
|
values={
|
|
|
|
"id": push_rule_id,
|
|
|
|
"user_name": user_id,
|
|
|
|
"rule_id": rule_id,
|
|
|
|
"priority_class": priority_class,
|
|
|
|
"priority": priority,
|
|
|
|
"conditions": conditions_json,
|
|
|
|
"actions": actions_json,
|
|
|
|
},
|
|
|
|
)
|
|
|
|
|
|
|
|
if update_stream:
|
|
|
|
self._insert_push_rules_update_txn(
|
|
|
|
txn,
|
|
|
|
stream_id,
|
|
|
|
event_stream_ordering,
|
|
|
|
user_id,
|
|
|
|
rule_id,
|
|
|
|
op="ADD",
|
|
|
|
data={
|
|
|
|
"priority_class": priority_class,
|
|
|
|
"priority": priority,
|
|
|
|
"conditions": conditions_json,
|
|
|
|
"actions": actions_json,
|
|
|
|
},
|
|
|
|
)
|
|
|
|
|
2020-09-09 06:39:39 -04:00
|
|
|
# ensure we have a push_rules_enable row
|
|
|
|
# enabledness defaults to true
|
|
|
|
if isinstance(self.database_engine, PostgresEngine):
|
|
|
|
sql = """
|
|
|
|
INSERT INTO push_rules_enable (id, user_name, rule_id, enabled)
|
2023-07-26 14:45:47 -04:00
|
|
|
VALUES (?, ?, ?, 1)
|
2020-09-09 06:39:39 -04:00
|
|
|
ON CONFLICT DO NOTHING
|
|
|
|
"""
|
|
|
|
elif isinstance(self.database_engine, Sqlite3Engine):
|
|
|
|
sql = """
|
|
|
|
INSERT OR IGNORE INTO push_rules_enable (id, user_name, rule_id, enabled)
|
2023-07-26 14:45:47 -04:00
|
|
|
VALUES (?, ?, ?, 1)
|
2020-09-09 06:39:39 -04:00
|
|
|
"""
|
|
|
|
else:
|
|
|
|
raise RuntimeError("Unknown database engine")
|
|
|
|
|
|
|
|
new_enable_id = self._push_rules_enable_id_gen.get_next()
|
2023-07-26 14:45:47 -04:00
|
|
|
txn.execute(sql, (new_enable_id, user_id, rule_id))
|
2020-09-09 06:39:39 -04:00
|
|
|
|
2020-08-14 10:30:16 -04:00
|
|
|
async def delete_push_rule(self, user_id: str, rule_id: str) -> None:
|
2019-10-21 07:56:42 -04:00
|
|
|
"""
|
|
|
|
Delete a push rule. Args specify the row to be deleted and can be
|
|
|
|
any of the columns in the push_rule table, but below are the
|
|
|
|
standard ones
|
|
|
|
|
|
|
|
Args:
|
2020-08-14 10:30:16 -04:00
|
|
|
user_id: The matrix ID of the push rule owner
|
|
|
|
rule_id: The rule_id of the rule to be deleted
|
2019-10-21 07:56:42 -04:00
|
|
|
"""
|
|
|
|
|
2022-05-17 10:29:06 -04:00
|
|
|
def delete_push_rule_txn(
|
|
|
|
txn: LoggingTransaction,
|
|
|
|
stream_id: int,
|
|
|
|
event_stream_ordering: int,
|
|
|
|
) -> None:
|
2020-09-09 06:39:39 -04:00
|
|
|
# we don't use simple_delete_one_txn because that would fail if the
|
|
|
|
# user did not have a push_rule_enable row.
|
|
|
|
self.db_pool.simple_delete_txn(
|
|
|
|
txn, "push_rules_enable", {"user_name": user_id, "rule_id": rule_id}
|
|
|
|
)
|
|
|
|
|
2020-08-05 16:38:57 -04:00
|
|
|
self.db_pool.simple_delete_one_txn(
|
2019-10-21 07:56:42 -04:00
|
|
|
txn, "push_rules", {"user_name": user_id, "rule_id": rule_id}
|
|
|
|
)
|
|
|
|
|
|
|
|
self._insert_push_rules_update_txn(
|
|
|
|
txn, stream_id, event_stream_ordering, user_id, rule_id, op="DELETE"
|
|
|
|
)
|
|
|
|
|
2020-09-23 11:11:18 -04:00
|
|
|
async with self._push_rules_stream_id_gen.get_next() as stream_id:
|
2020-08-19 08:41:51 -04:00
|
|
|
event_stream_ordering = self._stream_id_gen.get_current_token()
|
|
|
|
|
2020-08-14 10:30:16 -04:00
|
|
|
await self.db_pool.runInteraction(
|
2019-10-21 07:56:42 -04:00
|
|
|
"delete_push_rule",
|
|
|
|
delete_push_rule_txn,
|
|
|
|
stream_id,
|
|
|
|
event_stream_ordering,
|
|
|
|
)
|
|
|
|
|
2020-09-09 06:39:39 -04:00
|
|
|
async def set_push_rule_enabled(
|
|
|
|
self, user_id: str, rule_id: str, enabled: bool, is_default_rule: bool
|
|
|
|
) -> None:
|
|
|
|
"""
|
|
|
|
Sets the `enabled` state of a push rule.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
user_id: the user ID of the user who wishes to enable/disable the rule
|
|
|
|
e.g. '@tina:example.org'
|
|
|
|
rule_id: the full rule ID of the rule to be enabled/disabled
|
|
|
|
e.g. 'global/override/.m.rule.roomnotif'
|
|
|
|
or 'global/override/myCustomRule'
|
|
|
|
enabled: True if the rule is to be enabled, False if it is to be
|
|
|
|
disabled
|
|
|
|
is_default_rule: True if and only if this is a server-default rule.
|
|
|
|
This skips the check for existence (as only user-created rules
|
|
|
|
are always stored in the database `push_rules` table).
|
|
|
|
|
|
|
|
Raises:
|
2022-04-27 09:55:33 -04:00
|
|
|
RuleNotFoundException if the rule does not exist.
|
2020-09-09 06:39:39 -04:00
|
|
|
"""
|
2020-09-23 11:11:18 -04:00
|
|
|
async with self._push_rules_stream_id_gen.get_next() as stream_id:
|
2020-08-19 08:41:51 -04:00
|
|
|
event_stream_ordering = self._stream_id_gen.get_current_token()
|
2020-08-14 10:30:16 -04:00
|
|
|
await self.db_pool.runInteraction(
|
2019-10-21 07:56:42 -04:00
|
|
|
"_set_push_rule_enabled_txn",
|
|
|
|
self._set_push_rule_enabled_txn,
|
|
|
|
stream_id,
|
|
|
|
event_stream_ordering,
|
|
|
|
user_id,
|
|
|
|
rule_id,
|
|
|
|
enabled,
|
2020-09-09 06:39:39 -04:00
|
|
|
is_default_rule,
|
2019-10-21 07:56:42 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
def _set_push_rule_enabled_txn(
|
2020-09-09 06:39:39 -04:00
|
|
|
self,
|
2022-05-17 10:29:06 -04:00
|
|
|
txn: LoggingTransaction,
|
|
|
|
stream_id: int,
|
|
|
|
event_stream_ordering: int,
|
|
|
|
user_id: str,
|
|
|
|
rule_id: str,
|
|
|
|
enabled: bool,
|
|
|
|
is_default_rule: bool,
|
|
|
|
) -> None:
|
2019-10-21 07:56:42 -04:00
|
|
|
new_id = self._push_rules_enable_id_gen.get_next()
|
2020-09-09 06:39:39 -04:00
|
|
|
|
|
|
|
if not is_default_rule:
|
|
|
|
# first check it exists; we need to lock for key share so that a
|
|
|
|
# transaction that deletes the push rule will conflict with this one.
|
|
|
|
# We also need a push_rule_enable row to exist for every push_rules
|
|
|
|
# row, otherwise it is possible to simultaneously delete a push rule
|
|
|
|
# (that has no _enable row) and enable it, resulting in a dangling
|
|
|
|
# _enable row. To solve this: we either need to use SERIALISABLE or
|
|
|
|
# ensure we always have a push_rule_enable row for every push_rule
|
|
|
|
# row. We chose the latter.
|
|
|
|
for_key_share = "FOR KEY SHARE"
|
|
|
|
if not isinstance(self.database_engine, PostgresEngine):
|
|
|
|
# For key share is not applicable/available on SQLite
|
|
|
|
for_key_share = ""
|
|
|
|
sql = (
|
|
|
|
"""
|
|
|
|
SELECT 1 FROM push_rules
|
|
|
|
WHERE user_name = ? AND rule_id = ?
|
|
|
|
%s
|
|
|
|
"""
|
|
|
|
% for_key_share
|
|
|
|
)
|
|
|
|
txn.execute(sql, (user_id, rule_id))
|
|
|
|
if txn.fetchone() is None:
|
2022-04-27 09:55:33 -04:00
|
|
|
raise RuleNotFoundException("Push rule does not exist.")
|
2020-09-09 06:39:39 -04:00
|
|
|
|
2020-08-05 16:38:57 -04:00
|
|
|
self.db_pool.simple_upsert_txn(
|
2019-10-21 07:56:42 -04:00
|
|
|
txn,
|
|
|
|
"push_rules_enable",
|
|
|
|
{"user_name": user_id, "rule_id": rule_id},
|
|
|
|
{"enabled": 1 if enabled else 0},
|
|
|
|
{"id": new_id},
|
|
|
|
)
|
|
|
|
|
|
|
|
self._insert_push_rules_update_txn(
|
|
|
|
txn,
|
|
|
|
stream_id,
|
|
|
|
event_stream_ordering,
|
|
|
|
user_id,
|
|
|
|
rule_id,
|
|
|
|
op="ENABLE" if enabled else "DISABLE",
|
|
|
|
)
|
|
|
|
|
2020-08-14 10:30:16 -04:00
|
|
|
async def set_push_rule_actions(
|
2020-09-09 06:39:39 -04:00
|
|
|
self,
|
|
|
|
user_id: str,
|
|
|
|
rule_id: str,
|
|
|
|
actions: List[Union[dict, str]],
|
|
|
|
is_default_rule: bool,
|
2020-08-14 10:30:16 -04:00
|
|
|
) -> None:
|
2020-09-09 06:39:39 -04:00
|
|
|
"""
|
|
|
|
Sets the `actions` state of a push rule.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
user_id: the user ID of the user who wishes to enable/disable the rule
|
|
|
|
e.g. '@tina:example.org'
|
|
|
|
rule_id: the full rule ID of the rule to be enabled/disabled
|
|
|
|
e.g. 'global/override/.m.rule.roomnotif'
|
|
|
|
or 'global/override/myCustomRule'
|
|
|
|
actions: A list of actions (each action being a dict or string),
|
|
|
|
e.g. ["notify", {"set_tweak": "highlight", "value": false}]
|
|
|
|
is_default_rule: True if and only if this is a server-default rule.
|
|
|
|
This skips the check for existence (as only user-created rules
|
|
|
|
are always stored in the database `push_rules` table).
|
2022-04-27 09:55:33 -04:00
|
|
|
|
|
|
|
Raises:
|
|
|
|
RuleNotFoundException if the rule does not exist.
|
2020-09-09 06:39:39 -04:00
|
|
|
"""
|
2020-08-07 08:02:55 -04:00
|
|
|
actions_json = json_encoder.encode(actions)
|
2019-10-21 07:56:42 -04:00
|
|
|
|
2022-05-17 10:29:06 -04:00
|
|
|
def set_push_rule_actions_txn(
|
|
|
|
txn: LoggingTransaction,
|
|
|
|
stream_id: int,
|
|
|
|
event_stream_ordering: int,
|
|
|
|
) -> None:
|
2019-10-21 07:56:42 -04:00
|
|
|
if is_default_rule:
|
|
|
|
# Add a dummy rule to the rules table with the user specified
|
|
|
|
# actions.
|
|
|
|
priority_class = -1
|
|
|
|
priority = 1
|
|
|
|
self._upsert_push_rule_txn(
|
|
|
|
txn,
|
|
|
|
stream_id,
|
|
|
|
event_stream_ordering,
|
|
|
|
user_id,
|
|
|
|
rule_id,
|
|
|
|
priority_class,
|
|
|
|
priority,
|
|
|
|
"[]",
|
|
|
|
actions_json,
|
|
|
|
update_stream=False,
|
|
|
|
)
|
|
|
|
else:
|
2020-09-09 06:39:39 -04:00
|
|
|
try:
|
|
|
|
self.db_pool.simple_update_one_txn(
|
|
|
|
txn,
|
|
|
|
"push_rules",
|
|
|
|
{"user_name": user_id, "rule_id": rule_id},
|
|
|
|
{"actions": actions_json},
|
|
|
|
)
|
|
|
|
except StoreError as serr:
|
|
|
|
if serr.code == 404:
|
|
|
|
# this sets the NOT_FOUND error Code
|
2022-04-27 09:55:33 -04:00
|
|
|
raise RuleNotFoundException("Push rule does not exist")
|
2020-09-09 06:39:39 -04:00
|
|
|
else:
|
|
|
|
raise
|
2019-10-21 07:56:42 -04:00
|
|
|
|
|
|
|
self._insert_push_rules_update_txn(
|
|
|
|
txn,
|
|
|
|
stream_id,
|
|
|
|
event_stream_ordering,
|
|
|
|
user_id,
|
|
|
|
rule_id,
|
|
|
|
op="ACTIONS",
|
|
|
|
data={"actions": actions_json},
|
|
|
|
)
|
|
|
|
|
2020-09-23 11:11:18 -04:00
|
|
|
async with self._push_rules_stream_id_gen.get_next() as stream_id:
|
2020-08-19 08:41:51 -04:00
|
|
|
event_stream_ordering = self._stream_id_gen.get_current_token()
|
|
|
|
|
2020-08-14 10:30:16 -04:00
|
|
|
await self.db_pool.runInteraction(
|
2019-10-21 07:56:42 -04:00
|
|
|
"set_push_rule_actions",
|
|
|
|
set_push_rule_actions_txn,
|
|
|
|
stream_id,
|
|
|
|
event_stream_ordering,
|
|
|
|
)
|
|
|
|
|
|
|
|
def _insert_push_rules_update_txn(
|
2022-05-17 10:29:06 -04:00
|
|
|
self,
|
|
|
|
txn: LoggingTransaction,
|
|
|
|
stream_id: int,
|
|
|
|
event_stream_ordering: int,
|
|
|
|
user_id: str,
|
|
|
|
rule_id: str,
|
|
|
|
op: str,
|
|
|
|
data: Optional[JsonDict] = None,
|
|
|
|
) -> None:
|
2019-10-21 07:56:42 -04:00
|
|
|
values = {
|
|
|
|
"stream_id": stream_id,
|
|
|
|
"event_stream_ordering": event_stream_ordering,
|
|
|
|
"user_id": user_id,
|
|
|
|
"rule_id": rule_id,
|
|
|
|
"op": op,
|
|
|
|
}
|
|
|
|
if data is not None:
|
|
|
|
values.update(data)
|
|
|
|
|
2020-08-05 16:38:57 -04:00
|
|
|
self.db_pool.simple_insert_txn(txn, "push_rules_stream", values=values)
|
2019-10-21 07:56:42 -04:00
|
|
|
|
|
|
|
txn.call_after(self.get_push_rules_for_user.invalidate, (user_id,))
|
|
|
|
txn.call_after(
|
|
|
|
self.push_rules_stream_cache.entity_has_changed, user_id, stream_id
|
|
|
|
)
|
|
|
|
|
2022-05-17 10:29:06 -04:00
|
|
|
def get_max_push_rules_stream_id(self) -> int:
|
2020-08-19 08:41:51 -04:00
|
|
|
return self._push_rules_stream_id_gen.get_current_token()
|
2022-05-18 05:37:48 -04:00
|
|
|
|
|
|
|
async def copy_push_rule_from_room_to_room(
|
2022-08-16 07:22:17 -04:00
|
|
|
self, new_room_id: str, user_id: str, rule: PushRule
|
2022-05-18 05:37:48 -04:00
|
|
|
) -> None:
|
|
|
|
"""Copy a single push rule from one room to another for a specific user.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
new_room_id: ID of the new room.
|
|
|
|
user_id : ID of user the push rule belongs to.
|
|
|
|
rule: A push rule.
|
|
|
|
"""
|
|
|
|
# Create new rule id
|
2022-08-16 07:22:17 -04:00
|
|
|
rule_id_scope = "/".join(rule.rule_id.split("/")[:-1])
|
2022-05-18 05:37:48 -04:00
|
|
|
new_rule_id = rule_id_scope + "/" + new_room_id
|
|
|
|
|
2022-08-16 07:22:17 -04:00
|
|
|
new_conditions = []
|
|
|
|
|
2022-05-18 05:37:48 -04:00
|
|
|
# Change room id in each condition
|
2022-08-16 07:22:17 -04:00
|
|
|
for condition in rule.conditions:
|
|
|
|
new_condition = condition
|
2022-05-18 05:37:48 -04:00
|
|
|
if condition.get("key") == "room_id":
|
2022-08-16 07:22:17 -04:00
|
|
|
new_condition = dict(condition)
|
|
|
|
new_condition["pattern"] = new_room_id
|
|
|
|
|
|
|
|
new_conditions.append(new_condition)
|
2022-05-18 05:37:48 -04:00
|
|
|
|
|
|
|
# Add the rule for the new room
|
|
|
|
await self.add_push_rule(
|
|
|
|
user_id=user_id,
|
|
|
|
rule_id=new_rule_id,
|
2022-08-16 07:22:17 -04:00
|
|
|
priority_class=rule.priority_class,
|
|
|
|
conditions=new_conditions,
|
|
|
|
actions=rule.actions,
|
2022-05-18 05:37:48 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
async def copy_push_rules_from_room_to_room_for_user(
|
|
|
|
self, old_room_id: str, new_room_id: str, user_id: str
|
|
|
|
) -> None:
|
|
|
|
"""Copy all of the push rules from one room to another for a specific
|
|
|
|
user.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
old_room_id: ID of the old room.
|
|
|
|
new_room_id: ID of the new room.
|
|
|
|
user_id: ID of user to copy push rules for.
|
|
|
|
"""
|
|
|
|
# Retrieve push rules for this user
|
|
|
|
user_push_rules = await self.get_push_rules_for_user(user_id)
|
|
|
|
|
|
|
|
# Get rules relating to the old room and copy them to the new room
|
2022-09-20 07:10:31 -04:00
|
|
|
for rule, enabled in user_push_rules.rules():
|
2022-08-16 07:22:17 -04:00
|
|
|
if not enabled:
|
|
|
|
continue
|
|
|
|
|
|
|
|
conditions = rule.conditions
|
2022-05-18 05:37:48 -04:00
|
|
|
if any(
|
|
|
|
(c.get("key") == "room_id" and c.get("pattern") == old_room_id)
|
|
|
|
for c in conditions
|
|
|
|
):
|
|
|
|
await self.copy_push_rule_from_room_to_room(new_room_id, user_id, rule)
|