How to use synapse - 10 common examples

To help you get started, we’ve selected a few synapse examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github matrix-org / synapse / synapse / handlers / stats.py View on Github external
now = (now // 1000 // self.stats_bucket_size) * self.stats_bucket_size

            if typ == EventTypes.Member:
                # we could use _get_key_change here but it's a bit inefficient
                # given we're not testing for a specific result; might as well
                # just grab the prev_membership and membership strings and
                # compare them.
                prev_event_content = {}
                if prev_event_id is not None:
                    prev_event = yield self.store.get_event(
                        prev_event_id, allow_none=True
                    )
                    if prev_event:
                        prev_event_content = prev_event.content

                membership = event_content.get("membership", Membership.LEAVE)
                prev_membership = prev_event_content.get("membership", Membership.LEAVE)

                if prev_membership == membership:
                    continue

                if prev_membership == Membership.JOIN:
                    yield self.store.update_stats_delta(
                        now, "room", room_id, "joined_members", -1
                    )
                elif prev_membership == Membership.INVITE:
                    yield self.store.update_stats_delta(
                        now, "room", room_id, "invited_members", -1
                    )
                elif prev_membership == Membership.LEAVE:
                    yield self.store.update_stats_delta(
                        now, "room", room_id, "left_members", -1
github matrix-org / synapse / synapse / rest / client / v2_alpha / keys.py View on Github external
],
            "keys": { // Must include a ed25519 signing key
              ":": "",
            },
            "signatures:" {
              // Must be signed with device's ed25519 key
              "/": {
                ":": ""
              }
              // Must be signed by this server.
              "": {
                ":": ""
    } } } } } }
    """

    PATTERNS = client_patterns("/keys/query$")

    def __init__(self, hs):
        """
        Args:
            hs (synapse.server.HomeServer):
        """
        super(KeyQueryServlet, self).__init__()
        self.auth = hs.get_auth()
        self.e2e_keys_handler = hs.get_e2e_keys_handler()

    async def on_POST(self, request):
        requester = await self.auth.get_user_by_req(request, allow_guest=True)
        user_id = requester.user.to_string()
        timeout = parse_integer(request, "timeout", 10 * 1000)
        body = parse_json_object_from_request(request)
        result = await self.e2e_keys_handler.query_devices(body, timeout, user_id)
github matrix-org / synapse / tests / replication / test_resource.py View on Github external
def setUp(self):
        self.hs = yield setup_test_homeserver(
            "red",
            http_client=None,
            replication_layer=Mock(),
            ratelimiter=NonCallableMock(spec_set=[
                "send_message",
            ]),
        )
        self.user_id = "@seeing:red"
        self.user = UserID.from_string(self.user_id)

        self.hs.get_ratelimiter().send_message.return_value = (True, 0)

        self.resource = ReplicationResource(self.hs)
github matrix-org / synapse / tests / rest / client / v1 / test_presence.py View on Github external
self.mock_datastore.get_profile_avatar_url = get_profile_avatar_url

        def user_rooms_intersect(user_list):
            room_member_ids = map(lambda u: u.to_string(), self.room_members)

            shared = all(map(lambda i: i in room_member_ids, user_list))
            return defer.succeed(shared)
        self.mock_datastore.user_rooms_intersect = user_rooms_intersect

        def get_joined_hosts_for_room(room_id):
            return []
        self.mock_datastore.get_joined_hosts_for_room = get_joined_hosts_for_room

        self.presence = hs.get_handlers().presence_handler

        self.u_apple = UserID.from_string("@apple:test")
        self.u_banana = UserID.from_string("@banana:test")
github matrix-org / synapse / tests / rest / client / v1 / test_rooms.py View on Github external
pagination_handler._purges_by_id[purge_id] = PurgeStatus()
        self.get_success(
            pagination_handler._purge_history(
                purge_id=purge_id,
                room_id=self.room_id,
                token=second_token,
                delete_local_events=True,
            )
        )

        # Check that we only get the second message through /message now that the first
        # has been purged.
        request, channel = self.make_request(
            "GET",
            "/rooms/%s/messages?access_token=x&from=%s&dir=b&filter=%s"
            % (self.room_id, second_token, json.dumps({"types": [EventTypes.Message]})),
        )
        self.render(request)
        self.assertEqual(channel.code, 200, channel.json_body)

        chunk = channel.json_body["chunk"]
        self.assertEqual(len(chunk), 1, [event["content"] for event in chunk])

        # Check that we get no event, but also no error, when querying /messages with
        # the token that was pointing at the first event, because we don't have it
        # anymore.
        request, channel = self.make_request(
            "GET",
            "/rooms/%s/messages?access_token=x&from=%s&dir=b&filter=%s"
            % (self.room_id, first_token, json.dumps({"types": [EventTypes.Message]})),
        )
        self.render(request)
github matrix-org / synapse / tests / storage / test_redaction.py View on Github external
def inject_room_member(
        self, room, user, membership, replaces_state=None, extra_content={}
    ):
        content = {"membership": membership}
        content.update(extra_content)
        builder = self.event_builder_factory.for_room_version(
            RoomVersions.V1,
            {
                "type": EventTypes.Member,
                "sender": user.to_string(),
                "state_key": user.to_string(),
                "room_id": room.to_string(),
                "content": content,
            },
        )

        event, context = self.get_success(
            self.event_creation_handler.create_new_client_event(builder)
        )

        self.get_success(self.storage.persistence.persist_event(event, context))

        return event
github matrix-org / synapse / tests / federation / test_complexity.py View on Github external
d = handler._remote_join(
            None,
            ["other.example.com"],
            room_1,
            UserID.from_string(u1),
            {"membership": "join"},
        )

        self.pump()

        # The request failed with a SynapseError saying the resource limit was
        # exceeded.
        f = self.get_failure(d, SynapseError)
        self.assertEqual(f.value.code, 400)
        self.assertEqual(f.value.errcode, Codes.RESOURCE_LIMIT_EXCEEDED)
github matrix-org / synapse / tests / handlers / test_presence.py View on Github external
def _add_new_user(self, room_id, user_id):
        """Add new user to the room by creating an event and poking the federation API.
        """

        hostname = get_domain_from_id(user_id)

        room_version = self.get_success(self.store.get_room_version(room_id))

        builder = EventBuilder(
            state=self.state,
            auth=self.auth,
            store=self.store,
            clock=self.clock,
            hostname=hostname,
            signing_key=self.random_signing_key,
            format_version=room_version_to_event_format(room_version),
            room_id=room_id,
            type=EventTypes.Member,
            sender=user_id,
            state_key=user_id,
            content={"membership": Membership.JOIN},
github matrix-org / synapse / tests / handlers / test_typing.py View on Github external
import json

from mock import ANY, Mock, call

from twisted.internet import defer

from synapse.api.errors import AuthError
from synapse.types import UserID

from tests import unittest
from tests.utils import register_federation_servlets

# Some local users to test with
U_APPLE = UserID.from_string("@apple:test")
U_BANANA = UserID.from_string("@banana:test")

# Remote user
U_ONION = UserID.from_string("@onion:farm")

# Test room id
ROOM_ID = "a-room"


def _expect_edu_transaction(edu_type, content, origin="test"):
    return {
        "origin": origin,
        "origin_server_ts": 1000000,
        "pdus": [],
        "edus": [{"edu_type": edu_type, "content": content}],
    }
github matrix-org / synapse / tests / storage / test_events.py View on Github external
def test_count_daily_messages(self):
        yield self.db_pool.runQuery("DELETE FROM stats_reporting")

        self.hs.clock.now = 100

        # Never reported before, and nothing which could be reported
        count = yield self.store.count_daily_messages()
        self.assertIsNone(count)
        count = yield self.db_pool.runQuery("SELECT COUNT(*) FROM stats_reporting")
        self.assertEqual([(0,)], count)

        # Create something to report
        room = RoomID.from_string("!abc123:test")
        user = UserID.from_string("@raccoonlover:test")
        yield self.event_injector.create_room(room, user)

        self.base_event = yield self._get_last_stream_token()

        yield self.event_injector.inject_message(room, user, "Raccoons are really cute")

        # Never reported before, something could be reported, but isn't because
        # it isn't old enough.
        count = yield self.store.count_daily_messages()
        self.assertIsNone(count)
        yield self._assert_stats_reporting(1, self.hs.clock.now)

        # Already reported yesterday, two new events from today.
        yield self.event_injector.inject_message(room, user, "Yeah they are!")
        yield self.event_injector.inject_message(room, user, "Incredibly!")
        self.hs.clock.now += 60 * 60 * 24