NS_DISCO = 'http://jabber.org/protocol/disco'
NS_DISCO_INFO = NS_DISCO + '#info'
NS_DISCO_ITEMS = NS_DISCO + '#items'
IQ_GET = '/iq[@type="get"]'
DISCO_INFO = IQ_GET + '/query[@xmlns="' + NS_DISCO_INFO + '"]'
DISCO_ITEMS = IQ_GET + '/query[@xmlns="' + NS_DISCO_ITEMS + '"]'
class DiscoFeature(unicode):
class DiscoIdentity(object):
class DiscoInfo(object):
class DiscoItem(object):
class DiscoItems(object):
class _DiscoRequest(generic.Request):
class DiscoClientProtocol(XMPPHandler):
class DiscoHandler(XMPPHandler, IQHandlerMixin):
    def toElement(self):
    def fromElement(element):
    def __init__(self, category, idType, name=None):
    def toElement(self):
    def fromElement(element):
    def __init__(self):
    def __iter__(self):
    def append(self, item):
    def toElement(self):
    def fromElement(element):
    def __init__(self, entity, nodeIdentifier='', name=None):
    def toElement(self):
    def fromElement(element):
    def __init__(self):
    def __iter__(self):
    def append(self, item):
    def toElement(self):
    def fromElement(element):
    def __init__(self, verb=None, nodeIdentifier='',
                       recipient=None, sender=None):
    def parseElement(self, element):
    def toElement(self):
    def requestInfo(self, entity, nodeIdentifier='', sender=None):
    def requestItems(self, entity, nodeIdentifier='', sender=None):
    def connectionInitialized(self):
    def _onDiscoInfo(self, iq):
        def toResponse(info):
    def _onDiscoItems(self, iq):
        def toResponse(items):
    def _gatherResults(self, deferredList):
        def cb(resultList):
        def eb(failure):
    def info(self, requestor, target, nodeIdentifier):
    def items(self, requestor, target, nodeIdentifier): NS_X_DATA = 'jabber:x:data'
class Error(Exception):
class FieldNameRequiredError(Error):
class TooManyValuesError(Error):
class Option(object):
class Field(object):
class Form(object):
    def __init__(self, value, label=None):
    def __repr__(self):
    def toElement(self):
    def fromElement(element):
    def __init__(self, fieldType='text-single', var=None, value=None,
                       values=None, options=None, label=None, desc=None,
                       required=False):
    def __repr__(self):
    def __value_set(self, value):
    def __value_get(self):
    def typeCheck(self):
    def toElement(self, asForm=False):
    def _parse_desc(field, element):
    def _parse_option(field, element):
    def _parse_required(field, element):
    def _parse_value(field, element):
    def fromElement(element):
    def fromDict(fieldDict):
    def __init__(self, formType, title=None, instructions=None,
                       formNamespace=None, fields=None):
    def __repr__(self):
    def addField(self, field):
    def removeField(self, field):
    def makeFields(self, values, fieldDefs=None, filterUnknown=True):
    def toElement(self):
    def _parse_title(form, element):
    def _parse_instructions(form, element):
    def _parse_field(form, element):
    def fromElement(element):
    def __iter__(self):
    def __len__(self):
    def __getitem__(self, key):
    def get(self, key, default=None):
    def __contains__(self, key):
    def iterkeys(self):
    def itervalues(self):
    def iteritems(self):
        def keys(self):
        def values(self):
        def items(self):
    def getValues(self):
    def typeCheck(self, fieldDefs=None, filterUnknown=False):
def findForm(element, formNamespace): IQ_GET = '/iq[@type="get"]'
IQ_SET = '/iq[@type="set"]'
NS_VERSION = 'jabber:iq:version'
VERSION = IQ_GET + '/query[@xmlns="' + NS_VERSION + '"]'
def parseXml(string):
def stripNamespace(rootElement):
    def strip(element):
    def connectionInitialized(self):
    def iqFallback(self, iq):
    def __init__(self, name, version):
    def connectionInitialized(self):
    def onVersion(self, iq):
    def getDiscoInfo(self, requestor, target, nodeIdentifier=''):
    def getDiscoItems(self, requestor, target, nodeIdentifier=''):
    def __init__(self):
    def __init__(self, recipient=None, sender=None):
    def fromElement(Class, element):
    def parseElement(self, element):
    def toElement(self):
    def parseElement(self, element):
    def __init__(self, recipient=None, sender=None, stanzaType=None):
    def parseRequest(self, element):
    def toElement(self):
    def __init__(self, authenticator):
    def buildProtocol(self, addr):
    def clientConnectionFailed(self, connector, reason):
