Example #1
0
def test_body_with_languages():
    msg = aioxmpp.Message(type_=aioxmpp.MessageType.CHAT)
    msg.body["en"] = "Hello World"
    msg.body["es"] = "Hola Mundo"

    new_msg = Message.from_node(msg)
    assert new_msg.body == "Hello World"
Example #2
0
    async def send_party_message(self, content: str) -> None:
        if self.muc_room is None:
            raise PartyError('Can\'t send message. Reason: No party found')

        msg = aioxmpp.Message(type_=aioxmpp.MessageType.GROUPCHAT)
        msg.body[None] = content
        self.muc_room.send_message(msg)
Example #3
0
    async def send_message(self, message):
        if not self.connected:
            await self.connect()
        msg = aioxmpp.Message(
            type_=aioxmpp.MessageType.NORMAL
        )
        payload = FCMMessage()

        payload_body = message.as_dict()

        payload.text = json.dumps(payload_body)
        msg.fcm_payload = payload

        future_response = asyncio.Future()
        self.requests[message.message_id] = future_response

        self.refresh_inactivity_timer()
        try:
            await self.xmpp_client.stream.send(msg)
        except Exception:
            self.requests.pop(message.message_id)
            raise

        response = await future_response
        return response
 def test_leave_non_protocol_messages_intact(self):
     stanza = aioxmpp.Message(
         aioxmpp.MessageType.NORMAL,
         from_=TEST_JID1,
         to=TEST_FROM,
     )
     self.assertIs(self.s._handle_message(stanza), stanza)
Example #5
0
    def test_send_with_attached_tracker(self):
        msg_delivered = asyncio.Event()

        def state_change_cb(new_state, *args):
            if (new_state ==
                    aioxmpp.tracking.MessageState.DELIVERED_TO_RECIPIENT):
                msg_delivered.set()

        msg = aioxmpp.Message(type_=aioxmpp.MessageType.CHAT,
                              to=self.b.local_jid)
        msg.body[LANG] = "This is a non-colourful test message!"

        tracker = self.a_mdr.attach_tracker(msg)
        tracker.on_state_changed.connect(state_change_cb)

        msg_recvd = asyncio.Future()

        def cb(message):
            msg_recvd.set_result(message)

        self.b_recv.register_callback(aioxmpp.MessageType.CHAT, None, cb)

        yield from self.a.send(msg)

        msg_b = yield from msg_recvd
        self.assertDictEqual(msg_b.body,
                             {LANG: "This is a non-colourful test message!"})
        self.assertTrue(msg_b.xep0184_request_receipt)

        self.assertFalse(msg_delivered.is_set())

        response = aioxmpp.mdr.compose_receipt(msg_b)
        yield from self.b.send(response)

        yield from msg_delivered.wait()
Example #6
0
    def test_forward_normal_even_without_body_to_existing(self):
        msg = aioxmpp.Message(
            type_=aioxmpp.MessageType.NORMAL,
            from_=PEER_JID.replace(resource="foo"),
        )
        msg.body[None] = "foo"

        conv = self.s.get_conversation(PEER_JID.bare())

        with contextlib.ExitStack() as stack:
            _handle_message = stack.enter_context(
                unittest.mock.patch.object(
                    conv,
                    "_handle_message",
                ))

            self.assertIsNone(
                self.s._filter_message(
                    msg,
                    msg.from_,
                    False,
                    im_dispatcher.MessageSource.STREAM,
                ))

        _handle_message.assert_called_once_with(
            msg,
            msg.from_,
            False,
            im_dispatcher.MessageSource.STREAM,
        )
Example #7
0
def test_message_from_node():
    aiomsg = aioxmpp.Message(type_=aioxmpp.MessageType.CHAT)
    data = forms_xso.Data(type_=forms_xso.DataType.FORM)

    data.fields.append(
        forms_xso.Field(
            var="performative",
            type_=forms_xso.FieldType.TEXT_SINGLE,
            values=["request"],
        )
    )

    data.fields.append(
        forms_xso.Field(
            var="_thread_node",
            type_=forms_xso.FieldType.TEXT_SINGLE,
            values=["thread-id"],
        )
    )
    data.title = SPADE_X_METADATA
    aiomsg.xep0004_data = [data]

    msg = Message.from_node(aiomsg)

    assert msg.thread == "thread-id"
    assert msg.get_metadata("performative") == "request"
    assert msg.metadata == {"performative": "request"}
