Exemplo n.º 1
0
async def register(jid, password):
    metadata = aioxmpp.make_security_layer(None)
    _, stream, features = await aioxmpp.node.connect_xmlstream(jid, metadata)

    query = ibr.Query(jid.localpart, password)
    await ibr.register(stream, query)
    print("Registered")
Exemplo n.º 2
0
    def __init__(self, bot, jabber_server, logger):
        config = jabber_server['jabber_id'].split(':')
        jabber_id = aioxmpp.JID.fromstr(config[0])
        override_peer = []
        if len(config) > 1:
            port = config[1]
            override_peer = [(jabber_id.domain, port,
                              aioxmpp.connector.STARTTLSConnector())]

        super(JabberRelay, self).__init__(
            aioxmpp.JID.fromstr(jabber_server['jabber_id']),
            aioxmpp.make_security_layer(jabber_server['password'],
                                        no_verify=True),
            override_peer=override_peer,
            logger=logger)

        self.bot = bot
        self.relay_from = jabber_server['relay_from']
        self.jabber_server = jabber_server
        self.embed_colour = get_embed_colour(jabber_server['logo_url'])
        self.languages = [LanguageRange(tag='en'), LanguageRange.WILDCARD]
        self.summon(aioxmpp.DiscoServer)
        self.summon(aioxmpp.RosterClient)

        message_dispatcher = self.summon(
            aioxmpp.dispatcher.SimpleMessageDispatcher)
        message_dispatcher.register_callback(None, None,
                                             self.message_receieved)

        self.presence = aioxmpp.PresenceState(True, aioxmpp.PresenceShow.AWAY)
Exemplo n.º 3
0
    def __init__(self, xmpp_config, client_logger=None):
        super().__init__()
        self.__config = xmpp_config

        override_peer = []
        if xmpp_config.get("host"):
            override_peer.append(
                (xmpp_config["host"], xmpp_config.get("port", 5222),
                 aioxmpp.connector.STARTTLSConnector()))

        security_args = {}
        if xmpp_config.get("public_key_pin"):
            security_args["pin_store"] = xmpp_config["public_key_pin"]
            security_args[
                "pin_type"] = aioxmpp.security_layer.PinType.PUBLIC_KEY

        self.client = aioxmpp.Client(
            aioxmpp.JID.fromstr(xmpp_config["jid"]),
            aioxmpp.make_security_layer(
                xmpp_config["password"],
                **security_args,
            ),
            override_peer=override_peer,
            logger=client_logger,
        )

        self.__nested_cm = None

        self.buddies = self.client.summon(Buddies)
        self.buddies.load_buddies(xmpp_config.get("buddies", []))
Exemplo n.º 4
0
 def start(self, user):
     Log.info('开始登陆', user)
     self.jid = aioxmpp.JID.fromstr(user['JID'])
     self.password = user['PWD']
     try:
         # no_verify=True大坑!,注意关闭认证;参考:https://docs.zombofant.net/aioxmpp/devel/api/public/security_layer.html
         # 可能要自己定义security_layer以达到通信安全
         self.client = aioxmpp.PresenceManagedClient(
             self.jid,
             aioxmpp.make_security_layer(self.password, no_verify=True),
             loop=self._loop)
         self.client.set_presence(
             aioxmpp.PresenceState(available=True,
                                   show=aioxmpp.PresenceShow.FREE_FOR_CHAT),
             {aioxmpp.structs.LanguageTag.fromstr('en'): '在线'})
         self.client.on_failure.connect(self.on_failure)  #启动失败时操作
         self.client.on_stream_established.connect(
             self.on_login_success)  #在链接服务器时操作
         self.client.on_stream_suspended.connect(
             self.on_internet_disconnect)  #服务器链接中断时操作
         self.client.on_stream_destroyed.connect(
             self.on_internet_disconnect)  #服务器链接失败时操作
     except ConnectionRefusedError:
         self._sign_login.emit(3)
         return
     except Exception:
         return
Exemplo n.º 5
0
    async def run(self) -> None:
        resource_id = (uuid.uuid4().hex).upper()
        resource = 'V2:Fortnite:{0.client.platform.value}::{1}'.format(
            self, resource_id)

        self.xmpp_client = aioxmpp.PresenceManagedClient(
            aioxmpp.JID(self.client.user.id, self.client.service_host,
                        resource),
            aioxmpp.make_security_layer(self.client.auth.access_token,
                                        no_verify=True),
            override_peer=[(self.client.service_domain,
                            self.client.service_port,
                            XMPPOverWebsocketConnector())],
            loop=self.client.loop)
        self.muc_service = self.xmpp_client.summon(aioxmpp.MUCClient)
        self.setup_callbacks()

        future = self.client.loop.create_future()
        self._task = asyncio.ensure_future(self._run(future),
                                           loop=self.client.loop)
        await future
        self._ping_task = asyncio.ensure_future(self.loop_ping(),
                                                loop=self.client.loop)

        asyncio.ensure_future(self.send_presence_on_start(),
                              loop=self.client.loop)
        self.client.dispatch_event('xmpp_session_establish')
