This repository was 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
Add a module callback to react to account data changes #12327
Merged
Merged
Changes from 7 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
033efc6
Add a module callback to react to account data changes
babolivier 3024a28
Document the new callback
babolivier d885cc0
Add a test for the callback
babolivier e4ef4d4
Sneakily correct lying documentation
babolivier 6179f08
Changelog
babolivier b010201
Merge branch 'develop' of github.com:matrix-org/synapse into babolivi…
babolivier a166bf8
Fix test
babolivier fb8caf6
Add new doc page to summary
babolivier 916c3e6
Apply suggestions from code review
babolivier 7aed48e
Incorporate review comments
babolivier 6f836cd
Update docs/modules/account_data_callbacks.md
babolivier File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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 hidden or 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 change with 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 presence router callbacks are: | ||
babolivier marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| ### `on_account_data_change` | ||
|
|
||
| _First introduced in Synapse v1.57.0_ | ||
|
|
||
| ```python | ||
| async def on_account_data_change( | ||
babolivier marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| user_id: str, | ||
| room_id: Optional[str], | ||
| account_data_type: str, | ||
| content: "synapse.module_api.JsonDict", | ||
| ) -> None: | ||
| ``` | ||
|
|
||
| Called after processing a change with a user's account data. 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) change. In Matrix, deleting account data consists in | ||
babolivier marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| 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_change` callback, and | ||
babolivier marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| 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_change=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 hidden or 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 hidden or 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 hidden or 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 hidden or 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_changes_callback(self) -> None: | ||
| """Tests that the on_account_data_changes 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_change_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 | ||
| ) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.