test_typing.py 14 KB

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