test_typing.py 12 KB

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