with self.lock:<EOL><INDENT>if self.initiator:<EOL><INDENT>if self._output_state is None:<EOL><INDENT>self._initiate()<EOL><DEDENT><DEDENT><DEDENT>

Called when transport has been connected.

        Send the stream head if initiator.


event.stream = self<EOL>logger.debug(u"<STR_LIT>".format(event))<EOL>self.settings["<STR_LIT>"].put(event)<EOL>return False<EOL>

Handle a stream event.

        Called when connection state is changed.

        Should not be called with self.lock acquired!


<EOL>return unicode(uuid.uuid4())<EOL>

Generate a random and unique stream ID.

        :return: the id string generated.


self.transport.send_element(element)<EOL>

Same as `write_element` but with `lock` already acquired.


def __init__(self, stanza_namespace, stanza_route, handlers,<EOL>settings = None):

XMLStreamHandler.__init__(self)<EOL>self.lock = threading.RLock()<EOL>if settings is None:<EOL><INDENT>settings = XMPPSettings()<EOL><DEDENT>self.settings = settings<EOL>self.stanza_namespace = stanza_namespace<EOL>self._stanza_namespace_p = "<STR_LIT>".format(stanza_namespace)<EOL>self.stanza_route = stanza_route<EOL>self.handlers = handlers<EOL>self._stream_feature_handlers = []<EOL>for handler in handlers:<EOL><INDENT>if isinstance(handler, StreamFeatureHandler):<EOL><INDENT>self._stream_feature_handlers.append(handler)<EOL><DEDENT><DEDENT>self.me = None<EOL>self.peer = None<EOL>self.stream_id = None<EOL>self.initiator = None<EOL>self.features = None<EOL>self.authenticated = False<EOL>self.peer_authenticated = False<EOL>self.tls_established = False<EOL>self.auth_method_used = None<EOL>self.version = None<EOL>self.language = None<EOL>self.peer_language = None<EOL>self.transport = None<EOL>self._input_state = None<EOL>self._output_state = None<EOL>self._element_handlers = {}<EOL>

Initialize StreamBase object

        :Parameters:
          - `stanza_namespace`: stream's default namespace URI ("jabber:client"
            for client, "jabber:server" for server, etc.)
          - `stanza_route`: object to handle received stanzas
          - `handlers`: objects to handle the stream events and elements
          - `settings`: extra settings
        :Types:
          - `stanza_namespace`: `unicode`
          - `stanza_route`: `StanzaRoute`
          - `settings`: XMPPSettings
          - `handlers`: `list` of objects


with self.lock:<EOL><INDENT>self._write_element(element)<EOL><DEDENT>

Write XML `element` to the stream.

        :Parameters:
            - `element`: Element node to send.
        :Types:
            - `element`: :etree:`ElementTree.Element`


with self.lock:<EOL><INDENT>self.transport = transport<EOL>transport.set_target(self)<EOL>self.me = JID(myname)<EOL>self.initiator = False<EOL>self._setup_stream_element_handlers()<EOL><DEDENT>

Receive an XMPP connection over the `transport`.

        :Parameters:
            - `transport`: an XMPP transport instance
            - `myname`: local stream endpoint name.


self.send_stream_error("<STR_LIT>")<EOL>raise StreamParseError(descr)<EOL>

Called when an error is encountered in the stream.

        :Parameters:
            - `descr`: description of the error
        :Types:
            - `descr`: `unicode`


tag = element.tag<EOL>if tag in self._element_handlers:<EOL><INDENT>handler = self._element_handlers[tag]<EOL>logger.debug("<STR_LIT>"<EOL>.format(element, handler))<EOL>handled = handler(self, element)<EOL>if handled:<EOL><INDENT>return<EOL><DEDENT><DEDENT>if tag.startswith(self._stanza_namespace_p):<EOL><INDENT>stanza = stanza_factory(element, self, self.language)<EOL>self.uplink_receive(stanza)<EOL><DEDENT>elif tag == ERROR_TAG:<EOL><INDENT>error = StreamErrorElement(element)<EOL>self.process_stream_error(error)<EOL><DEDENT>elif tag == FEATURES_TAG:<EOL><INDENT>logger.debug("<STR_LIT>".format(serialize(element)))<EOL>self._got_features(element)<EOL><DEDENT>else:<EOL><INDENT>logger.debug("<STR_LIT>".format(serialize(element)))<EOL>logger.debug("<STR_LIT>".format(<EOL>self._element_handlers))<EOL><DEDENT>

Process first level element of the stream.

        The element may be stream error or features, StartTLS
        request/response, SASL request/response or a stanza.

        :Parameters:
            - `element`: XML element
        :Types:
            - `element`: :etree:`ElementTree.Element`


self.features = self._make_stream_features()<EOL>self._write_element(self.features)<EOL>

Send stream <features/>.

        [receiving entity only]


def set_peer_authenticated(self, peer, restart_stream = False):

with self.lock:<EOL><INDENT>self.peer_authenticated = True<EOL>self.peer = peer<EOL>if restart_stream:<EOL><INDENT>self._restart_stream()<EOL><DEDENT><DEDENT>self.event(AuthenticatedEvent(self.peer))<EOL>

Mark the other side of the stream authenticated as `peer`

        :Parameters:
            - `peer`: local JID just authenticated
            - `restart_stream`: `True` when stream should be restarted (needed
              after SASL authentication)
        :Types:
            - `peer`: `JID`
            - `restart_stream`: `bool`


self._setup_stream_element_handlers()<EOL>self._send_stream_start()<EOL>

Initiate an XMPP connection over a connected `transport`.

        [ called with `lock` acquired ]


def request_software_version(stanza_processor, target_jid, callback,<EOL>error_callback = None):

stanza = Iq(to_jid = target_jid, stanza_type = "<STR_LIT>")<EOL>payload = VersionPayload()<EOL>stanza.set_payload(payload)<EOL>def wrapper(stanza):<EOL><INDENT>"""<STR_LIT>"""<EOL>payload = stanza.get_payload(VersionPayload)<EOL>if payload is None:<EOL><INDENT>if error_callback:<EOL><INDENT>error_callback(stanza)<EOL><DEDENT>else:<EOL><INDENT>logger.warning("<STR_LIT>")<EOL><DEDENT><DEDENT>else:<EOL><INDENT>callback(payload)<EOL><DEDENT><DEDENT>stanza_processor.set_response_handlers(stanza, wrapper, error_callback)<EOL>stanza_processor.send(stanza)<EOL>

Request software version information from a remote entity.

    When a valid response is received the `callback` will be handled
    with a `VersionPayload` instance as its only argument. The object will
    provide the requested infromation.

    In case of error stanza received or invalid response the `error_callback`
    (if provided) will be called with the offending stanza (which can
    be ``<iq type='error'/>`` or ``<iq type='result'>``) as its argument.

    The same function will be called on timeout, with the argument set to
    `None`.

    :Parameters:
        - `stanza_processor`: a object used to send the query and handle
          response. E.g. a `pyxmpp2.client.Client` instance
        - `target_jid`: the JID of the entity to query
        - `callback`: function to be called with a valid response
        - `error_callback`: function to be called on error
    :Types:
        - `stanza_processor`: `StanzaProcessor`
        - `target_jid`: `JID`


<EOL>if "<STR_LIT>" not in settings:<EOL><INDENT>return unicode(pyxmpp2_version)<EOL><DEDENT>else:<EOL><INDENT>return u"<STR_LIT>".format(pyxmpp2_version)<EOL><DEDENT>

Factory for the :r:`software_version setting` default.


Initialize the Delay object.

:Parameters:
    - `node_or_datetime`: an XML node to parse or the timestamp.
    - `delay_from`: JID of the entity which adds the delay mark
      (when `node_or_datetime` is a timestamp).
    - `reason`: reason of the delay (when `node_or_datetime` is a
      timestamp).
    - `utc`: if `True` then the timestamp is assumed to be UTC,
      otherwise it is assumed to be local time.
:Types:
    - `node_or_datetime`: `libxml2.xmlNode` or `datetime.datetime`
    - `delay_from`: `pyxmpp.JID`
    - `reason`: `unicode`
    - `utc`: `bool`


warnings.warn("<STR_LIT>", DeprecationWarning, stacklevel=<NUM_LIT:1>)<EOL>


if not category:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>category = str(category)<EOL>self.xmlnode.setProp("<STR_LIT>", category.encode("<STR_LIT:utf-8>"))<EOL>

Set the category of the item.

        :Parameters:
            - `category`: the new category.
        :Types:
            - `category`: `unicode`


pass<EOL>


var = self.xmlnode.prop("<STR_LIT:name>")<EOL>if not var:<EOL><INDENT>var = "<STR_LIT>"<EOL><DEDENT>return var.decode("<STR_LIT:utf-8>")<EOL>

Get the name of the item.

        :return: the name of the item or `None`.
        :returntype: `unicode`


def __init__(self,xmlnode_or_node=None, parent=None, doc=None):

Initialize an `DiscoInfo` object.

        Wrap an existing disco#info XML element or create a new one.

        :Parameters:
            - `xmlnode_or_node`: XML node to be wrapped into `self` or an item
              node name.
            - `parent`: parent node for the `DiscoInfo` element.
            - `doc`: document for the `DiscoInfo` element.
        :Types:
            - `xmlnode_or_node`: `libxml2.xmlNode` or `unicode`
            - `parent`: `libxml2.xmlNode`
            - `doc`: `libxml2.xmlDoc`


Remove `self` from the containing `DiscoItems` object.


if not var:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if '<STR_LIT:">' not in var:<EOL><INDENT>expr='<STR_LIT>' % (var,)<EOL><DEDENT>elif "<STR_LIT:'>" not in var:<EOL><INDENT>expr="<STR_LIT>" % (var,)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>l=self.xpath_ctxt.xpathEval(to_utf8(expr))<EOL>if l:<EOL><INDENT>return True<EOL><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT>

Check if `self` contains the named feature.

        :Parameters:
            - `var`: the feature name.
        :Types:
            - `var`: `unicode`

        :return: `True` if the feature is found in `self`.
        :returntype: `bool`


return DiscoItem(self,jid,node,name,action)<EOL>

Add a new item to the `DiscoItems` object.

        :Parameters:
            - `jid`: item JID.
            - `node`: item node name.
            - `name`: item name.
            - `action`: action for a "disco push".
        :Types:
            - `jid`: `pyxmpp.JID`
            - `node`: `unicode`
            - `name`: `unicode`
            - `action`: `unicode`

        :returns: the item created.
        :returntype: `DiscoItem`.


return DiscoIdentity(self,item_name,item_category,item_type)<EOL>

Add an identity to the `DiscoInfo` object.

        :Parameters:
            - `item_name`: name of the item.
            - `item_category`: category of the item.
            - `item_type`: type of the item.
        :Types:
            - `item_name`: `unicode`
            - `item_category`: `unicode`
            - `item_type`: `unicode`

        :returns: the identity created.
        :returntype: `DiscoIdentity`


node = self.xmlnode.prop("<STR_LIT>")<EOL>if node is None:<EOL><INDENT>return None<EOL><DEDENT>return node.decode("<STR_LIT:utf-8>")<EOL>

Get the node of the item.

        :return: the node of the item or `None`.
        :returntype: `unicode`


Remove `self` from the containing `DiscoInfo` object.


for identity in self.identities:<EOL><INDENT>identity.remove()<EOL><DEDENT>for identity in identities:<EOL><INDENT>try:<EOL><INDENT>self.add_identity(identity.name,identity.category,identity.type)<EOL><DEDENT>except AttributeError:<EOL><INDENT>self.add_identity(*identity)<EOL><DEDENT><DEDENT>

Set identities in the disco#info object.

        Remove all existing identities from `self`.

        :Parameters:
            - `identities`: list of identities or identity properties
              (jid,node,category,type,name).
        :Types:
            - `identities`: sequence of `DiscoIdentity` or sequence of sequences


action=self.xmlnode.prop("<STR_LIT:action>")<EOL>if action is None:<EOL><INDENT>return None<EOL><DEDENT>return action.decode("<STR_LIT:utf-8>")<EOL>

Get the action attribute of the item.

        :return: the action of the item or `None`.
        :returntype: `unicode`


Initialize an `DiscoItems` object.

        Wrap an existing disco#items XML element or create a new one.

        :Parameters:
            - `xmlnode_or_node`: XML node to be wrapped into `self` or an item
              node name.
        :Types:
            - `xmlnode_or_node`: `libxml2.xmlNode` or `unicode`


node = self.xmlnode.prop("<STR_LIT>")<EOL>if not node:<EOL><INDENT>return None<EOL><DEDENT>return node.decode("<STR_LIT:utf-8>")<EOL>

Get the node address of the `DiscoItems` object.

        :return: the node name.
        :returntype: `unicode`


jid = self.xmlnode.prop("<STR_LIT>")<EOL>return JID( jid.decode("<STR_LIT:utf-8>") )<EOL>

Get the JID of the item.

        :return: the JID of the item.
        :returntype: `JID`


if not var:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if '<STR_LIT:">' not in var:<EOL><INDENT>expr='<STR_LIT>' % (var,)<EOL><DEDENT>elif "<STR_LIT:'>" not in var:<EOL><INDENT>expr="<STR_LIT>" % (var,)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>l=self.xpath_ctxt.xpathEval(expr)<EOL>if not l:<EOL><INDENT>return<EOL><DEDENT>for f in l:<EOL><INDENT>f.unlinkNode()<EOL>f.freeNode()<EOL><DEDENT>

Remove a feature from `self`.

        :Parameters:
            - `var`: the feature name.
        :Types:
            - `var`: `unicode`


l=self.xpath_ctxt.xpathEval("<STR_LIT>")<EOL>if l is None:<EOL><INDENT>return False<EOL><DEDENT>for it in l:<EOL><INDENT>di=DiscoItem(self,it)<EOL>if di.jid==jid and di.node==node:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL>

Check if `self` contains an item.

        :Parameters:
            - `jid`: JID of the item.
            - `node`: node name of the item.
        :Types:
            - `jid`: `JID`
            - `node`: `libxml2.xmlNode`

        :return: `True` if the item is found in `self`.
        :returntype: `bool`