Exemplo n.º 6
0
 async def run(self):
     resource_id = (uuid.uuid4().hex).upper()
     self.xmpp_client = aioxmpp.PresenceManagedClient(
         aioxmpp.JID(
             self.client.user.id, 
             self.client.service_host, 
             'V2:Fortnite:{0.client.platform.value}::{1}'.format(self, resource_id)
         ),
         aioxmpp.make_security_layer(
             self.client.auth.access_token,
             no_verify=True
         ),
         override_peer=[(
             self.client.service_domain,
             self.client.service_port,
             aioxmpp.connector.STARTTLSConnector()
         )],
         loop=self.client.loop
     )
     self.muc_service = self.xmpp_client.summon(aioxmpp.MUCClient)
     self.setup_callbacks()
     
     future = self.client.loop.create_future()
     self._task = asyncio.ensure_future(self._run(future), loop=self.client.loop)
     await future
     self._ping_task = asyncio.ensure_future(self.loop_ping(), loop=self.client.loop)
    def __init__(self, host, loop, access_key, encryption):
        """
        :param host: aka serial number
        :param access_key:
        :param password:
        :param host:
        :param sasl_mech:
        """
        self.serial_number = host
        self.loop = loop
        self._encryption = encryption
        self._request_timeout = 10
        self._lock = asyncio.Lock()
        self.msg_event = None

        identifier = self.serial_number + "@" + self.xmpp_host
        self._from = self._rrc_contact_prefix + identifier
        self._to = self.jid(self._rrc_gateway_prefix + identifier)
        self._jid = self.jid(self._from)
        self.xmppclient = aioxmpp.PresenceManagedClient(
            self._jid,
            aioxmpp.make_security_layer(self._accesskey_prefix + access_key)
        )
        self.message_dispatcher = self.xmppclient.summon(
            aioxmpp.dispatcher.SimpleMessageDispatcher
        )
Exemplo n.º 8
0
async def main(local_jid, password):
    client = aioxmpp.PresenceManagedClient(
        local_jid, aioxmpp.make_security_layer(password))

    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)

    message_dispatcher = client.summon(
        aioxmpp.dispatcher.SimpleMessageDispatcher)
    message_dispatcher.register_callback(
        aioxmpp.MessageType.CHAT,
        None,
        message_received,
    )

    async with client.connected():
        while True:
            await asyncio.sleep(1)
Exemplo n.º 9
0
async def _executor(my_jid, my_passwd, master_jid):
    masters = [aioxmpp.JID.fromstr(i) for i in master_jid.split(',')]
    client = aioxmpp.PresenceManagedClient(
        aioxmpp.JID.fromstr(my_jid),
        aioxmpp.make_security_layer(my_passwd),
    )
    # auto re-connect every 10s after conn down
    client.backoff_factor = 1
    client.backoff_cap = timedelta(seconds=10)
    G['client'] = client
    message_dispatcher = client.summon(
        aioxmpp.dispatcher.SimpleMessageDispatcher)
    for m in masters:
        message_dispatcher.register_callback(
            aioxmpp.MessageType.CHAT,
            m,
            message_received,
        )
    roster_client = client.summon(aioxmpp.RosterClient)
    while True:
        try:
            async with client.connected():
                for m in masters:
                    roster_client.approve(m)
                    roster_client.subscribe(m)
                logger.info('Connected')
                await asyncio.sleep(time.time())
        except asyncio.CancelledError:
            # asyncio.sleep
            # KeyboardInterrupt
            raise
        except Exception as e:
            logger.warning(repr(e))
Exemplo n.º 10
0
async def main(local_jid, password):
    client = aioxmpp.PresenceManagedClient(
        local_jid,
        aioxmpp.make_security_layer(password)
    )

    def message_received(msg):
        if msg.type_ != aioxmpp.MessageType.CHAT:
            return

        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.stream.enqueue_stanza(reply)

    client.stream.register_message_callback(
        aioxmpp.MessageType.CHAT,
        None,
        message_received,
    )

    async with client.connected():
        while True:
            await asyncio.sleep(1)