Example #8
0
 def sendMsg(self,data):
     msgData = aioxmpp.Message(
         to=data['JID'],  # recipient_jid must be an aioxmpp.JID
         type_=aioxmpp.MessageType.GROUPCHAT,
     )
     msgData.body[None] = data['msg']
     self.roomList[str(data['JID'])]['room'].send_message(msgData)
    async def test_message_from_a_to_b(self):
        a = await self.provisioner.get_connected_client()
        b = await self.provisioner.get_connected_client()

        fut = asyncio.Future()

        def cb(msg):
            fut.set_result(msg)

        with aioxmpp.stream.message_handler(b.stream, aioxmpp.MessageType.CHAT,
                                            a.local_jid, cb):

            msg_sent = aioxmpp.Message(
                to=b.local_jid,
                type_=aioxmpp.MessageType.CHAT,
            )
            msg_sent.body[aioxmpp.structs.LanguageTag.fromstr("en")] = \
                "Hello World!"

            await a.send(msg_sent)

            msg_rcvd = await fut

        self.assertEqual(
            msg_rcvd.body[aioxmpp.structs.LanguageTag.fromstr("en")],
            "Hello World!")
Example #10
0
    async def bridge(self, client, message, *, edited=False):
        """Take a discord message and send it over to the MUC."""
        room = discord.utils.find(
            lambda room: room["channel_id"] == message.channel.id,
            self.config["rooms"])

        if not room or room.get("disabled", False):
            return

        if room.get("discord_log", False):
            content = extract_message_content(message)
            log.info("[discord] <%s> %s", message.author, content)

        reply = aioxmpp.Message(
            type_=aioxmpp.MessageType.GROUPCHAT,
            to=aioxmpp.JID.fromstr(room["jid"]),
        )

        formatted_content = await format_discord_message(client, message)

        if edited:
            formatted_content += " (edited)"

        reply.body[None] = formatted_content
        await self.client.send(reply)
Example #11
0
def construct_message(to, body):
    msg = aioxmpp.Message(
        to=aioxmpp.JID.fromstr(to),  # recipient_jid must be an aioxmpp.JID
        type_=aioxmpp.MessageType.CHAT,
    )
    # None is for "default language"
    msg.body[None] = body
    return msg
Example #12
0
 def sendMsg(self, data):
     msg = aioxmpp.Message(
         to=data['JID'],
         type_=aioxmpp.MessageType.CHAT,
     )
     msg.body[None] = data['msg']
     self.conversationList[str(
         data['JID'])]['conversation'].send_message(msg)