try:<EOL><INDENT>self.error(stanza.get_error())<EOL><DEDENT>except ProtocolError:<EOL><INDENT>from ..error import StanzaErrorNode<EOL>self.error(StanzaErrorNode("<STR_LIT>"))<EOL><DEDENT>

Handle disco error response.

        :Parameters:
            - `stanza`: the stanza received.
        :Types:
            - `stanza`: `pyxmpp.stanza.Stanza`


if action is None:<EOL><INDENT>if self.xmlnode.hasProp("<STR_LIT:action>"):<EOL><INDENT>self.xmlnode.unsetProp("<STR_LIT:action>")<EOL><DEDENT>return<EOL><DEDENT>if action not in ("<STR_LIT>","<STR_LIT>"):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>action = str(action)<EOL>self.xmlnode.setProp("<STR_LIT:action>", action.encode("<STR_LIT:utf-8>"))<EOL>

Set the action of the item.

        :Parameters:
            - `action`: the new action or `None`.
        :Types:
            - `action`: `unicode`


def _digest_auth_in_stage2(self, username, _unused, stanza):

Handle the second stage (<iq type='set'/>) of legacy "digest"
        authentication.

        [server only]


ClientStream._reset(self)<EOL>self.available_auth_methods = None<EOL>self.auth_stanza = None<EOL>self.registration_callback = None<EOL>

Reset the `LegacyClientStream` object state, making the object ready
        to handle new connections.


def _plain_auth_in_stage2(self, username, _unused, stanza):

Handle the second stage (<iq type='set'/>) of legacy "plain"
        authentication.

        [server only]


if self.authenticated:<EOL><INDENT>self.__logger.debug("<STR_LIT>")<EOL>return<EOL><DEDENT>self.__logger.debug("<STR_LIT>" % (self._auth_methods_left,))<EOL>if not self._auth_methods_left:<EOL><INDENT>raise LegacyAuthenticationError("<STR_LIT>")<EOL><DEDENT>method=self._auth_methods_left[<NUM_LIT:0>]<EOL>if method.startswith("<STR_LIT>"):<EOL><INDENT>return ClientStream._try_auth(self)<EOL><DEDENT>elif method not in ("<STR_LIT>","<STR_LIT>"):<EOL><INDENT>self._auth_methods_left.pop(<NUM_LIT:0>)<EOL>self.__logger.debug("<STR_LIT>" % method)<EOL>return self._try_auth()<EOL><DEDENT>elif self.available_auth_methods is not None:<EOL><INDENT>if method in self.available_auth_methods:<EOL><INDENT>self._auth_methods_left.pop(<NUM_LIT:0>)<EOL>self.auth_method_used=method<EOL>if method=="<STR_LIT>":<EOL><INDENT>self._digest_auth_stage2(self.auth_stanza)<EOL><DEDENT>else:<EOL><INDENT>self._plain_auth_stage2(self.auth_stanza)<EOL><DEDENT>self.auth_stanza=None<EOL>return<EOL><DEDENT>else:<EOL><INDENT>self.__logger.debug("<STR_LIT>" % method)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self._auth_stage1()<EOL><DEDENT>

Try to authenticate using the first one of allowed authentication
        methods left.

        [client only]


Do the second stage (<iq type='set'/>) of legacy "digest"
        authentication.

        [client only]


self.lock.acquire()<EOL>try:<EOL><INDENT>if "<STR_LIT>" not in self.auth_methods and "<STR_LIT>" not in self.auth_methods:<EOL><INDENT>iq=stanza.make_error_response("<STR_LIT>")<EOL>self.send(iq)<EOL>return<EOL><DEDENT>username=stanza.xpath_eval("<STR_LIT>",{"<STR_LIT:a>":"<STR_LIT>"})<EOL>if username:<EOL><INDENT>username=from_utf8(username[<NUM_LIT:0>].getContent())<EOL><DEDENT>resource=stanza.xpath_eval("<STR_LIT>",{"<STR_LIT:a>":"<STR_LIT>"})<EOL>if resource:<EOL><INDENT>resource=from_utf8(resource[<NUM_LIT:0>].getContent())<EOL><DEDENT>if not username or not resource:<EOL><INDENT>self.__logger.debug("<STR_LIT>")<EOL>iq=stanza.make_error_response("<STR_LIT>")<EOL>self.send(iq)<EOL>return<EOL><DEDENT>if stanza.xpath_eval("<STR_LIT>",{"<STR_LIT:a>":"<STR_LIT>"}):<EOL><INDENT>if "<STR_LIT>" not in self.auth_methods:<EOL><INDENT>iq=stanza.make_error_response("<STR_LIT>")<EOL>self.send(iq)<EOL>return<EOL><DEDENT>else:<EOL><INDENT>return self._plain_auth_in_stage2(username,resource,stanza)<EOL><DEDENT><DEDENT>if stanza.xpath_eval("<STR_LIT>",{"<STR_LIT:a>":"<STR_LIT>"}):<EOL><INDENT>if "<STR_LIT>" not in self.auth_methods:<EOL><INDENT>iq=stanza.make_error_response("<STR_LIT>")<EOL>self.send(iq)<EOL>return<EOL><DEDENT>else:<EOL><INDENT>return self._digest_auth_in_stage2(username,resource,stanza)<EOL><DEDENT><DEDENT><DEDENT>finally:<EOL><INDENT>self.lock.release()<EOL><DEDENT>

Handle the second stage (<iq type='set'/>) of legacy ("plain" or
        "digest") authentication.

        [server only]


Handle legacy authentication error.

        [client only]


Handle legacy authentication timeout.

        [client only]


Authenticate on the server.

        [component only]


Stream.accept(self,sock,None)<EOL>

Accept an incoming component connection.

        [server only]

        :Parameters:
            - `sock`: a listening socket.


def __init__(self, jid, secret, server, port, keepalive = <NUM_LIT:0>, owner = None):

Stream.__init__(self, "<STR_LIT>",<EOL>sasl_mechanisms = [],<EOL>tls_settings = None,<EOL>keepalive = keepalive,<EOL>owner = owner)<EOL>self.server=server<EOL>self.port=port<EOL>self.me=jid<EOL>self.secret=secret<EOL>self.process_all_stanzas=<NUM_LIT:1><EOL>self.__logger=logging.getLogger("<STR_LIT>")<EOL>

Initialize a `ComponentStream` object.

        :Parameters:
            - `jid`: JID of the component.
            - `secret`: authentication secret.
            - `server`: server address.
            - `port`: TCP port number on the server.
            - `keepalive`: keepalive interval. 0 to disable.
            - `owner`: `Client`, `Component` or similar object "owning" this stream.


if self.initiator:<EOL><INDENT>self._auth()<EOL><DEDENT>

Initialize authentication when the connection is established
        and we are the initiator.


if self.me.node or self.me.resource:<EOL><INDENT>raise Value("<STR_LIT>")<EOL><DEDENT>if not server:<EOL><INDENT>server=self.server<EOL><DEDENT>if not port:<EOL><INDENT>port=self.port<EOL><DEDENT>if not server or not port:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>Stream._connect(self,server,port,None,self.me)<EOL>

Same as `ComponentStream.connect` but assume `self.lock` is acquired.


def complete_xml_element(self, xmlnode, doc):

ns = xmlnode.ns()<EOL>if self.instructions is not None:<EOL><INDENT>xmlnode.newTextChild(ns, "<STR_LIT>", to_utf8(self.instructions))<EOL><DEDENT>if self.form:<EOL><INDENT>self.form.as_xml(xmlnode, doc)<EOL><DEDENT>if self.remove:<EOL><INDENT>xmlnode.newChild(ns, "<STR_LIT>", None)<EOL><DEDENT>else:<EOL><INDENT>if self.registered:<EOL><INDENT>xmlnode.newChild(ns, "<STR_LIT>", None)<EOL><DEDENT>for field in legacy_fields:<EOL><INDENT>value = getattr(self, field)<EOL>if value is not None:<EOL><INDENT>xmlnode.newTextChild(ns, field, to_utf8(value))<EOL><DEDENT><DEDENT><DEDENT>

Complete the XML node with `self` content.

        :Parameters:
            - `xmlnode`: XML node with the element being built. It has already
              right name and namespace, but no attributes or content.
            - `doc`: document to which the element belongs.
        :Types:
            - `xmlnode`: `libxml2.xmlNode`
            - `doc`: `libxml2.xmlDoc`


def get_form(self, form_type = "<STR_LIT>"):

if self.form:<EOL><INDENT>if self.form.type != form_type:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>return self.form<EOL><DEDENT>form = Form(form_type, instructions = self.instructions)<EOL>form.add_field("<STR_LIT>", [u"<STR_LIT>"], "<STR_LIT>")<EOL>for field in legacy_fields:<EOL><INDENT>field_type, field_label = legacy_fields[field]<EOL>value = getattr(self, field)<EOL>if value is None:<EOL><INDENT>continue<EOL><DEDENT>if form_type == "<STR_LIT>":<EOL><INDENT>if not value:<EOL><INDENT>value = None<EOL><DEDENT>form.add_field(name = field, field_type = field_type, label = field_label,<EOL>value = value, required = True)<EOL><DEDENT>else:<EOL><INDENT>form.add_field(name = field, value = value)<EOL><DEDENT><DEDENT>return form<EOL>

Return Data Form for the `Register` object.

        Convert legacy fields to a data form if `self.form` is `None`, return `self.form` otherwise.

        :Parameters:
            - `form_type`: If "form", then a form to fill-in should be
              returned. If "sumbit", then a form with submitted data.
        :Types:
            - `form_type`: `unicode`

        :return: `self.form` or a form created from the legacy fields
        :returntype: `pyxmpp.jabber.dataforms.Form`


if self.muc_child:<EOL><INDENT>self.muc_child.free_borrowed()<EOL>self.muc_child=None<EOL><DEDENT>if not self.xmlnode.children:<EOL><INDENT>return<EOL><DEDENT>n=self.xmlnode.children<EOL>while n:<EOL><INDENT>if n.name not in ("<STR_LIT:x>","<STR_LIT>"):<EOL><INDENT>n=n.next<EOL>continue<EOL><DEDENT>ns=n.ns()<EOL>if not ns:<EOL><INDENT>n=n.next<EOL>continue<EOL><DEDENT>ns_uri=ns.getContent()<EOL>if ns_uri in (MUC_NS,MUC_USER_NS,MUC_ADMIN_NS,MUC_OWNER_NS):<EOL><INDENT>n.unlinkNode()<EOL>n.freeNode()<EOL><DEDENT>n=n.next<EOL><DEDENT>

Remove the MUC specific stanza payload element.


Evaluate XPath expression in context of `self.xmlnode`.

:Parameters:
    - `expr`: the XPath expression
:Types:
    - `expr`: `unicode`

:return: the result of the expression evaluation.
:returntype: list of `libxml2.xmlNode`


if self.__class__ is MucStanzaExt:<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>self.xmlnode=None<EOL>self.muc_child=None<EOL>

Initialize a `MucStanzaExt` derived object.


for child in xml_element_iter(self.xmlnode.children):<EOL><INDENT>if get_node_ns_uri(child) == MUC_NS and child.name == "<STR_LIT>":<EOL><INDENT>child.unlinkNode()<EOL>child.freeNode()<EOL>break<EOL><DEDENT><DEDENT>if parameters.maxchars and parameters.maxchars < <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if parameters.maxstanzas and parameters.maxstanzas < <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if parameters.maxseconds and parameters.maxseconds < <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>hnode=self.xmlnode.newChild(self.xmlnode.ns(), "<STR_LIT>", None)<EOL>if parameters.maxchars is not None:<EOL><INDENT>hnode.setProp("<STR_LIT>", str(parameters.maxchars))<EOL><DEDENT>if parameters.maxstanzas is not None:<EOL><INDENT>hnode.setProp("<STR_LIT>", str(parameters.maxstanzas))<EOL><DEDENT>if parameters.maxseconds is not None:<EOL><INDENT>hnode.setProp("<STR_LIT>", str(parameters.maxseconds))<EOL><DEDENT>if parameters.since is not None:<EOL><INDENT>hnode.setProp("<STR_LIT>", parameters.since.strftime("<STR_LIT>"))<EOL><DEDENT>

Set history parameters.

Types:
    - `parameters`: `HistoryParameters`


for child in xml_element_iter(self.xmlnode.children):<EOL><INDENT>if get_node_ns_uri(child) == MUC_NS and child.name == "<STR_LIT:password>":<EOL><INDENT>child.unlinkNode()<EOL>child.freeNode()<EOL>break<EOL><DEDENT><DEDENT>if password is not None:<EOL><INDENT>self.xmlnode.newTextChild(self.xmlnode.ns(), "<STR_LIT:password>", to_utf8(password))<EOL><DEDENT>

Set password for the MUC request.

        :Parameters:
            - `password`: password
        :Types:
            - `password`: `unicode`


Initialize a `MucItem` object.

:Parameters:
    - `xmlnode_or_affiliation`: XML node to be pased or the affiliation of
      the user being described.
    - `role`: role of the user.
    - `jid`: JID of the user.
    - `nick`: nickname of the user.
    - `actor`: actor modyfying the user data.
    - `reason`: reason of change of the user data.
:Types:
    - `xmlnode_or_affiliation`: `libxml2.xmlNode` or `str`
    - `role`: `str`
    - `jid`: `JID`
    - `nick`: `unicode`
    - `actor`: `JID`
    - `reason`: `unicode`


self.xmlnode=None<EOL>


Free the data associated with this `MucIq` object.


self.clear_muc_child()<EOL>self.muc_child=MucUserX(parent=self.xmlnode)<EOL>return self.muc_child<EOL>

Create <x xmlns="...muc#user"/> element in the stanza.

:return: the element created.
:returntype: `MucUserX`


return self.xmlnode.serialize()<EOL>

Serialize `self` as XML.

:return: serialized `self.xmlnode`.
:returntype: `str`


Make the iq stanza a MUC room participant kick request.

:Parameters:
    - `nick`: nickname of user to kick.
    - `reason`: reason of the kick.
:Types:
    - `nick`: `unicode`
    - `reason`: `unicode`

:return: object describing the kick request details.
:returntype: `MucItem`


