test_typing.py 12 KB

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