test_presence_router.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. # Copyright 2021 The Matrix.org Foundation C.I.C.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the 'License');
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an 'AS IS' BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from typing import Dict, Iterable, List, Optional, Set, Tuple, Union
  15. from unittest.mock import Mock
  16. import attr
  17. from synapse.api.constants import EduTypes
  18. from synapse.events.presence_router import PresenceRouter
  19. from synapse.federation.units import Transaction
  20. from synapse.handlers.presence import UserPresenceState
  21. from synapse.module_api import ModuleApi
  22. from synapse.rest import admin
  23. from synapse.rest.client.v1 import login, presence, room
  24. from synapse.types import JsonDict, StreamToken, create_requester
  25. from tests.handlers.test_sync import generate_sync_config
  26. from tests.unittest import FederatingHomeserverTestCase, TestCase, override_config
  27. @attr.s
  28. class PresenceRouterTestConfig:
  29. users_who_should_receive_all_presence = attr.ib(type=List[str], default=[])
  30. class PresenceRouterTestModule:
  31. def __init__(self, config: PresenceRouterTestConfig, module_api: ModuleApi):
  32. self._config = config
  33. self._module_api = module_api
  34. async def get_users_for_states(
  35. self, state_updates: Iterable[UserPresenceState]
  36. ) -> Dict[str, Set[UserPresenceState]]:
  37. users_to_state = {
  38. user_id: set(state_updates)
  39. for user_id in self._config.users_who_should_receive_all_presence
  40. }
  41. return users_to_state
  42. async def get_interested_users(
  43. self, user_id: str
  44. ) -> Union[Set[str], PresenceRouter.ALL_USERS]:
  45. if user_id in self._config.users_who_should_receive_all_presence:
  46. return PresenceRouter.ALL_USERS
  47. return set()
  48. @staticmethod
  49. def parse_config(config_dict: dict) -> PresenceRouterTestConfig:
  50. """Parse a configuration dictionary from the homeserver config, do
  51. some validation and return a typed PresenceRouterConfig.
  52. Args:
  53. config_dict: The configuration dictionary.
  54. Returns:
  55. A validated config object.
  56. """
  57. # Initialise a typed config object
  58. config = PresenceRouterTestConfig()
  59. config.users_who_should_receive_all_presence = config_dict.get(
  60. "users_who_should_receive_all_presence"
  61. )
  62. return config
  63. class PresenceRouterTestCase(FederatingHomeserverTestCase):
  64. servlets = [
  65. admin.register_servlets,
  66. login.register_servlets,
  67. room.register_servlets,
  68. presence.register_servlets,
  69. ]
  70. def make_homeserver(self, reactor, clock):
  71. return self.setup_test_homeserver(
  72. federation_transport_client=Mock(spec=["send_transaction"]),
  73. )
  74. def prepare(self, reactor, clock, homeserver):
  75. self.sync_handler = self.hs.get_sync_handler()
  76. self.module_api = homeserver.get_module_api()
  77. @override_config(
  78. {
  79. "presence": {
  80. "presence_router": {
  81. "module": __name__ + ".PresenceRouterTestModule",
  82. "config": {
  83. "users_who_should_receive_all_presence": [
  84. "@presence_gobbler:test",
  85. ]
  86. },
  87. }
  88. },
  89. "send_federation": True,
  90. }
  91. )
  92. def test_receiving_all_presence(self):
  93. """Test that a user that does not share a room with another other can receive
  94. presence for them, due to presence routing.
  95. """
  96. # Create a user who should receive all presence of others
  97. self.presence_receiving_user_id = self.register_user(
  98. "presence_gobbler", "monkey"
  99. )
  100. self.presence_receiving_user_tok = self.login("presence_gobbler", "monkey")
  101. # And two users who should not have any special routing
  102. self.other_user_one_id = self.register_user("other_user_one", "monkey")
  103. self.other_user_one_tok = self.login("other_user_one", "monkey")
  104. self.other_user_two_id = self.register_user("other_user_two", "monkey")
  105. self.other_user_two_tok = self.login("other_user_two", "monkey")
  106. # Put the other two users in a room with each other
  107. room_id = self.helper.create_room_as(
  108. self.other_user_one_id, tok=self.other_user_one_tok
  109. )
  110. self.helper.invite(
  111. room_id,
  112. self.other_user_one_id,
  113. self.other_user_two_id,
  114. tok=self.other_user_one_tok,
  115. )
  116. self.helper.join(room_id, self.other_user_two_id, tok=self.other_user_two_tok)
  117. # User one sends some presence
  118. send_presence_update(
  119. self,
  120. self.other_user_one_id,
  121. self.other_user_one_tok,
  122. "online",
  123. "boop",
  124. )
  125. # Check that the presence receiving user gets user one's presence when syncing
  126. presence_updates, sync_token = sync_presence(
  127. self, self.presence_receiving_user_id
  128. )
  129. self.assertEqual(len(presence_updates), 1)
  130. presence_update = presence_updates[0] # type: UserPresenceState
  131. self.assertEqual(presence_update.user_id, self.other_user_one_id)
  132. self.assertEqual(presence_update.state, "online")
  133. self.assertEqual(presence_update.status_msg, "boop")
  134. # Have all three users send presence
  135. send_presence_update(
  136. self,
  137. self.other_user_one_id,
  138. self.other_user_one_tok,
  139. "online",
  140. "user_one",
  141. )
  142. send_presence_update(
  143. self,
  144. self.other_user_two_id,
  145. self.other_user_two_tok,
  146. "online",
  147. "user_two",
  148. )
  149. send_presence_update(
  150. self,
  151. self.presence_receiving_user_id,
  152. self.presence_receiving_user_tok,
  153. "online",
  154. "presence_gobbler",
  155. )
  156. # Check that the presence receiving user gets everyone's presence
  157. presence_updates, _ = sync_presence(
  158. self, self.presence_receiving_user_id, sync_token
  159. )
  160. self.assertEqual(len(presence_updates), 3)
  161. # But that User One only get itself and User Two's presence
  162. presence_updates, _ = sync_presence(self, self.other_user_one_id)
  163. self.assertEqual(len(presence_updates), 2)
  164. found = False
  165. for update in presence_updates:
  166. if update.user_id == self.other_user_two_id:
  167. self.assertEqual(update.state, "online")
  168. self.assertEqual(update.status_msg, "user_two")
  169. found = True
  170. self.assertTrue(found)
  171. @override_config(
  172. {
  173. "presence": {
  174. "presence_router": {
  175. "module": __name__ + ".PresenceRouterTestModule",
  176. "config": {
  177. "users_who_should_receive_all_presence": [
  178. "@presence_gobbler1:test",
  179. "@presence_gobbler2:test",
  180. "@far_away_person:island",
  181. ]
  182. },
  183. }
  184. },
  185. "send_federation": True,
  186. }
  187. )
  188. def test_send_local_online_presence_to_with_module(self):
  189. """Tests that send_local_presence_to_users sends local online presence to a set
  190. of specified local and remote users, with a custom PresenceRouter module enabled.
  191. """
  192. # Create a user who will send presence updates
  193. self.other_user_id = self.register_user("other_user", "monkey")
  194. self.other_user_tok = self.login("other_user", "monkey")
  195. # And another two users that will also send out presence updates, as well as receive
  196. # theirs and everyone else's
  197. self.presence_receiving_user_one_id = self.register_user(
  198. "presence_gobbler1", "monkey"
  199. )
  200. self.presence_receiving_user_one_tok = self.login("presence_gobbler1", "monkey")
  201. self.presence_receiving_user_two_id = self.register_user(
  202. "presence_gobbler2", "monkey"
  203. )
  204. self.presence_receiving_user_two_tok = self.login("presence_gobbler2", "monkey")
  205. # Have all three users send some presence updates
  206. send_presence_update(
  207. self,
  208. self.other_user_id,
  209. self.other_user_tok,
  210. "online",
  211. "I'm online!",
  212. )
  213. send_presence_update(
  214. self,
  215. self.presence_receiving_user_one_id,
  216. self.presence_receiving_user_one_tok,
  217. "online",
  218. "I'm also online!",
  219. )
  220. send_presence_update(
  221. self,
  222. self.presence_receiving_user_two_id,
  223. self.presence_receiving_user_two_tok,
  224. "unavailable",
  225. "I'm in a meeting!",
  226. )
  227. # Mark each presence-receiving user for receiving all user presence
  228. self.get_success(
  229. self.module_api.send_local_online_presence_to(
  230. [
  231. self.presence_receiving_user_one_id,
  232. self.presence_receiving_user_two_id,
  233. ]
  234. )
  235. )
  236. # Perform a sync for each user
  237. # The other user should only receive their own presence
  238. presence_updates, _ = sync_presence(self, self.other_user_id)
  239. self.assertEqual(len(presence_updates), 1)
  240. presence_update = presence_updates[0] # type: UserPresenceState
  241. self.assertEqual(presence_update.user_id, self.other_user_id)
  242. self.assertEqual(presence_update.state, "online")
  243. self.assertEqual(presence_update.status_msg, "I'm online!")
  244. # Whereas both presence receiving users should receive everyone's presence updates
  245. presence_updates, _ = sync_presence(self, self.presence_receiving_user_one_id)
  246. self.assertEqual(len(presence_updates), 3)
  247. presence_updates, _ = sync_presence(self, self.presence_receiving_user_two_id)
  248. self.assertEqual(len(presence_updates), 3)
  249. # Test that sending to a remote user works
  250. remote_user_id = "@far_away_person:island"
  251. # Note that due to the remote user being in our module's
  252. # users_who_should_receive_all_presence config, they would have
  253. # received user presence updates already.
  254. #
  255. # Thus we reset the mock, and try sending all online local user
  256. # presence again
  257. self.hs.get_federation_transport_client().send_transaction.reset_mock()
  258. # Broadcast local user online presence
  259. self.get_success(
  260. self.module_api.send_local_online_presence_to([remote_user_id])
  261. )
  262. # Check that the expected presence updates were sent
  263. expected_users = [
  264. self.other_user_id,
  265. self.presence_receiving_user_one_id,
  266. self.presence_receiving_user_two_id,
  267. ]
  268. calls = (
  269. self.hs.get_federation_transport_client().send_transaction.call_args_list
  270. )
  271. for call in calls:
  272. call_args = call[0]
  273. federation_transaction = call_args[0] # type: Transaction
  274. # Get the sent EDUs in this transaction
  275. edus = federation_transaction.get_dict()["edus"]
  276. for edu in edus:
  277. # Make sure we're only checking presence-type EDUs
  278. if edu["edu_type"] != EduTypes.Presence:
  279. continue
  280. # EDUs can contain multiple presence updates
  281. for presence_update in edu["content"]["push"]:
  282. # Check for presence updates that contain the user IDs we're after
  283. expected_users.remove(presence_update["user_id"])
  284. # Ensure that no offline states are being sent out
  285. self.assertNotEqual(presence_update["presence"], "offline")
  286. self.assertEqual(len(expected_users), 0)
  287. def send_presence_update(
  288. testcase: TestCase,
  289. user_id: str,
  290. access_token: str,
  291. presence_state: str,
  292. status_message: Optional[str] = None,
  293. ) -> JsonDict:
  294. # Build the presence body
  295. body = {"presence": presence_state}
  296. if status_message:
  297. body["status_msg"] = status_message
  298. # Update the user's presence state
  299. channel = testcase.make_request(
  300. "PUT", "/presence/%s/status" % (user_id,), body, access_token=access_token
  301. )
  302. testcase.assertEqual(channel.code, 200)
  303. return channel.json_body
  304. def sync_presence(
  305. testcase: TestCase,
  306. user_id: str,
  307. since_token: Optional[StreamToken] = None,
  308. ) -> Tuple[List[UserPresenceState], StreamToken]:
  309. """Perform a sync request for the given user and return the user presence updates
  310. they've received, as well as the next_batch token.
  311. This method assumes testcase.sync_handler points to the homeserver's sync handler.
  312. Args:
  313. testcase: The testcase that is currently being run.
  314. user_id: The ID of the user to generate a sync response for.
  315. since_token: An optional token to indicate from at what point to sync from.
  316. Returns:
  317. A tuple containing a list of presence updates, and the sync response's
  318. next_batch token.
  319. """
  320. requester = create_requester(user_id)
  321. sync_config = generate_sync_config(requester.user.to_string())
  322. sync_result = testcase.get_success(
  323. testcase.sync_handler.wait_for_sync_for_user(
  324. requester, sync_config, since_token
  325. )
  326. )
  327. return sync_result.presence, sync_result.next_batch