if not affiliation:<EOL><INDENT>affiliation=None<EOL><DEDENT>elif affiliation not in affiliations:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self.affiliation=affiliation<EOL>if not role:<EOL><INDENT>role=None<EOL><DEDENT>elif role not in roles:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self.role=role<EOL>if jid:<EOL><INDENT>self.jid=JID(jid)<EOL><DEDENT>else:<EOL><INDENT>self.jid=None<EOL><DEDENT>if actor:<EOL><INDENT>self.actor=JID(actor)<EOL><DEDENT>else:<EOL><INDENT>self.actor=None<EOL><DEDENT>self.nick=nick<EOL>self.reason=reason<EOL>

Initialize a `MucItem` object from a set of attributes.

        :Parameters:
            - `affiliation`: affiliation of the user.
            - `role`: role of the user.
            - `jid`: JID of the user.
            - `nick`: nickname of the user.
            - `actor`: actor modyfying the user data.
            - `reason`: reason of change of the user data.
        :Types:
            - `affiliation`: `str`
            - `role`: `str`
            - `jid`: `JID`
            - `nick`: `unicode`
            - `actor`: `JID`
            - `reason`: `unicode`


return MucIq(self)<EOL>


Initialize a `MucItem` object from an XML node.

        :Parameters:
            - `xmlnode`: the XML node.
        :Types:
            - `xmlnode`: `libxml2.xmlNode`


if not self.xmlnode.children:<EOL><INDENT>return<EOL><DEDENT>n=self.xmlnode.children<EOL>while n:<EOL><INDENT>ns=n.ns()<EOL>if ns and ns.getContent()!=MUC_USER_NS:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>n.unlinkNode()<EOL>n.freeNode()<EOL><DEDENT>n=n.next<EOL><DEDENT>

Clear the content of `self.xmlnode` removing all <item/>, <status/>, etc.


if not isinstance(item,MucItemBase):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>item.as_xml(self.xmlnode)<EOL>

Add an item to `self`.

        :Parameters:
            - `item`: the item to add.
        :Types:
            - `item`: `MucItemBase`


return MucPresence(self)<EOL>


self.handler.room_configuration_error(stanza)<EOL>

Process error response for a room configuration request.

:Parameters:
    - `stanza`: the stanza received.
:Types:
    - `stanza`: `Presence`


pass<EOL>

Called whenever user's presence changes (includes nick, role or
affiliation changes).

:Parameters:
    - `user`: MucRoomUser object describing the user.
    - `stanza`: the stanza received.

:Types:
    - `user`: `MucRoomUser`
    - `stanza`: `pyxmpp.stanza.Stanza`


fr=stanza.get_from()<EOL>if not fr.resource:<EOL><INDENT>return<EOL><DEDENT>nick=fr.resource<EOL>user=self.users.get(nick)<EOL>if user:<EOL><INDENT>old_user=MucRoomUser(user)<EOL>user.update_presence(stanza)<EOL>self.handler.presence_changed(user,stanza)<EOL>if user.new_nick:<EOL><INDENT>mc=stanza.get_muc_child()<EOL>if isinstance(mc,MucUserX):<EOL><INDENT>renames=[i for i in mc.get_items() if isinstance(i,MucStatus) and i.code==<NUM_LIT>]<EOL>if renames:<EOL><INDENT>self.users[user.new_nick]=user<EOL>del self.users[nick]<EOL>return<EOL><DEDENT><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>old_user=None<EOL>user=MucRoomUser(stanza)<EOL>self.users[user.nick]=user<EOL>self.handler.presence_changed(user,stanza)<EOL><DEDENT>if fr==self.room_jid and self.joined:<EOL><INDENT>self.joined=False<EOL>self.handler.user_left(user,stanza)<EOL>self.manager.forget(self)<EOL>self.me=user<EOL><DEDENT>elif old_user:<EOL><INDENT>self.handler.user_left(user,stanza)<EOL><DEDENT>

Process <presence type="unavailable"/> received from the room.

:Parameters:
    - `stanza`: the stanza received.
:Types:
    - `stanza`: `MucPresence`


pass<EOL>

Called when a new participant joins the room.

:Parameters:
    - `user`: the user joining.
    - `stanza`: the stanza received.

:Types:
    - `user`: `MucRoomUser`
    - `stanza`: `pyxmpp.stanza.Stanza`


_unused = stream<EOL>if self.joined and self.handler:<EOL><INDENT>self.handler.user_left(self.me,None)<EOL><DEDENT>self.joined=False<EOL>

Called when current stream changes.

Mark the room not joined and inform `self.handler` that it was left.

:Parameters:
    - `stream`: the new stream.
:Types:
    - `stream`: `pyxmpp.stream.Stream`


m=Message(to_jid=self.room_jid.bare(),stanza_type="<STR_LIT>",subject=subject)<EOL>self.manager.stream.send(m)<EOL>

Send a subject change request to the room.

:Parameters:
    - `subject`: the new subject.
:Types:
    - `subject`: `unicode`


self.jid=stream.me<EOL>self.stream=stream<EOL>for r in self.rooms.values():<EOL><INDENT>r.set_stream(stream)<EOL><DEDENT>

Change the stream assigned to `self`.

:Parameters:
    - `stream`: the new stream to be assigned to `self`.
:Types:
    - `stream`: `pyxmpp.stream.Stream`


fr=stanza.get_from()<EOL>key=fr.bare().as_unicode()<EOL>rs=self.rooms.get(key)<EOL>if not rs:<EOL><INDENT>return False<EOL><DEDENT>rs.process_error_message(stanza)<EOL>return True<EOL>

Process an error message from a MUC room.

        :Parameters:
            - `stanza`: the stanza received.
        :Types:
            - `stanza`: `Message`

        :return: `True` if the message was properly recognized as directed to
            one of the managed rooms, `False` otherwise.
        :returntype: `bool`


pass<EOL>

Called after a user nick has been changed.

:Parameters:
    - `user`: the user (after update).
    - `old_nick`: the old nick.
    - `stanza`: the stanza received.

:Types:
    - `user`: `MucRoomUser`
    - `old_nick`: `unicode`
    - `stanza`: `pyxmpp.stanza.Stanza`


return self.room_jid.resource<EOL>

Get own nick.

:return: own nick.
:returntype: `unicode`


return self.room_jid==other.room_jid<EOL>

Check if two `MucRoomUser` objects describe the same user in the
        same room.

        :Parameters:
            - `other`: the user object to compare `self` with.
        :Types:
            - `other`: `MucRoomUser`

        :return: `True` if the two object describe the same user.
        :returntype: `bool`


m=Message(to_jid=self.room_jid.bare(),stanza_type="<STR_LIT>",body=body)<EOL>self.manager.stream.send(m)<EOL>

Send a message to the room.

:Parameters:
    - `body`: the message body.
:Types:
    - `body`: `unicode`


Assign MUC stanza handlers to the `self.stream`.

:Parameters:
    - `priority`: priority for the handlers.
:Types:
    - `priority`: `int`


pass<EOL>

Called when a requested configuration form is received.

The form, after filling-in shoul be passed to `self.room_state.configure_room`.

:Parameters:
    - `form`: the configuration form.

:Types:
    - `form`: `pyxmpp.jabber.dataforms.Form`


self.handler.error(stanza)<EOL>

Process error response for a room configuration form request.

:Parameters:
    - `stanza`: the stanza received.
:Types:
    - `stanza`: `Presence`


pass<EOL>

Called when a role of an user has been changed.

:Parameters:
    - `user`: the user (after update).
    - `old_role`: user's role before update.
    - `new_role`: user's role after update.
    - `stanza`: the stanza received.

:Types:
    - `user`: `MucRoomUser`
    - `old_role`: `unicode`
    - `new_role`: `unicode`
    - `stanza`: `pyxmpp.stanza.Stanza`


new_room_jid=JID(self.room_jid.node,self.room_jid.domain,new_nick)<EOL>p=Presence(to_jid=new_room_jid)<EOL>self.manager.stream.send(p)<EOL>

Send a nick change request to the room.

:Parameters:
    - `new_nick`: the new nickname requested.
:Types:
    - `new_nick`: `unicode`


Process <message type="groupchat"/> received from the room.

:Parameters:
    - `stanza`: the stanza received.
:Types:
    - `stanza`: `Message`


if nick is None:<EOL><INDENT>return self.room_jid<EOL><DEDENT>return JID(self.room_jid.node,self.room_jid.domain,nick)<EOL>

Get own room JID or a room JID for given `nick`.

:Parameters:
    - `nick`: a nick for which the room JID is requested.
:Types:
    - `nick`: `unicode`

:return: the room JID.
:returntype: `JID`


if self.joined:<EOL><INDENT>p=MucPresence(to_jid=self.room_jid,stanza_type="<STR_LIT>")<EOL>self.manager.stream.send(p)<EOL><DEDENT>


fr=stanza.get_from()<EOL>key=fr.bare().as_unicode()<EOL>rs=self.rooms.get(key)<EOL>if not rs:<EOL><INDENT>return False<EOL><DEDENT>rs.process_available_presence(MucPresence(stanza))<EOL>return True<EOL>

Process an available presence from a MUC room.

        :Parameters:
            - `stanza`: the stanza received.
        :Types:
            - `stanza`: `Presence`

        :return: `True` if the stanza was properly recognized as generated by
            one of the managed rooms, `False` otherwise.
        :returntype: `bool`


Initialize a `MucRoomUser` object.

:Parameters:
    - `presence_or_user_or_jid`: a MUC presence stanza with user
      information, a user object to copy or a room JID of a user.
:Types:
    - `presence_or_user_or_jid`: `MucPresence` or `MucRoomUser` or
      `JID`

When `presence_or_user_or_jid` is a JID user's
role and affiliation are set to "none".


Initialize a `MucRoomState` object.

:Parameters:
    - `manager`: an object to manage this room.
    - `own_jid`: real JID of the owner (client using this class).
    - `room_jid`: room JID of the owner (provides the room name and
      the nickname).
    - `handler`: an object to handle room events.
:Types:
    - `manager`: `MucRoomManager`
    - `own_jid`: JID
    - `room_jid`: JID
    - `handler`: `MucRoomHandler`


pass<EOL>

Called after a successfull room configuration.


if self.uri:<EOL><INDENT>return rfc2425encode(self.name,self.uri,{"<STR_LIT:value>":"<STR_LIT>"})<EOL><DEDENT>elif self.sound:<EOL><INDENT>return rfc2425encode(self.name,self.sound)<EOL><DEDENT>

RFC2426-encode the field content.

        :return: the field in the RFC 2426 format.
        :returntype: `str`


def __init__(self,name, value, rfc2425parameters = None, empty_ok = False):

_unused = rfc2425parameters<EOL>VCardField.__init__(self,name)<EOL>if isinstance(value,libxml2.xmlNode):<EOL><INDENT>value=value.getContent()<EOL>if value:<EOL><INDENT>self.value=unicode(value,"<STR_LIT:utf-8>","<STR_LIT:replace>").strip()<EOL><DEDENT>else:<EOL><INDENT>self.value=u"<STR_LIT>"<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.value=value<EOL><DEDENT>if not self.value and not empty_ok:<EOL><INDENT>raise Empty("<STR_LIT>")<EOL><DEDENT>

Initialize a `VCardString` object.

        :Parameters:
            - `name`: field name
            - `value`: field value as string or an XML node
            - `rfc2425parameters`: optional RFC 2425 parameters
        :Types:
            - `name`: `str`
            - `value`: `str` or `libxml2.xmlNode`
            - `rfc2425parameters`: `dict`


def complete_xml_element(self, xmlnode, _unused):

for _unused1, value in self.content.items():<EOL><INDENT>if value is None:<EOL><INDENT>continue<EOL><DEDENT>if type(value) is list:<EOL><INDENT>for v in value:<EOL><INDENT>v.as_xml(xmlnode)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>value.as_xml(xmlnode)<EOL><DEDENT><DEDENT>

Complete the XML node with `self` content.

        Should be overriden in classes derived from `StanzaPayloadObject`.

        :Parameters:
            - `xmlnode`: XML node with the element being built. It has already
              right name and namespace, but no attributes or content.
            - `_unused`: document to which the element belongs.
        :Types:
            - `xmlnode`: `libxml2.xmlNode`
            - `_unused`: `libxml2.xmlDoc`


ns=get_node_ns(data)<EOL>if ns and ns.getContent()!=VCARD_NS:<EOL><INDENT>raise ValueError("<STR_LIT>" % (VCARD_NS,))<EOL><DEDENT>if data.name!="<STR_LIT>":<EOL><INDENT>raise ValueError("<STR_LIT>" % (data.name,))<EOL><DEDENT>n=data.children<EOL>dns=get_node_ns(data)<EOL>while n:<EOL><INDENT>if n.type!='<STR_LIT>':<EOL><INDENT>n=n.next<EOL>continue<EOL><DEDENT>ns=get_node_ns(n)<EOL>if (ns and dns and ns.getContent()!=dns.getContent()):<EOL><INDENT>n=n.next<EOL>continue<EOL><DEDENT>if not self.components.has_key(n.name):<EOL><INDENT>n=n.next<EOL>continue<EOL><DEDENT>cl,tp=self.components[n.name]<EOL>if tp in ("<STR_LIT>","<STR_LIT>"):<EOL><INDENT>if self.content.has_key(n.name):<EOL><INDENT>raise ValueError("<STR_LIT>" % (n.name,))<EOL><DEDENT>try:<EOL><INDENT>self.content[n.name]=cl(n.name,n)<EOL><DEDENT>except Empty:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>elif tp=="<STR_LIT>":<EOL><INDENT>if not self.content.has_key(n.name):<EOL><INDENT>self.content[n.name]=[]<EOL><DEDENT>try:<EOL><INDENT>self.content[n.name].append(cl(n.name,n))<EOL><DEDENT>except Empty:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>n=n.next<EOL><DEDENT>

Initialize a VCard object from XML node.

        :Parameters:
            - `data`: vcard to parse.
        :Types:
            - `data`: `libxml2.xmlNode`


