test_api.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  1. # Copyright 2020 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 unittest.mock import Mock
  15. from twisted.internet import defer
  16. from synapse.api.constants import EduTypes, EventTypes
  17. from synapse.events import EventBase
  18. from synapse.federation.units import Transaction
  19. from synapse.handlers.presence import UserPresenceState
  20. from synapse.rest import admin
  21. from synapse.rest.client import login, presence, profile, room
  22. from synapse.types import create_requester
  23. from tests.events.test_presence_router import send_presence_update, sync_presence
  24. from tests.replication._base import BaseMultiWorkerStreamTestCase
  25. from tests.test_utils import simple_async_mock
  26. from tests.test_utils.event_injection import inject_member_event
  27. from tests.unittest import HomeserverTestCase, override_config
  28. from tests.utils import USE_POSTGRES_FOR_TESTS
  29. class ModuleApiTestCase(HomeserverTestCase):
  30. servlets = [
  31. admin.register_servlets,
  32. login.register_servlets,
  33. room.register_servlets,
  34. presence.register_servlets,
  35. profile.register_servlets,
  36. ]
  37. def prepare(self, reactor, clock, homeserver):
  38. self.store = homeserver.get_datastores().main
  39. self.module_api = homeserver.get_module_api()
  40. self.event_creation_handler = homeserver.get_event_creation_handler()
  41. self.sync_handler = homeserver.get_sync_handler()
  42. self.auth_handler = homeserver.get_auth_handler()
  43. def make_homeserver(self, reactor, clock):
  44. # Mock out the calls over federation.
  45. fed_transport_client = Mock(spec=["send_transaction"])
  46. fed_transport_client.send_transaction = simple_async_mock({})
  47. return self.setup_test_homeserver(
  48. federation_transport_client=fed_transport_client,
  49. )
  50. def test_can_register_user(self):
  51. """Tests that an external module can register a user"""
  52. # Register a new user
  53. user_id, access_token = self.get_success(
  54. self.module_api.register(
  55. "bob", displayname="Bobberino", emails=["bob@bobinator.bob"]
  56. )
  57. )
  58. # Check that the new user exists with all provided attributes
  59. self.assertEqual(user_id, "@bob:test")
  60. self.assertTrue(access_token)
  61. self.assertTrue(self.get_success(self.store.get_user_by_id(user_id)))
  62. # Check that the email was assigned
  63. emails = self.get_success(self.store.user_get_threepids(user_id))
  64. self.assertEqual(len(emails), 1)
  65. email = emails[0]
  66. self.assertEqual(email["medium"], "email")
  67. self.assertEqual(email["address"], "bob@bobinator.bob")
  68. # Should these be 0?
  69. self.assertEqual(email["validated_at"], 0)
  70. self.assertEqual(email["added_at"], 0)
  71. # Check that the displayname was assigned
  72. displayname = self.get_success(self.store.get_profile_displayname("bob"))
  73. self.assertEqual(displayname, "Bobberino")
  74. def test_get_userinfo_by_id(self):
  75. user_id = self.register_user("alice", "1234")
  76. found_user = self.get_success(self.module_api.get_userinfo_by_id(user_id))
  77. self.assertEqual(found_user.user_id.to_string(), user_id)
  78. self.assertIdentical(found_user.is_admin, False)
  79. def test_get_userinfo_by_id__no_user_found(self):
  80. found_user = self.get_success(self.module_api.get_userinfo_by_id("@alice:test"))
  81. self.assertIsNone(found_user)
  82. def test_get_user_ip_and_agents(self):
  83. user_id = self.register_user("test_get_user_ip_and_agents_user", "1234")
  84. # Initially, we should have no ip/agent for our user.
  85. info = self.get_success(self.module_api.get_user_ip_and_agents(user_id))
  86. self.assertEqual(info, [])
  87. # Insert a first ip, agent. We should be able to retrieve it.
  88. self.get_success(
  89. self.store.insert_client_ip(
  90. user_id, "access_token", "ip_1", "user_agent_1", "device_1", None
  91. )
  92. )
  93. info = self.get_success(self.module_api.get_user_ip_and_agents(user_id))
  94. self.assertEqual(len(info), 1)
  95. last_seen_1 = info[0].last_seen
  96. # Insert a second ip, agent at a later date. We should be able to retrieve it.
  97. last_seen_2 = last_seen_1 + 10000
  98. self.get_success(
  99. self.store.insert_client_ip(
  100. user_id, "access_token", "ip_2", "user_agent_2", "device_2", last_seen_2
  101. )
  102. )
  103. info = self.get_success(self.module_api.get_user_ip_and_agents(user_id))
  104. self.assertEqual(len(info), 2)
  105. ip_1_seen = False
  106. ip_2_seen = False
  107. for i in info:
  108. if i.ip == "ip_1":
  109. ip_1_seen = True
  110. self.assertEqual(i.user_agent, "user_agent_1")
  111. self.assertEqual(i.last_seen, last_seen_1)
  112. elif i.ip == "ip_2":
  113. ip_2_seen = True
  114. self.assertEqual(i.user_agent, "user_agent_2")
  115. self.assertEqual(i.last_seen, last_seen_2)
  116. self.assertTrue(ip_1_seen)
  117. self.assertTrue(ip_2_seen)
  118. # If we fetch from a midpoint between last_seen_1 and last_seen_2,
  119. # we should only find the second ip, agent.
  120. info = self.get_success(
  121. self.module_api.get_user_ip_and_agents(
  122. user_id, (last_seen_1 + last_seen_2) / 2
  123. )
  124. )
  125. self.assertEqual(len(info), 1)
  126. self.assertEqual(info[0].ip, "ip_2")
  127. self.assertEqual(info[0].user_agent, "user_agent_2")
  128. self.assertEqual(info[0].last_seen, last_seen_2)
  129. # If we fetch from a point later than last_seen_2, we shouldn't
  130. # find anything.
  131. info = self.get_success(
  132. self.module_api.get_user_ip_and_agents(user_id, last_seen_2 + 10000)
  133. )
  134. self.assertEqual(info, [])
  135. def test_get_user_ip_and_agents__no_user_found(self):
  136. info = self.get_success(
  137. self.module_api.get_user_ip_and_agents(
  138. "@test_get_user_ip_and_agents_user_nonexistent:example.com"
  139. )
  140. )
  141. self.assertEqual(info, [])
  142. def test_sending_events_into_room(self):
  143. """Tests that a module can send events into a room"""
  144. # Mock out create_and_send_nonmember_event to check whether events are being sent
  145. self.event_creation_handler.create_and_send_nonmember_event = Mock(
  146. spec=[],
  147. side_effect=self.event_creation_handler.create_and_send_nonmember_event,
  148. )
  149. # Create a user and room to play with
  150. user_id = self.register_user("summer", "monkey")
  151. tok = self.login("summer", "monkey")
  152. room_id = self.helper.create_room_as(user_id, tok=tok)
  153. # Create and send a non-state event
  154. content = {"body": "I am a puppet", "msgtype": "m.text"}
  155. event_dict = {
  156. "room_id": room_id,
  157. "type": "m.room.message",
  158. "content": content,
  159. "sender": user_id,
  160. }
  161. event: EventBase = self.get_success(
  162. self.module_api.create_and_send_event_into_room(event_dict)
  163. )
  164. self.assertEqual(event.sender, user_id)
  165. self.assertEqual(event.type, "m.room.message")
  166. self.assertEqual(event.room_id, room_id)
  167. self.assertFalse(hasattr(event, "state_key"))
  168. self.assertDictEqual(event.content, content)
  169. expected_requester = create_requester(
  170. user_id, authenticated_entity=self.hs.hostname
  171. )
  172. # Check that the event was sent
  173. self.event_creation_handler.create_and_send_nonmember_event.assert_called_with(
  174. expected_requester,
  175. event_dict,
  176. ratelimit=False,
  177. ignore_shadow_ban=True,
  178. )
  179. # Create and send a state event
  180. content = {
  181. "events_default": 0,
  182. "users": {user_id: 100},
  183. "state_default": 50,
  184. "users_default": 0,
  185. "events": {"test.event.type": 25},
  186. }
  187. event_dict = {
  188. "room_id": room_id,
  189. "type": "m.room.power_levels",
  190. "content": content,
  191. "sender": user_id,
  192. "state_key": "",
  193. }
  194. event: EventBase = self.get_success(
  195. self.module_api.create_and_send_event_into_room(event_dict)
  196. )
  197. self.assertEqual(event.sender, user_id)
  198. self.assertEqual(event.type, "m.room.power_levels")
  199. self.assertEqual(event.room_id, room_id)
  200. self.assertEqual(event.state_key, "")
  201. self.assertDictEqual(event.content, content)
  202. # Check that the event was sent
  203. self.event_creation_handler.create_and_send_nonmember_event.assert_called_with(
  204. expected_requester,
  205. {
  206. "type": "m.room.power_levels",
  207. "content": content,
  208. "room_id": room_id,
  209. "sender": user_id,
  210. "state_key": "",
  211. },
  212. ratelimit=False,
  213. ignore_shadow_ban=True,
  214. )
  215. # Check that we can't send membership events
  216. content = {
  217. "membership": "leave",
  218. }
  219. event_dict = {
  220. "room_id": room_id,
  221. "type": "m.room.member",
  222. "content": content,
  223. "sender": user_id,
  224. "state_key": user_id,
  225. }
  226. self.get_failure(
  227. self.module_api.create_and_send_event_into_room(event_dict), Exception
  228. )
  229. def test_public_rooms(self):
  230. """Tests that a room can be added and removed from the public rooms list,
  231. as well as have its public rooms directory state queried.
  232. """
  233. # Create a user and room to play with
  234. user_id = self.register_user("kermit", "monkey")
  235. tok = self.login("kermit", "monkey")
  236. room_id = self.helper.create_room_as(user_id, tok=tok)
  237. # The room should not currently be in the public rooms directory
  238. is_in_public_rooms = self.get_success(
  239. self.module_api.public_room_list_manager.room_is_in_public_room_list(
  240. room_id
  241. )
  242. )
  243. self.assertFalse(is_in_public_rooms)
  244. # Let's try adding it to the public rooms directory
  245. self.get_success(
  246. self.module_api.public_room_list_manager.add_room_to_public_room_list(
  247. room_id
  248. )
  249. )
  250. # And checking whether it's in there...
  251. is_in_public_rooms = self.get_success(
  252. self.module_api.public_room_list_manager.room_is_in_public_room_list(
  253. room_id
  254. )
  255. )
  256. self.assertTrue(is_in_public_rooms)
  257. # Let's remove it again
  258. self.get_success(
  259. self.module_api.public_room_list_manager.remove_room_from_public_room_list(
  260. room_id
  261. )
  262. )
  263. # Should be gone
  264. is_in_public_rooms = self.get_success(
  265. self.module_api.public_room_list_manager.room_is_in_public_room_list(
  266. room_id
  267. )
  268. )
  269. self.assertFalse(is_in_public_rooms)
  270. def test_send_local_online_presence_to(self):
  271. # Test sending local online presence to users from the main process
  272. _test_sending_local_online_presence_to_local_user(self, test_with_workers=False)
  273. @override_config({"send_federation": True})
  274. def test_send_local_online_presence_to_federation(self):
  275. """Tests that send_local_presence_to_users sends local online presence to remote users."""
  276. # Create a user who will send presence updates
  277. self.presence_sender_id = self.register_user("presence_sender1", "monkey")
  278. self.presence_sender_tok = self.login("presence_sender1", "monkey")
  279. # And a room they're a part of
  280. room_id = self.helper.create_room_as(
  281. self.presence_sender_id,
  282. tok=self.presence_sender_tok,
  283. )
  284. # Mark them as online
  285. send_presence_update(
  286. self,
  287. self.presence_sender_id,
  288. self.presence_sender_tok,
  289. "online",
  290. "I'm online!",
  291. )
  292. # Make up a remote user to send presence to
  293. remote_user_id = "@far_away_person:island"
  294. # Create a join membership event for the remote user into the room.
  295. # This allows presence information to flow from one user to the other.
  296. self.get_success(
  297. inject_member_event(
  298. self.hs,
  299. room_id,
  300. sender=remote_user_id,
  301. target=remote_user_id,
  302. membership="join",
  303. )
  304. )
  305. # The remote user would have received the existing room members' presence
  306. # when they joined the room.
  307. #
  308. # Thus we reset the mock, and try sending online local user
  309. # presence again
  310. self.hs.get_federation_transport_client().send_transaction.reset_mock()
  311. # Broadcast local user online presence
  312. self.get_success(
  313. self.module_api.send_local_online_presence_to([remote_user_id])
  314. )
  315. # Check that a presence update was sent as part of a federation transaction
  316. found_update = False
  317. calls = (
  318. self.hs.get_federation_transport_client().send_transaction.call_args_list
  319. )
  320. for call in calls:
  321. call_args = call[0]
  322. federation_transaction: Transaction = call_args[0]
  323. # Get the sent EDUs in this transaction
  324. edus = federation_transaction.get_dict()["edus"]
  325. for edu in edus:
  326. # Make sure we're only checking presence-type EDUs
  327. if edu["edu_type"] != EduTypes.Presence:
  328. continue
  329. # EDUs can contain multiple presence updates
  330. for presence_update in edu["content"]["push"]:
  331. if presence_update["user_id"] == self.presence_sender_id:
  332. found_update = True
  333. self.assertTrue(found_update)
  334. def test_update_membership(self):
  335. """Tests that the module API can update the membership of a user in a room."""
  336. peter = self.register_user("peter", "hackme")
  337. lesley = self.register_user("lesley", "hackme")
  338. tok = self.login("peter", "hackme")
  339. lesley_tok = self.login("lesley", "hackme")
  340. # Make peter create a public room.
  341. room_id = self.helper.create_room_as(
  342. room_creator=peter, is_public=True, tok=tok
  343. )
  344. # Set a profile for lesley.
  345. channel = self.make_request(
  346. method="PUT",
  347. path="/_matrix/client/r0/profile/%s/displayname" % lesley,
  348. content={"displayname": "Lesley May"},
  349. access_token=lesley_tok,
  350. )
  351. self.assertEqual(channel.code, 200, channel.result)
  352. channel = self.make_request(
  353. method="PUT",
  354. path="/_matrix/client/r0/profile/%s/avatar_url" % lesley,
  355. content={"avatar_url": "some_url"},
  356. access_token=lesley_tok,
  357. )
  358. self.assertEqual(channel.code, 200, channel.result)
  359. # Make Peter invite Lesley to the room.
  360. self.get_success(
  361. defer.ensureDeferred(
  362. self.module_api.update_room_membership(peter, lesley, room_id, "invite")
  363. )
  364. )
  365. res = self.helper.get_state(
  366. room_id=room_id,
  367. event_type="m.room.member",
  368. state_key=lesley,
  369. tok=tok,
  370. )
  371. # Check the membership is correct.
  372. self.assertEqual(res["membership"], "invite")
  373. # Also check that the profile was correctly filled out, and that it's not
  374. # Peter's.
  375. self.assertEqual(res["displayname"], "Lesley May")
  376. self.assertEqual(res["avatar_url"], "some_url")
  377. # Make lesley join it.
  378. self.get_success(
  379. defer.ensureDeferred(
  380. self.module_api.update_room_membership(lesley, lesley, room_id, "join")
  381. )
  382. )
  383. # Check that the membership of lesley in the room is "join".
  384. res = self.helper.get_state(
  385. room_id=room_id,
  386. event_type="m.room.member",
  387. state_key=lesley,
  388. tok=tok,
  389. )
  390. self.assertEqual(res["membership"], "join")
  391. # Also check that the profile was correctly filled out.
  392. self.assertEqual(res["displayname"], "Lesley May")
  393. self.assertEqual(res["avatar_url"], "some_url")
  394. # Make peter kick lesley from the room.
  395. self.get_success(
  396. defer.ensureDeferred(
  397. self.module_api.update_room_membership(peter, lesley, room_id, "leave")
  398. )
  399. )
  400. # Check that the membership of lesley in the room is "leave".
  401. res = self.helper.get_state(
  402. room_id=room_id,
  403. event_type="m.room.member",
  404. state_key=lesley,
  405. tok=tok,
  406. )
  407. self.assertEqual(res["membership"], "leave")
  408. # Try to send a membership update from a non-local user and check that it fails.
  409. d = defer.ensureDeferred(
  410. self.module_api.update_room_membership(
  411. "@nicolas:otherserver.com",
  412. lesley,
  413. room_id,
  414. "invite",
  415. )
  416. )
  417. self.get_failure(d, RuntimeError)
  418. # Check that inviting a user that doesn't have a profile falls back to using a
  419. # default (localpart + no avatar) profile.
  420. simone = "@simone:" + self.hs.config.server.server_name
  421. self.get_success(
  422. defer.ensureDeferred(
  423. self.module_api.update_room_membership(peter, simone, room_id, "invite")
  424. )
  425. )
  426. res = self.helper.get_state(
  427. room_id=room_id,
  428. event_type="m.room.member",
  429. state_key=simone,
  430. tok=tok,
  431. )
  432. self.assertEqual(res["membership"], "invite")
  433. self.assertEqual(res["displayname"], "simone")
  434. self.assertIsNone(res["avatar_url"])
  435. def test_get_room_state(self):
  436. """Tests that a module can retrieve the state of a room through the module API."""
  437. user_id = self.register_user("peter", "hackme")
  438. tok = self.login("peter", "hackme")
  439. # Create a room and send some custom state in it.
  440. room_id = self.helper.create_room_as(tok=tok)
  441. self.helper.send_state(room_id, "org.matrix.test", {}, tok=tok)
  442. # Check that the module API can successfully fetch state for the room.
  443. state = self.get_success(
  444. defer.ensureDeferred(self.module_api.get_room_state(room_id))
  445. )
  446. # Check that a few standard events are in the returned state.
  447. self.assertIn((EventTypes.Create, ""), state)
  448. self.assertIn((EventTypes.Member, user_id), state)
  449. # Check that our custom state event is in the returned state.
  450. self.assertEqual(state[("org.matrix.test", "")].sender, user_id)
  451. self.assertEqual(state[("org.matrix.test", "")].state_key, "")
  452. self.assertEqual(state[("org.matrix.test", "")].content, {})
  453. class ModuleApiWorkerTestCase(BaseMultiWorkerStreamTestCase):
  454. """For testing ModuleApi functionality in a multi-worker setup"""
  455. # Testing stream ID replication from the main to worker processes requires postgres
  456. # (due to needing `MultiWriterIdGenerator`).
  457. if not USE_POSTGRES_FOR_TESTS:
  458. skip = "Requires Postgres"
  459. servlets = [
  460. admin.register_servlets,
  461. login.register_servlets,
  462. room.register_servlets,
  463. presence.register_servlets,
  464. ]
  465. def default_config(self):
  466. conf = super().default_config()
  467. conf["stream_writers"] = {"presence": ["presence_writer"]}
  468. conf["instance_map"] = {
  469. "presence_writer": {"host": "testserv", "port": 1001},
  470. }
  471. return conf
  472. def prepare(self, reactor, clock, homeserver):
  473. self.module_api = homeserver.get_module_api()
  474. self.sync_handler = homeserver.get_sync_handler()
  475. def test_send_local_online_presence_to_workers(self):
  476. # Test sending local online presence to users from a worker process
  477. _test_sending_local_online_presence_to_local_user(self, test_with_workers=True)
  478. def _test_sending_local_online_presence_to_local_user(
  479. test_case: HomeserverTestCase, test_with_workers: bool = False
  480. ):
  481. """Tests that send_local_presence_to_users sends local online presence to local users.
  482. This simultaneously tests two different usecases:
  483. * Testing that this method works when either called from a worker or the main process.
  484. - We test this by calling this method from both a TestCase that runs in monolith mode, and one that
  485. runs with a main and generic_worker.
  486. * Testing that multiple devices syncing simultaneously will all receive a snapshot of local,
  487. online presence - but only once per device.
  488. Args:
  489. test_with_workers: If True, this method will call ModuleApi.send_local_online_presence_to on a
  490. worker process. The test users will still sync with the main process. The purpose of testing
  491. with a worker is to check whether a Synapse module running on a worker can inform other workers/
  492. the main process that they should include additional presence when a user next syncs.
  493. """
  494. if test_with_workers:
  495. # Create a worker process to make module_api calls against
  496. worker_hs = test_case.make_worker_hs(
  497. "synapse.app.generic_worker", {"worker_name": "presence_writer"}
  498. )
  499. # Create a user who will send presence updates
  500. test_case.presence_receiver_id = test_case.register_user(
  501. "presence_receiver1", "monkey"
  502. )
  503. test_case.presence_receiver_tok = test_case.login("presence_receiver1", "monkey")
  504. # And another user that will send presence updates out
  505. test_case.presence_sender_id = test_case.register_user("presence_sender2", "monkey")
  506. test_case.presence_sender_tok = test_case.login("presence_sender2", "monkey")
  507. # Put them in a room together so they will receive each other's presence updates
  508. room_id = test_case.helper.create_room_as(
  509. test_case.presence_receiver_id,
  510. tok=test_case.presence_receiver_tok,
  511. )
  512. test_case.helper.join(
  513. room_id, test_case.presence_sender_id, tok=test_case.presence_sender_tok
  514. )
  515. # Presence sender comes online
  516. send_presence_update(
  517. test_case,
  518. test_case.presence_sender_id,
  519. test_case.presence_sender_tok,
  520. "online",
  521. "I'm online!",
  522. )
  523. # Presence receiver should have received it
  524. presence_updates, sync_token = sync_presence(
  525. test_case, test_case.presence_receiver_id
  526. )
  527. test_case.assertEqual(len(presence_updates), 1)
  528. presence_update: UserPresenceState = presence_updates[0]
  529. test_case.assertEqual(presence_update.user_id, test_case.presence_sender_id)
  530. test_case.assertEqual(presence_update.state, "online")
  531. if test_with_workers:
  532. # Replicate the current sync presence token from the main process to the worker process.
  533. # We need to do this so that the worker process knows the current presence stream ID to
  534. # insert into the database when we call ModuleApi.send_local_online_presence_to.
  535. test_case.replicate()
  536. # Syncing again should result in no presence updates
  537. presence_updates, sync_token = sync_presence(
  538. test_case, test_case.presence_receiver_id, sync_token
  539. )
  540. test_case.assertEqual(len(presence_updates), 0)
  541. # We do an (initial) sync with a second "device" now, getting a new sync token.
  542. # We'll use this in a moment.
  543. _, sync_token_second_device = sync_presence(
  544. test_case, test_case.presence_receiver_id
  545. )
  546. # Determine on which process (main or worker) to call ModuleApi.send_local_online_presence_to on
  547. if test_with_workers:
  548. module_api_to_use = worker_hs.get_module_api()
  549. else:
  550. module_api_to_use = test_case.module_api
  551. # Trigger sending local online presence. We expect this information
  552. # to be saved to the database where all processes can access it.
  553. # Note that we're syncing via the master.
  554. d = module_api_to_use.send_local_online_presence_to(
  555. [
  556. test_case.presence_receiver_id,
  557. ]
  558. )
  559. d = defer.ensureDeferred(d)
  560. if test_with_workers:
  561. # In order for the required presence_set_state replication request to occur between the
  562. # worker and main process, we need to pump the reactor. Otherwise, the coordinator that
  563. # reads the request on the main process won't do so, and the request will time out.
  564. while not d.called:
  565. test_case.reactor.advance(0.1)
  566. test_case.get_success(d)
  567. # The presence receiver should have received online presence again.
  568. presence_updates, sync_token = sync_presence(
  569. test_case, test_case.presence_receiver_id, sync_token
  570. )
  571. test_case.assertEqual(len(presence_updates), 1)
  572. presence_update: UserPresenceState = presence_updates[0]
  573. test_case.assertEqual(presence_update.user_id, test_case.presence_sender_id)
  574. test_case.assertEqual(presence_update.state, "online")
  575. # We attempt to sync with the second sync token we received above - just to check that
  576. # multiple syncing devices will each receive the necessary online presence.
  577. presence_updates, sync_token_second_device = sync_presence(
  578. test_case, test_case.presence_receiver_id, sync_token_second_device
  579. )
  580. test_case.assertEqual(len(presence_updates), 1)
  581. presence_update: UserPresenceState = presence_updates[0]
  582. test_case.assertEqual(presence_update.user_id, test_case.presence_sender_id)
  583. test_case.assertEqual(presence_update.state, "online")
  584. # However, if we now sync with either "device", we won't receive another burst of online presence
  585. # until the API is called again sometime in the future
  586. presence_updates, sync_token = sync_presence(
  587. test_case, test_case.presence_receiver_id, sync_token
  588. )
  589. # Now we check that we don't receive *offline* updates using ModuleApi.send_local_online_presence_to.
  590. # Presence sender goes offline
  591. send_presence_update(
  592. test_case,
  593. test_case.presence_sender_id,
  594. test_case.presence_sender_tok,
  595. "offline",
  596. "I slink back into the darkness.",
  597. )
  598. # Presence receiver should have received the updated, offline state
  599. presence_updates, sync_token = sync_presence(
  600. test_case, test_case.presence_receiver_id, sync_token
  601. )
  602. test_case.assertEqual(len(presence_updates), 1)
  603. # Now trigger sending local online presence.
  604. d = module_api_to_use.send_local_online_presence_to(
  605. [
  606. test_case.presence_receiver_id,
  607. ]
  608. )
  609. d = defer.ensureDeferred(d)
  610. if test_with_workers:
  611. # In order for the required presence_set_state replication request to occur between the
  612. # worker and main process, we need to pump the reactor. Otherwise, the coordinator that
  613. # reads the request on the main process won't do so, and the request will time out.
  614. while not d.called:
  615. test_case.reactor.advance(0.1)
  616. test_case.get_success(d)
  617. # Presence receiver should *not* have received offline state
  618. presence_updates, sync_token = sync_presence(
  619. test_case, test_case.presence_receiver_id, sync_token
  620. )
  621. test_case.assertEqual(len(presence_updates), 0)