def prepareIDNName(name):
class FallbackHandler(XMPPHandler):
class VersionHandler(XMPPHandler):
class XmlPipe(object):
class Stanza(object):
class ErrorStanza(Stanza):
class Request(Stanza):
class DeferredXmlStreamFactory(BootstrapMixin, protocol.ClientFactory): NS_SHIM = "http://jabber.org/protocol/shim"
class Headers(domish.Element):
    def __init__(self, headers):
def extractHeaders(stanza): class IQ(xmlstream.IQ):
    def __init__(self, *args, **kwargs):
        # Make sure we have a reactor parameter
        try:
            reactor = kwargs['reactor']
        except KeyError:
            from twisted.internet import reactor
        kwargs['reactor'] = reactor

        # Check if IQ's init accepts the reactor parameter
        try:
            xmlstream.IQ.__init__(self, *args, **kwargs)
        except TypeError:
            # Guess not. Remove the reactor parameter and try again.
            del kwargs['reactor']
            xmlstream.IQ.__init__(self, *args, **kwargs)

            # Patch the XmlStream instance so that it has a _callLater
            self._xmlstream._callLater = reactor.callLater class IQHandlerMixin(object):
    """
    XMPP subprotocol mixin for handle incoming IQ stanzas.

    This matches up the iq with XPath queries to call methods on itself,
    wrapping the call so that exceptions result in proper error responses,
    or, when succesful will reply with a response with optional payload.

    Derivatives of this class must provide an
    L{XmlStream<twisted.words.protocols.jabber.xmlstream.XmlStream>} instance
    in its C{xmlstream} attribute.

    The optional payload is taken from the result of the handler and is
    expected to be a child or a list of childs.

    If an exception is raised, or the deferred has its errback called,
    the exception is checked for being a L{error.StanzaError}. If so,
    an error response is sent. Any other exception will cause a error
    response of C{internal-server-error} to be sent.

    A typical way to use this mixin, is to set up L{xpath} observers on the
    C{xmlstream} to call handleRequest, for example in an overridden
    L{XMPPHandler.connectionMade}. It is likely a good idea to only listen for
    incoming iq get and/org iq set requests, and not for any iq, to prevent
    hijacking incoming responses to outgoing iq requests. An example:

        >>> QUERY_ROSTER = "/query[@xmlns='jabber:iq:roster']"
        >>> class MyHandler(XMPPHandler, IQHandlerMixin):
        ...    iqHandlers = {"/iq[@type='get']" + QUERY_ROSTER: 'onRosterGet',
        ...                  "/iq[@type='set']" + QUERY_ROSTER: 'onRosterSet'}
        ...    def connectionMade(self):
        ...        self.xmlstream.addObserver(
        ...          "/iq[@type='get' or @type='set']" + QUERY_ROSTER,
        ...          self.handleRequest)
        ...    def onRosterGet(self, iq):
        ...        pass
        ...    def onRosterSet(self, iq):
        ...        pass

    @cvar iqHandlers: Mapping from XPath queries (as a string) to the method
                      name that will handle requests that match the query.
    @type iqHandlers: C{dict}
    """

    iqHandlers = None

    def handleRequest(self, iq):
        """
        Find a handler and wrap the call for sending a response stanza.
        """
        def toResult(result, iq):
            response = toResponse(iq, 'result')

            if result:
                if IElement.providedBy(result):
                    response.addChild(result)
                else:
                    for element in result:
                        response.addChild(element)

            return response

        def checkNotImplemented(failure):
            failure.trap(NotImplementedError)
            raise error.StanzaError('feature-not-implemented')

        def fromStanzaError(failure, iq):
            failure.trap(error.StanzaError)
            return failure.value.toResponse(iq)

        def fromOtherError(failure, iq):
            log.msg("Unhandled error in iq handler:", isError=True)
            log.err(failure)
            return error.StanzaError('internal-server-error').toResponse(iq)

        handler = None
        for queryString, method in iteritems(self.iqHandlers):
            if xpath.internQuery(queryString).matches(iq):
                handler = getattr(self, method)

        if handler:
            d = defer.maybeDeferred(handler, iq)
        else:
            d = defer.fail(NotImplementedError())

        d.addCallback(toResult, iq)
        d.addErrback(checkNotImplemented)
        d.addErrback(fromStanzaError, iq)
        d.addErrback(fromOtherError, iq)

        d.addCallback(self.send)

        iq.handled = True class XMPPHandler(object):
    """
    XMPP protocol handler.

    Classes derived from this class implement (part of) one or more XMPP
    extension protocols, and are referred to as a subprotocol implementation.
    """

    def __init__(self):
        self.parent = None
        self.xmlstream = None


    def setHandlerParent(self, parent):
        self.parent = parent
        self.parent.addHandler(self)


    def disownHandlerParent(self, parent):
        self.parent.removeHandler(self)
        self.parent = None


    def makeConnection(self, xs):
        self.xmlstream = xs
        self.connectionMade()


    def connectionMade(self):
        """
        Called after a connection has been established.

        Can be overridden to perform work before stream initialization.
        """


    def connectionInitialized(self):
        """
        The XML stream has been initialized.

        Can be overridden to perform work after stream initialization, e.g. to
        set up observers and start exchanging XML stanzas.
        """


    def connectionLost(self, reason):
        """
        The XML stream has been closed.

        This method can be extended to inspect the C{reason} argument and
        act on it.
        """
        self.xmlstream = None


    def send(self, obj):
        """
        Send data over the managed XML stream.

        @note: The stream manager maintains a queue for data sent using this
               method when there is no current initialized XML stream. This
               data is then sent as soon as a new stream has been established
               and initialized. Subsequently, L{connectionInitialized} will be
               called again. If this queueing is not desired, use C{send} on
               C{self.xmlstream}.

        @param obj: data to be sent over the XML stream. This is usually an
                    object providing L{domish.IElement}, or serialized XML. See
                    L{xmlstream.XmlStream} for details.
        """
        self.parent.send(obj)


    def request(self, request):
        """
        Send an IQ request and track the response.

        This passes the request to the parent for sending and response
        tracking.

        @see: L{StreamManager.request}.
        """
        return self.parent.request(request) class IPubSubClient(Interface):

    def itemsReceived(event):
        """
        Called when an items notification has been received for a node.

        An item can be an element named C{item} or C{retract}. Respectively,
        they signal an item being published or retracted, optionally
        accompanied with an item identifier in the C{id} attribute.

        @param event: The items event.
        @type event: L{ItemsEvent<wokkel.pubsub.ItemsEvent>}
        """


    def deleteReceived(event):
        """
        Called when a deletion notification has been received for a node.

        @param event: The items event.
        @type event: L{ItemsEvent<wokkel.pubsub.DeleteEvent>}
        """


    def purgeReceived(event):
        """
        Called when a purge notification has been received for a node.

        Upon receiving this notification all items associated should be
        considered retracted.

        @param event: The items event.
        @type event: L{ItemsEvent<wokkel.pubsub.PurgeEvent>}
        """

    def createNode(service, nodeIdentifier=None):
        """
        Create a new publish subscribe node.

        @param service: The publish-subscribe service entity.
        @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param nodeIdentifier: Optional suggestion for the new node's
                               identifier. If omitted, the creation of an
                               instant node will be attempted.
        @type nodeIdentifier: C{unicode}
        @return: a deferred that fires with the identifier of the newly created
                 node. Note that this can differ from the suggested identifier
                 if the publish subscribe service chooses to modify or ignore
                 the suggested identifier.
        @rtype: L{Deferred<twisted.internet.defer.Deferred>}
        """

    def deleteNode(service, nodeIdentifier):
        """
        Delete a node.

        @param service: The publish-subscribe service entity.
        @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param nodeIdentifier: Identifier of the node to be deleted.
        @type nodeIdentifier: C{unicode}
        @rtype: L{Deferred<twisted.internet.defer.Deferred>}
        """

    def subscribe(service, nodeIdentifier, subscriber):
        """
        Subscribe to a node with a given JID.

        @param service: The publish-subscribe service entity.
        @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param nodeIdentifier: Identifier of the node to subscribe to.
        @type nodeIdentifier: C{unicode}
        @param subscriber: JID to subscribe to the node.
        @type subscriber: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @rtype: L{Deferred<twisted.internet.defer.Deferred>}
        """

    def unsubscribe(service, nodeIdentifier, subscriber):
        """
        Unsubscribe from a node with a given JID.

        @param service: The publish-subscribe service entity.
        @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param nodeIdentifier: Identifier of the node to unsubscribe from.
        @type nodeIdentifier: C{unicode}
        @param subscriber: JID to unsubscribe from the node.
        @type subscriber: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @rtype: L{Deferred<twisted.internet.defer.Deferred>}
        """

    def publish(service, nodeIdentifier, items=[]):
        """
        Publish to a node.

        Node that the C{items} parameter is optional, because so-called
        transient, notification-only nodes do not use items and publish
        actions only signify a change in some resource.

        @param service: The publish-subscribe service entity.
        @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param nodeIdentifier: Identifier of the node to publish to.
        @type nodeIdentifier: C{unicode}
        @param items: List of item elements.
        @type items: C{list} of L{Item}
        @rtype: L{Deferred<twisted.internet.defer.Deferred>}
        """ class IPubSubService(Interface):
    """
    Interface for an XMPP Publish Subscribe Service.

    All methods that are called as the result of an XMPP request are to
    return a deferred that fires when the requested action has been performed.
    Alternatively, exceptions maybe raised directly or by calling C{errback}
    on the returned deferred.
    """

    def notifyPublish(service, nodeIdentifier, notifications):
        """
        Send out notifications for a publish event.

        @param service: The entity the notifications will originate from.
        @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param nodeIdentifier: The identifier of the node that was published
            to.
        @type nodeIdentifier: C{unicode}
        @param notifications: The notifications as tuples of subscriber, the
            list of subscriptions and the list of items to be notified.
        @type notifications: C{list} of
            (L{JID<twisted.words.protocols.jabber.jid.JID>}, C{list} of
            L{Subscription<wokkel.pubsub.Subscription>}, C{list} of
            L{Element<twisted.words.xish.domish.Element>})
        """


    def notifyDelete(service, nodeIdentifier, subscribers,
                     redirectURI=None):
        """
        Send out node deletion notifications.

        @param service: The entity the notifications will originate from.
        @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param nodeIdentifier: The identifier of the node that was deleted.
        @type nodeIdentifier: C{unicode}
        @param subscribers: The subscribers for which a notification should be
            sent out.
        @type subscribers: C{list} of
            L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param redirectURI: Optional XMPP URI of another node that subscribers
            are redirected to.
        @type redirectURI: C{str}
        """

    def publish(requestor, service, nodeIdentifier, items):
        """
        Called when a publish request has been received.

        @param requestor: The entity the request originated from.
        @type requestor: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param service: The entity the request was addressed to.
        @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param nodeIdentifier: The identifier of the node to publish to.
        @type nodeIdentifier: C{unicode}
        @param items: The items to be published as elements.
        @type items: C{list} of C{Element<twisted.words.xish.domish.Element>}
        @return: deferred that fires on success.
        @rtype: L{Deferred<twisted.internet.defer.Deferred>}
        """

    def subscribe(requestor, service, nodeIdentifier, subscriber):
        """
        Called when a subscribe request has been received.

        @param requestor: The entity the request originated from.
        @type requestor: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param service: The entity the request was addressed to.
        @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param nodeIdentifier: The identifier of the node to subscribe to.
        @type nodeIdentifier: C{unicode}
        @param subscriber: The entity to be subscribed.
        @type subscriber: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @return: A deferred that fires with a
                 L{Subscription<wokkel.pubsub.Subscription>}.
        @rtype: L{Deferred<twisted.internet.defer.Deferred>}
        """

    def unsubscribe(requestor, service, nodeIdentifier, subscriber):
        """
        Called when a subscribe request has been received.

        @param requestor: The entity the request originated from.
        @type requestor: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param service: The entity the request was addressed to.
        @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param nodeIdentifier: The identifier of the node to unsubscribe from.
        @type nodeIdentifier: C{unicode}
        @param subscriber: The entity to be unsubscribed.
        @type subscriber: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @return: A deferred that fires with C{None} when unsubscription has
                 succeeded.
        @rtype: L{Deferred<twisted.internet.defer.Deferred>}
        """

    def subscriptions(requestor, service):
        """
        Called when a subscriptions retrieval request has been received.

        @param requestor: The entity the request originated from.
        @type requestor: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param service: The entity the request was addressed to.
        @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @return: A deferred that fires with a C{list} of subscriptions as
                 L{Subscription<wokkel.pubsub.Subscription>}.
        @rtype: L{Deferred<twisted.internet.defer.Deferred>}
        """

    def affiliations(requestor, service):
        """
        Called when a affiliations retrieval request has been received.

        @param requestor: The entity the request originated from.
        @type requestor: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param service: The entity the request was addressed to.
        @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @return: A deferred that fires with a C{list} of affiliations as
            C{tuple}s of (node identifier as C{unicode}, affiliation state as
            C{str}). The affiliation can be C{'owner'}, C{'publisher'}, or
            C{'outcast'}.
        @rtype: L{Deferred<twisted.internet.defer.Deferred>}
        """

    def create(requestor, service, nodeIdentifier):
        """
        Called when a node creation request has been received.

        @param requestor: The entity the request originated from.
        @type requestor: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param service: The entity the request was addressed to.
        @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param nodeIdentifier: The suggestion for the identifier of the node
            to be created. If the request did not include a suggestion for the
            node identifier, the value is C{None}.
        @type nodeIdentifier: C{unicode} or C{NoneType}
        @return: A deferred that fires with a C{unicode} that represents
                 the identifier of the new node.
        @rtype: L{Deferred<twisted.internet.defer.Deferred>}
        """

    def getConfigurationOptions():
        """
        Retrieve all known node configuration options.

        The returned dictionary holds the possible node configuration options
        by option name. The value of each entry represents the specifics for
        that option in a dictionary:

         - C{'type'} (C{str}): The option's type (see
           L{Field<wokkel.data_form.Field>}'s doc string for possible values).
         - C{'label'} (C{unicode}): A human readable label for this option.
         - C{'options'} (C{dict}): Optional list of possible values for this
           option.

        Example::

            {
            "pubsub#persist_items":
                {"type": "boolean",
                 "label": "Persist items to storage"},
            "pubsub#deliver_payloads":
                {"type": "boolean",
                 "label": "Deliver payloads with event notifications"},
            "pubsub#send_last_published_item":
                {"type": "list-single",
                 "label": "When to send the last published item",
                 "options": {
                     "never": "Never",
                     "on_sub": "When a new subscription is processed"}
                }
            }

        @rtype: C{dict}.
        """

    def getDefaultConfiguration(requestor, service, nodeType):
        """
        Called when a default node configuration request has been received.

        @param requestor: The entity the request originated from.
        @type requestor: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param service: The entity the request was addressed to.
        @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param nodeType: The type of node for which the configuration is
                         retrieved, C{'leaf'} or C{'collection'}.
        @type nodeType: C{str}
        @return: A deferred that fires with a C{dict} representing the default
                 node configuration. Keys are C{str}s that represent the
                 field name. Values can be of types C{unicode}, C{int} or
                 C{bool}.
        @rtype: L{Deferred<twisted.internet.defer.Deferred>}
        """

    def getConfiguration(requestor, service, nodeIdentifier):
        """
        Called when a node configuration retrieval request has been received.

        @param requestor: The entity the request originated from.
        @type requestor: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param service: The entity the request was addressed to.
        @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param nodeIdentifier: The identifier of the node to retrieve the
                               configuration from.
        @type nodeIdentifier: C{unicode}
        @return: A deferred that fires with a C{dict} representing the node
            configuration. Keys are C{str}s that represent the field name.
            Values can be of types C{unicode}, C{int} or C{bool}.
        @rtype: L{Deferred<twisted.internet.defer.Deferred>}
        """

    def setConfiguration(requestor, service, nodeIdentifier, options):
        """
        Called when a node configuration change request has been received.

        @param requestor: The entity the request originated from.
        @type requestor: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param service: The entity the request was addressed to.
        @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param nodeIdentifier: The identifier of the node to change the
                               configuration of.
        @type nodeIdentifier: C{unicode}
        @return: A deferred that fires with C{None} when the node's
                 configuration has been changed.
        @rtype: L{Deferred<twisted.internet.defer.Deferred>}
        """

    def items(requestor, service, nodeIdentifier, maxItems, itemIdentifiers):
        """
        Called when a items retrieval request has been received.

        @param requestor: The entity the request originated from.
        @type requestor: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param service: The entity the request was addressed to.
        @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param nodeIdentifier: The identifier of the node to retrieve items
                               from.
        @type nodeIdentifier: C{unicode}
        """

    def retract(requestor, service, nodeIdentifier, itemIdentifiers):
        """
        Called when a item retraction request has been received.

        @param requestor: The entity the request originated from.
        @type requestor: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param service: The entity the request was addressed to.
        @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param nodeIdentifier: The identifier of the node to retract items
                               from.
        @type nodeIdentifier: C{unicode}
        """

    def purge(requestor, service, nodeIdentifier):
        """
        Called when a node purge request has been received.

        @param requestor: The entity the request originated from.
        @type requestor: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param service: The entity the request was addressed to.
        @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param nodeIdentifier: The identifier of the node to be purged.
        @type nodeIdentifier: C{unicode}
        """

    def delete(requestor, service, nodeIdentifier):
        """
        Called when a node deletion request has been received.

        @param requestor: The entity the request originated from.
        @type requestor: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param service: The entity the request was addressed to.
        @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param nodeIdentifier: The identifier of the node to be delete.
        @type nodeIdentifier: C{unicode}
        """ class IPubSubResource(Interface):

    def locateResource(request):
        """
        Locate a resource that will handle the request.

        @param request: The publish-subscribe request.
        @type request: L{wokkel.pubsub.PubSubRequest}
        """


    def getInfo(requestor, service, nodeIdentifier):
        """
        Get node type and meta data.

        @param requestor: The entity the request originated from.
        @type requestor: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param service: The publish-subscribe service entity.
        @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param nodeIdentifier: Identifier of the node to request the info for.
        @type nodeIdentifier: C{unicode}
        @return: A deferred that fires with a dictionary. If not empty,
                 it must have the keys C{'type'} and C{'meta-data'} to keep
                 respectively the node type and a dictionary with the meta
                 data for that node.
        @rtype: L{Deferred<twisted.internet.defer.Deferred>}
        """


    def getNodes(requestor, service, nodeIdentifier):
        """
        Get all nodes contained by this node.

        @param requestor: The entity the request originated from.
        @type requestor: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param service: The publish-subscribe service entity.
        @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param nodeIdentifier: Identifier of the node to request the childs
            for.
        @type nodeIdentifier: C{unicode}
        @return: A deferred that fires with a list of child node identifiers.
        @rtype: L{Deferred<twisted.internet.defer.Deferred>}
        """


    def getConfigurationOptions():
        """
        Retrieve all known node configuration options.

        The returned dictionary holds the possible node configuration options
        by option name. The value of each entry represents the specifics for
        that option in a dictionary:

         - C{'type'} (C{str}): The option's type (see
           L{Field<wokkel.data_form.Field>}'s doc string for possible values).
         - C{'label'} (C{unicode}): A human readable label for this option.
         - C{'options'} (C{dict}): Optional list of possible values for this
           option.

        Example::

            {
            "pubsub#persist_items":
                {"type": "boolean",
                 "label": "Persist items to storage"},
            "pubsub#deliver_payloads":
                {"type": "boolean",
                 "label": "Deliver payloads with event notifications"},
            "pubsub#send_last_published_item":
                {"type": "list-single",
                 "label": "When to send the last published item",
                 "options": {
                     "never": "Never",
                     "on_sub": "When a new subscription is processed"}
                }
            }

        @rtype: C{dict}.
        """


    def publish(request):
        """
        Called when a publish request has been received.

        @param request: The publish-subscribe request.
        @type request: L{wokkel.pubsub.PubSubRequest}
        @return: deferred that fires on success.
        @rtype: L{Deferred<twisted.internet.defer.Deferred>}
        """


    def subscribe(request):
        """
        Called when a subscribe request has been received.

        @param request: The publish-subscribe request.
        @type request: L{wokkel.pubsub.PubSubRequest}
        @return: A deferred that fires with a
                 L{Subscription<wokkel.pubsub.Subscription>}.
        @rtype: L{Deferred<twisted.internet.defer.Deferred>}
        """


    def unsubscribe(request):
        """
        Called when a subscribe request has been received.

        @param request: The publish-subscribe request.
        @type request: L{wokkel.pubsub.PubSubRequest}
        @return: A deferred that fires with C{None} when unsubscription has
                 succeeded.
        @rtype: L{Deferred<twisted.internet.defer.Deferred>}
        """


    def subscriptions(request):
        """
        Called when a subscriptions retrieval request has been received.

        @param request: The publish-subscribe request.
        @type request: L{wokkel.pubsub.PubSubRequest}
        @return: A deferred that fires with a C{list} of subscriptions as
                 L{Subscription<wokkel.pubsub.Subscription>}.
        @rtype: L{Deferred<twisted.internet.defer.Deferred>}
        """


    def affiliations(request):
        """
        Called when a affiliations retrieval request has been received.

        @param request: The publish-subscribe request.
        @type request: L{wokkel.pubsub.PubSubRequest}
        @return: A deferred that fires with a C{list} of affiliations as
            C{tuple}s of (node identifier as C{unicode}, affiliation state as
            C{str}). The affiliation can be C{'owner'}, C{'publisher'}, or
            C{'outcast'}.
        @rtype: L{Deferred<twisted.internet.defer.Deferred>}
        """


    def create(request):
        """
        Called when a node creation request has been received.

        @param request: The publish-subscribe request.
        @type request: L{wokkel.pubsub.PubSubRequest}
        @return: A deferred that fires with a C{unicode} that represents
                 the identifier of the new node.
        @rtype: L{Deferred<twisted.internet.defer.Deferred>}
        """


    def default(request):
        """
        Called when a default node configuration request has been received.

        @param request: The publish-subscribe request.
        @type request: L{wokkel.pubsub.PubSubRequest}
        @return: A deferred that fires with a C{dict} representing the default
                 node configuration. Keys are C{str}s that represent the
                 field name. Values can be of types C{unicode}, C{int} or
                 C{bool}.
        @rtype: L{Deferred<twisted.internet.defer.Deferred>}
        """


    def configureGet(request):
        """
        Called when a node configuration retrieval request has been received.

        @param request: The publish-subscribe request.
        @type request: L{wokkel.pubsub.PubSubRequest}
        @return: A deferred that fires with a C{dict} representing the node
            configuration. Keys are C{str}s that represent the field name.
            Values can be of types C{unicode}, C{int} or C{bool}.
        @rtype: L{Deferred<twisted.internet.defer.Deferred>}
        """


    def configureSet(request):
        """
        Called when a node configuration change request has been received.

        @param request: The publish-subscribe request.
        @type request: L{wokkel.pubsub.PubSubRequest}
        @return: A deferred that fires with C{None} when the node's
                 configuration has been changed.
        @rtype: L{Deferred<twisted.internet.defer.Deferred>}
        """


    def items(request):
        """
        Called when a items retrieval request has been received.

        @param request: The publish-subscribe request.
        @type request: L{wokkel.pubsub.PubSubRequest}
        @return: A deferred that fires with a C{list} of L{pubsub.Item}.
        @rtype: L{Deferred<twisted.internet.defer.Deferred>}
        """


    def retract(request):
        """
        Called when a item retraction request has been received.

        @param request: The publish-subscribe request.
        @type request: L{wokkel.pubsub.PubSubRequest}
        @return: A deferred that fires with C{None} when the given items have
                 been retracted.
        @rtype: L{Deferred<twisted.internet.defer.Deferred>}
        """


    def purge(request):
        """
        Called when a node purge request has been received.

        @param request: The publish-subscribe request.
        @type request: L{wokkel.pubsub.PubSubRequest}
        @return: A deferred that fires with C{None} when the node has been
                 purged.
        @rtype: L{Deferred<twisted.internet.defer.Deferred>}
        """


    def delete(request):
        """
        Called when a node deletion request has been received.

        @param request: The publish-subscribe request.
        @type request: L{wokkel.pubsub.PubSubRequest}
        @return: A deferred that fires with C{None} when the node has been
                 deleted.
        @rtype: L{Deferred<twisted.internet.defer.Deferred>}
        """


    def affiliationsGet(request):
        """
        Called when an owner affiliations retrieval request been received.

        @param request: The publish-subscribe request.
        @type request: L{wokkel.pubsub.PubSubRequest}
        @return: A deferred that fires with a C{dict} of affiliations with the
            entity as key (L{JID<twisted.words.protocols.jabber.jid.JID>}) and
            the affiliation state as value (C{unicode}).  The affiliation can
            be C{u'owner'}, C{u'publisher'}, or C{u'outcast'}.
        @rtype: L{Deferred<twisted.internet.defer.Deferred>}

        @note: Affiliations are always on the bare JID. An implementation of
        this method MUST NOT return JIDs with a resource part.
        """


    def affiliationsSet(request):
        """
        Called when a affiliations modify request has been received.

        @param request: The publish-subscribe request.
        @type request: L{wokkel.pubsub.PubSubRequest}

        @return: A deferred that fires with C{None} when the affiliation
            changes were succesfully processed..
        @rtype: L{Deferred<twisted.internet.defer.Deferred>}

        @note: Affiliations are always on the bare JID. The JIDs in
            L{wokkel.pubsub.PubSubRequest}'s C{affiliations} attribute are
            already stripped of any resource.
        """