_unused = rfc2425parameters<EOL>VCardField.__init__(self,name)<EOL>if isinstance(value,libxml2.xmlNode):<EOL><INDENT>try:<EOL><INDENT>self.value=pyxmpp.jid.JID(value.getContent())<EOL><DEDENT>except JIDError:<EOL><INDENT>raise JIDMalformedProtocolError("<STR_LIT>")<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.value=pyxmpp.jid.JID(value)<EOL><DEDENT>if not self.value:<EOL><INDENT>raise Empty("<STR_LIT>")<EOL><DEDENT>

Initialize a `VCardJID` object.

        :Parameters:
            - `name`: field name
            - `value`: field value as string or an XML node
            - `rfc2425parameters`: optional RFC 2425 parameters
        :Types:
            - `name`: `str`
            - `value`: `str` or `libxml2.xmlNode`
            - `rfc2425parameters`: `dict`


VCardField.__init__(self,name)<EOL>if not rfc2425parameters:<EOL><INDENT>rfc2425parameters={}<EOL><DEDENT>self.uri,self.sound,self.phonetic=[None]*<NUM_LIT:3><EOL>if isinstance(value,libxml2.xmlNode):<EOL><INDENT>n=value.children<EOL>vns=get_node_ns(value)<EOL>while n:<EOL><INDENT>if n.type!='<STR_LIT>':<EOL><INDENT>n=n.next<EOL>continue<EOL><DEDENT>ns=get_node_ns(n)<EOL>if (ns and vns and ns.getContent()!=vns.getContent()):<EOL><INDENT>n=n.next<EOL>continue<EOL><DEDENT>if n.name=='<STR_LIT>':<EOL><INDENT>if (self.phonetic or self.uri):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self.sound=base64.decodestring(n.getContent())<EOL><DEDENT>if n.name=='<STR_LIT>':<EOL><INDENT>if (self.sound or self.uri):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self.phonetic=unicode(n.getContent(),"<STR_LIT:utf-8>","<STR_LIT:replace>")<EOL><DEDENT>if n.name=='<STR_LIT>':<EOL><INDENT>if (self.phonetic or self.sound):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self.uri=unicode(n.getContent(),"<STR_LIT:utf-8>","<STR_LIT:replace>")<EOL><DEDENT>n=n.next<EOL><DEDENT>if (not self.phonetic and not self.uri and not self.sound):<EOL><INDENT>raise Empty("<STR_LIT>")<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if rfc2425parameters.get("<STR_LIT:value>", "<STR_LIT>").lower()=="<STR_LIT>":<EOL><INDENT>self.uri=value<EOL>self.sound=None<EOL>self.phonetic=None<EOL><DEDENT>else:<EOL><INDENT>self.sound=value<EOL>self.uri=None<EOL>self.phonetic=None<EOL><DEDENT><DEDENT>

Initialize a `VCardSound` object.

        :Parameters:
            - `name`: field name
            - `value`: field value as string or an XML node
            - `rfc2425parameters`: optional RFC 2425 parameters
        :Types:
            - `name`: `str`
            - `value`: `str` or `libxml2.xmlNode`
            - `rfc2425parameters`: `dict`


if self.value in ("<STR_LIT>","<STR_LIT>","<STR_LIT>"):<EOL><INDENT>n=parent.newChild(None,self.name.upper(),None)<EOL>n.newChild(None,self.value.upper(),None)<EOL>return n<EOL><DEDENT>return None<EOL>

Create vcard-tmp XML representation of the field.

        :Parameters:
            - `parent`: parent node for the element
        :Types:
            - `parent`: `libxml2.xmlNode`

        :return: xml node with the field data.
        :returntype: `libxml2.xmlNode`


n=parent.newChild(None,"<STR_LIT>",None)<EOL>for t in ("<STR_LIT>","<STR_LIT>","<STR_LIT>","<STR_LIT>","<STR_LIT>","<STR_LIT>","<STR_LIT>"):<EOL><INDENT>if t in self.type:<EOL><INDENT>n.newChild(None,t.upper(),None)<EOL><DEDENT><DEDENT>for l in self.lines:<EOL><INDENT>n.newTextChild(None,"<STR_LIT>",l)<EOL><DEDENT>return n<EOL>


Initialize a `VCardTel` object.

        :Parameters:
            - `name`: field name
            - `value`: field value as string or an XML node
            - `rfc2425parameters`: optional RFC 2425 parameters
        :Types:
            - `name`: `str`
            - `value`: `str` or `libxml2.xmlNode`
            - `rfc2425parameters`: `dict`


n=parent.newChild(None,"<STR_LIT>",None)<EOL>n.newTextChild(None,"<STR_LIT>",to_utf8(self.lat))<EOL>n.newTextChild(None,"<STR_LIT>",to_utf8(self.lon))<EOL>return n<EOL>


return rfc2425encode(self.name,self.value)<EOL>


VCardField.__init__(self,name)<EOL>if not rfc2425parameters:<EOL><INDENT>rfc2425parameters={}<EOL><DEDENT>self.uri,self.type,self.image=[None]*<NUM_LIT:3><EOL>if isinstance(value,libxml2.xmlNode):<EOL><INDENT>n=value.children<EOL>vns=get_node_ns(value)<EOL>while n:<EOL><INDENT>if n.type!='<STR_LIT>':<EOL><INDENT>n=n.next<EOL>continue<EOL><DEDENT>ns=get_node_ns(n)<EOL>if (ns and vns and ns.getContent()!=vns.getContent()):<EOL><INDENT>n=n.next<EOL>continue<EOL><DEDENT>if n.name=='<STR_LIT>':<EOL><INDENT>self.type=unicode(n.getContent(),"<STR_LIT:utf-8>","<STR_LIT:replace>")<EOL><DEDENT>if n.name=='<STR_LIT>':<EOL><INDENT>self.image=base64.decodestring(n.getContent())<EOL><DEDENT>if n.name=='<STR_LIT>':<EOL><INDENT>self.uri=unicode(n.getContent(),"<STR_LIT:utf-8>","<STR_LIT:replace>")<EOL><DEDENT>n=n.next<EOL><DEDENT>if (self.uri and self.image) or (not self.uri and not self.image):<EOL><INDENT>raise ValueError("<STR_LIT>" % (name,))<EOL><DEDENT>if (not self.uri and not self.image):<EOL><INDENT>raise Empty("<STR_LIT>" % (name,))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if rfc2425parameters.get("<STR_LIT:value>", "<STR_LIT>").lower()=="<STR_LIT>":<EOL><INDENT>self.uri=value<EOL>self.type=None<EOL><DEDENT>else:<EOL><INDENT>self.type=rfc2425parameters.get("<STR_LIT:type>")<EOL>self.image=value<EOL><DEDENT><DEDENT>

Initialize a `VCardImage` object.

        :Parameters:
            - `name`: field name
            - `value`: field value as string or an XML node
            - `rfc2425parameters`: optional RFC 2425 parameters
        :Types:
            - `name`: `str`
            - `value`: `str` or `libxml2.xmlNode`
            - `rfc2425parameters`: `dict`


n=value.children<EOL>vns=get_node_ns(value)<EOL>while n:<EOL><INDENT>if n.type!='<STR_LIT>':<EOL><INDENT>n=n.next<EOL>continue<EOL><DEDENT>ns=get_node_ns(n)<EOL>if (ns and vns and ns.getContent()!=vns.getContent()):<EOL><INDENT>n=n.next<EOL>continue<EOL><DEDENT>if n.name=='<STR_LIT>':<EOL><INDENT>self.pobox=unicode(n.getContent(),"<STR_LIT:utf-8>","<STR_LIT:replace>")<EOL><DEDENT>elif n.name in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>self.extadr=unicode(n.getContent(),"<STR_LIT:utf-8>","<STR_LIT:replace>")<EOL><DEDENT>elif n.name=='<STR_LIT>':<EOL><INDENT>self.street=unicode(n.getContent(),"<STR_LIT:utf-8>","<STR_LIT:replace>")<EOL><DEDENT>elif n.name=='<STR_LIT>':<EOL><INDENT>self.locality=unicode(n.getContent(),"<STR_LIT:utf-8>","<STR_LIT:replace>")<EOL><DEDENT>elif n.name=='<STR_LIT>':<EOL><INDENT>self.region=unicode(n.getContent(),"<STR_LIT:utf-8>","<STR_LIT:replace>")<EOL><DEDENT>elif n.name=='<STR_LIT>':<EOL><INDENT>self.pcode=unicode(n.getContent(),"<STR_LIT:utf-8>","<STR_LIT:replace>")<EOL><DEDENT>elif n.name=='<STR_LIT>':<EOL><INDENT>self.ctry=unicode(n.getContent(),"<STR_LIT:utf-8>","<STR_LIT:replace>")<EOL><DEDENT>elif n.name in ("<STR_LIT>","<STR_LIT>","<STR_LIT>","<STR_LIT>","<STR_LIT>","<STR_LIT>",<EOL>"<STR_LIT>"):<EOL><INDENT>self.type.append(n.name.lower())<EOL><DEDENT>n=n.next<EOL><DEDENT>if self.type==[]:<EOL><INDENT>self.type=["<STR_LIT>","<STR_LIT>","<STR_LIT>","<STR_LIT>"]<EOL><DEDENT>elif "<STR_LIT>" in self.type and "<STR_LIT>" in self.type:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>

Initialize a `VCardAdr` object from and XML element.

        :Parameters:
            - `value`: field value as an XML node
        :Types:
            - `value`: `libxml2.xmlNode`


return rfc2425encode("<STR_LIT>",u'<STR_LIT:;>'.join(quote_semicolon(val) for val in<EOL>(self.lat,self.lon)))<EOL>


_unused = rfc2425parameters<EOL>VCardField.__init__(self,name)<EOL>if isinstance(value,libxml2.xmlNode):<EOL><INDENT>self.value=None<EOL>n=value.children<EOL>vns=get_node_ns(value)<EOL>while n:<EOL><INDENT>if n.type!='<STR_LIT>':<EOL><INDENT>n=n.next<EOL>continue<EOL><DEDENT>ns=get_node_ns(n)<EOL>if (ns and vns and ns.getContent()!=vns.getContent()):<EOL><INDENT>n=n.next<EOL>continue<EOL><DEDENT>if n.name=='<STR_LIT>':<EOL><INDENT>self.value="<STR_LIT>"<EOL><DEDENT>elif n.name=='<STR_LIT>':<EOL><INDENT>self.value="<STR_LIT>"<EOL><DEDENT>elif n.name=='<STR_LIT>':<EOL><INDENT>self.value="<STR_LIT>"<EOL><DEDENT>n=n.next<EOL><DEDENT>if not self.value:<EOL><INDENT>raise Empty<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.value=value<EOL><DEDENT>

Initialize a `VCardPrivacy` object.

        :Parameters:
            - `name`: field name
            - `value`: field value as string or an XML node
            - `rfc2425parameters`: optional RFC 2425 parameters
        :Types:
            - `name`: `str`
            - `value`: `str` or `libxml2.xmlNode`
            - `rfc2425parameters`: `dict`


return parent.newTextChild(None, to_utf8(self.name.upper()), to_utf8(self.value))<EOL>


return rfc2425encode("<STR_LIT:email>",self.address,{"<STR_LIT:type>":"<STR_LIT:U+002C>".join(self.type)})<EOL>


name=to_utf8(self.name.upper())<EOL>content=self.value.as_utf8()<EOL>return parent.newTextChild(None, name, content)<EOL>


<EOL>self.n = None<EOL>del self.n<EOL>self.content={}<EOL>if isinstance(data,libxml2.xmlNode):<EOL><INDENT>self.__from_xml(data)<EOL><DEDENT>else:<EOL><INDENT>self.__from_rfc2426(data)<EOL><DEDENT>if not self.content.get("<STR_LIT:N>") and self.content.get("<STR_LIT>"):<EOL><INDENT>s=self.content['<STR_LIT>'].value.replace("<STR_LIT:;>","<STR_LIT:U+002C>")<EOL>s=s.split(None,<NUM_LIT:2>)<EOL>if len(s)==<NUM_LIT:2>:<EOL><INDENT>s=u"<STR_LIT>" % (s[<NUM_LIT:1>],s[<NUM_LIT:0>])<EOL><DEDENT>elif len(s)==<NUM_LIT:3>:<EOL><INDENT>s=u"<STR_LIT>" % (s[<NUM_LIT:2>],s[<NUM_LIT:0>],s[<NUM_LIT:1>])<EOL><DEDENT>else:<EOL><INDENT>s=u"<STR_LIT>" % (s[<NUM_LIT:0>],)<EOL><DEDENT>self.content["<STR_LIT:N>"]=VCardName("<STR_LIT:N>",s)<EOL><DEDENT>elif not self.content.get("<STR_LIT>") and self.content.get("<STR_LIT:N>"):<EOL><INDENT>self.__make_fn()<EOL><DEDENT>for c, (_unused, tp) in self.components.items():<EOL><INDENT>if self.content.has_key(c):<EOL><INDENT>continue<EOL><DEDENT>if tp=="<STR_LIT>":<EOL><INDENT>raise ValueError("<STR_LIT>" % (c,))<EOL><DEDENT>elif tp=="<STR_LIT>":<EOL><INDENT>self.content[c]=[]<EOL><DEDENT>elif tp=="<STR_LIT>":<EOL><INDENT>self.content[c]=None<EOL><DEDENT>else:<EOL><INDENT>continue<EOL><DEDENT><DEDENT>

Initialize a VCard object from data which may be XML node
        or an RFC2426 string.

        :Parameters:
            - `data`: vcard to parse.
        :Types:
            - `data`: `libxml2.xmlNode`, `unicode` or `str`


n=parent.newChild(None,"<STR_LIT>",None)<EOL>for t in ("<STR_LIT>","<STR_LIT>","<STR_LIT>","<STR_LIT>"):<EOL><INDENT>if t in self.type:<EOL><INDENT>n.newChild(None,t.upper(),None)<EOL><DEDENT><DEDENT>n.newTextChild(None,"<STR_LIT>",to_utf8(self.address))<EOL>return n<EOL>


self.name=name<EOL>

Initialize a `VCardField` object.

        Set its name.

        :Parameters:
            - `name`: field name
        :Types:
            - `name`: `str`