Exemplo n.º 11
0
 def _create_client(self, sender_id, api_key, loop=None) -> aioxmpp.Client:
     xmpp_client = aioxmpp.Client(
         local_jid=aioxmpp.JID.fromstr('*****@*****.**' % sender_id),
         security_layer=aioxmpp.make_security_layer(api_key),
         override_peer=[
             (self.FCM_HOST, self.FCM_PORT,
              aioxmpp.connector.XMPPOverTLSConnector())
         ],
         loop=loop
     )
     xmpp_client.on_stream_established.connect(
         lambda: self._wait_connection.set_result(True)
     )
     xmpp_client.on_stream_destroyed.connect(
         self._on_stream_destroyed
     )
     xmpp_client.on_failure.connect(
         lambda exc: self._wait_connection.set_exception(exc)
     )
     xmpp_client.stream.register_message_callback(
         type_=aioxmpp.MessageType.NORMAL,
         from_=None,
         cb=self.on_response
     )
     return xmpp_client
Exemplo n.º 12
0
    async def run(self):
        jid = aioxmpp.JID.fromstr(self.wizard().field("jid"))

        self.client = aioxmpp.Client(
            jid,
            aioxmpp.make_security_layer(self.wizard().field("password"), ),
            logger=self.logger,
        )
        self.client.summon(aioxmpp.DiscoClient)

        self.user_logger.info("Trying to connect as %s", jid)

        async with self.client.connected():
            self.user_logger.info("Successfully connected!")

            self.ui.progress.setRange(0, len(self.optional_steps) * 100)
            self.ui.progress.setValue(0)
            for i, step in enumerate(self.optional_steps):
                await step(i)
                self.ui.progress.setValue((i + 1) * 100)

            self.user_logger.info("Settings checked, done!")

        self._complete = True
        self.completeChanged.emit()
Exemplo n.º 13
0
 async def async_register(self):  # pragma: no cover
     """ Register the agent in the XMPP server from a coroutine. """
     metadata = aioxmpp.make_security_layer(
         None, no_verify=not self.verify_security)
     query = ibr.Query(self.jid.localpart, self.password)
     _, stream, features = await aioxmpp.node.connect_xmlstream(
         self.jid, metadata)
     await ibr.register(stream, query)
 def configure(self, section):
     super().configure(section)
     self.__host = section.get("host")
     self._domain = aioxmpp.JID.fromstr(section.get("domain", self.__host))
     self.__port = section.getint("port")
     self.__security_layer = aioxmpp.make_security_layer(
         None, anonymous="", **configure_tls_config(section))
     self._quirks = configure_quirks(section)
 def _load_accounts(self, cfg):
     result = []
     for username, password in ast.literal_eval(cfg):
         result.append((aioxmpp.JID(localpart=username,
                                    domain=self._domain.domain,
                                    resource=None),
                        aioxmpp.make_security_layer(password,
                                                    **self.__tls_config)))
     return result
Exemplo n.º 16
0
async def cancel(jid, password):
    client = aioxmpp.PresenceManagedClient(
        jid,
        aioxmpp.make_security_layer(password)
    )

    async with client.connected() as stream:
        service = ibr.RegistrationService(stream)
        await service.cancel_registration()
Exemplo n.º 17
0
    def register(self):  # pragma: no cover
        """ Register the agent in the XMPP server. """

        metadata = aioxmpp.make_security_layer(
            None, no_verify=not self.verify_security)
        query = ibr.Query(self.jid.localpart, self.password)
        _, stream, features = self.loop.run_until_complete(
            aioxmpp.node.connect_xmlstream(self.jid, metadata))
        self.loop.run_until_complete(ibr.register(stream, query))
Exemplo n.º 18
0
    def __init__(self, jid: str, password: str, *, config):
        self.config = config
        self.client = aioxmpp.PresenceManagedClient(
            aioxmpp.JID.fromstr(jid),
            aioxmpp.make_security_layer(password, no_verify=True),
        )
        self.muc = self.client.summon(aioxmpp.MUCClient)

        self.on_message_handlers = []
Exemplo n.º 19
0
    async def _async_start(self, auto_register=True):
        """
        Starts the agent from a coroutine. This fires some actions:

            * if auto_register: register the agent in the server
            * runs the event loop
            * connects the agent to the server
            * runs the registered behaviours

        Args:
          auto_register (bool, optional): register the agent in the server (Default value = True)

        """

        await self._hook_plugin_before_connection()

        if auto_register:
            await self._async_register()
        self.client = aioxmpp.PresenceManagedClient(
            self.jid,
            aioxmpp.make_security_layer(self.password,
                                        no_verify=not self.verify_security),
            loop=self.loop,
            logger=logging.getLogger(self.jid.localpart),
        )

        # obtain an instance of the service
        self.message_dispatcher = self.client.summon(SimpleMessageDispatcher)

        # Presence service
        self.presence = PresenceManager(self)

        await self._async_connect()

        # register a message callback here
        self.message_dispatcher.register_callback(
            aioxmpp.MessageType.CHAT,
            None,
            self._message_received,
        )

        await self._hook_plugin_after_connection()

        # pubsub initialization
        try:
            self._node = str(self.jid.bare())
            await self.pubsub.create(self.pubsub_server, f"{self._node}")
        except XMPPCancelError as e:
            logger.info(f"Node {self._node} already registered")
        except XMPPAuthError as e:
            logger.error(
                f"Artifact {self._node} is not allowed to publish properties.")
            raise e

        await self.setup()
        self._alive.set()
        asyncio.run_coroutine_threadsafe(self.run(), loop=self.loop)
