test_typing.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. # Copyright 2014-2016 OpenMarket Ltd
  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. import json
  15. from typing import Dict
  16. from unittest.mock import ANY, Mock, call
  17. from twisted.internet import defer
  18. from twisted.web.resource import Resource
  19. from synapse.api.errors import AuthError
  20. from synapse.federation.transport.server import TransportLayerServer
  21. from synapse.types import UserID, create_requester
  22. from tests import unittest
  23. from tests.test_utils import make_awaitable
  24. from tests.unittest import override_config
  25. # Some local users to test with
  26. U_APPLE = UserID.from_string("@apple:test")
  27. U_BANANA = UserID.from_string("@banana:test")
  28. # Remote user
  29. U_ONION = UserID.from_string("@onion:farm")
  30. # Test room id
  31. ROOM_ID = "a-room"
  32. # Room we're not in
  33. OTHER_ROOM_ID = "another-room"
  34. def _expect_edu_transaction(edu_type, content, origin="test"):
  35. return {
  36. "origin": origin,
  37. "origin_server_ts": 1000000,
  38. "pdus": [],
  39. "edus": [{"edu_type": edu_type, "content": content}],
  40. }
  41. def _make_edu_transaction_json(edu_type, content):
  42. return json.dumps(_expect_edu_transaction(edu_type, content)).encode("utf8")
  43. class TypingNotificationsTestCase(unittest.HomeserverTestCase):
  44. def make_homeserver(self, reactor, clock):
  45. # we mock out the keyring so as to skip the authentication check on the
  46. # federation API call.
  47. mock_keyring = Mock(spec=["verify_json_for_server"])
  48. mock_keyring.verify_json_for_server.return_value = defer.succeed(True)
  49. # we mock out the federation client too
  50. mock_federation_client = Mock(spec=["put_json"])
  51. mock_federation_client.put_json.return_value = defer.succeed((200, "OK"))
  52. # the tests assume that we are starting at unix time 1000
  53. reactor.pump((1000,))
  54. hs = self.setup_test_homeserver(
  55. notifier=Mock(),
  56. federation_http_client=mock_federation_client,
  57. keyring=mock_keyring,
  58. replication_streams={},
  59. )
  60. return hs
  61. def create_resource_dict(self) -> Dict[str, Resource]:
  62. d = super().create_resource_dict()
  63. d["/_matrix/federation"] = TransportLayerServer(self.hs)
  64. return d
  65. def prepare(self, reactor, clock, hs):
  66. mock_notifier = hs.get_notifier()
  67. self.on_new_event = mock_notifier.on_new_event
  68. self.handler = hs.get_typing_handler()
  69. self.event_source = hs.get_event_sources().sources.typing
  70. self.datastore = hs.get_datastore()
  71. self.datastore.get_destination_retry_timings = Mock(
  72. return_value=defer.succeed(None)
  73. )
  74. self.datastore.get_device_updates_by_remote = Mock(
  75. return_value=make_awaitable((0, []))
  76. )
  77. self.datastore.get_destination_last_successful_stream_ordering = Mock(
  78. return_value=make_awaitable(None)
  79. )
  80. def get_received_txn_response(*args):
  81. return defer.succeed(None)
  82. self.datastore.get_received_txn_response = get_received_txn_response
  83. self.room_members = []
  84. async def check_user_in_room(room_id, user_id):
  85. if user_id not in [u.to_string() for u in self.room_members]:
  86. raise AuthError(401, "User is not in the room")
  87. return None
  88. hs.get_auth().check_user_in_room = check_user_in_room
  89. async def check_host_in_room(room_id, server_name):
  90. return room_id == ROOM_ID
  91. hs.get_event_auth_handler().check_host_in_room = check_host_in_room
  92. def get_joined_hosts_for_room(room_id):
  93. return {member.domain for member in self.room_members}
  94. self.datastore.get_joined_hosts_for_room = get_joined_hosts_for_room
  95. async def get_users_in_room(room_id):
  96. return {str(u) for u in self.room_members}
  97. self.datastore.get_users_in_room = get_users_in_room
  98. self.datastore.get_user_directory_stream_pos = Mock(
  99. side_effect=(
  100. # we deliberately return a non-None stream pos to avoid doing an initial_spam
  101. lambda: make_awaitable(1)
  102. )
  103. )
  104. self.datastore.get_current_state_deltas = Mock(return_value=(0, None))
  105. self.datastore.get_to_device_stream_token = lambda: 0
  106. self.datastore.get_new_device_msgs_for_remote = (
  107. lambda *args, **kargs: make_awaitable(([], 0))
  108. )
  109. self.datastore.delete_device_msgs_for_remote = (
  110. lambda *args, **kargs: make_awaitable(None)
  111. )
  112. self.datastore.set_received_txn_response = (
  113. lambda *args, **kwargs: make_awaitable(None)
  114. )
  115. def test_started_typing_local(self):
  116. self.room_members = [U_APPLE, U_BANANA]
  117. self.assertEquals(self.event_source.get_current_key(), 0)
  118. self.get_success(
  119. self.handler.started_typing(
  120. target_user=U_APPLE,
  121. requester=create_requester(U_APPLE),
  122. room_id=ROOM_ID,
  123. timeout=20000,
  124. )
  125. )
  126. self.on_new_event.assert_has_calls([call("typing_key", 1, rooms=[ROOM_ID])])
  127. self.assertEquals(self.event_source.get_current_key(), 1)
  128. events = self.get_success(
  129. self.event_source.get_new_events(
  130. user=U_APPLE, from_key=0, limit=None, room_ids=[ROOM_ID], is_guest=False
  131. )
  132. )
  133. self.assertEquals(
  134. events[0],
  135. [
  136. {
  137. "type": "m.typing",
  138. "room_id": ROOM_ID,
  139. "content": {"user_ids": [U_APPLE.to_string()]},
  140. }
  141. ],
  142. )
  143. @override_config({"send_federation": True})
  144. def test_started_typing_remote_send(self):
  145. self.room_members = [U_APPLE, U_ONION]
  146. self.get_success(
  147. self.handler.started_typing(
  148. target_user=U_APPLE,
  149. requester=create_requester(U_APPLE),
  150. room_id=ROOM_ID,
  151. timeout=20000,
  152. )
  153. )
  154. put_json = self.hs.get_federation_http_client().put_json
  155. put_json.assert_called_once_with(
  156. "farm",
  157. path="/_matrix/federation/v1/send/1000000",
  158. data=_expect_edu_transaction(
  159. "m.typing",
  160. content={
  161. "room_id": ROOM_ID,
  162. "user_id": U_APPLE.to_string(),
  163. "typing": True,
  164. },
  165. ),
  166. json_data_callback=ANY,
  167. long_retries=True,
  168. backoff_on_404=True,
  169. try_trailing_slash_on_400=True,
  170. )
  171. def test_started_typing_remote_recv(self):
  172. self.room_members = [U_APPLE, U_ONION]
  173. self.assertEquals(self.event_source.get_current_key(), 0)
  174. channel = self.make_request(
  175. "PUT",
  176. "/_matrix/federation/v1/send/1000000",
  177. _make_edu_transaction_json(
  178. "m.typing",
  179. content={
  180. "room_id": ROOM_ID,
  181. "user_id": U_ONION.to_string(),
  182. "typing": True,
  183. },
  184. ),
  185. federation_auth_origin=b"farm",
  186. )
  187. self.assertEqual(channel.code, 200)
  188. self.on_new_event.assert_has_calls([call("typing_key", 1, rooms=[ROOM_ID])])
  189. self.assertEquals(self.event_source.get_current_key(), 1)
  190. events = self.get_success(
  191. self.event_source.get_new_events(
  192. user=U_APPLE, from_key=0, limit=None, room_ids=[ROOM_ID], is_guest=False
  193. )
  194. )
  195. self.assertEquals(
  196. events[0],
  197. [
  198. {
  199. "type": "m.typing",
  200. "room_id": ROOM_ID,
  201. "content": {"user_ids": [U_ONION.to_string()]},
  202. }
  203. ],
  204. )
  205. def test_started_typing_remote_recv_not_in_room(self):
  206. self.room_members = [U_APPLE, U_ONION]
  207. self.assertEquals(self.event_source.get_current_key(), 0)
  208. channel = self.make_request(
  209. "PUT",
  210. "/_matrix/federation/v1/send/1000000",
  211. _make_edu_transaction_json(
  212. "m.typing",
  213. content={
  214. "room_id": OTHER_ROOM_ID,
  215. "user_id": U_ONION.to_string(),
  216. "typing": True,
  217. },
  218. ),
  219. federation_auth_origin=b"farm",
  220. )
  221. self.assertEqual(channel.code, 200)
  222. self.on_new_event.assert_not_called()
  223. self.assertEquals(self.event_source.get_current_key(), 0)
  224. events = self.get_success(
  225. self.event_source.get_new_events(
  226. user=U_APPLE,
  227. from_key=0,
  228. limit=None,
  229. room_ids=[OTHER_ROOM_ID],
  230. is_guest=False,
  231. )
  232. )
  233. self.assertEquals(events[0], [])
  234. self.assertEquals(events[1], 0)
  235. @override_config({"send_federation": True})
  236. def test_stopped_typing(self):
  237. self.room_members = [U_APPLE, U_BANANA, U_ONION]
  238. # Gut-wrenching
  239. from synapse.handlers.typing import RoomMember
  240. member = RoomMember(ROOM_ID, U_APPLE.to_string())
  241. self.handler._member_typing_until[member] = 1002000
  242. self.handler._room_typing[ROOM_ID] = {U_APPLE.to_string()}
  243. self.assertEquals(self.event_source.get_current_key(), 0)
  244. self.get_success(
  245. self.handler.stopped_typing(
  246. target_user=U_APPLE,
  247. requester=create_requester(U_APPLE),
  248. room_id=ROOM_ID,
  249. )
  250. )
  251. self.on_new_event.assert_has_calls([call("typing_key", 1, rooms=[ROOM_ID])])
  252. put_json = self.hs.get_federation_http_client().put_json
  253. put_json.assert_called_once_with(
  254. "farm",
  255. path="/_matrix/federation/v1/send/1000000",
  256. data=_expect_edu_transaction(
  257. "m.typing",
  258. content={
  259. "room_id": ROOM_ID,
  260. "user_id": U_APPLE.to_string(),
  261. "typing": False,
  262. },
  263. ),
  264. json_data_callback=ANY,
  265. long_retries=True,
  266. backoff_on_404=True,
  267. try_trailing_slash_on_400=True,
  268. )
  269. self.assertEquals(self.event_source.get_current_key(), 1)
  270. events = self.get_success(
  271. self.event_source.get_new_events(
  272. user=U_APPLE, from_key=0, limit=None, room_ids=[ROOM_ID], is_guest=False
  273. )
  274. )
  275. self.assertEquals(
  276. events[0],
  277. [{"type": "m.typing", "room_id": ROOM_ID, "content": {"user_ids": []}}],
  278. )
  279. def test_typing_timeout(self):
  280. self.room_members = [U_APPLE, U_BANANA]
  281. self.assertEquals(self.event_source.get_current_key(), 0)
  282. self.get_success(
  283. self.handler.started_typing(
  284. target_user=U_APPLE,
  285. requester=create_requester(U_APPLE),
  286. room_id=ROOM_ID,
  287. timeout=10000,
  288. )
  289. )
  290. self.on_new_event.assert_has_calls([call("typing_key", 1, rooms=[ROOM_ID])])
  291. self.on_new_event.reset_mock()
  292. self.assertEquals(self.event_source.get_current_key(), 1)
  293. events = self.get_success(
  294. self.event_source.get_new_events(
  295. user=U_APPLE,
  296. from_key=0,
  297. limit=None,
  298. room_ids=[ROOM_ID],
  299. is_guest=False,
  300. )
  301. )
  302. self.assertEquals(
  303. events[0],
  304. [
  305. {
  306. "type": "m.typing",
  307. "room_id": ROOM_ID,
  308. "content": {"user_ids": [U_APPLE.to_string()]},
  309. }
  310. ],
  311. )
  312. self.reactor.pump([16])
  313. self.on_new_event.assert_has_calls([call("typing_key", 2, rooms=[ROOM_ID])])
  314. self.assertEquals(self.event_source.get_current_key(), 2)
  315. events = self.get_success(
  316. self.event_source.get_new_events(
  317. user=U_APPLE,
  318. from_key=1,
  319. limit=None,
  320. room_ids=[ROOM_ID],
  321. is_guest=False,
  322. )
  323. )
  324. self.assertEquals(
  325. events[0],
  326. [{"type": "m.typing", "room_id": ROOM_ID, "content": {"user_ids": []}}],
  327. )
  328. # SYN-230 - see if we can still set after timeout
  329. self.get_success(
  330. self.handler.started_typing(
  331. target_user=U_APPLE,
  332. requester=create_requester(U_APPLE),
  333. room_id=ROOM_ID,
  334. timeout=10000,
  335. )
  336. )
  337. self.on_new_event.assert_has_calls([call("typing_key", 3, rooms=[ROOM_ID])])
  338. self.on_new_event.reset_mock()
  339. self.assertEquals(self.event_source.get_current_key(), 3)
  340. events = self.get_success(
  341. self.event_source.get_new_events(
  342. user=U_APPLE,
  343. from_key=0,
  344. limit=None,
  345. room_ids=[ROOM_ID],
  346. is_guest=False,
  347. )
  348. )
  349. self.assertEquals(
  350. events[0],
  351. [
  352. {
  353. "type": "m.typing",
  354. "room_id": ROOM_ID,
  355. "content": {"user_ids": [U_APPLE.to_string()]},
  356. }
  357. ],
  358. )