s=[]<EOL>if self.n.prefix:<EOL><INDENT>s.append(self.n.prefix)<EOL><DEDENT>if self.n.given:<EOL><INDENT>s.append(self.n.given)<EOL><DEDENT>if self.n.middle:<EOL><INDENT>s.append(self.n.middle)<EOL><DEDENT>if self.n.family:<EOL><INDENT>s.append(self.n.family)<EOL><DEDENT>if self.n.suffix:<EOL><INDENT>s.append(self.n.suffix)<EOL><DEDENT>s=u"<STR_LIT:U+0020>".join(s)<EOL>self.content["<STR_LIT>"]=VCardString("<STR_LIT>", s, empty_ok = True)<EOL>

Initialize the mandatory `self.fn` from `self.n`.

        This is a workaround for buggy clients which set only one of them.


VCardField.__init__(self,name)<EOL>if not rfc2425parameters:<EOL><INDENT>rfc2425parameters={}<EOL><DEDENT>if self.name.upper()!="<STR_LIT>":<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>if isinstance(value,libxml2.xmlNode):<EOL><INDENT>self.lines=[]<EOL>self.type=[]<EOL>n=value.children<EOL>vns=get_node_ns(value)<EOL>while n:<EOL><INDENT>if n.type!='<STR_LIT>':<EOL><INDENT>n=n.next<EOL>continue<EOL><DEDENT>ns=get_node_ns(n)<EOL>if (ns and vns and ns.getContent()!=vns.getContent()):<EOL><INDENT>n=n.next<EOL>continue<EOL><DEDENT>if n.name=='<STR_LIT>':<EOL><INDENT>l=unicode(n.getContent(),"<STR_LIT:utf-8>","<STR_LIT:replace>").strip()<EOL>l=l.replace("<STR_LIT:\n>","<STR_LIT:U+0020>").replace("<STR_LIT:\r>","<STR_LIT:U+0020>")<EOL>self.lines.append(l)<EOL><DEDENT>elif n.name in ("<STR_LIT>","<STR_LIT>","<STR_LIT>","<STR_LIT>","<STR_LIT>","<STR_LIT>",<EOL>"<STR_LIT>"):<EOL><INDENT>self.type.append(n.name.lower())<EOL><DEDENT>n=n.next<EOL><DEDENT>if self.type==[]:<EOL><INDENT>self.type=["<STR_LIT>","<STR_LIT>","<STR_LIT>","<STR_LIT>"]<EOL><DEDENT>elif "<STR_LIT>" in self.type and "<STR_LIT>" in self.type:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if not self.lines:<EOL><INDENT>self.lines=["<STR_LIT>"]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>t=rfc2425parameters.get("<STR_LIT:type>")<EOL>if t:<EOL><INDENT>self.type=t.split("<STR_LIT:U+002C>")<EOL><DEDENT>else:<EOL><INDENT>self.type=["<STR_LIT>","<STR_LIT>","<STR_LIT>","<STR_LIT>"]<EOL><DEDENT>self.lines=value.split("<STR_LIT>")<EOL><DEDENT>

Initialize a `VCardLabel` object.

        :Parameters:
            - `name`: field name
            - `value`: field value as string or an XML node
            - `rfc2425parameters`: optional RFC 2425 parameters
        :Types:
            - `name`: `str`
            - `value`: `str` or `libxml2.xmlNode`
            - `rfc2425parameters`: `dict`


n=parent.newChild(None,"<STR_LIT>",None)<EOL>n.newTextChild(None,"<STR_LIT>",to_utf8(self.name))<EOL>n.newTextChild(None,"<STR_LIT>",to_utf8(self.unit))<EOL>return n<EOL>


if self.unit:<EOL><INDENT>return rfc2425encode("<STR_LIT>",u'<STR_LIT:;>'.join(quote_semicolon(val) for val in<EOL>(self.name,self.unit)))<EOL><DEDENT>else:<EOL><INDENT>return rfc2425encode("<STR_LIT>",unicode(quote_semicolon(self.name)))<EOL><DEDENT>


if self.type is not None and self.type not in self.allowed_types:<EOL><INDENT>raise ValueError("<STR_LIT>" % (self.type,))<EOL><DEDENT>if self.type is not None:<EOL><INDENT>xmlnode.setProp("<STR_LIT:type>", self.type)<EOL><DEDENT>if not self.label is None:<EOL><INDENT>xmlnode.setProp("<STR_LIT:label>", to_utf8(self.label))<EOL><DEDENT>if not self.name is None:<EOL><INDENT>xmlnode.setProp("<STR_LIT>", to_utf8(self.name))<EOL><DEDENT>if self.values:<EOL><INDENT>if self.type and len(self.values) > <NUM_LIT:1> and not self.type.endswith(u"<STR_LIT>"):<EOL><INDENT>raise ValueError("<STR_LIT>" % (self.type,))<EOL><DEDENT>for value in self.values:<EOL><INDENT>xmlnode.newTextChild(xmlnode.ns(), "<STR_LIT:value>", to_utf8(value))<EOL><DEDENT><DEDENT>for option in self.options:<EOL><INDENT>option.as_xml(xmlnode, doc)<EOL><DEDENT>if self.required:<EOL><INDENT>xmlnode.newChild(xmlnode.ns(), "<STR_LIT>", None)<EOL><DEDENT>if self.desc:<EOL><INDENT>xmlnode.newTextChild(xmlnode.ns(), "<STR_LIT>", to_utf8(self.desc))<EOL><DEDENT>return xmlnode<EOL>

Complete the XML node with `self` content.

        :Parameters:
            - `xmlnode`: XML node with the element being built. It has already
              right name and namespace, but no attributes or content.
            - `doc`: document to which the element belongs.
        :Types:
            - `xmlnode`: `libxml2.xmlNode`
            - `doc`: `libxml2.xmlDoc`


label = from_utf8(xmlnode.prop("<STR_LIT:label>"))<EOL>child = xmlnode.children<EOL>value = None<EOL>for child in xml_element_ns_iter(xmlnode.children, DATAFORM_NS):<EOL><INDENT>if child.name == "<STR_LIT:value>":<EOL><INDENT>value = from_utf8(child.getContent())<EOL>break<EOL><DEDENT><DEDENT>if value is None:<EOL><INDENT>raise BadRequestProtocolError("<STR_LIT>")<EOL><DEDENT>return cls(value, label)<EOL>

Create a new `Option` object from an XML element.

        :Parameters:
            - `xmlnode`: the XML element.
        :Types:
            - `xmlnode`: `libxml2.xmlNode`

        :return: the object created.
        :returntype: `Option`


def __init__(self, value = None, label = None, values = None):

