Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 
 
 

500 rindas
18 KiB

  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, load_legacy_presence_router
  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 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 LegacyPresenceRouterTestModule:
  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 PresenceRouterTestModule:
  64. def __init__(self, config: PresenceRouterTestConfig, api: ModuleApi):
  65. self._config = config
  66. self._module_api = api
  67. api.register_presence_router_callbacks(
  68. get_users_for_states=self.get_users_for_states,
  69. get_interested_users=self.get_interested_users,
  70. )
  71. async def get_users_for_states(
  72. self, state_updates: Iterable[UserPresenceState]
  73. ) -> Dict[str, Set[UserPresenceState]]:
  74. users_to_state = {
  75. user_id: set(state_updates)
  76. for user_id in self._config.users_who_should_receive_all_presence
  77. }
  78. return users_to_state
  79. async def get_interested_users(
  80. self, user_id: str
  81. ) -> Union[Set[str], PresenceRouter.ALL_USERS]:
  82. if user_id in self._config.users_who_should_receive_all_presence:
  83. return PresenceRouter.ALL_USERS
  84. return set()
  85. @staticmethod
  86. def parse_config(config_dict: dict) -> PresenceRouterTestConfig:
  87. """Parse a configuration dictionary from the homeserver config, do
  88. some validation and return a typed PresenceRouterConfig.
  89. Args:
  90. config_dict: The configuration dictionary.
  91. Returns:
  92. A validated config object.
  93. """
  94. # Initialise a typed config object
  95. config = PresenceRouterTestConfig()
  96. config.users_who_should_receive_all_presence = config_dict.get(
  97. "users_who_should_receive_all_presence"
  98. )
  99. return config
  100. class PresenceRouterTestCase(FederatingHomeserverTestCase):
  101. servlets = [
  102. admin.register_servlets,
  103. login.register_servlets,
  104. room.register_servlets,
  105. presence.register_servlets,
  106. ]
  107. def make_homeserver(self, reactor, clock):
  108. hs = self.setup_test_homeserver(
  109. federation_transport_client=Mock(spec=["send_transaction"]),
  110. )
  111. # Load the modules into the homeserver
  112. module_api = hs.get_module_api()
  113. for module, config in hs.config.modules.loaded_modules:
  114. module(config=config, api=module_api)
  115. load_legacy_presence_router(hs)
  116. return hs
  117. def prepare(self, reactor, clock, homeserver):
  118. self.sync_handler = self.hs.get_sync_handler()
  119. self.module_api = homeserver.get_module_api()
  120. @override_config(
  121. {
  122. "presence": {
  123. "presence_router": {
  124. "module": __name__ + ".LegacyPresenceRouterTestModule",
  125. "config": {
  126. "users_who_should_receive_all_presence": [
  127. "@presence_gobbler:test",
  128. ]
  129. },
  130. }
  131. },
  132. "send_federation": True,
  133. }
  134. )
  135. def test_receiving_all_presence_legacy(self):
  136. self.receiving_all_presence_test_body()
  137. @override_config(
  138. {
  139. "modules": [
  140. {
  141. "module": __name__ + ".PresenceRouterTestModule",
  142. "config": {
  143. "users_who_should_receive_all_presence": [
  144. "@presence_gobbler:test",
  145. ]
  146. },
  147. },
  148. ],
  149. "send_federation": True,
  150. }
  151. )
  152. def test_receiving_all_presence(self):
  153. self.receiving_all_presence_test_body()
  154. def receiving_all_presence_test_body(self):
  155. """Test that a user that does not share a room with another other can receive
  156. presence for them, due to presence routing.
  157. """
  158. # Create a user who should receive all presence of others
  159. self.presence_receiving_user_id = self.register_user(
  160. "presence_gobbler", "monkey"
  161. )
  162. self.presence_receiving_user_tok = self.login("presence_gobbler", "monkey")
  163. # And two users who should not have any special routing
  164. self.other_user_one_id = self.register_user("other_user_one", "monkey")
  165. self.other_user_one_tok = self.login("other_user_one", "monkey")
  166. self.other_user_two_id = self.register_user("other_user_two", "monkey")
  167. self.other_user_two_tok = self.login("other_user_two", "monkey")
  168. # Put the other two users in a room with each other
  169. room_id = self.helper.create_room_as(
  170. self.other_user_one_id, tok=self.other_user_one_tok
  171. )
  172. self.helper.invite(
  173. room_id,
  174. self.other_user_one_id,
  175. self.other_user_two_id,
  176. tok=self.other_user_one_tok,
  177. )
  178. self.helper.join(room_id, self.other_user_two_id, tok=self.other_user_two_tok)
  179. # User one sends some presence
  180. send_presence_update(
  181. self,
  182. self.other_user_one_id,
  183. self.other_user_one_tok,
  184. "online",
  185. "boop",
  186. )
  187. # Check that the presence receiving user gets user one's presence when syncing
  188. presence_updates, sync_token = sync_presence(
  189. self, self.presence_receiving_user_id
  190. )
  191. self.assertEqual(len(presence_updates), 1)
  192. presence_update: UserPresenceState = presence_updates[0]
  193. self.assertEqual(presence_update.user_id, self.other_user_one_id)
  194. self.assertEqual(presence_update.state, "online")
  195. self.assertEqual(presence_update.status_msg, "boop")
  196. # Have all three users send presence
  197. send_presence_update(
  198. self,
  199. self.other_user_one_id,
  200. self.other_user_one_tok,
  201. "online",
  202. "user_one",
  203. )
  204. send_presence_update(
  205. self,
  206. self.other_user_two_id,
  207. self.other_user_two_tok,
  208. "online",
  209. "user_two",
  210. )
  211. send_presence_update(
  212. self,
  213. self.presence_receiving_user_id,
  214. self.presence_receiving_user_tok,
  215. "online",
  216. "presence_gobbler",
  217. )
  218. # Check that the presence receiving user gets everyone's presence
  219. presence_updates, _ = sync_presence(
  220. self, self.presence_receiving_user_id, sync_token
  221. )
  222. self.assertEqual(len(presence_updates), 3)
  223. # But that User One only get itself and User Two's presence
  224. presence_updates, _ = sync_presence(self, self.other_user_one_id)
  225. self.assertEqual(len(presence_updates), 2)
  226. found = False
  227. for update in presence_updates:
  228. if update.user_id == self.other_user_two_id:
  229. self.assertEqual(update.state, "online")
  230. self.assertEqual(update.status_msg, "user_two")
  231. found = True
  232. self.assertTrue(found)
  233. @override_config(
  234. {
  235. "presence": {
  236. "presence_router": {
  237. "module": __name__ + ".LegacyPresenceRouterTestModule",
  238. "config": {
  239. "users_who_should_receive_all_presence": [
  240. "@presence_gobbler1:test",
  241. "@presence_gobbler2:test",
  242. "@far_away_person:island",
  243. ]
  244. },
  245. }
  246. },
  247. "send_federation": True,
  248. }
  249. )
  250. def test_send_local_online_presence_to_with_module_legacy(self):
  251. self.send_local_online_presence_to_with_module_test_body()
  252. @override_config(
  253. {
  254. "modules": [
  255. {
  256. "module": __name__ + ".PresenceRouterTestModule",
  257. "config": {
  258. "users_who_should_receive_all_presence": [
  259. "@presence_gobbler1:test",
  260. "@presence_gobbler2:test",
  261. "@far_away_person:island",
  262. ]
  263. },
  264. },
  265. ],
  266. "send_federation": True,
  267. }
  268. )
  269. def test_send_local_online_presence_to_with_module(self):
  270. self.send_local_online_presence_to_with_module_test_body()
  271. def send_local_online_presence_to_with_module_test_body(self):
  272. """Tests that send_local_presence_to_users sends local online presence to a set
  273. of specified local and remote users, with a custom PresenceRouter module enabled.
  274. """
  275. # Create a user who will send presence updates
  276. self.other_user_id = self.register_user("other_user", "monkey")
  277. self.other_user_tok = self.login("other_user", "monkey")
  278. # And another two users that will also send out presence updates, as well as receive
  279. # theirs and everyone else's
  280. self.presence_receiving_user_one_id = self.register_user(
  281. "presence_gobbler1", "monkey"
  282. )
  283. self.presence_receiving_user_one_tok = self.login("presence_gobbler1", "monkey")
  284. self.presence_receiving_user_two_id = self.register_user(
  285. "presence_gobbler2", "monkey"
  286. )
  287. self.presence_receiving_user_two_tok = self.login("presence_gobbler2", "monkey")
  288. # Have all three users send some presence updates
  289. send_presence_update(
  290. self,
  291. self.other_user_id,
  292. self.other_user_tok,
  293. "online",
  294. "I'm online!",
  295. )
  296. send_presence_update(
  297. self,
  298. self.presence_receiving_user_one_id,
  299. self.presence_receiving_user_one_tok,
  300. "online",
  301. "I'm also online!",
  302. )
  303. send_presence_update(
  304. self,
  305. self.presence_receiving_user_two_id,
  306. self.presence_receiving_user_two_tok,
  307. "unavailable",
  308. "I'm in a meeting!",
  309. )
  310. # Mark each presence-receiving user for receiving all user presence
  311. self.get_success(
  312. self.module_api.send_local_online_presence_to(
  313. [
  314. self.presence_receiving_user_one_id,
  315. self.presence_receiving_user_two_id,
  316. ]
  317. )
  318. )
  319. # Perform a sync for each user
  320. # The other user should only receive their own presence
  321. presence_updates, _ = sync_presence(self, self.other_user_id)
  322. self.assertEqual(len(presence_updates), 1)
  323. presence_update: UserPresenceState = presence_updates[0]
  324. self.assertEqual(presence_update.user_id, self.other_user_id)
  325. self.assertEqual(presence_update.state, "online")
  326. self.assertEqual(presence_update.status_msg, "I'm online!")
  327. # Whereas both presence receiving users should receive everyone's presence updates
  328. presence_updates, _ = sync_presence(self, self.presence_receiving_user_one_id)
  329. self.assertEqual(len(presence_updates), 3)
  330. presence_updates, _ = sync_presence(self, self.presence_receiving_user_two_id)
  331. self.assertEqual(len(presence_updates), 3)
  332. # We stagger sending of presence, so we need to wait a bit for them to
  333. # get sent out.
  334. self.reactor.advance(60)
  335. # Test that sending to a remote user works
  336. remote_user_id = "@far_away_person:island"
  337. # Note that due to the remote user being in our module's
  338. # users_who_should_receive_all_presence config, they would have
  339. # received user presence updates already.
  340. #
  341. # Thus we reset the mock, and try sending all online local user
  342. # presence again
  343. self.hs.get_federation_transport_client().send_transaction.reset_mock()
  344. # Broadcast local user online presence
  345. self.get_success(
  346. self.module_api.send_local_online_presence_to([remote_user_id])
  347. )
  348. # We stagger sending of presence, so we need to wait a bit for them to
  349. # get sent out.
  350. self.reactor.advance(60)
  351. # Check that the expected presence updates were sent
  352. # We explicitly compare using sets as we expect that calling
  353. # module_api.send_local_online_presence_to will create a presence
  354. # update that is a duplicate of the specified user's current presence.
  355. # These are sent to clients and will be picked up below, thus we use a
  356. # set to deduplicate. We're just interested that non-offline updates were
  357. # sent out for each user ID.
  358. expected_users = {
  359. self.other_user_id,
  360. self.presence_receiving_user_one_id,
  361. self.presence_receiving_user_two_id,
  362. }
  363. found_users = set()
  364. calls = (
  365. self.hs.get_federation_transport_client().send_transaction.call_args_list
  366. )
  367. for call in calls:
  368. call_args = call[0]
  369. federation_transaction: Transaction = call_args[0]
  370. # Get the sent EDUs in this transaction
  371. edus = federation_transaction.get_dict()["edus"]
  372. for edu in edus:
  373. # Make sure we're only checking presence-type EDUs
  374. if edu["edu_type"] != EduTypes.Presence:
  375. continue
  376. # EDUs can contain multiple presence updates
  377. for presence_update in edu["content"]["push"]:
  378. # Check for presence updates that contain the user IDs we're after
  379. found_users.add(presence_update["user_id"])
  380. # Ensure that no offline states are being sent out
  381. self.assertNotEqual(presence_update["presence"], "offline")
  382. self.assertEqual(found_users, expected_users)
  383. def send_presence_update(
  384. testcase: TestCase,
  385. user_id: str,
  386. access_token: str,
  387. presence_state: str,
  388. status_message: Optional[str] = None,
  389. ) -> JsonDict:
  390. # Build the presence body
  391. body = {"presence": presence_state}
  392. if status_message:
  393. body["status_msg"] = status_message
  394. # Update the user's presence state
  395. channel = testcase.make_request(
  396. "PUT", "/presence/%s/status" % (user_id,), body, access_token=access_token
  397. )
  398. testcase.assertEqual(channel.code, 200)
  399. return channel.json_body
  400. def sync_presence(
  401. testcase: TestCase,
  402. user_id: str,
  403. since_token: Optional[StreamToken] = None,
  404. ) -> Tuple[List[UserPresenceState], StreamToken]:
  405. """Perform a sync request for the given user and return the user presence updates
  406. they've received, as well as the next_batch token.
  407. This method assumes testcase.sync_handler points to the homeserver's sync handler.
  408. Args:
  409. testcase: The testcase that is currently being run.
  410. user_id: The ID of the user to generate a sync response for.
  411. since_token: An optional token to indicate from at what point to sync from.
  412. Returns:
  413. A tuple containing a list of presence updates, and the sync response's
  414. next_batch token.
  415. """
  416. requester = create_requester(user_id)
  417. sync_config = generate_sync_config(requester.user.to_string())
  418. sync_result = testcase.get_success(
  419. testcase.sync_handler.wait_for_sync_for_user(
  420. requester, sync_config, since_token
  421. )
  422. )
  423. return sync_result.presence, sync_result.next_batch