Example #13
0
    def setup(self):
        self.web.start(templates_path="examples")
        template1 = Template(sender="agent0@fake_server")
        template2 = Template(sender="agent1@fake_server")
        template3 = Template(sender="agent2@fake_server")
        template4 = Template(sender="agent3@fake_server")

        # Create some dummy behaviours
        dummybehav = self.DummyBehav()
        self.add_behaviour(dummybehav, template=template1)
        periodbehav = self.DummyPeriodBehav(period=12.7)
        self.add_behaviour(periodbehav, template=template2)
        timeoutbehav = self.DummyTimeoutBehav(start_at=datetime.datetime.now())
        self.add_behaviour(timeoutbehav, template=template3)
        fsm_behav = self.DummyFSMBehav()
        self.add_behaviour(fsm_behav, template=template4)
        behavs = [dummybehav, periodbehav, timeoutbehav, fsm_behav]

        # Create some fake contacts
        self.add_fake_contact("agent0@fake_server", PresenceType.AVAILABLE)
        self.add_fake_contact("agent1@fake_server",
                              PresenceType.AVAILABLE,
                              show=PresenceShow.AWAY)
        self.add_fake_contact(
            "agent2@fake_server",
            PresenceType.AVAILABLE,
            show=PresenceShow.DO_NOT_DISTURB,
        )
        self.add_fake_contact("agent3@fake_server", PresenceType.UNAVAILABLE)
        self.add_fake_contact("agent4@fake_server",
                              PresenceType.AVAILABLE,
                              show=PresenceShow.CHAT)
        self.add_fake_contact("agent5@fake_server", PresenceType.UNAVAILABLE)

        # Send and Receive some fake messages
        self.traces.reset()
        for i in range(20):
            number = random.randint(0, 3)
            from_ = JID.fromstr("agent{}@fake_server".format(number))
            msg = aioxmpp.Message(from_=from_,
                                  to=self.jid,
                                  type_=MessageType.CHAT)
            msg.body[None] = "Hello from {}! This is a long message.".format(
                from_.localpart)
            msg = Message.from_node(msg)
            msg.metadata = {
                "performative": "inform",
                "acl-representation": "xml"
            }
            msg = msg.prepare()
            self._message_received(msg=msg)
            msg = Message(sender=str(self.jid),
                          to=str(from_),
                          body="This is my answer.")
            msg.sent = True
            self.traces.append(msg, category=str(behavs[number]))
Example #14
0
    async def send_friend_message(self, jid, content):
        if self.stream is None:
            raise XMPPError('xmpp is not connected')

        msg = aioxmpp.Message(
            to=jid,
            type_=aioxmpp.MessageType.CHAT,
        )
        msg.body[None] = content
        await self.stream.send(msg)
Example #15
0
async def test_send_message_from_user2_to_nonexisting(client):
    recipient_jid = aioxmpp.JID.fromstr("nonexisting@localhost")
    async with client.connected() as stream:
        msg = aioxmpp.Message(
            to=recipient_jid,
            type_=aioxmpp.MessageType.CHAT,
        )
        msg.body[None] = "Hello World!"

        await client.send(msg)
Example #16
0
async def test_can_not_log_in_with_wrong_password(client):
    with pytest.raises(aiosasl.AuthenticationFailure):
        recipient_jid = aioxmpp.JID.fromstr("nonexisting@localhost")
        async with client.connected() as stream:
            msg = aioxmpp.Message(
                to=recipient_jid,
                type_=aioxmpp.MessageType.CHAT,
            )
            msg.body[None] = "Hello World!"

            await client.send(msg)
Example #17
0
async def test_send_message_from_admin_to_user1(client):
    recipient_jid = aioxmpp.JID.fromstr("user1@localhost")
    async with client.connected() as stream:
        msg = aioxmpp.Message(
            to=recipient_jid,
            type_=aioxmpp.MessageType.CHAT,
        )
        # None is for "default language"
        msg.body[None] = "Hello World!"

        await client.send(msg)
Example #18
0
async def _send_message(from_jid, from_passwd, to_jid, message):
    client = aioxmpp.PresenceManagedClient(
        aioxmpp.JID.fromstr(from_jid),
        aioxmpp.make_security_layer(from_passwd),
    )
    msg = aioxmpp.Message(
        to=aioxmpp.JID.fromstr(to_jid),
        type_=aioxmpp.MessageType.CHAT,
    )
    msg.body[None] = message
    async with client.connected():
        await client.send(msg)
Example #19
0
 def send_update(self, jid, event):
     msg = aioxmpp.Message(
         to=jid,
         type_=aioxmpp.MessageType.CHAT,
     )
     msg.body[None] = '\n'.join(
         filter(None, [
             strip_html(deref_multi(event['info'][0], x) or '')
             for x in (['headline'], ['description'], ['instruction'],
                       ['area', 0, 'areaDesc'], ['effective'], ['expires'])
         ]))
     self.client.enqueue(msg)
async def main(from_jid, to_jid, password, message):
    client = aioxmpp.PresenceManagedClient(
        aioxmpp.JID.fromstr(from_jid),
        aioxmpp.make_security_layer(password),
    )

    async with client.connected() as stream:
        msg = aioxmpp.Message(
            to=aioxmpp.JID.fromstr(to_jid),
            type_=aioxmpp.MessageType.CHAT,
        )
        msg.body[None] = message
        await stream.send(msg)
