def get_presence(self, user_id):
        if user_id in self.activity_change:
            return {"presence": "online", "last_active_ago": self.activity_change[user_id] * 1000}
        if user_id in self.user_presence:
            return {"presence": "offline", "last_active_ago": self.user_presence[user_id] * 1000}

        raise MatrixRequestError()
    async def test_get_nick(self):
        self.connector.room_specific_nicks = True

        with amock.patch(api_string.format(
                "get_room_displayname")) as patched_roomname, amock.patch(
                    api_string.format("get_display_name")) as patched_globname:
            patched_roomname.return_value = asyncio.Future()
            patched_roomname.return_value.set_result("")

            mxid = "@notaperson:matrix.org"
            assert await self.connector.get_nick("#notaroom:localhost",
                                                 mxid) == ""
            # Test if a room displayname couldn't be found
            patched_roomname.side_effect = Exception()

            # Test if that leads to a global displayname being returned
            patched_globname.return_value = asyncio.Future()
            patched_globname.return_value.set_result("@notaperson")
            assert (await self.connector.get_nick("#notaroom:localhost",
                                                  mxid) == "@notaperson")

            # Test that failed nickname lookup returns the mxid
            patched_globname.side_effect = MatrixRequestError()
            assert await self.connector.get_nick("#notaroom:localhost",
                                                 mxid) == mxid
    async def test_alias_already_exists(self):

        with amock.patch(api_string.format("set_room_alias")) as patched_alias:
            patched_alias.side_effect = MatrixRequestError(409)

            await self.connector._send_room_address(
                events.RoomAddress(target="!test:localhost", address="hello"))
Example #4
0
def test_join_global_room():
    """ join_global_room should try joining, fail and then create global public room """
    ownserver = 'https://ownserver.com'
    api = Mock()
    api.base_url = ownserver

    client = Mock()
    client.api = api

    def create_room(alias, is_public=False, invitees=None):
        room = Room(client, f'!room_id:ownserver.com')
        room.canonical_alias = alias
        return room

    client.create_room = Mock(side_effect=create_room)
    client.join_room = Mock(side_effect=MatrixRequestError(404))

    room_name = 'raiden_ropsten_discovery'

    room = join_global_room(
        client=client,
        name=room_name,
        servers=['https://invalid.server'],
    )
    assert client.join_room.call_count == 2  # room not found on own and invalid servers
    client.create_room.assert_called_once_with(
        room_name, is_public=True)  # created successfuly
    assert room and isinstance(room, Room)
Example #5
0
    async def _send(self,
                    method,
                    path,
                    content=None,
                    query_params=None,
                    headers=None,
                    api_path=MATRIX_V2_API_PATH):

        args = self._prepare_send(method, content, query_params, headers, path, api_path)
        content, query_params, headers, endpoint = args

        while True:
            request = self.client_session.request(
                method,
                endpoint,
                params=query_params,
                data=content,
                headers=headers)

            async with request as response:
                if response.status == 429:
                    responsejson = await response.json()
                    await sleep(self._get_waittime(responsejson))

                elif response.status < 200 or response.status >= 300:
                    raise MatrixRequestError(
                        code=response.status, content=await response.text())

                else:
                    return await response.json()
Example #6
0
    def _send(self,
              method,
              path,
              content=None,
              query_params=None,
              headers=None,
              api_path=MATRIX_V2_API_PATH):

        args = self._prepare_send(method, content, query_params, headers, path,
                                  api_path)
        content, query_params, headers, endpoint = args

        while True:
            try:
                response = self.session.request(method,
                                                endpoint,
                                                params=query_params,
                                                data=content,
                                                headers=headers,
                                                verify=self.validate_cert)
            except RequestException as e:
                raise MatrixHttpLibError(e, method, endpoint)

            if response.status_code == 429:
                sleep(self._get_waittime(response.json()))
            else:
                break

        if response.status_code < 200 or response.status_code >= 300:
            raise MatrixRequestError(code=response.status_code,
                                     content=response.text)

        return response.json()
async def test_get_no_key_500(patched_send, opsdroid_matrix):
    patched_send.side_effect = MatrixRequestError(code=500)

    db = DatabaseMatrix({"single_state_key": False}, opsdroid=opsdroid_matrix)

    data = await db.get("twim")

    assert data is None
Example #8
0
    async def test_already_in_room(self):

        with amock.patch(api_string.format("invite_user")) as patched_invite:
            patched_invite.side_effect = MatrixRequestError(
                403, json.dumps({"error": "@neo.matrix.org is already in the room"})
            )

            await self.connector._send_user_invitation(
                events.UserInvite(target="!test:localhost", user_id="@neo:matrix.org")
            )
Example #9
0
    async def _send(self,
                    method,
                    path,
                    content=None,
                    query_params={},
                    headers={},
                    api_path="/_matrix/client/r0"):
        if not content:
            content = {}

        method = method.upper()
        if method not in ["GET", "PUT", "DELETE", "POST"]:
            raise MatrixError("Unsupported HTTP method: %s" % method)

        if "Content-Type" not in headers:
            headers["Content-Type"] = "application/json"

        if self.token:
            query_params["access_token"] = self.token
        endpoint = self.base_url + api_path + path

        if headers["Content-Type"] == "application/json":
            content = json.dumps(content)

        while True:
            request = self.client_session.request(method,
                                                  endpoint,
                                                  params=query_params,
                                                  data=content,
                                                  headers=headers)
            async with request as response:
                if response.status == 429:
                    respjson = await response.json()
                    await sleep(respjson['retry_after_ms'] / 1000)
                elif response.status < 200 or response.status >= 300:
                    raise MatrixRequestError(code=response.status,
                                             content=await response.text())
                else:
                    return await response.json()
Example #10
0
 def mock_join_room(self, room_id_or_alias):
     raise MatrixRequestError(
         code=404, content={"errcode": "M_UNKNOWN", "error": "No known servers"}
     )
Example #11
0
 def get_user_presence(self, user_id: str) -> str:
     presence = self._user_presence.get(user_id)
     if presence is None:
         raise MatrixRequestError(404, "Unknown user")
     return presence
Example #12
0
 def get_user(self, user_id: str) -> User:
     all_users = list(self.search_user_directory(user_id))
     if len(all_users):
         return all_users[0]
     raise MatrixRequestError(404, "Unknown user")
 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}"
Example #14
0
 def mock_login(user, pw, sync=True):
     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}'
Example #15
0
 def raise_ex(room_id):
     raise MatrixRequestError()