예제 #1
0
    def _setup_client(self, matrix_client: GMatrixClient) -> None:
        exception_str = "Could not login/register to matrix."

        try:
            login(matrix_client,
                  signer=self.local_signer,
                  device_id=self.device_id)
            exception_str = "Could not join broadcasting room."
            server = urlparse(matrix_client.api.base_url).netloc
            room_alias = f"#{self.broadcast_room_alias_prefix}:{server}"

            broadcast_room = join_broadcast_room(
                client=matrix_client, broadcast_room_alias=room_alias)
            broadcast_room_id = broadcast_room.room_id

            if matrix_client == self.main_client:
                self.broadcast_room = broadcast_room
                self.broadcast_room_id = broadcast_room_id

            # Don't listen for messages on the discovery room on all clients
            sync_filter_id = matrix_client.create_sync_filter(
                not_rooms=[broadcast_room])
            matrix_client.set_sync_filter_id(sync_filter_id)
        except (MatrixRequestError, ValueError):
            raise ConnectionError(exception_str)
예제 #2
0
def create_logged_in_client(server: str) -> Tuple[GMatrixClient, Signer]:
    client = make_client(ignore_messages, ignore_member_join, [server])
    signer = factories.make_signer()

    login(client, signer)

    return client, signer
def create_logged_in_client(server: str) -> Tuple[GMatrixClient, Signer]:
    client = make_client([server])
    signer = factories.make_signer()

    login(client, signer)

    return client, signer
예제 #4
0
def monitor_server_presence(server: str, signer: Signer,
                            network_names: List[str], stop_event: Event):
    server_name = urlparse(server).netloc
    client = make_client(lambda x: False, lambda x: None, [server])
    login(client=client, signer=signer)
    client.add_presence_listener(partial(log_presence, server))
    client.start_listener_thread(30_000, 1_000)
    for network_name in network_names:
        discovery_room_alias = make_room_alias(CHAINNAME_TO_ID[network_name],
                                               DISCOVERY_DEFAULT_ROOM)

        discovery_room = join_broadcast_room(
            client, f"#{discovery_room_alias}:{server_name}")
    log.info("Monitoring started", server=server)
    stop_event.wait()
    client.stop()
예제 #5
0
def new_user(matrix_server_url: str) -> LoggedUser:
    client = GMatrixClient(time_messages, ignore_member_join, matrix_server_url)
    signer = factories.make_signer()

    with logtime(USER) as details:
        user = login(client, signer)
        details["user_id"] = user.user_id

    return LoggedUser(client, signer, user)
예제 #6
0
    def _start_client(self, server_url: str) -> GMatrixClient:
        assert self.user_manager
        if self.stop_event.is_set():
            raise TransportError()

        if server_url == self.main_client.api.base_url:
            client = self.main_client
        else:
            # Also handle messages on the other clients,
            # since to-device communication to the PFS only happens via the local user
            # on each homeserver
            client = make_client(
                handle_messages_callback=self.main_client.
                handle_messages_callback,
                servers=[server_url],
                http_pool_maxsize=4,
                http_retry_timeout=40,
                http_retry_delay=matrix_http_retry_delay,
            )

            self.server_url_to_other_clients[server_url] = client
            log.debug("Created client for other server", server_url=server_url)
        try:
            login(client, signer=self.local_signer, device_id=self.device_id)
            log.debug("Matrix login successful", server_url=server_url)

        except (MatrixRequestError, ValueError):
            raise ConnectionError("Could not login/register to matrix.")

        client.start_listener_thread(
            DEFAULT_TRANSPORT_MATRIX_SYNC_TIMEOUT,
            DEFAULT_TRANSPORT_MATRIX_SYNC_LATENCY,
        )

        # main client is already added upon MultiClientUserAddressManager.start()
        if server_url != self.main_client.api.base_url:
            self.user_manager.add_client(client)
        return client
예제 #7
0
    def _start_client(self) -> None:
        try:
            if self._user_manager:
                self._user_manager.start()

            login(self.client,
                  signer=LocalSigner(private_key=decode_hex(self.private_key)))
        except (MatrixRequestError, ValueError):
            raise ConnectionError("Could not login/register to matrix.")

        try:
            self.join_global_rooms(client=self.client,
                                   available_servers=self.available_servers)
        except (MatrixRequestError, TransportError):
            raise ConnectionError(
                "Could not join monitoring broadcasting room.")

        # Add listener for global rooms
        for broadcast_room in self.broadcast_rooms:
            broadcast_room.add_listener(self._handle_message, "m.room.message")

        # Signal that startup is finished
        self.startup_finished.set()
예제 #8
0
def test_login_for_the_first_time_must_set_the_display_name():
    ownserver = "https://ownserver.com"
    api = Mock()
    api.base_url = ownserver
    server_name = urlparse(ownserver).netloc

    client = Mock()
    client.api = api

    # login will assert user is hex-encoded address and pw is server_name signed with that address
    def mock_login(user, pw, sync=True, device_id=None):  # pylint: disable=unused-argument
        recovered = recover(data=server_name.encode(), signature=decode_hex(pw))
        if recovered != to_canonical_address(user):
            raise MatrixRequestError(403)
        client.user_id = f"@{user}:{server_name}"

    client.login = Mock(side_effect=mock_login)

    MockUser = create_autospec(User)

    client.get_user = Mock(side_effect=lambda user_id: MockUser(api, user_id))

    signer = make_signer()

    user = login(client=client, signer=signer)

    # client.user_id will be set by login
    assert client.user_id.startswith(f"@{to_normalized_address(signer.address)}")
    # login returns our own user object
    assert isinstance(user, User)
    # get_user must have been called once to generate above user
    client.get_user.assert_called_once_with(client.user_id)
    # assert set_display_name was called once on ourselves
    assert user.set_display_name.call_count == 1
    # assert the user.set_display_name was called with the signature of the user_id
    assert (
        recover(
            data=client.user_id.encode(),
            signature=decode_hex(user.set_display_name.call_args[0][0]),
        )
        == signer.address
    )
예제 #9
0
def main(keystore_file: str, password: str, host: str, room_id: str, other_user_id: str):
    private_key = get_private_key(keystore_file, password)
    client = GMatrixClient(host)

    user = login(client=client, signer=LocalSigner(private_key=decode_hex(private_key)))

    log.info("Logged in", user=user, server=host, room_id=room_id)
    # print("TKN: \n" + client.token)

    client.add_presence_listener(callback)
    client.start_listener_thread()

    # try:
    client.join_room(room_id)
    # except MatrixRequestError:
    #     client.create_room(alias="raiden_goerli_discovery", is_public=True)

    while True:
        current_presence = client.get_user_presence(other_user_id)
        log.warning("User presence", other_user=other_user_id, presence=current_presence)

        gevent.sleep(1)