Example #21
0
    def test_autocreate_with_fulljid_if_muc_tagged(self):
        msg = aioxmpp.Message(
            type_=aioxmpp.MessageType.CHAT,
            from_=PEER_JID.replace(resource="foo"),
        )
        msg.body[None] = "foo"
        msg.xep0045_muc_user = muc_xso.UserExt()

        with contextlib.ExitStack() as stack:
            Conversation = stack.enter_context(unittest.mock.patch(
                "aioxmpp.im.p2p.Conversation",
            ))

            self.assertIsNone(self.s._filter_message(
                msg,
                PEER_JID.replace(localpart="fnord", resource="foo"),
                False,
                im_dispatcher.MessageSource.STREAM,
            ))
            Conversation.assert_called_once_with(
                self.s,
                PEER_JID.replace(localpart="fnord", resource="foo"),
                parent=None
            )

            c = self.s.get_conversation(
                PEER_JID.replace(localpart="fnord", resource="foo")
            )
            Conversation.assert_called_once_with(
                self.s,
                PEER_JID.replace(localpart="fnord", resource="foo"),
                parent=None
            )

            self.assertEqual(c, Conversation())

            self.listener.on_conversation_new.assert_called_once_with(
                Conversation()
            )

            self.listener.on_spontaneous_conversation.assert_called_once_with(
                Conversation()
            )

            Conversation()._handle_message.assert_called_once_with(
                msg,
                PEER_JID.replace(localpart="fnord", resource="foo"),
                False,
                im_dispatcher.MessageSource.STREAM,
            )
Example #22
0
    async def run(self):
        """
        Run the program. That means connecting, then sending a message to the
        account that can send text to this buffer, signaling that this buffer
        is now available.
        After that an infinite loop is started so the program can receive
        messages. This loop can be broken when self.running is set to false.
        """
        async with self.client.connected() as stream:
            msg = aioxmpp.Message(to=aioxmpp.JID.fromstr(self.receive_from),
                                  type_=aioxmpp.MessageType.CHAT)
            msg.body[None] = "Ready to receive now!"
            await self.client.send(msg)

            while self.running:
                await asyncio.sleep(10)

            msg = aioxmpp.Message(to=aioxmpp.JID.fromstr(self.receive_from),
                                  type_=aioxmpp.MessageType.CHAT)
            msg.body[None] = "Shutting down!"
            await self.client.send(msg)

            sys.exit(0)
    async def test_exception_from_non_wellformed(self):
        c = await self.provisioner.get_connected_client()

        msg = aioxmpp.Message(
            to=c.local_jid,
            type_=aioxmpp.MessageType.NORMAL,
        )
        msg.body[None] = "foo\u0000"

        with self.assertRaisesRegex(ValueError, "not allowed"):
            await c.send(msg)

        msg.body[None] = "foo"

        await c.send(msg)
Example #24
0
    def message_received(msg):
        if not msg.body:
            # do not reflect anything without a body
            return

        # we could also use reply = msg.make_reply() instead
        reply = aioxmpp.Message(
            type_=msg.type_,
            to=msg.from_,
        )

        # make_reply() would not set the body though
        reply.body.update(msg.body)

        client.enqueue(reply)
Example #25
0
    async def async_send_messages(self, messages):
        client = aioxmpp.Client(
            self.g_jid,
            self.g_security_layer,
        )
        client.resumption_timeout = 0

        async with client.connected() as stream:
            for message_content in messages:
                msg = aioxmpp.Message(
                    to=self.to_jid,
                    type_=aioxmpp.MessageType.CHAT,
                )
                msg.body[None] = message_content

                await stream.send(msg)