Exemplo n.º 20
0
    async def jabber(self, jid, password):
        await self.bot.wait_until_ready()
        print('Waiting for pings from Jabber.')
        client = aioxmpp.PresenceManagedClient(
            jid, aioxmpp.make_security_layer(password, no_verify=True))

        icon_url = self.icon_url
        bot = self.bot

        def message_recieved(msg):
            if not msg.body:
                # We dont want to do anything with an empty message.
                return

            if msg.from_.bare() == aioxmpp.JID.fromstr(self.target).bare():
                # Take the message and pass it to an async task so we can post it.
                return asyncio.Task(post(msg))
            return

        # noinspection PyUnresolvedReferences
        message_dispatcher = client.summon(
            aioxmpp.dispatcher.SimpleMessageDispatcher)
        message_dispatcher.register_callback(aioxmpp.MessageType.CHAT, None,
                                             message_recieved)

        async def post(msg):
            body = msg.body[list(msg.body.keys())[0]]
            bot.logger.info('Ping Received.')
            urls = re.findall(
                'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+',
                body)
            if len(urls) == 0:
                urlstr = ''
            else:
                urlstr = "**PING CONTAINS THE FOLLOWING URLS** \n> " + ' \n> '.join(
                    urls) + "\n\n"
            time = datetime.datetime.utcnow()
            embed = discord.Embed(
                description=f'```\n{body}```\n '
                f'{urlstr}'
                f'***THIS IS PING HAS BEEN AUTOMATICALLY FORWARDED FROM JABBER***',
                color=discord.Color.red(),
                timestamp=time)
            embed.set_author(name=f'{self.target}', icon_url=f'{icon_url}')
            embed.set_thumbnail(url=f'{icon_url}')
            embed.set_footer(icon_url=bot.user.avatar_url_as(format='png'),
                             text=f"Service provided by {bot.user.name}")
            return await self.channel.send(embed=embed)

        # noinspection PyUnresolvedReferences
        @aioxmpp.service.iq_handler()
        async def iq_handle():
            pass

        async with client.connected():
            while 'JabberPings' in self.bot.cogs:
                await asyncio.sleep(1)
Exemplo n.º 21
0
 def __init__(self, jid: str, password: str, nick_name=None):
     self._jid = jid
     self._nick_name = nick_name
     if self._nick_name is None:
         self._nick_name = jid.split('@')[0] if '@' in jid else 'tcgl_bot'
     self._client = aioxmpp.PresenceManagedClient(
         aioxmpp.JID.fromstr(jid),
         aioxmpp.make_security_layer(password, no_verify=True))
     self._muc = self._client.summon(aioxmpp.muc.MUCClient)
     self._stream = None
Exemplo n.º 22
0
async def get_info(jid, password):
    client = aioxmpp.PresenceManagedClient(
        jid,
        aioxmpp.make_security_layer(password)
    )

    async with client.connected() as stream:
        service = ibr.RegistrationService(stream)
        reply = await service.get_client_info()
        print("Username: " + reply.username)
Exemplo n.º 23
0
    def __init__(self, jid, password, recipient):
        self.g_jid = aioxmpp.JID.fromstr(jid)
        self.g_security_layer = aioxmpp.make_security_layer(password)._replace(
            ssl_context_factory=self.my_ssl_factory, )

        self.to_jid = aioxmpp.JID.fromstr(recipient)

        if os.name == 'nt':
            asyncio.set_event_loop_policy(
                asyncio.WindowsSelectorEventLoopPolicy())
