summary refs log tree commit diff
diff options
context:
space:
mode:
-rw-r--r--synapse/handlers/room.py7
-rw-r--r--synapse/handlers/typing.py27
-rw-r--r--synapse/rest/room.py32
-rw-r--r--tests/handlers/test_room.py44
-rw-r--r--tests/handlers/test_typing.py10
-rw-r--r--tests/rest/test_rooms.py4
-rw-r--r--tests/rest/test_typing.py113
7 files changed, 230 insertions, 7 deletions
diff --git a/synapse/handlers/room.py b/synapse/handlers/room.py
index a000b44036..c802e8f69d 100644
--- a/synapse/handlers/room.py
+++ b/synapse/handlers/room.py
@@ -260,6 +260,7 @@ class RoomMemberHandler(BaseHandler):
 
         self.distributor = hs.get_distributor()
         self.distributor.declare("user_joined_room")
+        self.distributor.declare("user_left_room")
 
     @defer.inlineCallbacks
     def get_room_members(self, room_id, membership=Membership.JOIN):
@@ -387,6 +388,12 @@ class RoomMemberHandler(BaseHandler):
                 do_auth=do_auth,
             )
 
+            if prev_state and prev_state.membership == Membership.JOIN:
+                user = self.hs.parse_userid(event.user_id)
+                self.distributor.fire(
+                    "user_left_room", user=user, room_id=event.room_id
+                )
+
         defer.returnValue({"room_id": room_id})
 
     @defer.inlineCallbacks
diff --git a/synapse/handlers/typing.py b/synapse/handlers/typing.py
index 989f73947f..46a0b299a1 100644
--- a/synapse/handlers/typing.py
+++ b/synapse/handlers/typing.py
@@ -43,6 +43,8 @@ class TypingNotificationHandler(BaseHandler):
 
         self.federation.register_edu_handler("m.typing", self._recv_edu)
 
+        hs.get_distributor().observe("user_left_room", self.user_left_room)
+
         self._member_typing_until = {} # clock time we expect to stop
         self._member_typing_timer = {} # deferreds to manage theabove
 
@@ -52,6 +54,13 @@ class TypingNotificationHandler(BaseHandler):
         # map room IDs to sets of users currently typing
         self._room_typing = {}
 
+    def tearDown(self):
+        """Cancels all the pending timers.
+        Normally this shouldn't be needed, but it's required from unit tests
+        to avoid a "Reactor was unclean" warning."""
+        for t in self._member_typing_timer.values():
+            self.clock.cancel_call_later(t)
+
     @defer.inlineCallbacks
     def started_typing(self, target_user, auth_user, room_id, timeout):
         if not target_user.is_mine:
@@ -60,6 +69,12 @@ class TypingNotificationHandler(BaseHandler):
         if target_user != auth_user:
             raise AuthError(400, "Cannot set another user's typing state")
 
+        yield self.auth.check_joined_room(room_id, target_user.to_string())
+
+        logger.debug(
+            "%s has started typing in %s", target_user.to_string(), room_id
+        )
+
         until = self.clock.time_msec() + timeout
         member = RoomMember(room_id=room_id, user=target_user)
 
@@ -91,11 +106,23 @@ class TypingNotificationHandler(BaseHandler):
         if target_user != auth_user:
             raise AuthError(400, "Cannot set another user's typing state")
 
+        yield self.auth.check_joined_room(room_id, target_user.to_string())
+
+        logger.debug(
+            "%s has stopped typing in %s", target_user.to_string(), room_id
+        )
+
         member = RoomMember(room_id=room_id, user=target_user)
 
         yield self._stopped_typing(member)
 
     @defer.inlineCallbacks
+    def user_left_room(self, user, room_id):
+        if user.is_mine:
+            member = RoomMember(room_id=room_id, user=user)
+            yield self._stopped_typing(member)
+
+    @defer.inlineCallbacks
     def _stopped_typing(self, member):
         if member not in self._member_typing_until:
             # No point
diff --git a/synapse/rest/room.py b/synapse/rest/room.py
index 3147d7a60b..e7f28c2784 100644
--- a/synapse/rest/room.py
+++ b/synapse/rest/room.py
@@ -483,6 +483,37 @@ class RoomRedactEventRestServlet(RestServlet):
         defer.returnValue(response)
 
 
