test_typing.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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 mock import ANY, Mock, call
  17. from twisted.internet import defer
  18. from synapse.api.errors import AuthError
  19. from synapse.types import UserID
  20. from tests import unittest
  21. from ..utils import (
  22. DeferredMockCallable,
  23. MockClock,
  24. MockHttpResource,
  25. setup_test_homeserver,
  26. )
  27. def _expect_edu(destination, edu_type, content, origin="test"):
  28. return {
  29. "origin": origin,
  30. "origin_server_ts": 1000000,
  31. "pdus": [],
  32. "edus": [{"edu_type": edu_type, "content": content}],
  33. }
  34. def _make_edu_json(origin, edu_type, content):
  35. return json.dumps(_expect_edu("test", edu_type, content, origin=origin)).encode(
  36. 'utf8'
  37. )
  38. class TypingNotificationsTestCase(unittest.TestCase):
  39. """Tests typing notifications to rooms."""
  40. @defer.inlineCallbacks
  41. def setUp(self):
  42. self.clock = MockClock()
  43. self.mock_http_client = Mock(spec=[])
  44. self.mock_http_client.put_json = DeferredMockCallable()
  45. self.mock_federation_resource = MockHttpResource()
  46. mock_notifier = Mock()
  47. self.on_new_event = mock_notifier.on_new_event
  48. self.auth = Mock(spec=[])
  49. self.state_handler = Mock()
  50. hs = yield setup_test_homeserver(
  51. self.addCleanup,
  52. "test",
  53. auth=self.auth,
  54. clock=self.clock,
  55. datastore=Mock(
  56. spec=[
  57. # Bits that Federation needs
  58. "prep_send_transaction",
  59. "delivered_txn",
  60. "get_received_txn_response",
  61. "set_received_txn_response",
  62. "get_destination_retry_timings",
  63. "get_devices_by_remote",
  64. # Bits that user_directory needs
  65. "get_user_directory_stream_pos",
  66. "get_current_state_deltas",
  67. ]
  68. ),
  69. state_handler=self.state_handler,
  70. handlers=Mock(),
  71. notifier=mock_notifier,
  72. resource_for_client=Mock(),
  73. resource_for_federation=self.mock_federation_resource,
  74. http_client=self.mock_http_client,
  75. keyring=Mock(),
  76. )
  77. self.handler = hs.get_typing_handler()
  78. self.event_source = hs.get_event_sources().sources["typing"]
  79. self.datastore = hs.get_datastore()
  80. retry_timings_res = {"destination": "", "retry_last_ts": 0, "retry_interval": 0}
  81. self.datastore.get_destination_retry_timings.return_value = defer.succeed(
  82. retry_timings_res
  83. )
  84. self.datastore.get_devices_by_remote.return_value = (0, [])
  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_id = "a-room"
  89. self.room_members = []
  90. def check_joined_room(room_id, user_id):
  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. def get_joined_hosts_for_room(room_id):
  94. return set(member.domain for member in self.room_members)
  95. self.datastore.get_joined_hosts_for_room = get_joined_hosts_for_room
  96. def get_current_user_in_room(room_id):
  97. return set(str(u) for u in self.room_members)
  98. self.state_handler.get_current_user_in_room = get_current_user_in_room
  99. self.datastore.get_user_directory_stream_pos.return_value = (
  100. # we deliberately return a non-None stream pos to avoid doing an initial_spam
  101. defer.succeed(1)
  102. )
  103. self.datastore.get_current_state_deltas.return_value = None
  104. self.auth.check_joined_room = check_joined_room
  105. self.datastore.get_to_device_stream_token = lambda: 0
  106. self.datastore.get_new_device_msgs_for_remote = lambda *args, **kargs: ([], 0)
  107. self.datastore.delete_device_msgs_for_remote = lambda *args, **kargs: None
  108. # Some local users to test with
  109. self.u_apple = UserID.from_string("@apple:test")
  110. self.u_banana = UserID.from_string("@banana:test")
  111. # Remote user
  112. self.u_onion = UserID.from_string("@onion:farm")
  113. @defer.inlineCallbacks
  114. def test_started_typing_local(self):
  115. self.room_members = [self.u_apple, self.u_banana]
  116. self.assertEquals(self.event_source.get_current_key(), 0)
  117. yield self.handler.started_typing(
  118. target_user=self.u_apple,
  119. auth_user=self.u_apple,
  120. room_id=self.room_id,
  121. timeout=20000,
  122. )
  123. self.on_new_event.assert_has_calls(
  124. [call('typing_key', 1, rooms=[self.room_id])]
  125. )
  126. self.assertEquals(self.event_source.get_current_key(), 1)
  127. events = yield self.event_source.get_new_events(
  128. room_ids=[self.room_id], from_key=0
  129. )
  130. self.assertEquals(
  131. events[0],
  132. [
  133. {
  134. "type": "m.typing",
  135. "room_id": self.room_id,
  136. "content": {"user_ids": [self.u_apple.to_string()]},
  137. }
  138. ],
  139. )
  140. @defer.inlineCallbacks
  141. def test_started_typing_remote_send(self):
  142. self.room_members = [self.u_apple, self.u_onion]
  143. put_json = self.mock_http_client.put_json
  144. put_json.expect_call_and_return(
  145. call(
  146. "farm",
  147. path="/_matrix/federation/v1/send/1000000/",
  148. data=_expect_edu(
  149. "farm",
  150. "m.typing",
  151. content={
  152. "room_id": self.room_id,
  153. "user_id": self.u_apple.to_string(),
  154. "typing": True,
  155. },
  156. ),
  157. json_data_callback=ANY,
  158. long_retries=True,
  159. backoff_on_404=True,
  160. ),
  161. defer.succeed((200, "OK")),
  162. )
  163. yield self.handler.started_typing(
  164. target_user=self.u_apple,
  165. auth_user=self.u_apple,
  166. room_id=self.room_id,
  167. timeout=20000,
  168. )
  169. yield put_json.await_calls()
  170. @defer.inlineCallbacks
  171. def test_started_typing_remote_recv(self):
  172. self.room_members = [self.u_apple, self.u_onion]
  173. self.assertEquals(self.event_source.get_current_key(), 0)
  174. yield self.mock_federation_resource.trigger(
  175. "PUT",
  176. "/_matrix/federation/v1/send/1000000/",
  177. _make_edu_json(
  178. "farm",
  179. "m.typing",
  180. content={
  181. "room_id": self.room_id,
  182. "user_id": self.u_onion.to_string(),
  183. "typing": True,
  184. },
  185. ),
  186. federation_auth=True,
  187. )
  188. self.on_new_event.assert_has_calls(
  189. [call('typing_key', 1, rooms=[self.room_id])]
  190. )
  191. self.assertEquals(self.event_source.get_current_key(), 1)
  192. events = yield self.event_source.get_new_events(
  193. room_ids=[self.room_id], from_key=0
  194. )
  195. self.assertEquals(
  196. events[0],
  197. [
  198. {
  199. "type": "m.typing",
  200. "room_id": self.room_id,
  201. "content": {"user_ids": [self.u_onion.to_string()]},
  202. }
  203. ],
  204. )
  205. @defer.inlineCallbacks
  206. def test_stopped_typing(self):
  207. self.room_members = [self.u_apple, self.u_banana, self.u_onion]
  208. put_json = self.mock_http_client.put_json
  209. put_json.expect_call_and_return(
  210. call(
  211. "farm",
  212. path="/_matrix/federation/v1/send/1000000/",
  213. data=_expect_edu(
  214. "farm",
  215. "m.typing",
  216. content={
  217. "room_id": self.room_id,
  218. "user_id": self.u_apple.to_string(),
  219. "typing": False,
  220. },
  221. ),
  222. json_data_callback=ANY,
  223. long_retries=True,
  224. backoff_on_404=True,
  225. ),
  226. defer.succeed((200, "OK")),
  227. )
  228. # Gut-wrenching
  229. from synapse.handlers.typing import RoomMember
  230. member = RoomMember(self.room_id, self.u_apple.to_string())
  231. self.handler._member_typing_until[member] = 1002000
  232. self.handler._room_typing[self.room_id] = set([self.u_apple.to_string()])
  233. self.assertEquals(self.event_source.get_current_key(), 0)
  234. yield self.handler.stopped_typing(
  235. target_user=self.u_apple, auth_user=self.u_apple, room_id=self.room_id
  236. )
  237. self.on_new_event.assert_has_calls(
  238. [call('typing_key', 1, rooms=[self.room_id])]
  239. )
  240. yield put_json.await_calls()
  241. self.assertEquals(self.event_source.get_current_key(), 1)
  242. events = yield self.event_source.get_new_events(
  243. room_ids=[self.room_id], from_key=0
  244. )
  245. self.assertEquals(
  246. events[0],
  247. [
  248. {
  249. "type": "m.typing",
  250. "room_id": self.room_id,
  251. "content": {"user_ids": []},
  252. }
  253. ],
  254. )
  255. @defer.inlineCallbacks
  256. def test_typing_timeout(self):
  257. self.room_members = [self.u_apple, self.u_banana]
  258. self.assertEquals(self.event_source.get_current_key(), 0)
  259. yield self.handler.started_typing(
  260. target_user=self.u_apple,
  261. auth_user=self.u_apple,
  262. room_id=self.room_id,
  263. timeout=10000,
  264. )
  265. self.on_new_event.assert_has_calls(
  266. [call('typing_key', 1, rooms=[self.room_id])]
  267. )
  268. self.on_new_event.reset_mock()
  269. self.assertEquals(self.event_source.get_current_key(), 1)
  270. events = yield self.event_source.get_new_events(
  271. room_ids=[self.room_id], from_key=0
  272. )
  273. self.assertEquals(
  274. events[0],
  275. [
  276. {
  277. "type": "m.typing",
  278. "room_id": self.room_id,
  279. "content": {"user_ids": [self.u_apple.to_string()]},
  280. }
  281. ],
  282. )
  283. self.clock.advance_time(16)
  284. self.on_new_event.assert_has_calls(
  285. [call('typing_key', 2, rooms=[self.room_id])]
  286. )
  287. self.assertEquals(self.event_source.get_current_key(), 2)
  288. events = yield self.event_source.get_new_events(
  289. room_ids=[self.room_id], from_key=1
  290. )
  291. self.assertEquals(
  292. events[0],
  293. [
  294. {
  295. "type": "m.typing",
  296. "room_id": self.room_id,
  297. "content": {"user_ids": []},
  298. }
  299. ],
  300. )
  301. # SYN-230 - see if we can still set after timeout
  302. yield self.handler.started_typing(
  303. target_user=self.u_apple,
  304. auth_user=self.u_apple,
  305. room_id=self.room_id,
  306. timeout=10000,
  307. )
  308. self.on_new_event.assert_has_calls(
  309. [call('typing_key', 3, rooms=[self.room_id])]
  310. )
  311. self.on_new_event.reset_mock()
  312. self.assertEquals(self.event_source.get_current_key(), 3)
  313. events = yield self.event_source.get_new_events(
  314. room_ids=[self.room_id], from_key=0
  315. )
  316. self.assertEquals(
  317. events[0],
  318. [
  319. {
  320. "type": "m.typing",
  321. "room_id": self.room_id,
  322. "content": {"user_ids": [self.u_apple.to_string()]},
  323. }
  324. ],
  325. )