Exemplo n.º 24
0
async def amain(loop, args, cfg):
    try:
        statefile = pathlib.Path(cfg["muchopping"]["statefile"])
    except KeyError:
        engine = muchopper.common.model.get_generic_engine(
            cfg["muchopping"]["db_uri"])
    else:
        engine = muchopper.common.model.get_sqlite_engine(statefile)

    limits = cfg["muchopping"].get("limits", {})

    state = muchopper.bot.state.State(
        engine,
        pathlib.Path(cfg["muchopping"]["logfile"]),
        int(limits.get("max_name_length", 1024)),
        int(limits.get("max_description_length", 1024)),
        int(limits.get("max_subject_length", 1024)),
        int(limits.get("max_language_length", 126)),
    )

    components = list(
        map(muchopper.bot.daemon.Component,
            cfg["muchopping"].get("components", ["watcher", "scanner"])))

    daemon = muchopper.bot.daemon.MUCHopper(
        loop,
        aioxmpp.JID.fromstr(cfg["xmpp"]["jid"]),
        aioxmpp.make_security_layer(cfg["xmpp"]["password"], ),
        cfg["muchopping"]["nickname"],
        state,
        list(
            map(aioxmpp.JID.fromstr,
                cfg["muchopping"].get("privileged_entities", []))),
        components,
        mirror_config=cfg["muchopping"].get("mirror", {}),
        spokesman_config=cfg["muchopping"].get("spokesman", {}),
        avatar_whitelist=frozenset(
            map(aioxmpp.JID.fromstr,
                cfg["muchopping"].get("avatar_whitelist", []))),
        address_blocklist=frozenset(
            map(aioxmpp.JID.fromstr,
                cfg["muchopping"].get("address_blocklist", [])), ),
        prometheus_config=cfg.get("prometheus"),
    )

    for addr in cfg["muchopping"].get("seed", []):
        state.require_domain(
            addr,
            seen=False,
        )

    try:
        await daemon.run()
    finally:
        pass
Exemplo n.º 25
0
async def amain() -> int:
    config: Config = environ.to_config(Config)

    logging.basicConfig(level={
        0: logging.ERROR,
        1: logging.WARNING,
        2: logging.INFO,
    }.get(config.lib_log_level, logging.DEBUG), )
    logging.getLogger("authbot").setLevel({
        0: logging.ERROR,
        1: logging.WARNING,
        2: logging.INFO,
    }.get(config.log_level, logging.DEBUG))

    client = aioxmpp.PresenceManagedClient(
        config.address,
        aioxmpp.make_security_layer(config.password, ),
    )

    client.summon(aioxmpp.MUCClient)
    client.summon(aioxmpp.DiscoClient)

    stop_event = asyncio.Event()
    loop = asyncio.get_event_loop()
    loop.add_signal_handler(signal.SIGINT, stop_event.set)
    loop.add_signal_handler(signal.SIGTERM, stop_event.set)

    stop_future = asyncio.create_task(stop_event.wait())

    async with client.connected() as stream:
        logger.info("connected as %s", stream.local_jid)

        bot_task = asyncio.create_task(
            bot.run_in_room(
                client,
                config.room_address,
                config.room_nickname,
            ))

        done, pending = await asyncio.wait(
            [bot_task, stop_future],
            return_when=asyncio.FIRST_COMPLETED,
        )

        for fut in pending:
            fut.cancel()

        for fut in done:
            fut.result()

        for fut in pending:
            try:
                await fut
            except asyncio.CancelledError:
                pass
Exemplo n.º 26
0
async def change_password(jid, old_password, new_password):
    client = aioxmpp.PresenceManagedClient(
        jid,
        aioxmpp.make_security_layer(old_password)
    )

    async with client.connected() as stream:
        service = ibr.RegistrationService(stream)
        await service.change_pass(new_password)

    print("Password changed")
 def configure(self, section):
     super().configure(section)
     self.__host = section.get("host")
     self._domain = aioxmpp.JID.fromstr(section.get("domain", self.__host))
     self.__port = section.getint("port")
     self.__security_layer = aioxmpp.make_security_layer(
         "foobar2342",  # password is irrelevant, but must be given.
         **configure_tls_config(section))
     self._quirks = configure_quirks(section)
     self.__username_rng = random.Random()
     self.__username_rng.seed(_rng.getrandbits(256))
Exemplo n.º 28
0
def client(client_username, password):

    jid = aioxmpp.JID.fromstr(client_username)

    client = aioxmpp.PresenceManagedClient(
        jid,
        aioxmpp.make_security_layer(
            password,
            no_verify=True
        ),
    )
    return client
async def main(local_jid, password):
    client = aioxmpp.PresenceManagedClient(
        local_jid, aioxmpp.make_security_layer(password))

    client.stream.register_iq_request_coro(
        "get",
        Query,
        handler,
    )

    async with client.connected():
        await asyncio.sleep(30)
