test_typing.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import json
  16. from typing import Dict
  17. from mock import ANY, Mock, call
  18. from twisted.internet import defer
  19. from twisted.web.resource import Resource
  20. from synapse.api.errors import AuthError
  21. from synapse.federation.transport.server import TransportLayerServer
  22. from synapse.types import UserID, create_requester
  23. from tests import unittest
  24. from tests.test_utils import make_awaitable
  25. from tests.unittest import override_config
  26. # Some local users to test with
  27. U_APPLE = UserID.from_string("@apple:test")
  28. U_BANANA = UserID.from_string("@banana:test")
  29. # Remote user
  30. U_ONION = UserID.from_string("@onion:farm")
  31. # Test room id
  32. ROOM_ID = "a-room"
  33. def _expect_edu_transaction(edu_type, content, origin="test"):
  34. return {
  35. "origin": origin,
  36. "origin_server_ts": 1000000,
  37. "pdus": [],
  38. "edus": [{"edu_type": edu_type, "content": content}],
  39. }
  40. def _make_edu_transaction_json(edu_type, content):
  41. return json.dumps(_expect_edu_transaction(edu_type, content)).encode("utf8")
  42. class TypingNotificationsTestCase(unittest.HomeserverTestCase):
  43. def make_homeserver(self, reactor, clock):
  44. # we mock out the keyring so as to skip the authentication check on the
  45. # federation API call.
  46. mock_keyring = Mock(spec=["verify_json_for_server"])
  47. mock_keyring.verify_json_for_server.return_value = defer.succeed(True)
  48. # we mock out the federation client too
  49. mock_federation_client = Mock(spec=["put_json"])
  50. mock_federation_client.put_json.return_value = defer.succeed((200, "OK"))
  51. # the tests assume that we are starting at unix time 1000
  52. reactor.pump((1000,))
  53. hs = self.setup_test_homeserver(
  54. notifier=Mock(),
  55. federation_http_client=mock_federation_client,
  56. keyring=mock_keyring,
  57. replication_streams={},
  58. )
  59. return hs
  60. def create_resource_dict(self) -> Dict[str, Resource]:
  61. d = super().create_resource_dict()
  62. d["/_matrix/federation"] = TransportLayerServer(self.hs)
  63. return d
  64. def prepare(self, reactor, clock, hs):
  65. mock_notifier = hs.get_notifier()
  66. self.on_new_event = mock_notifier.on_new_event
  67. self.handler = hs.get_typing_handler()
  68. self.event_source = hs.get_event_sources().sources["typing"]
  69. self.datastore = hs.get_datastore()
  70. retry_timings_res = {
  71. "destination": "",
  72. "retry_last_ts": 0,
  73. "retry_interval": 0,
  74. "failure_ts": None,
  75. }
  76. self.datastore.get_destination_retry_timings = Mock(
  77. return_value=defer.succeed(retry_timings_res)
  78. )
  79. self.datastore.get_device_updates_by_remote = Mock(
  80. return_value=make_awaitable((0, []))
  81. )
  82. self.datastore.get_destination_last_successful_stream_ordering = Mock(
  83. return_value=make_awaitable(None)
  84. )
  85. def get_received_txn_response(*args):
  86. return defer.succeed(None)
  87. self.datastore.get_received_txn_response = get_received_txn_response
  88. self.room_members = []
  89. async def check_user_in_room(room_id, user_id):
  90. if user_id not in [u.to_string() for u in self.room_members]:
  91. raise AuthError(401, "User is not in the room")
  92. return None
  93. hs.get_auth().check_user_in_room = check_user_in_room
  94. def get_joined_hosts_for_room(room_id):
  95. return {member.domain for member in self.room_members}
  96. self.datastore.get_joined_hosts_for_room = get_joined_hosts_for_room
  97. async def get_users_in_room(room_id):
  98. return {str(u) for u in self.room_members}
  99. self.datastore.get_users_in_room = get_users_in_room
  100. self.datastore.get_user_directory_stream_pos = Mock(
  101. side_effect=(
  102. # we deliberately return a non-None stream pos to avoid doing an initial_spam
  103. lambda: make_awaitable(1)
  104. )
  105. )
  106. self.datastore.get_current_state_deltas = Mock(return_value=(0, None))
  107. self.datastore.get_to_device_stream_token = lambda: 0
  108. self.datastore.get_new_device_msgs_for_remote = lambda *args, **kargs: make_awaitable(
  109. ([], 0)
  110. )
  111. self.datastore.delete_device_msgs_for_remote = lambda *args, **kargs: make_awaitable(
  112. None
  113. )
  114. self.datastore.set_received_txn_response = lambda *args, **kwargs: make_awaitable(
  115. None
  116. )
  117. def test_started_typing_local(self):
  118. self.room_members = [U_APPLE, U_BANANA]
  119. self.assertEquals(self.event_source.get_current_key(), 0)
  120. self.get_success(
  121. self.handler.started_typing(
  122. target_user=U_APPLE,
  123. requester=create_requester(U_APPLE),
  124. room_id=ROOM_ID,
  125. timeout=20000,
  126. )
  127. )
  128. self.on_new_event.assert_has_calls([call("typing_key", 1, rooms=[ROOM_ID])])
  129. self.assertEquals(self.event_source.get_current_key(), 1)
  130. events = self.get_success(
  131. self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=0)
  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(room_ids=[ROOM_ID], from_key=0)
  192. )
  193. self.assertEquals(
  194. events[0],
  195. [
  196. {
  197. "type": "m.typing",
  198. "room_id": ROOM_ID,
  199. "content": {"user_ids": [U_ONION.to_string()]},
  200. }
  201. ],
  202. )
  203. @override_config({"send_federation": True})
  204. def test_stopped_typing(self):
  205. self.room_members = [U_APPLE, U_BANANA, U_ONION]
  206. # Gut-wrenching
  207. from synapse.handlers.typing import RoomMember
  208. member = RoomMember(ROOM_ID, U_APPLE.to_string())
  209. self.handler._member_typing_until[member] = 1002000
  210. self.handler._room_typing[ROOM_ID] = {U_APPLE.to_string()}
  211. self.assertEquals(self.event_source.get_current_key(), 0)
  212. self.get_success(
  213. self.handler.stopped_typing(
  214. target_user=U_APPLE,
  215. requester=create_requester(U_APPLE),
  216. room_id=ROOM_ID,
  217. )
  218. )
  219. self.on_new_event.assert_has_calls([call("typing_key", 1, rooms=[ROOM_ID])])
  220. put_json = self.hs.get_federation_http_client().put_json
  221. put_json.assert_called_once_with(
  222. "farm",
  223. path="/_matrix/federation/v1/send/1000000",
  224. data=_expect_edu_transaction(
  225. "m.typing",
  226. content={
  227. "room_id": ROOM_ID,
  228. "user_id": U_APPLE.to_string(),
  229. "typing": False,
  230. },
  231. ),
  232. json_data_callback=ANY,
  233. long_retries=True,
  234. backoff_on_404=True,
  235. try_trailing_slash_on_400=True,
  236. )
  237. self.assertEquals(self.event_source.get_current_key(), 1)
  238. events = self.get_success(
  239. self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=0)
  240. )
  241. self.assertEquals(
  242. events[0],
  243. [{"type": "m.typing", "room_id": ROOM_ID, "content": {"user_ids": []}}],
  244. )
  245. def test_typing_timeout(self):
  246. self.room_members = [U_APPLE, U_BANANA]
  247. self.assertEquals(self.event_source.get_current_key(), 0)
  248. self.get_success(
  249. self.handler.started_typing(
  250. target_user=U_APPLE,
  251. requester=create_requester(U_APPLE),
  252. room_id=ROOM_ID,
  253. timeout=10000,
  254. )
  255. )
  256. self.on_new_event.assert_has_calls([call("typing_key", 1, rooms=[ROOM_ID])])
  257. self.on_new_event.reset_mock()
  258. self.assertEquals(self.event_source.get_current_key(), 1)
  259. events = self.get_success(
  260. self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=0)
  261. )
  262. self.assertEquals(
  263. events[0],
  264. [
  265. {
  266. "type": "m.typing",
  267. "room_id": ROOM_ID,
  268. "content": {"user_ids": [U_APPLE.to_string()]},
  269. }
  270. ],
  271. )
  272. self.reactor.pump([16])
  273. self.on_new_event.assert_has_calls([call("typing_key", 2, rooms=[ROOM_ID])])
  274. self.assertEquals(self.event_source.get_current_key(), 2)
  275. events = self.get_success(
  276. self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=1)
  277. )
  278. self.assertEquals(
  279. events[0],
  280. [{"type": "m.typing", "room_id": ROOM_ID, "content": {"user_ids": []}}],
  281. )
  282. # SYN-230 - see if we can still set after timeout
  283. self.get_success(
  284. self.handler.started_typing(
  285. target_user=U_APPLE,
  286. requester=create_requester(U_APPLE),
  287. room_id=ROOM_ID,
  288. timeout=10000,
  289. )
  290. )
  291. self.on_new_event.assert_has_calls([call("typing_key", 3, rooms=[ROOM_ID])])
  292. self.on_new_event.reset_mock()
  293. self.assertEquals(self.event_source.get_current_key(), 3)
  294. events = self.get_success(
  295. self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=0)
  296. )
  297. self.assertEquals(
  298. events[0],
  299. [
  300. {
  301. "type": "m.typing",
  302. "room_id": ROOM_ID,
  303. "content": {"user_ids": [U_APPLE.to_string()]},
  304. }
  305. ],
  306. )