async def wait_until(self, event: str, timeout=30) -> Any: """Utility method to wake on the next firing of an event. (Registers a disposable handler on it) :param str event: Event to wait on. :param int timeout: Timeout :raises: :class:`asyncio.TimeoutError` when the timeout is reached """ fut = asyncio.Future() def result_handler(event_data): if not fut.done(): fut.set_result(event_data) else: log.debug( "Future registered on event '%s' was alredy done", event ) self.add_event_handler( event, result_handler, disposable=True, ) return await asyncio.wait_for(fut, timeout)
async def start(self, event): """ Process the session_start event. Typical actions for the session_start event are requesting the roster and broadcasting an initial presence stanza. Arguments: event -- An empty dictionary. The session_start event does not provide any additional data. """ future = asyncio.Future() def callback(result): future.set_result(None) try: self.get_roster(callback=callback) await future except IqError as err: print('Error: %s' % err.iq['error']['condition']) except IqTimeout: print('Error: Request timed out') self.send_presence() print('Waiting for presence updates...\n') await asyncio.sleep(10) print('Roster for %s' % self.boundjid.bare) groups = self.client_roster.groups() for group in groups: print('\n%s' % group) print('-' * 72) for jid in groups[group]: sub = self.client_roster[jid][ 'subscription'] name = self.client_roster[jid]['name'] if self.client_roster[jid]['name']: print(' %s (%s) [%s]' % (name, jid, sub)) else: print(' %s [%s]' % (jid, sub)) connections = self.client_roster.presence( jid) for res, pres in connections.items(): show = 'available' if pres['show']: show = pres['show'] print(' - %s (%s)' % (res, show)) if pres['status']: print(' %s' % pres['status']) self.disconnect()
def abort(self): """ Forcibly close the connection """ if self.transport: self.transport.close() self.transport.abort() self.event("killed") self.disconnected.set_result(True) self.disconnected = asyncio.Future()
async def start(self, event): future = asyncio.Future() def callback(result): future.set_result(None) try: self.get_roster(callback=callback) await future except IqError as err: print('Error: %s' % err.iq['error']['condition']) except IqTimeout: print('Error: Request timed out') self.send_presence() print('Cargando usuarios...\n') await asyncio.sleep(10) print('Roster para %s' % self.boundjid.bare) groups = self.client_roster.groups() for group in groups: print('\n%s' % group) print('-' * 72) for jid in groups[group]: sub = self.client_roster[jid]['subscription'] name = self.client_roster[jid]['name'] if self.client_roster[jid]['name']: print(' %s (%s) [%s]' % (name, jid, sub)) else: print(' %s [%s]' % (jid, sub)) connections = self.client_roster.presence(jid) for res, pres in connections.items(): show = 'available' if pres['show']: show = pres['show'] print(' - %s (%s)' % (res, show)) if pres['status']: print(' %s' % pres['status']) self.send_presence() self.get_roster() #funcion para Agregar o Ver Detalles si se presiona 1 Se agrega y 2 se ven Detalles print("Agregar usuario") print("_______________________________________") pregunta = input("Deseas agregar un nuevo usuario (1) o ver Detalles de Usuario (2)") if pregunta == "1": newuser = input("Ingresa un nuevo usuario >>") #para agregar usuario era simplemente un send_presence del nuevo usuario con tipo subscribe xmpp.send_presence(pto=newuser, ptype = 'subscribe') print("Se a ingresado nuevo usuario") os.system("python menu.py") sys.exit() if pregunta =="2": #para ver el contacto ingresar al client_roster y dentro del client_roster buscamos el userdata en base a como se llama userdata = input("Ingrese el contacto que desea ver detalles: ") userroster = self.client_roster print("Detalles de usuario" + userdata + " :") print(userroster[userdata]) os.system("python menu.py") sys.exit()
def abort(self): """ Forcibly close the connection """ self.cancel_connection_attempt() if self.transport: self.transport.close() self.transport.abort() self.event("killed") self.disconnected.set_result(True) self.disconnected = asyncio.Future() self.event("disconnected", self.disconnect_reason)
async def wait_until(self, event: str, timeout=30) -> Any: """Utility method to wake on the next firing of an event. (Registers a disposable handler on it) :param str event: Event to wait on. :param int timeout: Timeout """ fut = asyncio.Future() self.add_event_handler( event, fut.set_result, disposable=True, ) return await asyncio.wait_for(fut, timeout)
async def start(self, event): future = asyncio.Future() def callback(result): future.set_result(None) try: self.get_roster(callback=callback) await future except IqError as err: print('Error: %s' % err.iq['error']['condition']) except IqTimeout: print('Error: Request timed out') self.send_presence() print('Waiting for presence updates...\n') await asyncio.sleep(10) print('Roster for %s' % self.boundjid.bare) groups = self.client_roster.groups() for group in groups: print('\n%s' % group) print('-' * 72) for jid in groups[group]: sub = self.client_roster[jid]['subscription'] name = self.client_roster[jid]['name'] if self.client_roster[jid]['name']: print(' %s (%s) [%s]' % (name, jid, sub)) else: print(' %s [%s]' % (jid, sub)) connections = self.client_roster.presence(jid) for res, pres in connections.items(): show = 'available' if pres['show']: show = pres['show'] print(' - %s (%s)' % (res, show)) if pres['status']: print(' %s' % pres['status']) self.disconnect()
def send(self, callback=None, timeout=None, timeout_callback=None): """Send an <iq> stanza over the XML stream. A callback handler can be provided that will be executed when the Iq stanza's result reply is received. Returns a future which result will be set to the result Iq if it is of type 'get' or 'set' (when it is received), or a future with the result set to None if it has another type. Overrides StanzaBase.send :param function callback: Optional reference to a stream handler function. Will be executed when a reply stanza is received. :param int timeout: The length of time (in seconds) to wait for a response before the timeout_callback is called, instead of the regular callback :param function timeout_callback: Optional reference to a stream handler function. Will be executed when the timeout expires before a response has been received for the originally-sent IQ stanza. :rtype: asyncio.Future """ if self.stream.session_bind_event.is_set(): matcher = MatchIDSender({ 'id': self['id'], 'self': self.stream.boundjid, 'peer': self['to'] }) else: matcher = MatcherId(self['id']) future = asyncio.Future() def callback_success(result): if result['type'] == 'error': future.set_exception(IqError(result)) else: future.set_result(result) if timeout is not None: self.stream.cancel_schedule('IqTimeout_%s' % self['id']) if callback is not None: callback(result) def callback_timeout(): future.set_exception(IqTimeout(self)) self.stream.remove_handler('IqCallback_%s' % self['id']) if timeout_callback is not None: timeout_callback(self) if self['type'] in ('get', 'set'): handler_name = 'IqCallback_%s' % self['id'] if asyncio.iscoroutinefunction(callback): constr = CoroutineCallback else: constr = Callback if timeout is not None: self.stream.schedule('IqTimeout_%s' % self['id'], timeout, callback_timeout, repeat=False) handler = constr(handler_name, matcher, callback_success, once=True) self.stream.register_handler(handler) else: future.set_result(None) StanzaBase.send(self) return future
def __init__(self, host='', port=0): # The asyncio.Transport object provided by the connection_made() # callback when we are connected self.transport = None # The socket that is used internally by the transport object self.socket = None self.connect_loop_wait = 0 self.parser = None self.xml_depth = 0 self.xml_root = None self.force_starttls = None self.disable_starttls = None self.waiting_queue = asyncio.Queue() # A dict of {name: handle} self.scheduled_events = {} self.ssl_context = ssl.create_default_context() self.ssl_context.check_hostname = False self.ssl_context.verify_mode = ssl.CERT_NONE # The event to trigger when the create_connection() succeeds. It can # be "connected" or "tls_success" depending on the step we are at. self.event_when_connected = "connected" #: The list of accepted ciphers, in OpenSSL Format. #: It might be useful to override it for improved security #: over the python defaults. self.ciphers = None #: Path to a file containing certificates for verifying the #: server SSL certificate. A non-``None`` value will trigger #: certificate checking. #: #: .. note:: #: #: On Mac OS X, certificates in the system keyring will #: be consulted, even if they are not in the provided file. self.ca_certs = None #: Path to a file containing a client certificate to use for #: authenticating via SASL EXTERNAL. If set, there must also #: be a corresponding `:attr:keyfile` value. self.certfile = None #: Path to a file containing the private key for the selected #: client certificate to use for authenticating via SASL EXTERNAL. self.keyfile = None self._der_cert = None # The asyncio event loop self._loop = None #: The default port to return when querying DNS records. self.default_port = int(port) #: The domain to try when querying DNS records. self.default_domain = '' #: The expected name of the server, for validation. self._expected_server_name = '' self._service_name = '' #: The desired, or actual, address of the connected server. self.address = (host, int(port)) #: Enable connecting to the server directly over SSL, in #: particular when the service provides two ports: one for #: non-SSL traffic and another for SSL traffic. self.use_ssl = False #: If set to ``True``, attempt to connect through an HTTP #: proxy based on the settings in :attr:`proxy_config`. self.use_proxy = False #: If set to ``True``, attempt to use IPv6. self.use_ipv6 = True #: If set to ``True``, allow using the ``dnspython`` DNS library #: if available. If set to ``False``, the builtin DNS resolver #: will be used, even if ``dnspython`` is installed. self.use_aiodns = True #: Use CDATA for escaping instead of XML entities. Defaults #: to ``False``. self.use_cdata = False #: An optional dictionary of proxy settings. It may provide: #: :host: The host offering proxy services. #: :port: The port for the proxy service. #: :username: Optional username for accessing the proxy. #: :password: Optional password for accessing the proxy. self.proxy_config = {} #: The default namespace of the stream content, not of the #: stream wrapper itself. self.default_ns = '' self.default_lang = None self.peer_default_lang = None #: The namespace of the enveloping stream element. self.stream_ns = '' #: The default opening tag for the stream element. self.stream_header = "<stream>" #: The default closing tag for the stream element. self.stream_footer = "</stream>" #: If ``True``, periodically send a whitespace character over the #: wire to keep the connection alive. Mainly useful for connections #: traversing NAT. self.whitespace_keepalive = True #: The default interval between keepalive signals when #: :attr:`whitespace_keepalive` is enabled. self.whitespace_keepalive_interval = 300 #: Flag for controlling if the session can be considered ended #: if the connection is terminated. self.end_session_on_disconnect = True #: A mapping of XML namespaces to well-known prefixes. self.namespace_map = {StanzaBase.xml_ns: 'xml'} self.__root_stanza = [] self.__handlers = [] self.__event_handlers = {} self.__filters = {'in': [], 'out': [], 'out_sync': []} # Current connection attempt (Future) self._current_connection_attempt = None #: A list of DNS results that have not yet been tried. self.dns_answers = None #: The service name to check with DNS SRV records. For #: example, setting this to ``'xmpp-client'`` would query the #: ``_xmpp-client._tcp`` service. self.dns_service = None #: The reason why we are disconnecting from the server self.disconnect_reason = None #: An asyncio Future being done when the stream is disconnected. self.disconnected = asyncio.Future() self.add_event_handler('disconnected', self._remove_schedules) self.add_event_handler('session_start', self._start_keepalive)
def _set_disconnected_future(self): """Set the self.disconnected future on disconnect""" if not self.disconnected.done(): self.disconnected.set_result(True) self.disconnected = asyncio.Future()