Exemplo n.º 30
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)
Exemplo n.º 31
0
    async def _async_start(self, auto_register=True):
        """
        Starts the agent from a coroutine. This fires some actions:

            * if auto_register: register the agent in the server
            * runs the event loop
            * connects the agent to the server
            * runs the registered behaviours

        Args:
          auto_register (bool, optional): register the agent in the server (Default value = True)

        """

        await self._hook_plugin_before_connection()

        if auto_register:
            await self._async_register()
        self.client = aioxmpp.PresenceManagedClient(
            self.jid,
            aioxmpp.make_security_layer(self.password,
                                        no_verify=not self.verify_security),
            loop=self.loop,
            logger=logging.getLogger(self.jid.localpart),
        )

        # obtain an instance of the service
        self.message_dispatcher = self.client.summon(SimpleMessageDispatcher)

        # Presence service
        self.presence = PresenceManager(self)

        await self._async_connect()

        # register a message callback here
        self.message_dispatcher.register_callback(
            aioxmpp.MessageType.CHAT,
            None,
            self._message_received,
        )

        await self._hook_plugin_after_connection()

        await self.setup()
        self._alive.set()
        for behaviour in self.behaviours:
            if not behaviour.is_running:
                behaviour.set_agent(self)
                if issubclass(type(behaviour), FSMBehaviour):
                    for _, state in behaviour.get_states().items():
                        state.set_agent(self)
                behaviour.start()
async def main(local_jid, password):
    client = aioxmpp.PresenceManagedClient(
        local_jid,
        aioxmpp.make_security_layer(password)
    )

    client.stream.register_iq_request_coro(
        "get",
        Query,
        handler,
    )

    async with client.connected():
        await asyncio.sleep(30)
Exemplo n.º 33
0
    def configure(self):
        self.args = self.argparse.parse_args()
        logging.basicConfig(
            level={
                0: logging.ERROR,
                1: logging.WARNING,
                2: logging.INFO,
            }.get(self.args.verbosity, logging.DEBUG)
        )

        self.config = configparser.ConfigParser()
        if self.args.config is not None:
            with self.args.config:
                self.config.read_file(self.args.config)

        self.g_jid = self.args.local_jid
        if self.g_jid is None:
            try:
                self.g_jid = aioxmpp.JID.fromstr(
                    self.config.get("global", "local_jid"),
                )
            except (configparser.NoSectionError,
                    configparser.NoOptionError):
                self.g_jid = aioxmpp.JID.fromstr(
                    input("Account JID> ")
                )

        if self.config.has_option("global", "pin_store"):
            with open(self.config.get("global", "pin_store")) as f:
                pin_store = json.load(f)
            pin_type = aioxmpp.security_layer.PinType(
                self.config.getint("global", "pin_type", fallback=0)
            )
        else:
            pin_store = None
            pin_type = None

        if self.args.ask_password:
            password = getpass.getpass()
        else:
            password = self.config.get("global", "password")

        self.g_security_layer = aioxmpp.make_security_layer(
            password,
            pin_store=pin_store,
            pin_type=pin_type,
        )
Exemplo n.º 34
0
 def configure(self, section):
     super().configure(section)
     self.__host = section.get("host")
     self.__domain = aioxmpp.JID.fromstr(section.get(
         "domain",
         self.__host
     ))
     self.__port = section.getint("port")
     self.__security_layer = aioxmpp.make_security_layer(
         None,
         anonymous="",
         **configure_tls_config(
             section
         )
     )
     self.__blockmap = configure_blockmap(section)
     self._quirks = configure_quirks(section)
Exemplo n.º 35
0
    async def _async_start(self, auto_register=True):
        """
        Starts the agent from a coroutine. This fires some actions:

            * if auto_register: register the agent in the server
            * runs the event loop
            * connects the agent to the server
            * runs the registered behaviours

        Args:
          auto_register (bool, optional): register the agent in the server (Default value = True)

        """

        if auto_register:
            await self._async_register()
        self.client = aioxmpp.PresenceManagedClient(self.jid,
                                                    aioxmpp.make_security_layer(self.password,
                                                                                no_verify=not self.verify_security),
                                                    loop=self.loop,
                                                    logger=logging.getLogger(self.jid.localpart))

        # obtain an instance of the service
        self.message_dispatcher = self.client.summon(SimpleMessageDispatcher)

        # Presence service
        self.presence = PresenceManager(self)

        await self._async_connect()

        # register a message callback here
        self.message_dispatcher.register_callback(
            aioxmpp.MessageType.CHAT,
            None,
            self._message_received,
        )
        await self.setup()
        self._alive.set()
        for behaviour in self.behaviours:
            if not behaviour.is_running:
                behaviour.start()