+class RoomTypingRestServlet(RestServlet):
+    PATTERN = client_path_pattern("/rooms/(?P<room_id>[^/]*)/typing/(?P<user_id>[^/]*)$")
+
+    @defer.inlineCallbacks
+    def on_PUT(self, request, room_id, user_id):
+        auth_user = yield self.auth.get_user_by_req(request)
+
+        room_id = urllib.unquote(room_id)
+        target_user = self.hs.parse_userid(urllib.unquote(user_id))
+
+        content = _parse_json(request)
+
+        typing_handler = self.handlers.typing_notification_handler
+
+        if content["typing"]:
+            yield typing_handler.started_typing(
+                target_user=target_user,
+                auth_user=auth_user,
+                room_id=room_id,
+                timeout=content.get("timeout", 30000),
+            )
+        else:
+            yield typing_handler.stopped_typing(
+                target_user=target_user,
+                auth_user=auth_user,
+                room_id=room_id,
+            )
+
+        defer.returnValue((200, {}))
+
+
 def _parse_json(request):
     try:
         content = json.loads(request.content.read())
@@ -538,3 +569,4 @@ def register_servlets(hs, http_server):
     RoomStateRestServlet(hs).register(http_server)
     RoomInitialSyncRestServlet(hs).register(http_server)
     RoomRedactEventRestServlet(hs).register(http_server)
+    RoomTypingRestServlet(hs).register(http_server)
diff --git a/tests/handlers/test_room.py b/tests/handlers/test_room.py
index 0279ab703a..3a71ed0aed 100644
--- a/tests/handlers/test_room.py
+++ b/tests/handlers/test_room.py
@@ -222,14 +222,52 @@ class RoomMemberHandlerTestCase(unittest.TestCase):
             user=user, room_id=room_id
         )
 
-    def _create_member(self, user_id, room_id):
+    @defer.inlineCallbacks
+    def test_simple_leave(self):
+        room_id = "!foo:red"
+        user_id = "@bob:red"
+        user = self.hs.parse_userid(user_id)
+
+        event = self._create_member(
+            user_id=user_id,
+            room_id=room_id,
+            membership=Membership.LEAVE,
+        )
+
+        prev_state = NonCallableMock()
+        prev_state.membership = Membership.JOIN
+        prev_state.sender = user_id
+        self.datastore.get_room_member.return_value = defer.succeed(prev_state)
+
+        event.state_events = {
+            (RoomMemberEvent.TYPE, user_id): event,
+        }
+
+        event.old_state_events = {
+            (RoomMemberEvent.TYPE, user_id): self._create_member(
+                user_id=user_id,
+                room_id=room_id,
+            ),
+        }
+
+        leave_signal_observer = Mock()
+        self.distributor.observe("user_left_room", leave_signal_observer)
+
+        # Actual invocation
+        yield self.room_member_handler.change_membership(event)
+
+        leave_signal_observer.assert_called_with(
+            user=user, room_id=room_id
+        )
+
+    def _create_member(self, user_id, room_id, membership=Membership.JOIN):
         return self.hs.get_event_factory().create_event(
             etype=RoomMemberEvent.TYPE,
             user_id=user_id,
             state_key=user_id,
             room_id=room_id,
-            membership=Membership.JOIN,
-            content={"membership": Membership.JOIN},
+            membership=membership,
+            content={"membership": membership},
         )
 
 
diff --git a/tests/handlers/test_typing.py b/tests/handlers/test_typing.py
index b858f96323..bc19db8dfa 100644
--- a/tests/handlers/test_typing.py
+++ b/tests/handlers/test_typing.py
@@ -22,6 +22,7 @@ import json
 
 from ..utils import MockHttpResource, MockClock, DeferredMockCallable, MockKey
 
+from synapse.api.errors import AuthError
 from synapse.server import HomeServer
 from synapse.handlers.typing import TypingNotificationHandler
 
@@ -68,7 +69,10 @@ class TypingNotificationsTestCase(unittest.TestCase):
         mock_notifier = Mock(spec=["on_new_user_event"])
         self.on_new_user_event = mock_notifier.on_new_user_event
 