from zope.interface import implementer
from twisted.internet import defer
from twisted.python import log
from twisted.python.compat import StringType, iteritems, unicode
from twisted.words.protocols.jabber import jid, error
from twisted.words.xish import domish
from wokkel import disco, data_form, generic, shim
from wokkel.compat import IQ
from wokkel.subprotocols import IQHandlerMixin, XMPPHandler
from wokkel.iwokkel import IPubSubClient, IPubSubService, IPubSubResource


    def items(self, service, nodeIdentifier, maxItems=None,
              subscriptionIdentifier=None, sender=None, itemIdentifiers=None):
        """
        Retrieve previously published items from a publish subscribe node.

        @param service: The publish subscribe service that keeps the node.
        @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}

        @param nodeIdentifier: The identifier of the node.
        @type nodeIdentifier: L{unicode}

        @param maxItems: Optional limit on the number of retrieved items.
        @type maxItems: L{int}

        @param subscriptionIdentifier: Optional subscription identifier. In
            case the node has been subscribed to multiple times, this narrows
            the results to the specific subscription.
        @type subscriptionIdentifier: L{unicode}

        @param itemIdentifiers: Identifiers of the items to be retrieved.
        @type itemIdentifiers: L{set} of L{unicode}
        """
        request = PubSubRequest('items')
        request.recipient = service
        request.nodeIdentifier = nodeIdentifier
        if maxItems:
            request.maxItems = str(int(maxItems))
        request.subscriptionIdentifier = subscriptionIdentifier
        request.sender = sender
        request.itemIdentifiers = itemIdentifiers

        def cb(iq):
            items = []
            for element in iq.pubsub.items.elements():
                if element.uri == NS_PUBSUB and element.name == 'item':
                    items.append(element)
            return items

        d = request.send(self.xmlstream)
        d.addCallback(cb)
        return d


    def getOptions(self, service, nodeIdentifier, subscriber,
                         subscriptionIdentifier=None, sender=None):
        """
        Get subscription options.

        @param service: The publish subscribe service that keeps the node.
        @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}

        @param nodeIdentifier: The identifier of the node.
        @type nodeIdentifier: L{unicode}

        @param subscriber: The entity subscribed to the node.
        @type subscriber: L{JID<twisted.words.protocols.jabber.jid.JID>}

        @param subscriptionIdentifier: Optional subscription identifier.
        @type subscriptionIdentifier: L{unicode}

        @rtype: L{data_form.Form}
        """
        request = PubSubRequest('optionsGet')
        request.recipient = service
        request.nodeIdentifier = nodeIdentifier
        request.subscriber = subscriber
        request.subscriptionIdentifier = subscriptionIdentifier
        request.sender = sender

        def cb(iq):
            form = data_form.findForm(iq.pubsub.options,
                                      NS_PUBSUB_SUBSCRIBE_OPTIONS)
            form.typeCheck()
            return form

        d = request.send(self.xmlstream)
        d.addCallback(cb)
        return d


    def setOptions(self, service, nodeIdentifier, subscriber,
                         options, subscriptionIdentifier=None, sender=None):
        """
        Set subscription options.

        @param service: The publish subscribe service that keeps the node.
        @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}

        @param nodeIdentifier: The identifier of the node.
        @type nodeIdentifier: L{unicode}

        @param subscriber: The entity subscribed to the node.
        @type subscriber: L{JID<twisted.words.protocols.jabber.jid.JID>}

        @param options: Subscription options.
        @type options: L{dict}.

        @param subscriptionIdentifier: Optional subscription identifier.
        @type subscriptionIdentifier: L{unicode}
        """
        request = PubSubRequest('optionsSet')
        request.recipient = service
        request.nodeIdentifier = nodeIdentifier
        request.subscriber = subscriber
        request.subscriptionIdentifier = subscriptionIdentifier
        request.sender = sender

        form = data_form.Form(formType='submit',
                              formNamespace=NS_PUBSUB_SUBSCRIBE_OPTIONS)
        form.makeFields(options)
        request.options = form

        d = request.send(self.xmlstream)
        return d



@implementer(IPubSubService, disco.IDisco)

class PubSubService(XMPPHandler, IQHandlerMixin):