Example #26
0
    def _send_message(self):
        body = self.ui.message_input.toPlainText()
        msg = aioxmpp.Message(type_=aioxmpp.MessageType.CHAT)
        msg.body[None] = body
        msg.xep0333_markable = True
        url_match = self.URL_RE.match(body)
        if url_match is not None:
            info = url_match.groupdict()
            url = info.get("url_name",
                           info.get("url_nonword", info.get("url_paren")))
            if url:
                msg.xep0066_oob = aioxmpp.misc.OOBExtension()
                msg.xep0066_oob.url = url

        self.ui.message_input.clear()
        yield from self._send_message_stanza(msg)
Example #27
0
def test_receive_without_behaviours():
    agent = make_connected_agent()
    aiomsg = aioxmpp.Message(type_=aioxmpp.MessageType.CHAT)
    msg = Message.from_node(aiomsg)

    assert agent.traces.len() == 0
    agent.start(auto_register=False)

    with LogCapture() as log:
        agent._message_received(aiomsg)
        log.check_present(('spade.Agent', 'WARNING', f"No behaviour matched for message: {msg}"))

    assert agent.traces.len() == 1
    assert msg in agent.traces.store[0]

    agent.stop()
Example #28
0
    def test_autocreate_conversation_from_recvd_normal_with_body(self):
        msg = aioxmpp.Message(
            type_=aioxmpp.MessageType.NORMAL,
            from_=PEER_JID.replace(resource="foo"),
        )
        msg.body[None] = "foo"

        with contextlib.ExitStack() as stack:
            Conversation = stack.enter_context(unittest.mock.patch(
                "aioxmpp.im.p2p.Conversation",
            ))

            self.assertIsNone(self.s._filter_message(
                msg,
                msg.from_,
                False,
                im_dispatcher.MessageSource.STREAM,
            ))
            Conversation.assert_called_once_with(
                self.s,
                msg.from_.bare(),
                parent=None
            )

            c = self.s.get_conversation(PEER_JID)
            Conversation.assert_called_once_with(
                self.s,
                msg.from_.bare(),
                parent=None
            )

            self.assertEqual(c, Conversation())

            self.listener.on_conversation_new.assert_called_once_with(
                Conversation()
            )

            self.listener.on_spontaneous_conversation.assert_called_once_with(
                Conversation()
            )

            Conversation()._handle_message.assert_called_once_with(
                msg,
                msg.from_,
                False,
                im_dispatcher.MessageSource.STREAM,
            )
Example #29
0
    async def send_ack(self, device_token, message_id):
        if not self.connected:
            await self.connect()
        msg = aioxmpp.Message(type_=aioxmpp.MessageType.NORMAL)
        payload = FCMMessage()

        payload_body = {
            "to": str(device_token),
            "message_id": str(message_id),
            "message_type": "ack"
        }

        payload.text = json.dumps(payload_body)
        msg.fcm_payload = payload

        self.refresh_inactivity_timer()
        await self.xmpp_client.stream.send(msg)
Example #30
0
    def test_converse_with_preexisting(self):
        c1 = yield from self.firstwitch.summon(p2p.Service).get_conversation(
            self.secondwitch.local_jid.bare()
        )

        c2 = yield from self.secondwitch.summon(p2p.Service).get_conversation(
            self.firstwitch.local_jid.bare()
        )

        fwmsgs = []
        fwev = asyncio.Event()

        def fwevset(message, member, source):
            if member == c1.me:
                return
            fwmsgs.append(message)
            fwev.set()

        swmsgs = []
        swev = asyncio.Event()

        def swevset(message, member, source):
            if member == c2.me:
                return
            swmsgs.append(message)
            swev.set()

        c1.on_message.connect(fwevset)
        c2.on_message.connect(swevset)

        msg = aioxmpp.Message(aioxmpp.MessageType.CHAT)
        msg.body[None] = "foo"
        yield from c1.send_message(msg)
        yield from swev.wait()

        self.assertEqual(len(swmsgs), 1)
        self.assertEqual(swmsgs[0].body[None], "foo")
        self.assertEqual(len(fwmsgs), 0)

        msg.body[None] = "bar"
        yield from c2.send_message(msg)
        yield from fwev.wait()

        self.assertEqual(len(fwmsgs), 1)
        self.assertEqual(fwmsgs[0].body[None], "bar")
        self.assertEqual(len(swmsgs), 1)