self.label = label<EOL>if value:<EOL><INDENT>self.value = value<EOL><DEDENT>elif values:<EOL><INDENT>warnings.warn("<STR_LIT>", DeprecationWarning, stacklevel=<NUM_LIT:1>)<EOL>self.value = values[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>

Initialize an `Option` object.

        :Parameters:
            - `value`: option value (mandatory).
            - `label`: option label (human-readable description).
            - `values`: for backward compatibility only.
        :Types:
            - `label`: `unicode`
            - `value`: `unicode`


self.fields = []<EOL>self.reported_fields = []<EOL>self.items = []<EOL>self.title = None<EOL>self.instructions = None<EOL>if (xmlnode.type != "<STR_LIT>" or xmlnode.name != "<STR_LIT:x>"<EOL>or xmlnode.ns().content != DATAFORM_NS):<EOL><INDENT>raise ValueError("<STR_LIT>" + xmlnode.serialize())<EOL><DEDENT>self.type = xmlnode.prop("<STR_LIT:type>")<EOL>if not self.type in self.allowed_types:<EOL><INDENT>raise BadRequestProtocolError("<STR_LIT>" % (self.type,))<EOL><DEDENT>child = xmlnode.children<EOL>while child:<EOL><INDENT>if child.type != "<STR_LIT>" or child.ns().content != DATAFORM_NS:<EOL><INDENT>pass<EOL><DEDENT>elif child.name == "<STR_LIT:title>":<EOL><INDENT>self.title = from_utf8(child.getContent())<EOL><DEDENT>elif child.name == "<STR_LIT>":<EOL><INDENT>self.instructions = from_utf8(child.getContent())<EOL><DEDENT>elif child.name == "<STR_LIT>":<EOL><INDENT>self.fields.append(Field._new_from_xml(child))<EOL><DEDENT>elif child.name == "<STR_LIT>":<EOL><INDENT>self.items.append(Item._new_from_xml(child))<EOL><DEDENT>elif child.name == "<STR_LIT>":<EOL><INDENT>self.__get_reported(child)<EOL><DEDENT>child = child.next<EOL><DEDENT>

Initialize a `Form` object from an XML element.

        :Parameters:
            - `xmlnode`: the XML element.
        :Types:
            - `xmlnode`: `libxml2.xmlNode`


def make_submit(self, keep_types = False):

result = Form("<STR_LIT>")<EOL>for field in self.fields:<EOL><INDENT>if field.type == "<STR_LIT>":<EOL><INDENT>continue<EOL><DEDENT>if not field.values:<EOL><INDENT>if field.required:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>continue<EOL><DEDENT>if keep_types:<EOL><INDENT>result.add_field(field.name, field.values, field.type)<EOL><DEDENT>else:<EOL><INDENT>result.add_field(field.name, field.values)<EOL><DEDENT><DEDENT>return result<EOL>

Make a "submit" form using data in `self`.

        Remove uneeded information from the form. The information removed
        includes: title, instructions, field labels, fixed fields etc.

        :raise ValueError: when any required field has no value.

        :Parameters:
            - `keep_types`: when `True` field type information will be included
              in the result form. That is usually not needed.
        :Types:
            - `keep_types`: `bool`

        :return: the form created.
        :returntype: `Form`


def add_field(self, name = None, values = None, field_type = None,<EOL>label = None, options = None, required = False, desc = None, value = None):

field = Field(name, values, field_type, label, options, required, desc, value)<EOL>self.fields.append(field)<EOL>return field<EOL>

Add a field to the item.

        :Parameters:
            - `name`: field name.
            - `values`: raw field values. Not to be used together with `value`.
            - `field_type`: field type.
            - `label`: field label.
            - `options`: optional values for the field.
            - `required`: `True` if the field is required.
            - `desc`: natural-language description of the field.
            - `value`: field value or values in a field_type-specific type. May be used only
              if `values` parameter is not provided.
        :Types:
            - `name`: `unicode`
            - `values`: `list` of `unicode`
            - `field_type`: `str`
            - `label`: `unicode`
            - `options`: `list` of `Option`
            - `required`: `bool`
            - `desc`: `unicode`
            - `value`: `bool` for "boolean" field, `JID` for "jid-single", `list` of `JID`
              for "jid-multi", `list` of `unicode` for "list-multi" and "text-multi"
              and `unicode` for other field types.

        :return: the field added.
        :returntype: `Field`


child = xmlnode.children<EOL>fields = []<EOL>while child:<EOL><INDENT>if child.type != "<STR_LIT>" or child.ns().content != DATAFORM_NS:<EOL><INDENT>pass<EOL><DEDENT>elif child.name == "<STR_LIT>":<EOL><INDENT>fields.append(Field._new_from_xml(child))<EOL><DEDENT>child = child.next<EOL><DEDENT>return cls(fields)<EOL>

Create a new `Item` object from an XML element.

        :Parameters:
            - `xmlnode`: the XML element.
        :Types:
            - `xmlnode`: `libxml2.xmlNode`

        :return: the object created.
        :returntype: `Item`


if not self._dirty:<EOL><INDENT>return self._element<EOL><DEDENT>element = self.as_xml()<EOL>self._element = element<EOL>self._dirty = False<EOL>return element<EOL>

Return the XML stanza representation.

        This returns the original or cached XML representation, which
        may be much more efficient than `as_xml`.

        Result of this function should never be modified.

        :returntype: :etree:`ElementTree.Element`


def __init__(self, element, from_jid = None, to_jid = None,<EOL>stanza_type = None, stanza_id = None,<EOL>error = None, error_cond = None,<EOL>return_path = None, language = None):

<EOL>self._error = None<EOL>self._from_jid = None<EOL>self._to_jid = None<EOL>self._stanza_type = None<EOL>self._stanza_id = None<EOL>self._language = language<EOL>if isinstance(element, ElementClass):<EOL><INDENT>self._element = element<EOL>self._dirty = False<EOL>self._decode_attributes()<EOL>if not element.tag.startswith("<STR_LIT:{>"):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>self._namespace, self.element_name = element.tag[<NUM_LIT:1>:].split("<STR_LIT:}>")<EOL>if self._namespace not in STANZA_NAMESPACES:<EOL><INDENT>raise BadRequestProtocolError("<STR_LIT>")<EOL><DEDENT><DEDENT>self._payload = None<EOL><DEDENT>else:<EOL><INDENT>self._element = None<EOL>self._dirty = True<EOL>self.element_name = unicode(element)<EOL>self._namespace = STANZA_CLIENT_NS<EOL>self._payload = []<EOL><DEDENT>self._ns_prefix = "<STR_LIT>".format(self._namespace)<EOL>self._element_qname = self._ns_prefix + self.element_name<EOL>if from_jid is not None:<EOL><INDENT>self.from_jid = from_jid<EOL><DEDENT>if to_jid is not None:<EOL><INDENT>self.to_jid = to_jid<EOL><DEDENT>if stanza_type:<EOL><INDENT>self.stanza_type = stanza_type<EOL><DEDENT>if stanza_id:<EOL><INDENT>self.stanza_id = stanza_id<EOL><DEDENT>if self.stanza_type == "<STR_LIT:error>":<EOL><INDENT>if error:<EOL><INDENT>self._error = StanzaErrorElement(error)<EOL><DEDENT>elif error_cond:<EOL><INDENT>self._error = StanzaErrorElement(error_cond)<EOL><DEDENT>else:<EOL><INDENT>self._decode_error()<EOL><DEDENT><DEDENT>if return_path is not None:<EOL><INDENT>self._return_path = weakref.ref(return_path)<EOL><DEDENT>

Initialize a Stanza object.

        :Parameters:
            - `element`: XML element of this stanza, or element name for a new
              stanza. If element is given it must not be modified later,
              unless `decode_payload()` and `mark_dirty()` methods are called
              first (the element changes won't affec the stanza then).
            - `from_jid`: sender JID.
            - `to_jid`: recipient JID.
            - `stanza_type`: staza type: one of: "get", "set", "result" or
              "error".
            - `stanza_id`: stanza id -- value of stanza's "id" attribute. If
              not given, then unique for the session value is generated.
            - `error`: error object. Ignored if `stanza_type` is not "error".
            - `error_cond`: error condition name. Ignored if `stanza_type` is
              not "error" or `error` is not None.
            - `return_path`: route for sending responses to this stanza. Will
              be weakly referenced.
            - `language`: default language for the stanza content
        :Types:
            - `element`: `unicode` or :etree:`ElementTree.Element`
            - `from_jid`: `JID`
            - `to_jid`: `JID`
            - `stanza_type`: `unicode`
            - `stanza_id`: `unicode`
            - `error`: `pyxmpp.error.StanzaErrorElement`
            - `error_cond`: `unicode`
            - `return_path`: `StanzaRoute`
            - `language`: `unicode`


def get_payload(self, payload_class, payload_key = None,<EOL>specialize = False):

if self._payload is None:<EOL><INDENT>self.decode_payload()<EOL><DEDENT>if payload_class is None:<EOL><INDENT>if self._payload:<EOL><INDENT>payload = self._payload[<NUM_LIT:0>]<EOL>if specialize and isinstance(payload, XMLPayload):<EOL><INDENT>klass = payload_class_for_element_name(<EOL>payload.element.tag)<EOL>if klass is not XMLPayload:<EOL><INDENT>payload = klass.from_xml(payload.element)<EOL>self._payload[<NUM_LIT:0>] = payload<EOL><DEDENT><DEDENT>return payload<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT><DEDENT>elements = payload_class._pyxmpp_payload_element_name<EOL>for i, payload in enumerate(self._payload):<EOL><INDENT>if isinstance(payload, XMLPayload):<EOL><INDENT>if payload_class is not XMLPayload:<EOL><INDENT>if payload.xml_element_name not in elements:<EOL><INDENT>continue<EOL><DEDENT>payload = payload_class.from_xml(payload.element)<EOL><DEDENT><DEDENT>elif not isinstance(payload, payload_class):<EOL><INDENT>continue<EOL><DEDENT>if payload_key is not None and payload_key != payload.handler_key():<EOL><INDENT>continue<EOL><DEDENT>self._payload[i] = payload<EOL>return payload<EOL><DEDENT>return None<EOL>

Get the first payload item matching the given class
        and optional key.

        Payloads may be addressed using a specific payload class or
        via the generic `XMLPayload` element, though the `XMLPayload`
        representation is available only as long as the element is not
        requested by a more specific type.

        :Parameters:
            - `payload_class`: requested payload class, a subclass of
              `StanzaPayload`. If `None` get the first payload in whatever
              class is available.
            - `payload_key`: optional key for additional match. When used
              with `payload_class` = `XMLPayload` this selects the element to
              match
            - `specialize`: If `True`, and `payload_class` is `None` then
              return object of a specialized `StanzaPayload` subclass whenever
              possible
        :Types:
            - `payload_class`: `StanzaPayload`
            - `specialize`: `bool`

        :Return: payload element found or `None`
        :Returntype: `StanzaPayload`


return self._return_path()<EOL>

Stream the stanza was received from.

        :returntype: `StanzaRoute`


if isinstance(payload, ElementClass):<EOL><INDENT>self._payload = [ XMLPayload(payload) ]<EOL><DEDENT>elif isinstance(payload, StanzaPayload):<EOL><INDENT>self._payload = [ payload ]<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>self._dirty = True<EOL>

Set stanza payload to a single item.

        All current stanza content of will be dropped.
        Marks the stanza dirty.

        :Parameters:
            - `payload`: XML element or stanza payload object to use
        :Types:
            - `payload`: :etree:`ElementTree.Element` or `StanzaPayload`


self._dirty = True<EOL>

Mark the stanza 'dirty' so the XML representation will be
        re-built the next time it is requested.

        This should be called each time the payload attached to the stanza is
        modifed.


return self._to_jid<EOL>

Destination JID of the stanza.

        :returntype: `JID`


return self._from_jid<EOL>

Source JID of the stanza.

        :returntype: `JID`


if self._payload is None:<EOL><INDENT>self.decode_payload()<EOL><DEDENT>if isinstance(payload, ElementClass):<EOL><INDENT>self._payload.append(XMLPayload(payload))<EOL><DEDENT>elif isinstance(payload, StanzaPayload):<EOL><INDENT>self._payload.append(payload)<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>self._dirty = True<EOL>

Add new the stanza payload.

        Marks the stanza dirty.

        :Parameters:
            - `payload`: XML element or stanza payload object to add
        :Types:
            - `payload`: :etree:`ElementTree.Element` or `StanzaPayload`


return serialize(self.get_xml())<EOL>

Serialize the stanza into a Unicode XML string.

        :return: serialized stanza.
        :returntype: `unicode`


result = Stanza(self.element_name, self.from_jid, self.to_jid,<EOL>self.stanza_type, self.stanza_id, self.error,<EOL>self._return_path())<EOL>if self._payload is None:<EOL><INDENT>self.decode_payload()<EOL><DEDENT>for payload in self._payload:<EOL><INDENT>result.add_payload(payload.copy())<EOL><DEDENT>return result<EOL>

Create a deep copy of the stanza.

        :returntype: `Stanza`


self.common_names = []<EOL>subject_name = []<EOL>for rdnss in subject:<EOL><INDENT>for rdns in rdnss:<EOL><INDENT>rdnss_list = []<EOL>for nameval in rdns:<EOL><INDENT>val_type = nameval.getComponentByName('<STR_LIT:type>')<EOL>value = nameval.getComponentByName('<STR_LIT:value>')<EOL>if val_type not in DN_OIDS:<EOL><INDENT>logger.debug("<STR_LIT>".format(val_type))<EOL>continue<EOL><DEDENT>val_type = DN_OIDS[val_type]<EOL>value = der_decoder.decode(value,<EOL>asn1Spec = DirectoryString())[<NUM_LIT:0>]<EOL>value = value.getComponent()<EOL>try:<EOL><INDENT>value = _decode_asn1_string(value)<EOL><DEDENT>except UnicodeError:<EOL><INDENT>logger.debug("<STR_LIT>".format(value))<EOL>continue<EOL><DEDENT>if val_type == "<STR_LIT>":<EOL><INDENT>self.common_names.append(value)<EOL><DEDENT>rdnss_list.append((val_type, value))<EOL><DEDENT>subject_name.append(tuple(rdnss_list))<EOL><DEDENT><DEDENT>self.subject_name = tuple(subject_name)<EOL>


<EOL>logger.debug("<STR_LIT>".format(data))<EOL>if cls._cert_asn1_type is None:<EOL><INDENT>cls._cert_asn1_type = Certificate()<EOL><DEDENT>cert = der_decoder.decode(data, asn1Spec = cls._cert_asn1_type)[<NUM_LIT:0>]<EOL>result = cls()<EOL>tbs_cert = cert.getComponentByName('<STR_LIT>')<EOL>subject = tbs_cert.getComponentByName('<STR_LIT>')<EOL>logger.debug("<STR_LIT>".format(subject))<EOL>result._decode_subject(subject)<EOL>validity = tbs_cert.getComponentByName('<STR_LIT>')<EOL>result._decode_validity(validity)<EOL>extensions = tbs_cert.getComponentByName('<STR_LIT>')<EOL>if extensions:<EOL><INDENT>for extension in extensions:<EOL><INDENT>logger.debug("<STR_LIT>".format(extension))<EOL>oid = extension.getComponentByName('<STR_LIT>')<EOL>logger.debug("<STR_LIT>".format(oid))<EOL>if oid != SUBJECT_ALT_NAME_OID:<EOL><INDENT>continue<EOL><DEDENT>value = extension.getComponentByName('<STR_LIT>')<EOL>logger.debug("<STR_LIT>".format(value))<EOL>if isinstance(value, Any):<EOL><INDENT>value = der_decoder.decode(value,<EOL>asn1Spec = OctetString())[<NUM_LIT:0>]<EOL><DEDENT>alt_names = der_decoder.decode(value,<EOL>asn1Spec = GeneralNames())[<NUM_LIT:0>]<EOL>logger.debug("<STR_LIT>".format(alt_names))<EOL>result._decode_alt_names(alt_names)<EOL><DEDENT><DEDENT>return result<EOL>

Decode DER-encoded certificate.

        :Parameters:
            - `data`: the encoded certificate
        :Types:
            - `data`: `bytes`

        :Return: decoded certificate data
        :Returntype: ASN1CertificateData


if self.subject_name is not None:<EOL><INDENT>subject_name = []<EOL>for part in self.subject_name:<EOL><INDENT>new_part = []<EOL>for name, value in part:<EOL><INDENT>try:<EOL><INDENT>name = name.decode("<STR_LIT:utf-8>")<EOL>value = value.decode("<STR_LIT:utf-8>")<EOL><DEDENT>except UnicodeError:<EOL><INDENT>continue<EOL><DEDENT>new_part.append((name, value))<EOL><DEDENT>subject_name.append(tuple(new_part))<EOL><DEDENT>self.subject_name = tuple(subject_name)<EOL><DEDENT>for key, old in list(self.alt_names.items()):<EOL><INDENT>new = []<EOL>for name in old:<EOL><INDENT>try:<EOL><INDENT>name = name.decode("<STR_LIT:utf-8>")<EOL><DEDENT>except UnicodeError:<EOL><INDENT>continue<EOL><DEDENT>new.append(name)<EOL><DEDENT>self.alt_names[key] = new<EOL><DEDENT>

Decode names (hopefully ASCII or UTF-8) into Unicode.


if self.subject_name:<EOL><INDENT>return "<STR_LIT:U+002CU+0020>".join( [ "<STR_LIT:U+002CU+0020>".join(<EOL>[ "<STR_LIT>".format(k,v) for k, v in dn_tuple ] )<EOL>for dn_tuple in self.subject_name ])<EOL><DEDENT>for name_type in ("<STR_LIT>", "<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>names = self.alt_names.get(name_type)<EOL>if names:<EOL><INDENT>return names[<NUM_LIT:0>]<EOL><DEDENT><DEDENT>return "<STR_LIT>"<EOL>

Get human-readable subject name derived from the SubjectName
        or SubjectAltName field.


result = []<EOL>if ("<STR_LIT>" in self.alt_names or "<STR_LIT>" in self.alt_names<EOL>or "<STR_LIT>" in self.alt_names):<EOL><INDENT>addrs =  self.alt_names.get("<STR_LIT>", [])<EOL>addrs += [ addr for addr in self.alt_names.get("<STR_LIT>", [])<EOL>if not addr.startswith("<STR_LIT>") ]<EOL>addrs += [ addr.split("<STR_LIT:.>", <NUM_LIT:1>)[<NUM_LIT:1>] for addr<EOL>in self.alt_names.get("<STR_LIT>", [])<EOL>if (addr.startswith("<STR_LIT>")<EOL>or addr.startswith("<STR_LIT>"))]<EOL>warn_bad = True<EOL><DEDENT>elif self.common_names:<EOL><INDENT>addrs = [addr for addr in self.common_names<EOL>if "<STR_LIT:@>" not in addr and "<STR_LIT:/>" not in addr]<EOL>warn_bad = False<EOL><DEDENT>else:<EOL><INDENT>return []<EOL><DEDENT>for addr in addrs:<EOL><INDENT>try:<EOL><INDENT>jid = JID(addr)<EOL>if jid not in result:<EOL><INDENT>result.append(jid)<EOL><DEDENT><DEDENT>except JIDError as err:<EOL><INDENT>if warn_bad:<EOL><INDENT>logger.warning("<STR_LIT>"<EOL>.format(addr, err))<EOL><DEDENT><DEDENT><DEDENT>return result<EOL>

Return JIDs for which this certificate is valid (except the domain
        wildcards).

        :Returtype: `list` of `JID`


def verify_jid_against_srv_name(self, jid, srv_type):

srv_prefix = "<STR_LIT:_>" + srv_type + "<STR_LIT:.>"<EOL>srv_prefix_l = len(srv_prefix)<EOL>for srv in self.alt_names.get("<STR_LIT>", []):<EOL><INDENT>logger.debug("<STR_LIT>".format(jid,<EOL>srv))<EOL>if not srv.startswith(srv_prefix):<EOL><INDENT>logger.debug("<STR_LIT>"<EOL>.format(srv, srv_prefix))<EOL>continue<EOL><DEDENT>try:<EOL><INDENT>srv_jid = JID(srv[srv_prefix_l:])<EOL><DEDENT>except ValueError:<EOL><INDENT>continue<EOL><DEDENT>if srv_jid == jid:<EOL><INDENT>logger.debug("<STR_LIT>")<EOL>return True<EOL><DEDENT><DEDENT>return False<EOL>

Check if the cerificate is valid for given domain-only JID
        and a service type.

        :Parameters:
            - `jid`: JID requested (domain part only)
            - `srv_type`: service type, e.g. 'xmpp-client'
        :Types:
            - `jid`: `JID`
            - `srv_type`: `unicode`
        :Returntype: `bool`


def verify_server(self, server_name, srv_type = '<STR_LIT>'):

server_jid = JID(server_name)<EOL>if "<STR_LIT>" not in self.alt_names and "<STR_LIT>" not in self.alt_namesand "<STR_LIT>" not in self.alt_names:<EOL><INDENT>return self.verify_jid_against_common_name(server_jid)<EOL><DEDENT>names = [name for name in self.alt_names.get("<STR_LIT>", [])<EOL>if not name.startswith("<STR_LIT>")]<EOL>names += self.alt_names.get("<STR_LIT>", [])<EOL>for name in names:<EOL><INDENT>logger.debug("<STR_LIT>".format(server_jid,<EOL>name))<EOL>try:<EOL><INDENT>jid = JID(name)<EOL><DEDENT>except ValueError:<EOL><INDENT>logger.debug("<STR_LIT>".format(name))<EOL>continue<EOL><DEDENT>if jid == server_jid:<EOL><INDENT>logger.debug("<STR_LIT>")<EOL>return True<EOL><DEDENT><DEDENT>if srv_type and self.verify_jid_against_srv_name(server_jid, srv_type):<EOL><INDENT>return True<EOL><DEDENT>wildcards = [name[<NUM_LIT:2>:] for name in self.alt_names.get("<STR_LIT>", [])<EOL>if name.startswith("<STR_LIT>")]<EOL>if not wildcards or not "<STR_LIT:.>" in server_jid.domain:<EOL><INDENT>return False<EOL><DEDENT>logger.debug("<STR_LIT>"<EOL>.format(server_jid, wildcards))<EOL>server_domain = JID(domain = server_jid.domain.split("<STR_LIT:.>", <NUM_LIT:1>)[<NUM_LIT:1>])<EOL>for domain in wildcards:<EOL><INDENT>logger.debug("<STR_LIT>".format(server_domain,<EOL>domain))<EOL>try:<EOL><INDENT>jid = JID(domain)<EOL><DEDENT>except ValueError:<EOL><INDENT>logger.debug("<STR_LIT>".format(name))<EOL>continue<EOL><DEDENT>if jid == server_domain:<EOL><INDENT>logger.debug("<STR_LIT>")<EOL>return True<EOL><DEDENT><DEDENT>return False<EOL>

Verify certificate for a server.

        :Parameters:
            - `server_name`: name of the server presenting the cerificate
            - `srv_type`: service type requested, as used in the SRV record
        :Types:
            - `server_name`: `unicode` or `JID`
            - `srv_type`: `unicode`

        :Return: `True` if the certificate is valid for given name, `False`
        otherwise.


not_after = validity.getComponentByName('<STR_LIT>')<EOL>not_after = str(not_after.getComponent())<EOL>if isinstance(not_after, GeneralizedTime):<EOL><INDENT>self.not_after = datetime.strptime(not_after, "<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>self.not_after = datetime.strptime(not_after, "<STR_LIT>")<EOL><DEDENT>self.alt_names = defaultdict(list)<EOL>


if self.stanza_type not in ("<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>stanza = Presence(stanza_type = DENY_RESPONSES[self.stanza_type],<EOL>from_jid = self.to_jid, to_jid = self.from_jid,<EOL>stanza_id = self.stanza_id)<EOL>return stanza<EOL>

Create "deny" response for the "subscribe" / "subscribed" /
        "unsubscribe" / "unsubscribed" presence stanza.

        :return: new presence stanza.
        :returntype: `Presence`


return self._show<EOL>

Presence status type.

        :returntype: `unicode`


used_prefixes = set(self._prefixes.values())<EOL>used_prefixes |= set(declared_prefixes.values())<EOL>while True:<EOL><INDENT>prefix = "<STR_LIT>".format(self._next_id)<EOL>self._next_id += <NUM_LIT:1><EOL>if prefix not in used_prefixes:<EOL><INDENT>break<EOL><DEDENT><DEDENT>return prefix<EOL>

Make up a new namespace prefix, which won't conflict
        with `_prefixes` and prefixes declared in the current scope.

        :Parameters:
            - `declared_prefixes`: namespace to prefix mapping for the current
              scope
        :Types:
            - `declared_prefixes`: `unicode` to `unicode` dictionary

        :Returns: a new prefix
        :Returntype: `unicode`


def _make_prefixed(self, name, is_element, declared_prefixes, declarations):

namespace, name = self._split_qname(name, is_element)<EOL>if namespace is None:<EOL><INDENT>prefix = None<EOL><DEDENT>elif namespace in declared_prefixes:<EOL><INDENT>prefix = declared_prefixes[namespace]<EOL><DEDENT>elif namespace in self._prefixes:<EOL><INDENT>prefix = self._prefixes[namespace]<EOL>declarations[namespace] = prefix<EOL>declared_prefixes[namespace] = prefix<EOL><DEDENT>else:<EOL><INDENT>if is_element:<EOL><INDENT>prefix = None<EOL><DEDENT>else:<EOL><INDENT>prefix = self._make_prefix(declared_prefixes)<EOL><DEDENT>declarations[namespace] = prefix<EOL>declared_prefixes[namespace] = prefix<EOL><DEDENT>if prefix:<EOL><INDENT>return prefix + "<STR_LIT::>" + name<EOL><DEDENT>else:<EOL><INDENT>return name<EOL><DEDENT>

Return namespace-prefixed tag or attribute name.

        Add appropriate declaration to `declarations` when neccessary.

        If no prefix for an element namespace is defined, make the elements
        namespace default (no prefix). For attributes, make up a prefix in such
        case.

        :Parameters:
            - `name`: QName ('{namespace-uri}local-name')
              to convert
            - `is_element`: `True` for element, `False` for an attribute
            - `declared_prefixes`: mapping of prefixes already declared
              at this scope
            - `declarations`: XMLNS declarations on the current element.
        :Types:
            - `name`: `unicode`
            - `is_element`: `bool`
            - `declared_prefixes`: `unicode` to `unicode` dictionary
            - `declarations`: `unicode` to `unicode` dictionary

        :Returntype: `unicode`


if not self._head_emitted:<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>string = self._emit_element(element, level = <NUM_LIT:1>,<EOL>declared_prefixes = self._root_prefixes)<EOL>return remove_evil_characters(string)<EOL>

Serialize a stanza.

        Must be called after `emit_head`.

        :Parameters:
            - `element`: the element to serialize
        :Types:
            - `element`: :etree:`ElementTree.Element`

        :Return: serialized element
        :Returntype: `unicode`


def _split_qname(self, name, is_element):

if name.startswith("<STR_LIT:{>"):<EOL><INDENT>namespace, name = name[<NUM_LIT:1>:].split("<STR_LIT:}>", <NUM_LIT:1>)<EOL>if namespace in STANZA_NAMESPACES:<EOL><INDENT>namespace = self.stanza_namespace<EOL><DEDENT><DEDENT>elif is_element:<EOL><INDENT>raise ValueError("<STR_LIT>".format(name))<EOL><DEDENT>else:<EOL><INDENT>namespace = None<EOL><DEDENT>return namespace, name<EOL>

Split an element of attribute qname into namespace and local
        name.

        :Parameters:
            - `name`: element or attribute QName
            - `is_element`: `True` for an element, `False` for an attribute
        :Types:
            - `name`: `unicode`
            - `is_element`: `bool`

        :Return: namespace URI, local name
        :returntype: `unicode`, `unicode`


if getattr(_THREAD, "<STR_LIT>", None) is None:<EOL><INDENT>_THREAD.serializer = XMPPSerializer("<STR_LIT>")<EOL>_THREAD.serializer.emit_head(None, None)<EOL><DEDENT>return _THREAD.serializer.emit_stanza(element)<EOL>

Serialize an XMPP element.

    Utility function for debugging or logging.

        :Parameters:
            - `element`: the element to serialize
        :Types:
            - `element`: :etree:`ElementTree.Element`

        :Return: serialized element
        :Returntype: `unicode`


def __init__(self, stanza_namespace, extra_prefixes = None):

self.stanza_namespace = stanza_namespace<EOL>self._prefixes = {}<EOL>if extra_prefixes:<EOL><INDENT>self._prefixes.update(extra_prefixes)<EOL><DEDENT>self._root_prefixes = None<EOL>self._head_emitted = False<EOL>self._next_id = <NUM_LIT:1><EOL>

:Parameters:
    - `stanza_namespace`: the default namespace used for XMPP stanzas.
      E.g. 'jabber:client' for c2s connections.
    - `extra_prefixes`: mapping of namespaces to prefixes (not the
      other way) to be used on the stream. These prefixes will be
      declared on the root element and used in all descendants. That
      may be used to optimize the stream for size.
:Types:
    - `stanza_namespace`: `unicode`
    - `extra_prefixes`: `unicode` to `unicode` mapping.


return EVIL_CHARACTERS_RE.sub("<STR_LIT>", data)<EOL>

Remove control characters (not allowed in XML) from a string.


self._quit = True<EOL>


def stop(self, join = False, timeout = None):

logger.debug("<STR_LIT>")<EOL>for handler in self.io_handlers:<EOL><INDENT>handler.close()<EOL><DEDENT>if self.event_thread and self.event_thread.is_alive():<EOL><INDENT>logger.debug("<STR_LIT>")<EOL>self.event_queue.put(QUIT)<EOL><DEDENT>logger.debug("<STR_LIT>")<EOL>threads = self.io_threads + self.timeout_threads<EOL>for thread in threads:<EOL><INDENT>logger.debug("<STR_LIT>".format(thread))<EOL>thread.stop()<EOL><DEDENT>if not join:<EOL><INDENT>return<EOL><DEDENT>if self.event_thread:<EOL><INDENT>threads.append(self.event_thread)<EOL><DEDENT>if timeout is None:<EOL><INDENT>for thread in threads:<EOL><INDENT>thread.join()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>timeout1 = (timeout * <NUM_LIT>) / len(threads)<EOL>threads_left = []<EOL>for thread in threads:<EOL><INDENT>logger.debug("<STR_LIT>".format(thread))<EOL>thread.join(timeout1)<EOL>if thread.is_alive():<EOL><INDENT>logger.debug("<STR_LIT>".format(thread))<EOL>threads_left.append(thread)<EOL><DEDENT><DEDENT>if threads_left:<EOL><INDENT>timeout2 = (timeout * <NUM_LIT>) / len(threads_left)<EOL>for thread in threads_left:<EOL><INDENT>logger.debug("<STR_LIT>".format(thread))<EOL>thread.join(timeout2)<EOL><DEDENT><DEDENT><DEDENT>self.io_threads = []<EOL>self.event_thread = None<EOL>

Stop the threads.

        :Parameters:
            - `join`: join the threads (wait until they exit)
            - `timeout`: maximum time (in seconds) to wait when `join` is
              `True`).  No limit when `timeout` is `None`.


raise NotImplementedError<EOL>


logger.debug("<STR_LIT>".format(self.name))<EOL>while True:<EOL><INDENT>try:<EOL><INDENT>self.run()<EOL><DEDENT>except Exception: <EOL><INDENT>self.exc_info = sys.exc_info()<EOL>logger.debug("<STR_LIT>"<EOL>.format(self.name), exc_info = self.exc_info)<EOL>if self.exc_queue:<EOL><INDENT>self.exc_queue.put( (self, self.exc_info) )<EOL>continue<EOL><DEDENT>else:<EOL><INDENT>logger.debug("<STR_LIT>".format(self.name))<EOL>return<EOL><DEDENT><DEDENT>except:<EOL><INDENT>logger.debug("<STR_LIT>".format(self.name))<EOL>return<EOL><DEDENT>break<EOL><DEDENT>logger.debug("<STR_LIT>".format(self.name))<EOL>

The thread function. Calls `self.run()` and if it raises
        an exception, stores it in self.exc_info


return self.thread.join(timeout)<EOL>


if handler not in self.timeout_handlers:<EOL><INDENT>return<EOL><DEDENT>self.timeout_handlers.remove(handler)<EOL>for thread in self.timeout_threads:<EOL><INDENT>if thread.method.__self__ is handler:<EOL><INDENT>thread.stop()<EOL><DEDENT><DEDENT>


return self.thread.is_alive()<EOL>


self.daemon = daemon<EOL>self.io_threads = []<EOL>self.event_thread = EventDispatcherThread(self.event_dispatcher,<EOL>daemon = daemon, exc_queue = self.exc_queue)<EOL>self.event_thread.start()<EOL>for handler in self.io_handlers:<EOL><INDENT>self._run_io_threads(handler)<EOL><DEDENT>for handler in self.timeout_handlers:<EOL><INDENT>self._run_timeout_threads(handler)<EOL><DEDENT>


reader = ReadingThread(self.settings, handler, daemon = self.daemon,<EOL>exc_queue = self.exc_queue)<EOL>writter = WrittingThread(self.settings, handler, daemon = self.daemon,<EOL>exc_queue = self.exc_queue)<EOL>self.io_threads += [reader, writter]<EOL>reader.start()<EOL>writter.start()<EOL>


<EOL>interval = self.settings["<STR_LIT>"]<EOL>prepared = False<EOL>timeout = <NUM_LIT:0.1><EOL>while not self._quit:<EOL><INDENT>if not prepared:<EOL><INDENT>logger.debug("<STR_LIT>".format(<EOL>self.name, self.io_handler))<EOL>ret = self.io_handler.prepare()<EOL>logger.debug("<STR_LIT>".format(self.name,<EOL>ret))<EOL>if isinstance(ret, HandlerReady):<EOL><INDENT>prepared = True<EOL><DEDENT>elif isinstance(ret, PrepareAgain):<EOL><INDENT>if ret.timeout is not None:<EOL><INDENT>timeout = ret.timeout<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT><DEDENT>if self.io_handler.is_readable():<EOL><INDENT>logger.debug("<STR_LIT>".format(self.name))<EOL>fileno = self.io_handler.fileno()<EOL>if fileno is not None:<EOL><INDENT>readable = wait_for_read(fileno, interval)<EOL>if readable:<EOL><INDENT>self.io_handler.handle_read()<EOL><DEDENT><DEDENT><DEDENT>elif not prepared:<EOL><INDENT>if timeout:<EOL><INDENT>time.sleep(timeout)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>logger.debug("<STR_LIT>".format(self.name))<EOL>if not self.io_handler.wait_for_readability():<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT>

The thread function.

        First, call the handler's 'prepare' method until it returns
        `HandlerReady` then loop waiting for the socket input and calling
        'handle_read' on the handler.


if handler not in self.io_handlers:<EOL><INDENT>return<EOL><DEDENT>self.io_handlers.remove(handler)<EOL>for thread in self.io_threads:<EOL><INDENT>if thread.io_handler is handler:<EOL><INDENT>thread.stop()<EOL><DEDENT><DEDENT>


self.io_handlers.append(handler)<EOL>if self.event_thread is None:<EOL><INDENT>return<EOL><DEDENT>


<EOL>for dummy, method in inspect.getmembers(handler, callable):<EOL><INDENT>if not hasattr(method, "<STR_LIT>"):<EOL><INDENT>continue<EOL><DEDENT>thread = TimeoutThread(method, daemon = self.daemon,<EOL>exc_queue = self.exc_queue)<EOL>self.timeout_threads.append(thread)<EOL>thread.start()<EOL><DEDENT>


def loop_iteration(self, timeout = <NUM_LIT:0.1>):

try:<EOL><INDENT>exc_info = self.exc_queue.get(True, timeout)[<NUM_LIT:1>]<EOL><DEDENT>except queue.Empty:<EOL><INDENT>return<EOL><DEDENT>exc_type, exc_value, ext_stack = exc_info<EOL>raise exc_type(exc_value).with_traceback(ext_stack)<EOL>

Wait up to `timeout` seconds, raise any exception from the
        threads.


if self.check_events():<EOL><INDENT>return<EOL><DEDENT>if handler in self._unprepared_handlers:<EOL><INDENT>old_fileno = self._unprepared_handlers[handler]<EOL>prepared = self._prepare_io_handler(handler)<EOL><DEDENT>else:<EOL><INDENT>old_fileno = None<EOL>prepared = True<EOL><DEDENT>fileno = handler.fileno()<EOL>if old_fileno is not None and fileno != old_fileno:<EOL><INDENT>del self._handlers[old_fileno]<EOL>try:<EOL><INDENT>self.poll.unregister(old_fileno)<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>if not prepared:<EOL><INDENT>self._unprepared_handlers[handler] = fileno<EOL><DEDENT>if not fileno:<EOL><INDENT>return<EOL><DEDENT>self._handlers[fileno] = handler<EOL>events = <NUM_LIT:0><EOL>if handler.is_readable():<EOL><INDENT>logger.debug("<STR_LIT>".format(handler))<EOL>events |= select.POLLIN<EOL><DEDENT>if handler.is_writable():<EOL><INDENT>logger.debug("<STR_LIT>".format(handler))<EOL>events |= select.POLLOUT<EOL><DEDENT>if events:<EOL><INDENT>logger.debug("<STR_LIT>"<EOL>"<STR_LIT>".format(handler, fileno, events))<EOL>self.poll.register(fileno, events)<EOL><DEDENT>

Register an io-handler at the polling object.


self._unprepared_handlers[handler] = None<EOL>self._configure_io_handler(handler)<EOL>


logger.debug("<STR_LIT>".format(handler))<EOL>ret = handler.prepare()<EOL>logger.debug("<STR_LIT>".format(ret))<EOL>if isinstance(ret, HandlerReady):<EOL><INDENT>del self._unprepared_handlers[handler]<EOL>prepared = True<EOL><DEDENT>elif isinstance(ret, PrepareAgain):<EOL><INDENT>if ret.timeout is not None:<EOL><INDENT>if self._timeout is not None:<EOL><INDENT>self._timeout = min(self._timeout, ret.timeout)<EOL><DEDENT>else:<EOL><INDENT>self._timeout = ret.timeout<EOL><DEDENT><DEDENT>prepared = False<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>return prepared<EOL>

Call the `interfaces.IOHandler.prepare` method and
        remove the handler from unprepared handler list when done.


def timeout_handler(interval, recurring = None):

def decorator(func):<EOL><INDENT>"""<STR_LIT>"""<EOL>func._pyxmpp_timeout = interval<EOL>func._pyxmpp_recurring = recurring<EOL>return func<EOL><DEDENT>return decorator<EOL>

Method decorator generator for decorating event handlers.

    To be used on `TimeoutHandler` subclass methods only.

    :Parameters:
        - `interval`: interval (in seconds) before the method will be called.
        - `recurring`: When `True`, the handler will be called each `interval`
          seconds, when `False` it will be called only once. If `True`,
          then the handler should return the next interval or `None` if it
          should not be called again.
    :Types:
        - `interval`: `float`
        - `recurring`: `bool`


pass<EOL>

Add a new handler to the main loop.

        Do nothing if the handler is not registered at the main loop.

        :Parameters:
            - `handler`: the handler object to add
        :Types:
            - `handler`: `IOHandler` or `EventHandler` or `TimeoutHandler`


@abstractmethod<EOL><INDENT>def loop_iteration(self, timeout = <NUM_LIT:1>):<DEDENT>

pass<EOL>

Single loop iteration.

        :Parameters:
            - `timeout`: maximum time (in seconds) to block for
        :Types:
            - `timeout`: `float`


return False<EOL>

:Return: `True` when the I/O channel can be written to


return None<EOL>

Return file descriptor to poll or select.


pass<EOL>

Handle the 'channel writable' state. E.g. send buffered data via a
socket.


return False<EOL>


return False<EOL>

`True` then the loop has been finished or is about to finish (the
        final iteration in progress).


pass<EOL>

Close the channell immediately, so it won't expect more events.


return False<EOL>

:Return: `True` when the I/O channel can be read


self._timeout_handlers = [(t, h) for (t, h)<EOL>in self._timeout_handlers<EOL>if h.im_self != handler]<EOL>

Remove `TimeoutHandler` from the main loop.


sources_handled = <NUM_LIT:0><EOL>now = time.time()<EOL>schedule = None<EOL>while self._timeout_handlers:<EOL><INDENT>schedule, handler = self._timeout_handlers[<NUM_LIT:0>]<EOL>if schedule <= now:<EOL><INDENT>logger.debug("<STR_LIT>"<EOL>.format(handler))<EOL>self._timeout_handlers = self._timeout_handlers[<NUM_LIT:1>:]<EOL>result = handler()<EOL>logger.debug("<STR_LIT>".format(result))<EOL>rec = handler._pyxmpp_recurring<EOL>if rec:<EOL><INDENT>logger.debug("<STR_LIT>"<EOL>.format(handler._pyxmpp_timeout))<EOL>self._timeout_handlers.append(<EOL>(now + handler._pyxmpp_timeout, handler))<EOL>self._timeout_handlers.sort(key = lambda x: x[<NUM_LIT:0>])<EOL><DEDENT>elif rec is None and result is not None:<EOL><INDENT>logger.debug("<STR_LIT>"<EOL>.format(result))<EOL>self._timeout_handlers.append((now + result, handler))<EOL>self._timeout_handlers.sort(key = lambda x: x[<NUM_LIT:0>])<EOL><DEDENT>sources_handled += <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT>if self.check_events():<EOL><INDENT>return <NUM_LIT:0>, sources_handled<EOL><DEDENT><DEDENT>if self._timeout_handlers and schedule:<EOL><INDENT>timeout = schedule - now<EOL><DEDENT>else:<EOL><INDENT>timeout = None<EOL><DEDENT>return timeout, sources_handled<EOL>

Call the timeout handlers due.

        :Return: (next_event_timeout, sources_handled) tuple.
            next_event_timeout is number of seconds until the next timeout
            event, sources_handled is number of handlers called.


timeout = None<EOL>readable = []<EOL>writable = []<EOL>for handler in self._handlers:<EOL><INDENT>if handler not in self._prepared:<EOL><INDENT>logger.debug("<STR_LIT>".format(handler))<EOL>ret = handler.prepare()<EOL>logger.debug("<STR_LIT>".format(ret))<EOL>if isinstance(ret, HandlerReady):<EOL><INDENT>self._prepared.add(handler)<EOL><DEDENT>elif isinstance(ret, PrepareAgain):<EOL><INDENT>if ret.timeout is not None:<EOL><INDENT>if timeout is None:<EOL><INDENT>timeout = ret.timeout<EOL><DEDENT>else:<EOL><INDENT>timeout = min(timeout, ret.timeout)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT><DEDENT>if not handler.fileno():<EOL><INDENT>logger.debug("<STR_LIT>".format(handler))<EOL>continue<EOL><DEDENT>if handler.is_readable():<EOL><INDENT>logger.debug("<STR_LIT>".format(handler))<EOL>readable.append(handler)<EOL><DEDENT>if handler.is_writable():<EOL><INDENT>logger.debug("<STR_LIT>".format(handler))<EOL>writable.append(handler)<EOL><DEDENT><DEDENT>return readable, writable, timeout<EOL>

Prepare the I/O handlers.

        :Return: (readable, writable, timeout) tuple. 'readable' is the list
            of readable handlers, 'writable' - the list of writable handlers,
            'timeout' the suggested maximum timeout for this loop iteration or
            `None`


if self.check_events():<EOL><INDENT>return<EOL><DEDENT>if handler in self._unprepared_handlers:<EOL><INDENT>old_fileno = self._unprepared_handlers[handler]<EOL>prepared = self._prepare_io_handler(handler)<EOL><DEDENT>else:<EOL><INDENT>old_fileno = None<EOL>prepared = True<EOL><DEDENT>fileno = handler.fileno()<EOL>if old_fileno is not None and fileno != old_fileno:<EOL><INDENT>tag = self._io_sources.pop(handler, None)<EOL>if tag is not None:<EOL><INDENT>glib.source_remove(tag)<EOL><DEDENT><DEDENT>if not prepared:<EOL><INDENT>self._unprepared_handlers[handler] = fileno<EOL><DEDENT>if fileno is None:<EOL><INDENT>logger.debug("<STR_LIT>"<EOL>.format(handler))<EOL>return<EOL><DEDENT>events = <NUM_LIT:0><EOL>if handler.is_readable():<EOL><INDENT>logger.debug("<STR_LIT>".format(handler))<EOL>events |= glib.IO_IN | glib.IO_ERR<EOL><DEDENT>if handler.is_writable():<EOL><INDENT>logger.debug("<STR_LIT>".format(handler))<EOL>events |= glib.IO_OUT | glib.IO_HUP | glib.IO_ERR<EOL><DEDENT>if events:<EOL><INDENT>logger.debug("<STR_LIT>"<EOL>"<STR_LIT>".format(handler, fileno, events))<EOL>glib.io_add_watch(fileno, events, self._io_callback, handler)<EOL><DEDENT>

Register an io-handler with the glib main loop.


if not self._unprepared_pending:<EOL><INDENT>return<EOL><DEDENT>for handler in list(self._unprepared_pending):<EOL><INDENT>self._configure_io_handler(handler)<EOL><DEDENT>self.check_events()<EOL>


self._anything_done = True<EOL>logger.debug("<STR_LIT>")<EOL>main_loop.quit()<EOL>

Stops the loop after the time specified in the `loop` call.


def __init__(self, settings = None, handlers = None):

if settings is None:<EOL><INDENT>settings = XMPPSettings()<EOL><DEDENT>self.queue = settings["<STR_LIT>"]<EOL>self._handler_map = defaultdict(list)<EOL>if handlers:<EOL><INDENT>self.handlers = list(handlers)<EOL><DEDENT>else:<EOL><INDENT>self.handlers = []<EOL><DEDENT>self._update_handlers()<EOL>self.lock = threading.RLock()<EOL>

Initialize the event dispatcher.

        :Parameters:
            - `settings`: the settings. "event_queue" settings provides the
              event queue object.
            - `handlers`: the initial list of event handler objects.
        :Types:
            - `settings`: `XMPPSettings`
            - `handlers`: iterable of objects


if not isinstance(handler, EventHandler):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>with self.lock:<EOL><INDENT>if handler in self.handlers:<EOL><INDENT>return<EOL><DEDENT>self.handlers.append(handler)<EOL>self._update_handlers()<EOL><DEDENT>

Add a handler object.

        :Parameters:
            - `handler`: the object providing event handler methods
        :Types:
            - `handler`: `EventHandler`


while self.dispatch(True) is not QUIT:<EOL><INDENT>pass<EOL><DEDENT>

Wait for and dispatch events until `QUIT` is reached.


if handler in self._unprepared_handlers:<EOL><INDENT>old_fileno = self._unprepared_handlers[handler]<EOL>del self._unprepared_handlers[handler]<EOL><DEDENT>else:<EOL><INDENT>old_fileno = handler.fileno()<EOL><DEDENT>if old_fileno is not None:<EOL><INDENT>del self._handlers[old_fileno]<EOL>self.io_loop.remove_handler(handler.fileno())<EOL><DEDENT>


if self.check_events():<EOL><INDENT>return<EOL><DEDENT>if handler in self._unprepared_handlers:<EOL><INDENT>old_fileno = self._unprepared_handlers[handler]<EOL>prepared = self._prepare_io_handler(handler)<EOL><DEDENT>else:<EOL><INDENT>old_fileno = None<EOL>prepared = True<EOL><DEDENT>fileno = handler.fileno()<EOL>if old_fileno is not None and fileno != old_fileno:<EOL><INDENT>del self._handlers[old_fileno]<EOL>self.io_loop.remove_handler(old_fileno)<EOL><DEDENT>if not prepared:<EOL><INDENT>self._unprepared_handlers[handler] = fileno<EOL><DEDENT>if not fileno:<EOL><INDENT>return<EOL><DEDENT>update = fileno in self._handlers<EOL>events = ioloop.IOLoop.NONE<EOL>if handler.is_readable():<EOL><INDENT>logger.debug("<STR_LIT>".format(handler))<EOL>events |= ioloop.IOLoop.READ<EOL><DEDENT>if handler.is_writable():<EOL><INDENT>logger.debug("<STR_LIT>".format(handler))<EOL>events |= ioloop.IOLoop.WRITE<EOL><DEDENT>if self._handlers.get(fileno, None) == events:<EOL><INDENT>return<EOL><DEDENT>self._handlers[fileno] = events<EOL>if events:<EOL><INDENT>logger.debug("<STR_LIT>"<EOL>"<STR_LIT>".format(handler, fileno, events))<EOL>if update:<EOL><INDENT>self.io_loop.update_handler(fileno, events)<EOL><DEDENT>else:<EOL><INDENT>self.io_loop.add_handler(<EOL>fileno, partial(self._handle_event, handler), events<EOL>)<EOL><DEDENT><DEDENT>

Register an io-handler at the polling object.


def stream_element_handler(element_name, usage_restriction = None):

def decorator(func):<EOL><INDENT>"""<STR_LIT>"""<EOL>func._pyxmpp_stream_element_handled = element_name<EOL>func._pyxmpp_usage_restriction = usage_restriction<EOL>return func<EOL><DEDENT>return decorator<EOL>

Method decorator generator for decorating stream element
    handler methods in `StreamFeatureHandler` subclasses.

    :Parameters:
        - `element_name`: stream element QName
        - `usage_restriction`: optional usage restriction: "initiator" or
          "receiver"
    :Types:
        - `element_name`: `unicode`
        - `usage_restriction`: `unicode`