Exemplo n.º 36
0
async def main(local_jid, password):
    client = aioxmpp.PresenceManagedClient(
        local_jid,
        aioxmpp.make_security_layer(password)
    )

    peer_jid = local_jid.bare().replace(localpart=None)

    async with client.connected() as stream:
        iq = aioxmpp.IQ(
            type_="get",
            payload=Query(),
            to=peer_jid,
        )

        print("sending query to {}".format(peer_jid))
        reply = await stream.send_iq_and_wait_for_reply(iq)
        print("got response! logging off...")

    print("    name: {!r}".format(reply.name))
    print("    version: {!r}".format(reply.version))
    print("    os: {!r}".format(reply.os))
Exemplo n.º 37
0
async def main(local, password, peer,
               strip_newlines, add_newlines):
    loop = asyncio.get_event_loop()
    swrite = await stdout_writer()

    sread = asyncio.StreamReader()
    tread, pread = await loop.connect_read_pipe(
        lambda: asyncio.StreamReaderProtocol(sread),
        sys.stdin,
    )

    client = aioxmpp.PresenceManagedClient(
        local,
        aioxmpp.make_security_layer(
            password,
        )
    )

    sigint = asyncio.Event()
    loop.add_signal_handler(signal.SIGINT, sigint.set)
    loop.add_signal_handler(signal.SIGTERM, sigint.set)

    def recv(message):
        body = message.body.lookup(
            [aioxmpp.structs.LanguageRange.fromstr("*")]
        )
        if add_newlines:
            body += "\n"
        swrite.write(body.encode("utf-8"))

    client.stream.register_message_callback(
        "chat",
        peer,
        recv
    )

    sigint_future = asyncio.ensure_future(sigint.wait())
    read_future = asyncio.ensure_future(sread.readline())

    try:
        async with client.connected() as stream:
            while True:
                done, pending = await asyncio.wait(
                    [
                        sigint_future,
                        read_future,
                    ],
                    return_when=asyncio.FIRST_COMPLETED,
                )

                if sigint_future in done:
                    break

                if read_future in done:
                    line = read_future.result().decode()
                    if not line:
                        break

                    if strip_newlines:
                        line = line.rstrip()

                    msg = aioxmpp.Message(
                        type_="chat",
                        to=peer,
                    )
                    msg.body[None] = line

                    await stream.send_and_wait_for_sent(msg)

                    read_future = asyncio.ensure_future(
                        sread.readline()
                    )

    finally:
        sigint_future.cancel()
        read_future.cancel()