+        self.auth = Mock(spec=[])
+
         hs = HomeServer("test",
+                auth=self.auth,
                 clock=self.clock,
                 db_pool=None,
                 datastore=Mock(spec=[
@@ -142,6 +146,12 @@ class TypingNotificationsTestCase(unittest.TestCase):
         self.room_member_handler.fetch_room_distributions_into = (
                 fetch_room_distributions_into)
 
+        def check_joined_room(room_id, user_id):
+            if user_id not in [u.to_string() for u in self.room_members]:
+                raise AuthError(401, "User is not in the room")
+
+        self.auth.check_joined_room = check_joined_room
+
         # Some local users to test with
         self.u_apple = hs.parse_userid("@apple:test")
         self.u_banana = hs.parse_userid("@banana:test")
diff --git a/tests/rest/test_rooms.py b/tests/rest/test_rooms.py
index ff7c9f0530..1f719beb0a 100644
--- a/tests/rest/test_rooms.py
+++ b/tests/rest/test_rooms.py
@@ -1066,7 +1066,3 @@ class RoomInitialSyncTestCase(RestTestCase):
         }
         self.assertTrue(self.user_id in presence_by_user)
         self.assertEquals("m.presence", presence_by_user[self.user_id]["type"])
-
-#        (code, response) = yield self.mock_resource.trigger("GET", path, None)
-#        self.assertEquals(200, code, msg=str(response))
-#        self.assert_dict(json.loads(content), response)
diff --git a/tests/rest/test_typing.py b/tests/rest/test_typing.py
new file mode 100644
index 0000000000..0b95d70718
--- /dev/null
+++ b/tests/rest/test_typing.py
@@ -0,0 +1,113 @@
+# -*- coding: utf-8 -*-
+# Copyright 2014 OpenMarket Ltd
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Tests REST events for /rooms paths."""
+
+# twisted imports
+from twisted.internet import defer
+
+import synapse.rest.room
+from synapse.server import HomeServer
+
+from ..utils import MockHttpResource, SQLiteMemoryDbPool, MockKey
+from .utils import RestTestCase
+
+from mock import Mock, NonCallableMock
+
+
+PATH_PREFIX = "/_matrix/client/api/v1"
+
+
+class RoomTypingTestCase(RestTestCase):
+    """ Tests /rooms/$room_id/typing/$user_id REST API. """
+    user_id = "@sid:red"
+
+    @defer.inlineCallbacks
+    def setUp(self):
+        self.mock_resource = MockHttpResource(prefix=PATH_PREFIX)
+        self.auth_user_id = self.user_id
+
+        self.mock_config = NonCallableMock()
+        self.mock_config.signing_key = [MockKey()]
+
+        db_pool = SQLiteMemoryDbPool()
+        yield db_pool.prepare()
+
+        hs = HomeServer(
+            "red",
+            db_pool=db_pool,
+            http_client=None,
+            replication_layer=Mock(),
+            ratelimiter=NonCallableMock(spec_set=[
+                "send_message",
+            ]),
+            config=self.mock_config,
+        )
+        self.hs = hs
+
+        self.event_source = hs.get_event_sources().sources["typing"]
+
+        self.ratelimiter = hs.get_ratelimiter()
+        self.ratelimiter.send_message.return_value = (True, 0)
+
+        hs.get_handlers().federation_handler = Mock()
+
+        def _get_user_by_token(token=None):
+            return {
+                "user": hs.parse_userid(self.auth_user_id),
+                "admin": False,
+                "device_id": None,
+            }
+
+        hs.get_auth().get_user_by_token = _get_user_by_token
+
+        def _insert_client_ip(*args, **kwargs):
+            return defer.succeed(None)
+        hs.get_datastore().insert_client_ip = _insert_client_ip
+
+        synapse.rest.room.register_servlets(hs, self.mock_resource)
+
+        self.room_id = yield self.create_room_as(self.user_id)
+        # Need another user to make notifications actually work
+        yield self.join(self.room_id, user="@jim:red")
+
+    def tearDown(self):
+        self.hs.get_handlers().typing_notification_handler.tearDown()
+
+    @defer.inlineCallbacks
+    def test_set_typing(self):
+        (code, _) = yield self.mock_resource.trigger("PUT",
+            "/rooms/%s/typing/%s" % (self.room_id, self.user_id),
+            '{"typing": true, "timeout": 30000}'
+        )
+        self.assertEquals(200, code)
+
+        self.assertEquals(self.event_source.get_current_key(), 1)
+        self.assertEquals(
+            self.event_source.get_new_events_for_user(self.user_id, 0, None)[0],
+            [
+                {"type": "m.typing",
+                 "room_id": self.room_id,
+                 "typing": [self.user_id]},
+            ]
+        )
+
+    @defer.inlineCallbacks
+    def test_set_not_typing(self):
+        (code, _) = yield self.mock_resource.trigger("PUT",
+            "/rooms/%s/typing/%s" % (self.room_id, self.user_id),
+            '{"typing": false}'
+        )
+        self.assertEquals(200, code)