# slixmpp.xmlstream.handler.waiter# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# Part of Slixmpp: The Slick XMPP Library# :copyright: (c) 2011 Nathanael C. Fritz# :license: MIT, see LICENSE for more detailsfrom__future__importannotationsimportloggingfromasyncioimportEvent,wait_for,TimeoutErrorfromtypingimportOptional,TYPE_CHECKING,Unionfromxml.etree.ElementTreeimportElementimportslixmppfromslixmpp.xmlstream.stanzabaseimportStanzaBasefromslixmpp.xmlstream.handler.baseimportBaseHandlerfromslixmpp.xmlstream.matcher.baseimportMatcherBaseifTYPE_CHECKING:fromslixmpp.xmlstream.xmlstreamimportXMLStreamlog=logging.getLogger(__name__)
[docs]classWaiter(BaseHandler):""" The Waiter handler allows an event handler to block until a particular stanza has been received. The handler will either be given the matched stanza, or ``False`` if the waiter has timed out. :param string name: The name of the handler. :param matcher: A :class:`~slixmpp.xmlstream.matcher.base.MatcherBase` derived object for matching stanza objects. :param stream: The :class:`~slixmpp.xmlstream.xmlstream.XMLStream` instance this handler should monitor. """_event:Eventdef__init__(self,name:str,matcher:MatcherBase,stream:Optional[XMLStream]=None):BaseHandler.__init__(self,name,matcher,stream=stream)self._event=Event()
[docs]defprerun(self,payload:StanzaBase)->None:"""Store the matched stanza when received during processing. :param payload: The matched :class:`~slixmpp.xmlstream.stanzabase.StanzaBase` object. """ifnotself._event.is_set():self._event.set()self._payload=payload
[docs]defrun(self,payload:StanzaBase)->None:"""Do not process this handler during the main event loop."""pass
[docs]asyncdefwait(self,timeout:Optional[int]=None)->Optional[StanzaBase]:"""Block an event handler while waiting for a stanza to arrive. Be aware that this will impact performance if called from a non-threaded event handler. Will return either the received stanza, or ``False`` if the waiter timed out. :param int timeout: The number of seconds to wait for the stanza to arrive. Defaults to the the stream's :class:`~slixmpp.xmlstream.xmlstream.XMLStream.response_timeout` value. """stream_ref=self.streamifstream_refisNone:raiseValueError('wait() called without a stream')stream=stream_ref()ifstreamisNone:raiseValueError('wait() called without a stream')iftimeoutisNone:timeout=slixmpp.xmlstream.RESPONSE_TIMEOUTtry:awaitwait_for(self._event.wait(),timeout,)exceptTimeoutError:log.warning("Timed out waiting for %s",self.name)stream.remove_handler(self.name)returnself._payload
[docs]defcheck_delete(self)->bool:"""Always remove waiters after use."""returnTrue