Exemplo n.º 38
0
Arquivo: xc.py Projeto: jbg/xc
async def xmpp_client():
  try:
    with open(os.path.join(os.getenv("HOME"), ".xc.conf"), "r") as config_file:
      config = json.load(config_file)
    if "jid" not in config:
      raise Exception("No JID")
  except Exception as e:
    print("Error reading configuration file.\n" + str(e) + "Please create ~/.xc.conf with content like:\n{\"jid\": \"[email protected]\"}")
    sys.exit(1)

  async def get_secret(jid, attempt):
    if attempt > 2:
      return None
    try:
      return await prompt_async("Secret (will not be stored): ", is_password=True)
    except:
      return None

  async def tls_handshake_callback(verifier):
    print("Warning: blindly accepting TLS certificate from %s" % verifier.transport.get_extra_info("server_hostname"))
    return True

  pin_store = PublicKeyPinStore()
  pin_store.import_from_json(config.get("pkps", {}))
  my_jid = aioxmpp.JID.fromstr(config["jid"])
  security = aioxmpp.make_security_layer(get_secret, pin_store=pin_store, pin_type=PinType.PUBLIC_KEY, post_handshake_deferred_failure=tls_handshake_callback)
  client = aioxmpp.PresenceManagedClient(my_jid, security)
  presence = client.summon(aioxmpp.presence.Service)
  roster = client.summon(aioxmpp.roster.Service)

  class RosterItemAndCommandCompleter(Completer):
    def get_completions(self, document, complete_event):
      text = document.text
      if not text or " " in text or ":" in text:
        return
      if text[0] == "/":
        part = text[1:]
        for command in ("roster", "name", "add", "del", "help", "quit"):
          if command.startswith(part):
            yield Completion(command + " ", start_position=-len(part), display=command)
      elif roster is not None:
        for item in roster.items.values():
          if item.name.startswith(text):
            yield Completion(item.name + ": ", start_position=-len(text), display=item.name)

  completer = RosterItemAndCommandCompleter()
  history = InMemoryHistory()

  next_recipient = None
  def get_prompt_tokens(_):
    return ((Token.Prompt, "%s> " % (next_recipient or "")),)

  cli_app = create_prompt_application(get_prompt_tokens=get_prompt_tokens,
                                      completer=completer,
                                      reserve_space_for_menu=0,
                                      history=history,
                                      get_title=lambda: "xc")
  cli_loop = create_asyncio_eventloop()
  cli = CommandLineInterface(application=cli_app, eventloop=cli_loop)
  above_prompt = cli.stdout_proxy()

  def name_for_jid(jid):
    try:
      return roster.items[jid].name
    except:
      return str(jid)

  def peer_available(jid, presence):
    above_prompt.write("%s is now online\n" % name_for_jid(jid.bare()))
  presence.on_available.connect(peer_available)

  def peer_unavailable(jid, presence):
    above_prompt.write("%s is now offline\n" % name_for_jid(jid.bare()))
  presence.on_unavailable.connect(peer_unavailable)

  def message_received(msg):
    content = " ".join(msg.body.values())
    if content:
      above_prompt.write("%s: %s\n" % (name_for_jid(msg.from_.bare()), content))
  client.stream.register_message_callback("chat", None, message_received)

  try:
    async with client.connected() as stream:
      while True:
        try:
          document = await cli.run_async()
        except (KeyboardInterrupt, EOFError):
          break
        line = document.text
        if line.startswith("/"):
          try:
            command, *args = line[1:].split(" ")
            if command == "roster":
              rows = [(item.name, str(jid), item.subscription) for jid, item in roster.items.items() if jid != my_jid]
              widths = [max(len(row[i] or "") for row in rows) for i in range(len(rows[0] or ""))]
              for row in rows:
                above_prompt.write("   ".join((cell or "").ljust(widths[i]) for i, cell in enumerate(row)) + "\n")
            elif command == "name":
              try:
                jid = args[0]
                name = args[1]
              except IndexError:
                above_prompt.write("usage: /name JID NAME\n")
              else:
                jid = aioxmpp.JID.fromstr(jid)
                await roster.set_entry(jid, name=name)
            elif command == "add":
              try:
                jid = args[0]
              except IndexError:
                above_prompt.write("usage: /add JID\n")
              else:
                jid = aioxmpp.JID.fromstr(jid)
                await roster.set_entry(jid)
                roster.subscribe(jid)
                roster.approve(jid)
            elif command == "del":
              try:
                jid = args[0]
              except IndexError:
                above_prompt.write("usage: /del JID\n")
              else:
                jid = aioxmpp.JID.fromstr(jid)
                await roster.remove_entry(jid)
            elif command == "quit":
              break
            elif command == "help":
              above_prompt.write("NAME: MESSAGE    send MESSAGE to NAME\n"
                                 "MESSAGE          send MESSAGE to the last correspondent\n"
                                 "/roster          print the roster\n"
                                 "/add JID         add JID to the roster\n"
                                 "/del JID         remove JID from the roster\n"
                                 "/name JID NAME   set the name of JID to NAME\n"
                                 "/quit            disconnect and then quit (also ctrl-d, ctrl-c)\n"
                                 "/help            this help\n")
            else:
              above_prompt.write("unrecognised command\n")
          except Exception as e:
            above_prompt.write("exception handling command: %s\n" % e)
        else:
          try:
            try:
              recipient, message = line.split(": ", 1)
            except ValueError:
              if next_recipient is not None:
                recipient = next_recipient
                message = line
              else:
                above_prompt.write("recipient: message\n")
                continue
            jid_for_name = lambda r: next((jid for jid, item in roster.items.items() if item.name == r), None)
            jid = jid_for_name(recipient)
            if jid is None:
              if next_recipient is not None and recipient != next_recipient:
                recipient = next_recipient
                jid = jid_for_name(recipient)
                message = line
            if jid is None:
              above_prompt.write("unknown recipient: %s\n" % recipient)
              continue
            msg = aioxmpp.Message(to=jid, type_="chat")
            msg.body[None] = message
            await stream.send_and_wait_for_sent(msg)
            next_recipient = recipient
          except Exception as e:
            above_prompt.write("exception sending message: %s\n" % e)

    print("Disconnecting…")
    client.stop()
  except Exception as e:
    print("Failed to connect: %s" % e)
Exemplo n.º 39
0
async def get_fields(jid):
    metadata = aioxmpp.make_security_layer(None)
    _, stream, features = await aioxmpp.node.connect_xmlstream(jid, metadata)
    reply = await ibr.get_registration_fields(stream)
    print(ibr.get_used_fields(reply))
Exemplo n.º 40
0
 async def _async_register(self):  # pragma: no cover
     """ Register the agent in the XMPP server from a coroutine. """
     metadata = aioxmpp.make_security_layer(None, no_verify=not self.verify_security)
     query = ibr.Query(self.jid.localpart, self.password)
     _, stream, features = await aioxmpp.node.connect_xmlstream(self.jid, metadata, loop=self.loop)
     await ibr.register(stream, query)