This repository has been archived by the owner on Apr 26, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add a module callback to react to account data changes (#12327)
Co-authored-by: Sean Quah <8349537+squahtx@users.noreply.github.com> Co-authored-by: Andrew Morgan <1342360+anoadragon453@users.noreply.github.com>
- Loading branch information
1 parent
4e900ec
commit e440930
Showing
7 changed files
with
250 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
Add a module callback to react to account data changes. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,106 @@ | ||
# Account data callbacks | ||
|
||
Account data callbacks allow module developers to react to changes of the account data | ||
of local users. Account data callbacks can be registered using the module API's | ||
`register_account_data_callbacks` method. | ||
|
||
## Callbacks | ||
|
||
The available account data callbacks are: | ||
|
||
### `on_account_data_updated` | ||
|
||
_First introduced in Synapse v1.57.0_ | ||
|
||
```python | ||
async def on_account_data_updated( | ||
user_id: str, | ||
room_id: Optional[str], | ||
account_data_type: str, | ||
content: "synapse.module_api.JsonDict", | ||
) -> None: | ||
``` | ||
|
||
Called after user's account data has been updated. The module is given the | ||
Matrix ID of the user whose account data is changing, the room ID the data is associated | ||
with, the type associated with the change, as well as the new content. If the account | ||
data is not associated with a specific room, then the room ID is `None`. | ||
|
||
This callback is triggered when new account data is added or when the data associated with | ||
a given type (and optionally room) changes. This includes deletion, since in Matrix, | ||
deleting account data consists of replacing the data associated with a given type | ||
(and optionally room) with an empty dictionary (`{}`). | ||
|
||
Note that this doesn't trigger when changing the tags associated with a room, as these are | ||
processed separately by Synapse. | ||
|
||
If multiple modules implement this callback, Synapse runs them all in order. | ||
|
||
## Example | ||
|
||
The example below is a module that implements the `on_account_data_updated` callback, and | ||
sends an event to an audit room when a user changes their account data. | ||
|
||
```python | ||
import json | ||
import attr | ||
from typing import Any, Dict, Optional | ||
|
||
from synapse.module_api import JsonDict, ModuleApi | ||
from synapse.module_api.errors import ConfigError | ||
|
||
|
||
@attr.s(auto_attribs=True) | ||
class CustomAccountDataConfig: | ||
audit_room: str | ||
sender: str | ||
|
||
|
||
class CustomAccountDataModule: | ||
def __init__(self, config: CustomAccountDataConfig, api: ModuleApi): | ||
self.api = api | ||
self.config = config | ||
|
||
self.api.register_account_data_callbacks( | ||
on_account_data_updated=self.log_new_account_data, | ||
) | ||
|
||
@staticmethod | ||
def parse_config(config: Dict[str, Any]) -> CustomAccountDataConfig: | ||
def check_in_config(param: str): | ||
if param not in config: | ||
raise ConfigError(f"'{param}' is required") | ||
|
||
check_in_config("audit_room") | ||
check_in_config("sender") | ||
|
||
return CustomAccountDataConfig( | ||
audit_room=config["audit_room"], | ||
sender=config["sender"], | ||
) | ||
|
||
async def log_new_account_data( | ||
self, | ||
user_id: str, | ||
room_id: Optional[str], | ||
account_data_type: str, | ||
content: JsonDict, | ||
) -> None: | ||
content_raw = json.dumps(content) | ||
msg_content = f"{user_id} has changed their account data for type {account_data_type} to: {content_raw}" | ||
|
||
if room_id is not None: | ||
msg_content += f" (in room {room_id})" | ||
|
||
await self.api.create_and_send_event_into_room( | ||
{ | ||
"room_id": self.config.audit_room, | ||
"sender": self.config.sender, | ||
"type": "m.room.message", | ||
"content": { | ||
"msgtype": "m.text", | ||
"body": msg_content | ||
} | ||
} | ||
) | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
# Copyright 2022 The Matrix.org Foundation C.I.C | ||
# | ||
# 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. | ||
from unittest.mock import Mock | ||
|
||
from synapse.rest import admin | ||
from synapse.rest.client import account_data, login, room | ||
|
||
from tests import unittest | ||
from tests.test_utils import make_awaitable | ||
|
||
|
||
class AccountDataTestCase(unittest.HomeserverTestCase): | ||
servlets = [ | ||
admin.register_servlets, | ||
login.register_servlets, | ||
room.register_servlets, | ||
account_data.register_servlets, | ||
] | ||
|
||
def test_on_account_data_updated_callback(self) -> None: | ||
"""Tests that the on_account_data_updated module callback is called correctly when | ||
a user's account data changes. | ||
""" | ||
mocked_callback = Mock(return_value=make_awaitable(None)) | ||
self.hs.get_account_data_handler()._on_account_data_updated_callbacks.append( | ||
mocked_callback | ||
) | ||
|
||
user_id = self.register_user("user", "password") | ||
tok = self.login("user", "password") | ||
account_data_type = "org.matrix.foo" | ||
account_data_content = {"bar": "baz"} | ||
|
||
# Change the user's global account data. | ||
channel = self.make_request( | ||
"PUT", | ||
f"/user/{user_id}/account_data/{account_data_type}", | ||
account_data_content, | ||
access_token=tok, | ||
) | ||
|
||
# Test that the callback is called with the user ID, the new account data, and | ||
# None as the room ID. | ||
self.assertEqual(channel.code, 200, channel.result) | ||
mocked_callback.assert_called_once_with( | ||
user_id, None, account_data_type, account_data_content | ||
) | ||
|
||
# Change the user's room-specific account data. | ||
room_id = self.helper.create_room_as(user_id, tok=tok) | ||
channel = self.make_request( | ||
"PUT", | ||
f"/user/{user_id}/rooms/{room_id}/account_data/{account_data_type}", | ||
account_data_content, | ||
access_token=tok, | ||
) | ||
|
||
# Test that the callback is called with the user ID, the room ID and the new | ||
# account data. | ||
self.assertEqual(channel.code, 200, channel.result) | ||
self.assertEqual(mocked_callback.call_count, 2) | ||
mocked_callback.assert_called_with( | ||
user_id, room_id, account_data_type, account_data_content | ||
) |