2011-11-22 05:50:40 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
2010-03-26 21:32:16 +00:00
|
|
|
"""
|
2011-11-22 05:50:40 +00:00
|
|
|
sleekxmpp.xmlstream.stanzabase
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
2010-03-26 21:32:16 +00:00
|
|
|
|
2013-02-14 09:24:09 +00:00
|
|
|
module implements a wrapper layer for XML objects
|
2011-11-22 05:50:40 +00:00
|
|
|
that allows them to be treated like dictionaries.
|
|
|
|
|
|
|
|
Part of SleekXMPP: The Sleek XMPP Library
|
|
|
|
|
|
|
|
:copyright: (c) 2011 Nathanael C. Fritz
|
|
|
|
:license: MIT, see LICENSE for more details
|
2010-03-26 21:32:16 +00:00
|
|
|
"""
|
2010-08-13 03:24:09 +00:00
|
|
|
|
2012-06-05 23:54:26 +00:00
|
|
|
from __future__ import with_statement, unicode_literals
|
|
|
|
|
2010-08-13 03:24:09 +00:00
|
|
|
import copy
|
2009-12-17 01:54:22 +00:00
|
|
|
import logging
|
2010-05-12 20:45:36 +00:00
|
|
|
import weakref
|
2010-08-13 03:24:09 +00:00
|
|
|
from xml.etree import cElementTree as ET
|
2010-01-29 10:04:15 +00:00
|
|
|
|
2010-08-13 03:24:09 +00:00
|
|
|
from sleekxmpp.xmlstream import JID
|
2010-08-06 00:26:41 +00:00
|
|
|
from sleekxmpp.xmlstream.tostring import tostring
|
2011-01-27 21:01:35 +00:00
|
|
|
from sleekxmpp.thirdparty import OrderedDict
|
2009-06-03 22:56:51 +00:00
|
|
|
|
2010-08-13 14:12:51 +00:00
|
|
|
|
2010-11-06 05:28:59 +00:00
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
2010-08-13 14:12:51 +00:00
|
|
|
# Used to check if an argument is an XML object.
|
|
|
|
XML_TYPE = type(ET.Element('xml'))
|
2010-01-14 15:37:44 +00:00
|
|
|
|
2010-07-19 17:58:53 +00:00
|
|
|
|
2012-06-05 23:54:26 +00:00
|
|
|
XML_NS = 'http://www.w3.org/XML/1998/namespace'
|
|
|
|
|
|
|
|
|
Allow a stanza plugin to override a parent's interfaces.
Each interface, say foo, may be overridden in three ways:
set_foo
get_foo
del_foo
To declare an override in a plugin, add the class field
overrides as so:
overrides = ['set_foo', 'del_foo']
Each override must have a matching set_foo(), etc method
for implementing the new behaviour.
To enable the overrides for a particular parent stanza,
pass the option overrides=True to register_stanza_plugin.
register_stanza_plugin(Stanza, Plugin, overrides=True)
Example code:
class Test(ElementBase):
name = 'test'
namespace = 'testing'
interfaces = set(('foo', 'bar'))
sub_interfaces = set(('bar',))
class TestOverride(ElementBase):
name = 'test-override'
namespace = 'testing'
plugin_attrib = 'override'
interfaces = set(('foo',))
overrides = ['set_foo']
def setup(self, xml):
# Don't include an XML element in the parent stanza
# since we're adding just an attribute.
# If adding a regular subelement, no need to do this.
self.xml = ET.Element('')
def set_foo(self, value):
print("overrides!")
self.parent()._set_attr('foo', 'override-%s' % value)
register_stanza_plugin(Test, TestOverride, overrides=True)
Example usage:
>>> t = TestStanza()
>>> t['foo'] = 'bar'
>>> t['foo']
'override-bar'
2011-03-24 16:25:17 +00:00
|
|
|
def register_stanza_plugin(stanza, plugin, iterable=False, overrides=False):
|
2010-08-13 14:12:51 +00:00
|
|
|
"""
|
|
|
|
Associate a stanza object as a plugin for another stanza.
|
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
>>> from sleekxmpp.xmlstream import register_stanza_plugin
|
|
|
|
>>> register_stanza_plugin(Iq, CustomStanza)
|
|
|
|
|
2012-05-05 21:01:13 +00:00
|
|
|
Plugin stanzas marked as iterable will be included in the list of
|
|
|
|
substanzas for the parent, using ``parent['substanzas']``. If the
|
|
|
|
attribute ``plugin_multi_attrib`` was defined for the plugin, then
|
|
|
|
the substanza set can be filtered to only instances of the plugin
|
2012-06-19 08:29:48 +00:00
|
|
|
class. For example, given a plugin class ``Foo`` with
|
2012-05-05 21:01:13 +00:00
|
|
|
``plugin_multi_attrib = 'foos'`` then::
|
|
|
|
|
|
|
|
parent['foos']
|
|
|
|
|
|
|
|
would return a collection of all ``Foo`` substanzas.
|
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
:param class stanza: The class of the parent stanza.
|
|
|
|
:param class plugin: The class of the plugin stanza.
|
|
|
|
:param bool iterable: Indicates if the plugin stanza should be
|
|
|
|
included in the parent stanza's iterable
|
|
|
|
``'substanzas'`` interface results.
|
|
|
|
:param bool overrides: Indicates if the plugin should be allowed
|
|
|
|
to override the interface handlers for
|
|
|
|
the parent stanza, based on the plugin's
|
|
|
|
``overrides`` field.
|
|
|
|
|
|
|
|
.. versionadded:: 1.0-Beta1
|
|
|
|
Made ``register_stanza_plugin`` the default name. The prior
|
|
|
|
``registerStanzaPlugin`` function name remains as an alias.
|
2010-08-13 14:12:51 +00:00
|
|
|
"""
|
|
|
|
tag = "{%s}%s" % (plugin.namespace, plugin.name)
|
2011-09-01 07:50:45 +00:00
|
|
|
|
|
|
|
# Prevent weird memory reference gotchas by ensuring
|
|
|
|
# that the parent stanza class has its own set of
|
|
|
|
# plugin info maps and is not using the mappings from
|
|
|
|
# an ancestor class (like ElementBase).
|
|
|
|
plugin_info = ('plugin_attrib_map', 'plugin_tag_map',
|
|
|
|
'plugin_iterables', 'plugin_overrides')
|
|
|
|
for attr in plugin_info:
|
|
|
|
info = getattr(stanza, attr)
|
|
|
|
setattr(stanza, attr, info.copy())
|
|
|
|
|
2010-08-13 14:12:51 +00:00
|
|
|
stanza.plugin_attrib_map[plugin.plugin_attrib] = plugin
|
|
|
|
stanza.plugin_tag_map[tag] = plugin
|
2011-09-01 07:50:45 +00:00
|
|
|
|
2011-01-26 15:04:36 +00:00
|
|
|
if iterable:
|
|
|
|
stanza.plugin_iterables.add(plugin)
|
2012-05-05 21:01:13 +00:00
|
|
|
if plugin.plugin_multi_attrib:
|
|
|
|
multiplugin = multifactory(plugin, plugin.plugin_multi_attrib)
|
|
|
|
register_stanza_plugin(stanza, multiplugin)
|
Allow a stanza plugin to override a parent's interfaces.
Each interface, say foo, may be overridden in three ways:
set_foo
get_foo
del_foo
To declare an override in a plugin, add the class field
overrides as so:
overrides = ['set_foo', 'del_foo']
Each override must have a matching set_foo(), etc method
for implementing the new behaviour.
To enable the overrides for a particular parent stanza,
pass the option overrides=True to register_stanza_plugin.
register_stanza_plugin(Stanza, Plugin, overrides=True)
Example code:
class Test(ElementBase):
name = 'test'
namespace = 'testing'
interfaces = set(('foo', 'bar'))
sub_interfaces = set(('bar',))
class TestOverride(ElementBase):
name = 'test-override'
namespace = 'testing'
plugin_attrib = 'override'
interfaces = set(('foo',))
overrides = ['set_foo']
def setup(self, xml):
# Don't include an XML element in the parent stanza
# since we're adding just an attribute.
# If adding a regular subelement, no need to do this.
self.xml = ET.Element('')
def set_foo(self, value):
print("overrides!")
self.parent()._set_attr('foo', 'override-%s' % value)
register_stanza_plugin(Test, TestOverride, overrides=True)
Example usage:
>>> t = TestStanza()
>>> t['foo'] = 'bar'
>>> t['foo']
'override-bar'
2011-03-24 16:25:17 +00:00
|
|
|
if overrides:
|
|
|
|
for interface in plugin.overrides:
|
|
|
|
stanza.plugin_overrides[interface] = plugin.plugin_attrib
|
2010-07-19 17:58:53 +00:00
|
|
|
|
|
|
|
|
2010-10-18 01:38:22 +00:00
|
|
|
# To maintain backwards compatibility for now, preserve the camel case name.
|
|
|
|
registerStanzaPlugin = register_stanza_plugin
|
|
|
|
|
|
|
|
|
2012-04-30 20:19:17 +00:00
|
|
|
def multifactory(stanza, plugin_attrib):
|
|
|
|
"""
|
|
|
|
Returns a ElementBase class for handling reoccuring child stanzas
|
|
|
|
"""
|
2012-06-19 08:29:48 +00:00
|
|
|
|
|
|
|
def plugin_filter(self):
|
|
|
|
return lambda x: isinstance(x, self._multistanza)
|
|
|
|
|
|
|
|
def plugin_lang_filter(self, lang):
|
|
|
|
return lambda x: isinstance(x, self._multistanza) and \
|
|
|
|
x['lang'] == lang
|
|
|
|
|
2012-04-30 20:19:17 +00:00
|
|
|
class Multi(ElementBase):
|
|
|
|
"""
|
|
|
|
Template class for multifactory
|
|
|
|
"""
|
|
|
|
def setup(self, xml=None):
|
|
|
|
self.xml = ET.Element('')
|
|
|
|
|
2012-06-05 23:54:26 +00:00
|
|
|
def get_multi(self, lang=None):
|
2012-04-30 20:19:17 +00:00
|
|
|
parent = self.parent()
|
2012-06-06 09:08:25 +00:00
|
|
|
if not lang or lang == '*':
|
2012-06-19 08:29:48 +00:00
|
|
|
res = filter(plugin_filter(self), parent)
|
2012-06-05 23:54:26 +00:00
|
|
|
else:
|
2012-06-19 08:29:48 +00:00
|
|
|
res = filter(plugin_filter(self, lang), parent)
|
2012-05-05 21:01:13 +00:00
|
|
|
return list(res)
|
2012-04-30 20:19:17 +00:00
|
|
|
|
2012-06-05 23:54:26 +00:00
|
|
|
def set_multi(self, val, lang=None):
|
2012-04-30 20:19:17 +00:00
|
|
|
parent = self.parent()
|
2012-06-06 09:08:25 +00:00
|
|
|
del_multi = getattr(self, 'del_%s' % plugin_attrib)
|
|
|
|
del_multi(lang)
|
2012-04-30 20:19:17 +00:00
|
|
|
for sub in val:
|
|
|
|
parent.append(sub)
|
|
|
|
|
2012-06-05 23:54:26 +00:00
|
|
|
def del_multi(self, lang=None):
|
2012-04-30 20:19:17 +00:00
|
|
|
parent = self.parent()
|
2012-06-06 09:08:25 +00:00
|
|
|
if not lang or lang == '*':
|
2012-06-19 08:29:48 +00:00
|
|
|
res = filter(plugin_filter(self), parent)
|
2012-06-05 23:54:26 +00:00
|
|
|
else:
|
2012-06-19 08:29:48 +00:00
|
|
|
res = filter(plugin_filter(self, lang), parent)
|
2012-06-06 09:08:25 +00:00
|
|
|
res = list(res)
|
|
|
|
if not res:
|
|
|
|
del parent.plugins[(plugin_attrib, None)]
|
|
|
|
parent.loaded_plugins.remove(plugin_attrib)
|
|
|
|
try:
|
|
|
|
parent.xml.remove(self.xml)
|
2013-02-14 09:24:09 +00:00
|
|
|
except ValueError:
|
2012-06-06 09:08:25 +00:00
|
|
|
pass
|
|
|
|
else:
|
|
|
|
for stanza in list(res):
|
|
|
|
parent.iterables.remove(stanza)
|
|
|
|
parent.xml.remove(stanza.xml)
|
2012-04-30 20:19:17 +00:00
|
|
|
|
|
|
|
Multi.is_extension = True
|
|
|
|
Multi.plugin_attrib = plugin_attrib
|
|
|
|
Multi._multistanza = stanza
|
2012-06-05 23:54:26 +00:00
|
|
|
Multi.interfaces = set([plugin_attrib])
|
|
|
|
Multi.lang_interfaces = set([plugin_attrib])
|
2012-04-30 20:19:17 +00:00
|
|
|
setattr(Multi, "get_%s" % plugin_attrib, get_multi)
|
|
|
|
setattr(Multi, "set_%s" % plugin_attrib, set_multi)
|
|
|
|
setattr(Multi, "del_%s" % plugin_attrib, del_multi)
|
|
|
|
return Multi
|
|
|
|
|
|
|
|
|
2012-01-18 06:28:44 +00:00
|
|
|
def fix_ns(xpath, split=False, propagate_ns=True, default_ns=''):
|
|
|
|
"""Apply the stanza's namespace to elements in an XPath expression.
|
|
|
|
|
|
|
|
:param string xpath: The XPath expression to fix with namespaces.
|
|
|
|
:param bool split: Indicates if the fixed XPath should be left as a
|
|
|
|
list of element names with namespaces. Defaults to
|
|
|
|
False, which returns a flat string path.
|
|
|
|
:param bool propagate_ns: Overrides propagating parent element
|
|
|
|
namespaces to child elements. Useful if
|
|
|
|
you wish to simply split an XPath that has
|
|
|
|
non-specified namespaces, and child and
|
|
|
|
parent namespaces are known not to always
|
|
|
|
match. Defaults to True.
|
|
|
|
"""
|
|
|
|
fixed = []
|
|
|
|
# Split the XPath into a series of blocks, where a block
|
|
|
|
# is started by an element with a namespace.
|
|
|
|
ns_blocks = xpath.split('{')
|
|
|
|
for ns_block in ns_blocks:
|
|
|
|
if '}' in ns_block:
|
|
|
|
# Apply the found namespace to following elements
|
|
|
|
# that do not have namespaces.
|
|
|
|
namespace = ns_block.split('}')[0]
|
|
|
|
elements = ns_block.split('}')[1].split('/')
|
|
|
|
else:
|
|
|
|
# Apply the stanza's namespace to the following
|
|
|
|
# elements since no namespace was provided.
|
|
|
|
namespace = default_ns
|
|
|
|
elements = ns_block.split('/')
|
|
|
|
|
|
|
|
for element in elements:
|
|
|
|
if element:
|
|
|
|
# Skip empty entry artifacts from splitting.
|
2013-01-20 23:43:02 +00:00
|
|
|
if propagate_ns and element[0] != '*':
|
2012-01-18 06:28:44 +00:00
|
|
|
tag = '{%s}%s' % (namespace, element)
|
|
|
|
else:
|
|
|
|
tag = element
|
|
|
|
fixed.append(tag)
|
|
|
|
if split:
|
|
|
|
return fixed
|
|
|
|
return '/'.join(fixed)
|
|
|
|
|
|
|
|
|
2010-08-06 00:26:41 +00:00
|
|
|
class ElementBase(object):
|
2010-08-26 17:49:36 +00:00
|
|
|
|
|
|
|
"""
|
|
|
|
The core of SleekXMPP's stanza XML manipulation and handling is provided
|
|
|
|
by ElementBase. ElementBase wraps XML cElementTree objects and enables
|
|
|
|
access to the XML contents through dictionary syntax, similar in style
|
|
|
|
to the Ruby XMPP library Blather's stanza implementation.
|
|
|
|
|
|
|
|
Stanzas are defined by their name, namespace, and interfaces. For
|
2011-11-22 05:50:40 +00:00
|
|
|
example, a simplistic Message stanza could be defined as::
|
2010-08-26 17:49:36 +00:00
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
>>> class Message(ElementBase):
|
|
|
|
... name = "message"
|
|
|
|
... namespace = "jabber:client"
|
|
|
|
... interfaces = set(('to', 'from', 'type', 'body'))
|
|
|
|
... sub_interfaces = set(('body',))
|
2010-08-26 17:49:36 +00:00
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
The resulting Message stanza's contents may be accessed as so::
|
2010-08-26 17:49:36 +00:00
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
>>> message['to'] = "user@example.com"
|
|
|
|
>>> message['body'] = "Hi!"
|
|
|
|
>>> message['body']
|
|
|
|
"Hi!"
|
|
|
|
>>> del message['body']
|
|
|
|
>>> message['body']
|
|
|
|
""
|
2010-08-26 17:49:36 +00:00
|
|
|
|
|
|
|
The interface values map to either custom access methods, stanza
|
|
|
|
XML attributes, or (if the interface is also in sub_interfaces) the
|
|
|
|
text contents of a stanza's subelement.
|
|
|
|
|
|
|
|
Custom access methods may be created by adding methods of the
|
|
|
|
form "getInterface", "setInterface", or "delInterface", where
|
2010-08-26 18:07:09 +00:00
|
|
|
"Interface" is the titlecase version of the interface name.
|
2010-08-26 17:49:36 +00:00
|
|
|
|
|
|
|
Stanzas may be extended through the use of plugins. A plugin
|
2011-11-22 05:50:40 +00:00
|
|
|
is simply a stanza that has a plugin_attrib value. For example::
|
2010-08-26 17:49:36 +00:00
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
>>> class MessagePlugin(ElementBase):
|
|
|
|
... name = "custom_plugin"
|
|
|
|
... namespace = "custom"
|
|
|
|
... interfaces = set(('useful_thing', 'custom'))
|
|
|
|
... plugin_attrib = "custom"
|
2010-08-26 17:49:36 +00:00
|
|
|
|
|
|
|
The plugin stanza class must be associated with its intended
|
2011-11-22 05:50:40 +00:00
|
|
|
container stanza by using register_stanza_plugin as so::
|
2010-08-26 17:49:36 +00:00
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
>>> register_stanza_plugin(Message, MessagePlugin)
|
2010-08-26 17:49:36 +00:00
|
|
|
|
|
|
|
The plugin may then be accessed as if it were built-in to the parent
|
2011-11-22 05:50:40 +00:00
|
|
|
stanza::
|
2010-08-26 17:49:36 +00:00
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
>>> message['custom']['useful_thing'] = 'foo'
|
2010-08-26 17:49:36 +00:00
|
|
|
|
|
|
|
If a plugin provides an interface that is the same as the plugin's
|
2011-01-20 00:49:13 +00:00
|
|
|
plugin_attrib value, then the plugin's interface may be assigned
|
|
|
|
directly from the parent stanza, as shown below, but retrieving
|
2011-11-22 05:50:40 +00:00
|
|
|
information will require all interfaces to be used, as so::
|
2010-08-26 17:49:36 +00:00
|
|
|
|
2012-06-19 08:29:48 +00:00
|
|
|
>>> # Same as using message['custom']['custom']
|
|
|
|
>>> message['custom'] = 'bar'
|
|
|
|
>>> # Must use all interfaces
|
|
|
|
>>> message['custom']['custom']
|
2011-11-22 05:50:40 +00:00
|
|
|
'bar'
|
2011-01-20 00:49:13 +00:00
|
|
|
|
2011-11-22 07:17:39 +00:00
|
|
|
If the plugin sets :attr:`is_extension` to ``True``, then both setting
|
2011-01-20 00:49:13 +00:00
|
|
|
and getting an interface value that is the same as the plugin's
|
2011-11-22 05:50:40 +00:00
|
|
|
plugin_attrib value will work, as so::
|
|
|
|
|
|
|
|
>>> message['custom'] = 'bar' # Using is_extension=True
|
|
|
|
>>> message['custom']
|
|
|
|
'bar'
|
|
|
|
|
|
|
|
|
|
|
|
:param xml: Initialize the stanza object with an existing XML object.
|
2012-06-19 23:20:54 +00:00
|
|
|
:param parent: Optionally specify a parent stanza object will
|
2011-11-22 05:50:40 +00:00
|
|
|
contain this substanza.
|
2010-08-26 17:49:36 +00:00
|
|
|
"""
|
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
#: The XML tag name of the element, not including any namespace
|
2012-06-19 08:29:48 +00:00
|
|
|
#: prefixes. For example, an :class:`ElementBase` object for
|
|
|
|
#: ``<message />`` would use ``name = 'message'``.
|
2010-08-13 14:15:52 +00:00
|
|
|
name = 'stanza'
|
2011-11-22 05:50:40 +00:00
|
|
|
|
|
|
|
#: The XML namespace for the element. Given ``<foo xmlns="bar" />``,
|
|
|
|
#: then ``namespace = "bar"`` should be used. The default namespace
|
|
|
|
#: is ``jabber:client`` since this is being used in an XMPP library.
|
2010-08-13 14:15:52 +00:00
|
|
|
namespace = 'jabber:client'
|
2011-11-22 05:50:40 +00:00
|
|
|
|
|
|
|
#: For :class:`ElementBase` subclasses which are intended to be used
|
|
|
|
#: as plugins, the ``plugin_attrib`` value defines the plugin name.
|
|
|
|
#: Plugins may be accessed by using the ``plugin_attrib`` value as
|
2011-12-31 06:28:41 +00:00
|
|
|
#: the interface. An example using ``plugin_attrib = 'foo'``::
|
2011-11-22 05:50:40 +00:00
|
|
|
#:
|
|
|
|
#: register_stanza_plugin(Message, FooPlugin)
|
|
|
|
#: msg = Message()
|
|
|
|
#: msg['foo']['an_interface_from_the_foo_plugin']
|
|
|
|
plugin_attrib = 'plugin'
|
|
|
|
|
2012-05-05 21:01:13 +00:00
|
|
|
#: For :class:`ElementBase` subclasses that are intended to be an
|
|
|
|
#: iterable group of items, the ``plugin_multi_attrib`` value defines
|
|
|
|
#: an interface for the parent stanza which returns the entire group
|
|
|
|
#: of matching substanzas. So the following are equivalent::
|
|
|
|
#:
|
|
|
|
#: # Given stanza class Foo, with plugin_multi_attrib = 'foos'
|
|
|
|
#: parent['foos']
|
|
|
|
#: filter(isinstance(item, Foo), parent['substanzas'])
|
|
|
|
plugin_multi_attrib = ''
|
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
#: The set of keys that the stanza provides for accessing and
|
|
|
|
#: manipulating the underlying XML object. This set may be augmented
|
|
|
|
#: with the :attr:`plugin_attrib` value of any registered
|
|
|
|
#: stanza plugins.
|
2010-08-13 14:15:52 +00:00
|
|
|
interfaces = set(('type', 'to', 'from', 'id', 'payload'))
|
2011-11-22 05:50:40 +00:00
|
|
|
|
|
|
|
#: A subset of :attr:`interfaces` which maps interfaces to direct
|
|
|
|
#: subelements of the underlying XML object. Using this set, the text
|
|
|
|
#: of these subelements may be set, retrieved, or removed without
|
|
|
|
#: needing to define custom methods.
|
2012-06-05 23:54:26 +00:00
|
|
|
sub_interfaces = set()
|
2011-11-22 05:50:40 +00:00
|
|
|
|
2012-03-28 04:05:50 +00:00
|
|
|
#: A subset of :attr:`interfaces` which maps the presence of
|
|
|
|
#: subelements to boolean values. Using this set allows for quickly
|
|
|
|
#: checking for the existence of empty subelements like ``<required />``.
|
|
|
|
#:
|
|
|
|
#: .. versionadded:: 1.1
|
2012-06-05 23:54:26 +00:00
|
|
|
bool_interfaces = set()
|
|
|
|
|
|
|
|
#: .. versionadded:: 1.1.2
|
|
|
|
lang_interfaces = set()
|
2012-03-28 04:05:50 +00:00
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
#: In some cases you may wish to override the behaviour of one of the
|
|
|
|
#: parent stanza's interfaces. The ``overrides`` list specifies the
|
|
|
|
#: interface name and access method to be overridden. For example,
|
|
|
|
#: to override setting the parent's ``'condition'`` interface you
|
|
|
|
#: would use::
|
|
|
|
#:
|
|
|
|
#: overrides = ['set_condition']
|
|
|
|
#:
|
|
|
|
#: Getting and deleting the ``'condition'`` interface would not
|
|
|
|
#: be affected.
|
|
|
|
#:
|
|
|
|
#: .. versionadded:: 1.0-Beta5
|
|
|
|
overrides = []
|
|
|
|
|
|
|
|
#: If you need to add a new interface to an existing stanza, you
|
|
|
|
#: can create a plugin and set ``is_extension = True``. Be sure
|
|
|
|
#: to set the :attr:`plugin_attrib` value to the desired interface
|
|
|
|
#: name, and that it is the only interface listed in
|
|
|
|
#: :attr:`interfaces`. Requests for the new interface from the
|
|
|
|
#: parent stanza will be passed to the plugin directly.
|
|
|
|
#:
|
|
|
|
#: .. versionadded:: 1.0-Beta5
|
|
|
|
is_extension = False
|
|
|
|
|
|
|
|
#: A map of interface operations to the overriding functions.
|
|
|
|
#: For example, after overriding the ``set`` operation for
|
|
|
|
#: the interface ``body``, :attr:`plugin_overrides` would be::
|
|
|
|
#:
|
|
|
|
#: {'set_body': <some function>}
|
|
|
|
#:
|
|
|
|
#: .. versionadded: 1.0-Beta5
|
Allow a stanza plugin to override a parent's interfaces.
Each interface, say foo, may be overridden in three ways:
set_foo
get_foo
del_foo
To declare an override in a plugin, add the class field
overrides as so:
overrides = ['set_foo', 'del_foo']
Each override must have a matching set_foo(), etc method
for implementing the new behaviour.
To enable the overrides for a particular parent stanza,
pass the option overrides=True to register_stanza_plugin.
register_stanza_plugin(Stanza, Plugin, overrides=True)
Example code:
class Test(ElementBase):
name = 'test'
namespace = 'testing'
interfaces = set(('foo', 'bar'))
sub_interfaces = set(('bar',))
class TestOverride(ElementBase):
name = 'test-override'
namespace = 'testing'
plugin_attrib = 'override'
interfaces = set(('foo',))
overrides = ['set_foo']
def setup(self, xml):
# Don't include an XML element in the parent stanza
# since we're adding just an attribute.
# If adding a regular subelement, no need to do this.
self.xml = ET.Element('')
def set_foo(self, value):
print("overrides!")
self.parent()._set_attr('foo', 'override-%s' % value)
register_stanza_plugin(Test, TestOverride, overrides=True)
Example usage:
>>> t = TestStanza()
>>> t['foo'] = 'bar'
>>> t['foo']
'override-bar'
2011-03-24 16:25:17 +00:00
|
|
|
plugin_overrides = {}
|
2011-11-22 05:50:40 +00:00
|
|
|
|
|
|
|
#: A mapping of the :attr:`plugin_attrib` values of registered
|
|
|
|
#: plugins to their respective classes.
|
|
|
|
plugin_attrib_map = {}
|
|
|
|
|
|
|
|
#: A mapping of root element tag names (in ``'{namespace}elementname'``
|
|
|
|
#: format) to the plugin classes responsible for them.
|
2010-08-13 14:15:52 +00:00
|
|
|
plugin_tag_map = {}
|
2011-11-22 05:50:40 +00:00
|
|
|
|
|
|
|
#: The set of stanza classes that can be iterated over using
|
|
|
|
#: the 'substanzas' interface. Classes are added to this set
|
|
|
|
#: when registering a plugin with ``iterable=True``::
|
|
|
|
#:
|
|
|
|
#: register_stanza_plugin(DiscoInfo, DiscoItem, iterable=True)
|
|
|
|
#:
|
|
|
|
#: .. versionadded:: 1.0-Beta5
|
|
|
|
plugin_iterables = set()
|
|
|
|
|
|
|
|
#: A deprecated version of :attr:`plugin_iterables` that remains
|
|
|
|
#: for backward compatibility. It required a parent stanza to
|
|
|
|
#: know beforehand what stanza classes would be iterable::
|
|
|
|
#:
|
|
|
|
#: class DiscoItem(ElementBase):
|
|
|
|
#: ...
|
|
|
|
#:
|
|
|
|
#: class DiscoInfo(ElementBase):
|
|
|
|
#: subitem = (DiscoItem, )
|
|
|
|
#: ...
|
|
|
|
#:
|
|
|
|
#: .. deprecated:: 1.0-Beta5
|
2011-03-23 00:42:43 +00:00
|
|
|
subitem = set()
|
2011-11-22 05:50:40 +00:00
|
|
|
|
|
|
|
#: The default XML namespace: ``http://www.w3.org/XML/1998/namespace``.
|
2012-06-05 23:54:26 +00:00
|
|
|
xml_ns = XML_NS
|
2010-08-13 14:15:52 +00:00
|
|
|
|
|
|
|
def __init__(self, xml=None, parent=None):
|
2011-11-22 05:50:40 +00:00
|
|
|
self._index = 0
|
2010-08-13 14:26:33 +00:00
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
#: The underlying XML object for the stanza. It is a standard
|
|
|
|
#: :class:`xml.etree.cElementTree` object.
|
2010-08-13 14:26:33 +00:00
|
|
|
self.xml = xml
|
2011-11-22 05:50:40 +00:00
|
|
|
|
|
|
|
#: An ordered dictionary of plugin stanzas, mapped by their
|
|
|
|
#: :attr:`plugin_attrib` value.
|
2011-01-27 21:01:35 +00:00
|
|
|
self.plugins = OrderedDict()
|
2012-06-05 23:54:26 +00:00
|
|
|
self.loaded_plugins = set()
|
2011-11-22 05:50:40 +00:00
|
|
|
|
|
|
|
#: A list of child stanzas whose class is included in
|
|
|
|
#: :attr:`plugin_iterables`.
|
2010-08-13 14:26:33 +00:00
|
|
|
self.iterables = []
|
2011-11-22 05:50:40 +00:00
|
|
|
|
|
|
|
#: The name of the tag for the stanza's root element. It is the
|
|
|
|
#: same as calling :meth:`tag_name()` and is formatted as
|
|
|
|
#: ``'{namespace}elementname'``.
|
2011-01-26 16:27:41 +00:00
|
|
|
self.tag = self.tag_name()
|
2010-08-13 14:26:33 +00:00
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
#: A :class:`weakref.weakref` to the parent stanza, if there is one.
|
|
|
|
#: If not, then :attr:`parent` is ``None``.
|
|
|
|
self.parent = None
|
|
|
|
if parent is not None:
|
2012-04-14 15:13:38 +00:00
|
|
|
if not isinstance(parent, weakref.ReferenceType):
|
|
|
|
self.parent = weakref.ref(parent)
|
|
|
|
else:
|
|
|
|
self.parent = parent
|
2010-10-18 01:38:22 +00:00
|
|
|
|
2011-03-23 00:42:43 +00:00
|
|
|
if self.subitem is not None:
|
|
|
|
for sub in self.subitem:
|
|
|
|
self.plugin_iterables.add(sub)
|
|
|
|
|
2010-08-13 14:26:33 +00:00
|
|
|
if self.setup(xml):
|
|
|
|
# If we generated our own XML, then everything is ready.
|
|
|
|
return
|
|
|
|
|
|
|
|
# Initialize values using provided XML
|
2012-06-19 16:47:31 +00:00
|
|
|
for child in self.xml:
|
2010-08-13 14:26:33 +00:00
|
|
|
if child.tag in self.plugin_tag_map:
|
2011-12-12 01:04:58 +00:00
|
|
|
plugin_class = self.plugin_tag_map[child.tag]
|
2012-06-05 23:54:26 +00:00
|
|
|
self.init_plugin(plugin_class.plugin_attrib,
|
|
|
|
existing_xml=child,
|
|
|
|
reuse=False)
|
2010-08-13 14:15:52 +00:00
|
|
|
|
2010-08-13 16:24:47 +00:00
|
|
|
def setup(self, xml=None):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Initialize the stanza's XML contents.
|
2010-08-13 16:24:47 +00:00
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
Will return ``True`` if XML was generated according to the stanza's
|
|
|
|
definition instead of building a stanza object from an existing
|
|
|
|
XML object.
|
2010-08-13 16:24:47 +00:00
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
:param xml: An existing XML object to use for the stanza's content
|
|
|
|
instead of generating new XML.
|
2010-08-13 16:24:47 +00:00
|
|
|
"""
|
|
|
|
if self.xml is None:
|
|
|
|
self.xml = xml
|
|
|
|
|
2012-02-17 19:40:07 +00:00
|
|
|
last_xml = self.xml
|
2010-08-13 16:24:47 +00:00
|
|
|
if self.xml is None:
|
|
|
|
# Generate XML from the stanza definition
|
|
|
|
for ename in self.name.split('/'):
|
|
|
|
new = ET.Element("{%s}%s" % (self.namespace, ename))
|
|
|
|
if self.xml is None:
|
|
|
|
self.xml = new
|
|
|
|
else:
|
|
|
|
last_xml.append(new)
|
|
|
|
last_xml = new
|
|
|
|
if self.parent is not None:
|
|
|
|
self.parent().xml.append(self.xml)
|
|
|
|
|
|
|
|
# We had to generate XML
|
|
|
|
return True
|
|
|
|
else:
|
|
|
|
# We did not generate XML
|
|
|
|
return False
|
|
|
|
|
2012-06-05 23:54:26 +00:00
|
|
|
def enable(self, attrib, lang=None):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Enable and initialize a stanza plugin.
|
2010-08-13 16:51:07 +00:00
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
Alias for :meth:`init_plugin`.
|
2010-08-13 16:51:07 +00:00
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
:param string attrib: The :attr:`plugin_attrib` value of the
|
|
|
|
plugin to enable.
|
2010-08-13 16:51:07 +00:00
|
|
|
"""
|
2012-06-05 23:54:26 +00:00
|
|
|
return self.init_plugin(attrib, lang)
|
|
|
|
|
2012-09-25 04:00:23 +00:00
|
|
|
def _get_plugin(self, name, lang=None, check=False):
|
2012-06-05 23:54:26 +00:00
|
|
|
if lang is None:
|
|
|
|
lang = self.get_lang()
|
2012-06-06 09:08:25 +00:00
|
|
|
|
|
|
|
if name not in self.plugin_attrib_map:
|
|
|
|
return None
|
|
|
|
|
2012-06-05 23:54:26 +00:00
|
|
|
plugin_class = self.plugin_attrib_map[name]
|
2012-06-06 09:08:25 +00:00
|
|
|
|
2012-06-05 23:54:26 +00:00
|
|
|
if plugin_class.is_extension:
|
|
|
|
if (name, None) in self.plugins:
|
|
|
|
return self.plugins[(name, None)]
|
|
|
|
else:
|
2012-09-25 04:00:23 +00:00
|
|
|
return None if check else self.init_plugin(name, lang)
|
2012-06-05 23:54:26 +00:00
|
|
|
else:
|
|
|
|
if (name, lang) in self.plugins:
|
|
|
|
return self.plugins[(name, lang)]
|
|
|
|
else:
|
2012-09-25 04:00:23 +00:00
|
|
|
return None if check else self.init_plugin(name, lang)
|
2010-08-13 16:51:07 +00:00
|
|
|
|
2012-06-05 23:54:26 +00:00
|
|
|
def init_plugin(self, attrib, lang=None, existing_xml=None, reuse=True):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Enable and initialize a stanza plugin.
|
2010-08-13 16:51:07 +00:00
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
:param string attrib: The :attr:`plugin_attrib` value of the
|
|
|
|
plugin to enable.
|
2010-08-13 16:51:07 +00:00
|
|
|
"""
|
2012-07-25 08:33:17 +00:00
|
|
|
default_lang = self.get_lang()
|
|
|
|
if not lang:
|
|
|
|
lang = default_lang
|
2012-06-05 23:54:26 +00:00
|
|
|
|
|
|
|
plugin_class = self.plugin_attrib_map[attrib]
|
|
|
|
|
|
|
|
if plugin_class.is_extension and (attrib, None) in self.plugins:
|
|
|
|
return self.plugins[(attrib, None)]
|
|
|
|
if reuse and (attrib, lang) in self.plugins:
|
|
|
|
return self.plugins[(attrib, lang)]
|
|
|
|
|
|
|
|
plugin = plugin_class(parent=self, xml=existing_xml)
|
|
|
|
|
|
|
|
if plugin.is_extension:
|
|
|
|
self.plugins[(attrib, None)] = plugin
|
|
|
|
else:
|
2012-07-25 08:33:17 +00:00
|
|
|
if lang != default_lang:
|
|
|
|
plugin['lang'] = lang
|
2012-06-05 23:54:26 +00:00
|
|
|
self.plugins[(attrib, lang)] = plugin
|
|
|
|
|
|
|
|
if plugin_class in self.plugin_iterables:
|
|
|
|
self.iterables.append(plugin)
|
|
|
|
if plugin_class.plugin_multi_attrib:
|
|
|
|
self.init_plugin(plugin_class.plugin_multi_attrib)
|
|
|
|
|
|
|
|
self.loaded_plugins.add(attrib)
|
|
|
|
|
|
|
|
return plugin
|
2010-08-13 16:51:07 +00:00
|
|
|
|
2010-10-18 01:38:22 +00:00
|
|
|
def _get_stanza_values(self):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Return A JSON/dictionary version of the XML content
|
|
|
|
exposed through the stanza's interfaces::
|
|
|
|
|
|
|
|
>>> msg = Message()
|
|
|
|
>>> msg.values
|
|
|
|
{'body': '', 'from': , 'mucnick': '', 'mucroom': '',
|
|
|
|
'to': , 'type': 'normal', 'id': '', 'subject': ''}
|
|
|
|
|
|
|
|
Likewise, assigning to :attr:`values` will change the XML
|
|
|
|
content::
|
2010-08-14 00:05:24 +00:00
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
>>> msg = Message()
|
|
|
|
>>> msg.values = {'body': 'Hi!', 'to': 'user@example.com'}
|
|
|
|
>>> msg
|
|
|
|
'<message to="user@example.com"><body>Hi!</body></message>'
|
|
|
|
|
|
|
|
.. versionadded:: 1.0-Beta1
|
2010-08-14 00:05:24 +00:00
|
|
|
"""
|
|
|
|
values = {}
|
2012-06-23 01:19:17 +00:00
|
|
|
values['lang'] = self['lang']
|
2010-08-14 00:05:24 +00:00
|
|
|
for interface in self.interfaces:
|
|
|
|
values[interface] = self[interface]
|
2012-06-06 09:08:25 +00:00
|
|
|
if interface in self.lang_interfaces:
|
|
|
|
values['%s|*' % interface] = self['%s|*' % interface]
|
2010-08-14 00:05:24 +00:00
|
|
|
for plugin, stanza in self.plugins.items():
|
2012-06-05 23:54:26 +00:00
|
|
|
lang = stanza['lang']
|
|
|
|
if lang:
|
2012-07-25 08:33:17 +00:00
|
|
|
values['%s|%s' % (plugin[0], lang)] = stanza.values
|
2012-06-05 23:54:26 +00:00
|
|
|
else:
|
|
|
|
values[plugin[0]] = stanza.values
|
2010-08-14 00:05:24 +00:00
|
|
|
if self.iterables:
|
|
|
|
iterables = []
|
|
|
|
for stanza in self.iterables:
|
2011-01-26 16:27:41 +00:00
|
|
|
iterables.append(stanza.values)
|
|
|
|
iterables[-1]['__childtag__'] = stanza.tag
|
2010-08-14 00:05:24 +00:00
|
|
|
values['substanzas'] = iterables
|
|
|
|
return values
|
|
|
|
|
2010-10-18 01:38:22 +00:00
|
|
|
def _set_stanza_values(self, values):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Set multiple stanza interface values using a dictionary.
|
2010-08-14 00:05:24 +00:00
|
|
|
|
|
|
|
Stanza plugin values may be set using nested dictionaries.
|
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
:param values: A dictionary mapping stanza interface with values.
|
|
|
|
Plugin interfaces may accept a nested dictionary that
|
|
|
|
will be used recursively.
|
|
|
|
|
|
|
|
.. versionadded:: 1.0-Beta1
|
2010-08-14 00:05:24 +00:00
|
|
|
"""
|
2011-03-23 00:42:43 +00:00
|
|
|
iterable_interfaces = [p.plugin_attrib for \
|
|
|
|
p in self.plugin_iterables]
|
|
|
|
|
2013-02-14 09:24:09 +00:00
|
|
|
if 'lang' in values:
|
|
|
|
self['lang'] = values['lang']
|
|
|
|
|
|
|
|
if 'substanzas' in values:
|
|
|
|
# Remove existing substanzas
|
|
|
|
for stanza in self.iterables:
|
|
|
|
try:
|
|
|
|
self.xml.remove(stanza.xml)
|
|
|
|
except ValueError:
|
|
|
|
pass
|
|
|
|
self.iterables = []
|
|
|
|
|
|
|
|
# Add new substanzas
|
|
|
|
for subdict in values['substanzas']:
|
|
|
|
if '__childtag__' in subdict:
|
|
|
|
for subclass in self.plugin_iterables:
|
|
|
|
child_tag = "{%s}%s" % (subclass.namespace,
|
|
|
|
subclass.name)
|
|
|
|
if subdict['__childtag__'] == child_tag:
|
|
|
|
sub = subclass(parent=self)
|
|
|
|
sub.values = subdict
|
|
|
|
self.iterables.append(sub)
|
|
|
|
|
2010-08-14 00:05:24 +00:00
|
|
|
for interface, value in values.items():
|
2012-06-05 23:54:26 +00:00
|
|
|
full_interface = interface
|
|
|
|
interface_lang = ('%s|' % interface).split('|')
|
|
|
|
interface = interface_lang[0]
|
|
|
|
lang = interface_lang[1] or self.get_lang()
|
|
|
|
|
2013-02-14 09:24:09 +00:00
|
|
|
if interface == 'lang':
|
|
|
|
continue
|
|
|
|
elif interface == 'substanzas':
|
|
|
|
continue
|
2010-08-14 00:05:24 +00:00
|
|
|
elif interface in self.interfaces:
|
2012-06-06 09:08:25 +00:00
|
|
|
self[full_interface] = value
|
2010-08-14 00:05:24 +00:00
|
|
|
elif interface in self.plugin_attrib_map:
|
2011-03-23 00:42:43 +00:00
|
|
|
if interface not in iterable_interfaces:
|
2012-06-05 23:54:26 +00:00
|
|
|
plugin = self._get_plugin(interface, lang)
|
2012-06-06 09:08:25 +00:00
|
|
|
if plugin:
|
|
|
|
plugin.values = value
|
2010-08-14 00:05:24 +00:00
|
|
|
return self
|
|
|
|
|
2010-08-14 01:33:11 +00:00
|
|
|
def __getitem__(self, attrib):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Return the value of a stanza interface using dict-like syntax.
|
|
|
|
|
|
|
|
Example::
|
2010-08-14 01:33:11 +00:00
|
|
|
|
|
|
|
>>> msg['body']
|
|
|
|
'Message contents'
|
|
|
|
|
|
|
|
Stanza interfaces are typically mapped directly to the underlying XML
|
2011-11-22 05:50:40 +00:00
|
|
|
object, but can be overridden by the presence of a ``get_attrib``
|
|
|
|
method (or ``get_foo`` where the interface is named ``'foo'``, etc).
|
2010-08-14 01:33:11 +00:00
|
|
|
|
|
|
|
The search order for interface value retrieval for an interface
|
2011-11-22 05:50:40 +00:00
|
|
|
named ``'foo'`` is:
|
|
|
|
|
|
|
|
1. The list of substanzas (``'substanzas'``)
|
|
|
|
2. The result of calling the ``get_foo`` override handler.
|
|
|
|
3. The result of calling ``get_foo``.
|
|
|
|
4. The result of calling ``getFoo``.
|
|
|
|
5. The contents of the ``foo`` subelement, if ``foo`` is listed
|
|
|
|
in :attr:`sub_interfaces`.
|
2012-03-28 04:05:50 +00:00
|
|
|
6. True or False depending on the existence of a ``foo``
|
|
|
|
subelement and ``foo`` is in :attr:`bool_interfaces`.
|
|
|
|
7. The value of the ``foo`` attribute of the XML object.
|
|
|
|
8. The plugin named ``'foo'``
|
|
|
|
9. An empty string.
|
2010-08-14 01:33:11 +00:00
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
:param string attrib: The name of the requested stanza interface.
|
2010-08-14 01:33:11 +00:00
|
|
|
"""
|
2012-06-05 23:54:26 +00:00
|
|
|
full_attrib = attrib
|
|
|
|
attrib_lang = ('%s|' % attrib).split('|')
|
|
|
|
attrib = attrib_lang[0]
|
2012-10-10 18:07:25 +00:00
|
|
|
lang = attrib_lang[1] or None
|
2012-06-05 23:54:26 +00:00
|
|
|
|
|
|
|
kwargs = {}
|
|
|
|
if lang and attrib in self.lang_interfaces:
|
|
|
|
kwargs['lang'] = lang
|
|
|
|
|
2010-08-14 01:33:11 +00:00
|
|
|
if attrib == 'substanzas':
|
|
|
|
return self.iterables
|
2012-06-23 01:19:17 +00:00
|
|
|
elif attrib in self.interfaces or attrib == 'lang':
|
2010-10-18 01:38:22 +00:00
|
|
|
get_method = "get_%s" % attrib.lower()
|
|
|
|
get_method2 = "get%s" % attrib.title()
|
Allow a stanza plugin to override a parent's interfaces.
Each interface, say foo, may be overridden in three ways:
set_foo
get_foo
del_foo
To declare an override in a plugin, add the class field
overrides as so:
overrides = ['set_foo', 'del_foo']
Each override must have a matching set_foo(), etc method
for implementing the new behaviour.
To enable the overrides for a particular parent stanza,
pass the option overrides=True to register_stanza_plugin.
register_stanza_plugin(Stanza, Plugin, overrides=True)
Example code:
class Test(ElementBase):
name = 'test'
namespace = 'testing'
interfaces = set(('foo', 'bar'))
sub_interfaces = set(('bar',))
class TestOverride(ElementBase):
name = 'test-override'
namespace = 'testing'
plugin_attrib = 'override'
interfaces = set(('foo',))
overrides = ['set_foo']
def setup(self, xml):
# Don't include an XML element in the parent stanza
# since we're adding just an attribute.
# If adding a regular subelement, no need to do this.
self.xml = ET.Element('')
def set_foo(self, value):
print("overrides!")
self.parent()._set_attr('foo', 'override-%s' % value)
register_stanza_plugin(Test, TestOverride, overrides=True)
Example usage:
>>> t = TestStanza()
>>> t['foo'] = 'bar'
>>> t['foo']
'override-bar'
2011-03-24 16:25:17 +00:00
|
|
|
|
|
|
|
if self.plugin_overrides:
|
2012-06-05 23:54:26 +00:00
|
|
|
name = self.plugin_overrides.get(get_method, None)
|
|
|
|
if name:
|
|
|
|
plugin = self._get_plugin(name, lang)
|
2012-06-06 09:08:25 +00:00
|
|
|
if plugin:
|
|
|
|
handler = getattr(plugin, get_method, None)
|
|
|
|
if handler:
|
|
|
|
return handler(**kwargs)
|
Allow a stanza plugin to override a parent's interfaces.
Each interface, say foo, may be overridden in three ways:
set_foo
get_foo
del_foo
To declare an override in a plugin, add the class field
overrides as so:
overrides = ['set_foo', 'del_foo']
Each override must have a matching set_foo(), etc method
for implementing the new behaviour.
To enable the overrides for a particular parent stanza,
pass the option overrides=True to register_stanza_plugin.
register_stanza_plugin(Stanza, Plugin, overrides=True)
Example code:
class Test(ElementBase):
name = 'test'
namespace = 'testing'
interfaces = set(('foo', 'bar'))
sub_interfaces = set(('bar',))
class TestOverride(ElementBase):
name = 'test-override'
namespace = 'testing'
plugin_attrib = 'override'
interfaces = set(('foo',))
overrides = ['set_foo']
def setup(self, xml):
# Don't include an XML element in the parent stanza
# since we're adding just an attribute.
# If adding a regular subelement, no need to do this.
self.xml = ET.Element('')
def set_foo(self, value):
print("overrides!")
self.parent()._set_attr('foo', 'override-%s' % value)
register_stanza_plugin(Test, TestOverride, overrides=True)
Example usage:
>>> t = TestStanza()
>>> t['foo'] = 'bar'
>>> t['foo']
'override-bar'
2011-03-24 16:25:17 +00:00
|
|
|
|
2010-08-14 01:33:11 +00:00
|
|
|
if hasattr(self, get_method):
|
2012-06-05 23:54:26 +00:00
|
|
|
return getattr(self, get_method)(**kwargs)
|
2010-10-18 01:38:22 +00:00
|
|
|
elif hasattr(self, get_method2):
|
2012-06-05 23:54:26 +00:00
|
|
|
return getattr(self, get_method2)(**kwargs)
|
2010-08-14 01:33:11 +00:00
|
|
|
else:
|
|
|
|
if attrib in self.sub_interfaces:
|
2012-06-06 09:08:25 +00:00
|
|
|
return self._get_sub_text(attrib, lang=lang)
|
2012-03-28 04:05:50 +00:00
|
|
|
elif attrib in self.bool_interfaces:
|
|
|
|
elem = self.xml.find('{%s}%s' % (self.namespace, attrib))
|
|
|
|
return elem is not None
|
2010-08-14 01:33:11 +00:00
|
|
|
else:
|
2010-10-18 01:38:22 +00:00
|
|
|
return self._get_attr(attrib)
|
2010-08-14 01:33:11 +00:00
|
|
|
elif attrib in self.plugin_attrib_map:
|
2012-06-05 23:54:26 +00:00
|
|
|
plugin = self._get_plugin(attrib, lang)
|
2012-06-06 09:08:25 +00:00
|
|
|
if plugin and plugin.is_extension:
|
2012-06-05 23:54:26 +00:00
|
|
|
return plugin[full_attrib]
|
|
|
|
return plugin
|
2010-08-14 01:33:11 +00:00
|
|
|
else:
|
|
|
|
return ''
|
|
|
|
|
2010-08-19 18:21:58 +00:00
|
|
|
def __setitem__(self, attrib, value):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Set the value of a stanza interface using dictionary-like syntax.
|
|
|
|
|
|
|
|
Example::
|
2010-08-19 18:21:58 +00:00
|
|
|
|
|
|
|
>>> msg['body'] = "Hi!"
|
|
|
|
>>> msg['body']
|
|
|
|
'Hi!'
|
|
|
|
|
|
|
|
Stanza interfaces are typically mapped directly to the underlying XML
|
2011-11-22 05:50:40 +00:00
|
|
|
object, but can be overridden by the presence of a ``set_attrib``
|
|
|
|
method (or ``set_foo`` where the interface is named ``'foo'``, etc).
|
2010-08-19 18:21:58 +00:00
|
|
|
|
|
|
|
The effect of interface value assignment for an interface
|
2011-11-22 05:50:40 +00:00
|
|
|
named ``'foo'`` will be one of:
|
|
|
|
|
2010-08-19 18:21:58 +00:00
|
|
|
1. Delete the interface's contents if the value is None.
|
2011-11-22 05:50:40 +00:00
|
|
|
2. Call the ``set_foo`` override handler, if it exists.
|
|
|
|
3. Call ``set_foo``, if it exists.
|
|
|
|
4. Call ``setFoo``, if it exists.
|
|
|
|
5. Set the text of a ``foo`` element, if ``'foo'`` is
|
|
|
|
in :attr:`sub_interfaces`.
|
2012-03-28 04:05:50 +00:00
|
|
|
6. Add or remove an empty subelement ``foo``
|
|
|
|
if ``foo`` is in :attr:`bool_interfaces`.
|
|
|
|
7. Set the value of a top level XML attribute named ``foo``.
|
|
|
|
8. Attempt to pass the value to a plugin named ``'foo'`` using
|
2011-11-22 05:50:40 +00:00
|
|
|
the plugin's ``'foo'`` interface.
|
2012-03-28 04:05:50 +00:00
|
|
|
9. Do nothing.
|
2010-08-19 18:21:58 +00:00
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
:param string attrib: The name of the stanza interface to modify.
|
|
|
|
:param value: The new value of the stanza interface.
|
2010-08-19 18:21:58 +00:00
|
|
|
"""
|
2012-06-05 23:54:26 +00:00
|
|
|
full_attrib = attrib
|
|
|
|
attrib_lang = ('%s|' % attrib).split('|')
|
|
|
|
attrib = attrib_lang[0]
|
2012-10-10 18:07:25 +00:00
|
|
|
lang = attrib_lang[1] or None
|
2012-06-05 23:54:26 +00:00
|
|
|
|
|
|
|
kwargs = {}
|
|
|
|
if lang and attrib in self.lang_interfaces:
|
|
|
|
kwargs['lang'] = lang
|
|
|
|
|
2012-06-23 01:19:17 +00:00
|
|
|
if attrib in self.interfaces or attrib == 'lang':
|
2010-08-19 18:21:58 +00:00
|
|
|
if value is not None:
|
2010-10-18 01:38:22 +00:00
|
|
|
set_method = "set_%s" % attrib.lower()
|
|
|
|
set_method2 = "set%s" % attrib.title()
|
Allow a stanza plugin to override a parent's interfaces.
Each interface, say foo, may be overridden in three ways:
set_foo
get_foo
del_foo
To declare an override in a plugin, add the class field
overrides as so:
overrides = ['set_foo', 'del_foo']
Each override must have a matching set_foo(), etc method
for implementing the new behaviour.
To enable the overrides for a particular parent stanza,
pass the option overrides=True to register_stanza_plugin.
register_stanza_plugin(Stanza, Plugin, overrides=True)
Example code:
class Test(ElementBase):
name = 'test'
namespace = 'testing'
interfaces = set(('foo', 'bar'))
sub_interfaces = set(('bar',))
class TestOverride(ElementBase):
name = 'test-override'
namespace = 'testing'
plugin_attrib = 'override'
interfaces = set(('foo',))
overrides = ['set_foo']
def setup(self, xml):
# Don't include an XML element in the parent stanza
# since we're adding just an attribute.
# If adding a regular subelement, no need to do this.
self.xml = ET.Element('')
def set_foo(self, value):
print("overrides!")
self.parent()._set_attr('foo', 'override-%s' % value)
register_stanza_plugin(Test, TestOverride, overrides=True)
Example usage:
>>> t = TestStanza()
>>> t['foo'] = 'bar'
>>> t['foo']
'override-bar'
2011-03-24 16:25:17 +00:00
|
|
|
|
|
|
|
if self.plugin_overrides:
|
2012-06-05 23:54:26 +00:00
|
|
|
name = self.plugin_overrides.get(set_method, None)
|
|
|
|
if name:
|
|
|
|
plugin = self._get_plugin(name, lang)
|
2012-06-06 09:08:25 +00:00
|
|
|
if plugin:
|
|
|
|
handler = getattr(plugin, set_method, None)
|
|
|
|
if handler:
|
|
|
|
return handler(value, **kwargs)
|
Allow a stanza plugin to override a parent's interfaces.
Each interface, say foo, may be overridden in three ways:
set_foo
get_foo
del_foo
To declare an override in a plugin, add the class field
overrides as so:
overrides = ['set_foo', 'del_foo']
Each override must have a matching set_foo(), etc method
for implementing the new behaviour.
To enable the overrides for a particular parent stanza,
pass the option overrides=True to register_stanza_plugin.
register_stanza_plugin(Stanza, Plugin, overrides=True)
Example code:
class Test(ElementBase):
name = 'test'
namespace = 'testing'
interfaces = set(('foo', 'bar'))
sub_interfaces = set(('bar',))
class TestOverride(ElementBase):
name = 'test-override'
namespace = 'testing'
plugin_attrib = 'override'
interfaces = set(('foo',))
overrides = ['set_foo']
def setup(self, xml):
# Don't include an XML element in the parent stanza
# since we're adding just an attribute.
# If adding a regular subelement, no need to do this.
self.xml = ET.Element('')
def set_foo(self, value):
print("overrides!")
self.parent()._set_attr('foo', 'override-%s' % value)
register_stanza_plugin(Test, TestOverride, overrides=True)
Example usage:
>>> t = TestStanza()
>>> t['foo'] = 'bar'
>>> t['foo']
'override-bar'
2011-03-24 16:25:17 +00:00
|
|
|
|
2010-08-19 23:14:18 +00:00
|
|
|
if hasattr(self, set_method):
|
2012-06-05 23:54:26 +00:00
|
|
|
getattr(self, set_method)(value, **kwargs)
|
2010-10-18 01:38:22 +00:00
|
|
|
elif hasattr(self, set_method2):
|
2012-06-05 23:54:26 +00:00
|
|
|
getattr(self, set_method2)(value, **kwargs)
|
2010-08-19 18:21:58 +00:00
|
|
|
else:
|
|
|
|
if attrib in self.sub_interfaces:
|
2012-06-06 09:08:25 +00:00
|
|
|
if lang == '*':
|
2012-06-19 08:29:48 +00:00
|
|
|
return self._set_all_sub_text(attrib,
|
|
|
|
value,
|
|
|
|
lang='*')
|
|
|
|
return self._set_sub_text(attrib, text=value,
|
|
|
|
lang=lang)
|
2012-03-28 04:05:50 +00:00
|
|
|
elif attrib in self.bool_interfaces:
|
|
|
|
if value:
|
2012-06-19 08:29:48 +00:00
|
|
|
return self._set_sub_text(attrib, '',
|
|
|
|
keep=True,
|
|
|
|
lang=lang)
|
2012-03-28 04:05:50 +00:00
|
|
|
else:
|
2012-06-19 08:29:48 +00:00
|
|
|
return self._set_sub_text(attrib, '',
|
|
|
|
keep=False,
|
|
|
|
lang=lang)
|
2010-08-19 18:21:58 +00:00
|
|
|
else:
|
2010-10-18 01:38:22 +00:00
|
|
|
self._set_attr(attrib, value)
|
2010-08-19 18:21:58 +00:00
|
|
|
else:
|
|
|
|
self.__delitem__(attrib)
|
|
|
|
elif attrib in self.plugin_attrib_map:
|
2012-06-05 23:54:26 +00:00
|
|
|
plugin = self._get_plugin(attrib, lang)
|
2012-06-06 09:08:25 +00:00
|
|
|
if plugin:
|
|
|
|
plugin[full_attrib] = value
|
2010-08-19 18:21:58 +00:00
|
|
|
return self
|
|
|
|
|
2010-08-19 23:11:12 +00:00
|
|
|
def __delitem__(self, attrib):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Delete the value of a stanza interface using dict-like syntax.
|
|
|
|
|
|
|
|
Example::
|
2010-08-19 23:11:12 +00:00
|
|
|
|
|
|
|
>>> msg['body'] = "Hi!"
|
|
|
|
>>> msg['body']
|
|
|
|
'Hi!'
|
|
|
|
>>> del msg['body']
|
|
|
|
>>> msg['body']
|
|
|
|
''
|
|
|
|
|
|
|
|
Stanza interfaces are typically mapped directly to the underlyig XML
|
2011-11-22 05:50:40 +00:00
|
|
|
object, but can be overridden by the presence of a ``del_attrib``
|
|
|
|
method (or ``del_foo`` where the interface is named ``'foo'``, etc).
|
2010-08-19 23:11:12 +00:00
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
The effect of deleting a stanza interface value named ``foo`` will be
|
2010-08-19 23:11:12 +00:00
|
|
|
one of:
|
2011-11-22 05:50:40 +00:00
|
|
|
|
|
|
|
1. Call ``del_foo`` override handler, if it exists.
|
|
|
|
2. Call ``del_foo``, if it exists.
|
|
|
|
3. Call ``delFoo``, if it exists.
|
|
|
|
4. Delete ``foo`` element, if ``'foo'`` is in
|
|
|
|
:attr:`sub_interfaces`.
|
2012-03-28 04:05:50 +00:00
|
|
|
5. Remove ``foo`` element if ``'foo'`` is in
|
|
|
|
:attr:`bool_interfaces`.
|
|
|
|
6. Delete top level XML attribute named ``foo``.
|
|
|
|
7. Remove the ``foo`` plugin, if it was loaded.
|
|
|
|
8. Do nothing.
|
2010-08-20 00:41:26 +00:00
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
:param attrib: The name of the affected stanza interface.
|
2010-08-19 23:11:12 +00:00
|
|
|
"""
|
2012-06-05 23:54:26 +00:00
|
|
|
full_attrib = attrib
|
|
|
|
attrib_lang = ('%s|' % attrib).split('|')
|
|
|
|
attrib = attrib_lang[0]
|
2012-10-10 18:07:25 +00:00
|
|
|
lang = attrib_lang[1] or None
|
2012-06-05 23:54:26 +00:00
|
|
|
|
|
|
|
kwargs = {}
|
|
|
|
if lang and attrib in self.lang_interfaces:
|
|
|
|
kwargs['lang'] = lang
|
|
|
|
|
2012-06-23 01:19:17 +00:00
|
|
|
if attrib in self.interfaces or attrib == 'lang':
|
2010-10-18 01:38:22 +00:00
|
|
|
del_method = "del_%s" % attrib.lower()
|
|
|
|
del_method2 = "del%s" % attrib.title()
|
Allow a stanza plugin to override a parent's interfaces.
Each interface, say foo, may be overridden in three ways:
set_foo
get_foo
del_foo
To declare an override in a plugin, add the class field
overrides as so:
overrides = ['set_foo', 'del_foo']
Each override must have a matching set_foo(), etc method
for implementing the new behaviour.
To enable the overrides for a particular parent stanza,
pass the option overrides=True to register_stanza_plugin.
register_stanza_plugin(Stanza, Plugin, overrides=True)
Example code:
class Test(ElementBase):
name = 'test'
namespace = 'testing'
interfaces = set(('foo', 'bar'))
sub_interfaces = set(('bar',))
class TestOverride(ElementBase):
name = 'test-override'
namespace = 'testing'
plugin_attrib = 'override'
interfaces = set(('foo',))
overrides = ['set_foo']
def setup(self, xml):
# Don't include an XML element in the parent stanza
# since we're adding just an attribute.
# If adding a regular subelement, no need to do this.
self.xml = ET.Element('')
def set_foo(self, value):
print("overrides!")
self.parent()._set_attr('foo', 'override-%s' % value)
register_stanza_plugin(Test, TestOverride, overrides=True)
Example usage:
>>> t = TestStanza()
>>> t['foo'] = 'bar'
>>> t['foo']
'override-bar'
2011-03-24 16:25:17 +00:00
|
|
|
|
|
|
|
if self.plugin_overrides:
|
2012-06-05 23:54:26 +00:00
|
|
|
name = self.plugin_overrides.get(del_method, None)
|
|
|
|
if name:
|
|
|
|
plugin = self._get_plugin(attrib, lang)
|
2012-06-06 09:08:25 +00:00
|
|
|
if plugin:
|
|
|
|
handler = getattr(plugin, del_method, None)
|
|
|
|
if handler:
|
|
|
|
return handler(**kwargs)
|
Allow a stanza plugin to override a parent's interfaces.
Each interface, say foo, may be overridden in three ways:
set_foo
get_foo
del_foo
To declare an override in a plugin, add the class field
overrides as so:
overrides = ['set_foo', 'del_foo']
Each override must have a matching set_foo(), etc method
for implementing the new behaviour.
To enable the overrides for a particular parent stanza,
pass the option overrides=True to register_stanza_plugin.
register_stanza_plugin(Stanza, Plugin, overrides=True)
Example code:
class Test(ElementBase):
name = 'test'
namespace = 'testing'
interfaces = set(('foo', 'bar'))
sub_interfaces = set(('bar',))
class TestOverride(ElementBase):
name = 'test-override'
namespace = 'testing'
plugin_attrib = 'override'
interfaces = set(('foo',))
overrides = ['set_foo']
def setup(self, xml):
# Don't include an XML element in the parent stanza
# since we're adding just an attribute.
# If adding a regular subelement, no need to do this.
self.xml = ET.Element('')
def set_foo(self, value):
print("overrides!")
self.parent()._set_attr('foo', 'override-%s' % value)
register_stanza_plugin(Test, TestOverride, overrides=True)
Example usage:
>>> t = TestStanza()
>>> t['foo'] = 'bar'
>>> t['foo']
'override-bar'
2011-03-24 16:25:17 +00:00
|
|
|
|
2010-08-19 23:11:12 +00:00
|
|
|
if hasattr(self, del_method):
|
2012-06-05 23:54:26 +00:00
|
|
|
getattr(self, del_method)(**kwargs)
|
2010-10-18 01:38:22 +00:00
|
|
|
elif hasattr(self, del_method2):
|
2012-06-05 23:54:26 +00:00
|
|
|
getattr(self, del_method2)(**kwargs)
|
2010-08-19 23:11:12 +00:00
|
|
|
else:
|
|
|
|
if attrib in self.sub_interfaces:
|
2012-06-06 09:08:25 +00:00
|
|
|
return self._del_sub(attrib, lang=lang)
|
2012-03-28 04:05:50 +00:00
|
|
|
elif attrib in self.bool_interfaces:
|
2012-06-06 09:08:25 +00:00
|
|
|
return self._del_sub(attrib, lang=lang)
|
2010-08-19 23:11:12 +00:00
|
|
|
else:
|
2010-10-18 01:38:22 +00:00
|
|
|
self._del_attr(attrib)
|
2010-08-19 23:11:12 +00:00
|
|
|
elif attrib in self.plugin_attrib_map:
|
2012-09-25 04:00:23 +00:00
|
|
|
plugin = self._get_plugin(attrib, lang, check=True)
|
2012-06-06 09:08:25 +00:00
|
|
|
if not plugin:
|
|
|
|
return self
|
2012-06-05 23:54:26 +00:00
|
|
|
if plugin.is_extension:
|
|
|
|
del plugin[full_attrib]
|
|
|
|
del self.plugins[(attrib, None)]
|
|
|
|
else:
|
2012-10-10 18:07:25 +00:00
|
|
|
del self.plugins[(attrib, plugin['lang'])]
|
2012-06-05 23:54:26 +00:00
|
|
|
self.loaded_plugins.remove(attrib)
|
|
|
|
try:
|
|
|
|
self.xml.remove(plugin.xml)
|
2013-02-14 09:24:09 +00:00
|
|
|
except ValueError:
|
2012-06-05 23:54:26 +00:00
|
|
|
pass
|
2010-08-19 23:11:12 +00:00
|
|
|
return self
|
|
|
|
|
2010-10-18 01:38:22 +00:00
|
|
|
def _set_attr(self, name, value):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Set the value of a top level attribute of the XML object.
|
2010-08-20 00:41:26 +00:00
|
|
|
|
|
|
|
If the new value is None or an empty string, then the attribute will
|
|
|
|
be removed.
|
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
:param name: The name of the attribute.
|
|
|
|
:param value: The new value of the attribute, or None or '' to
|
|
|
|
remove it.
|
2010-08-20 00:41:26 +00:00
|
|
|
"""
|
|
|
|
if value is None or value == '':
|
|
|
|
self.__delitem__(name)
|
|
|
|
else:
|
|
|
|
self.xml.attrib[name] = value
|
|
|
|
|
2010-10-18 01:38:22 +00:00
|
|
|
def _del_attr(self, name):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Remove a top level attribute of the XML object.
|
2010-08-20 00:41:26 +00:00
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
:param name: The name of the attribute.
|
2010-08-20 00:41:26 +00:00
|
|
|
"""
|
|
|
|
if name in self.xml.attrib:
|
|
|
|
del self.xml.attrib[name]
|
|
|
|
|
2010-10-18 01:38:22 +00:00
|
|
|
def _get_attr(self, name, default=''):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Return the value of a top level attribute of the XML object.
|
2010-08-20 00:41:26 +00:00
|
|
|
|
|
|
|
In case the attribute has not been set, a default value can be
|
|
|
|
returned instead. An empty string is returned if no other default
|
|
|
|
is supplied.
|
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
:param name: The name of the attribute.
|
|
|
|
:param default: Optional value to return if the attribute has not
|
|
|
|
been set. An empty string is returned otherwise.
|
2010-08-20 00:41:26 +00:00
|
|
|
"""
|
|
|
|
return self.xml.attrib.get(name, default)
|
|
|
|
|
2012-06-06 09:08:25 +00:00
|
|
|
def _get_sub_text(self, name, default='', lang=None):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Return the text contents of a sub element.
|
2010-08-24 13:44:09 +00:00
|
|
|
|
|
|
|
In case the element does not exist, or it has no textual content,
|
2010-08-26 14:08:22 +00:00
|
|
|
a default value can be returned instead. An empty string is returned
|
2010-08-24 13:44:09 +00:00
|
|
|
if no other default is supplied.
|
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
:param name: The name or XPath expression of the element.
|
|
|
|
:param default: Optional default to return if the element does
|
|
|
|
not exists. An empty string is returned otherwise.
|
2010-08-24 13:44:09 +00:00
|
|
|
"""
|
|
|
|
name = self._fix_ns(name)
|
2012-06-06 09:08:25 +00:00
|
|
|
if lang == '*':
|
|
|
|
return self._get_all_sub_text(name, default, None)
|
|
|
|
|
|
|
|
default_lang = self.get_lang()
|
|
|
|
if not lang:
|
|
|
|
lang = default_lang
|
|
|
|
|
|
|
|
stanzas = self.xml.findall(name)
|
|
|
|
if not stanzas:
|
2010-08-24 13:44:09 +00:00
|
|
|
return default
|
2012-06-06 09:08:25 +00:00
|
|
|
for stanza in stanzas:
|
|
|
|
if stanza.attrib.get('{%s}lang' % XML_NS, default_lang) == lang:
|
|
|
|
if stanza.text is None:
|
|
|
|
return default
|
|
|
|
return stanza.text
|
|
|
|
return default
|
|
|
|
|
|
|
|
def _get_all_sub_text(self, name, default='', lang=None):
|
|
|
|
name = self._fix_ns(name)
|
2010-08-24 12:55:37 +00:00
|
|
|
|
2012-06-06 09:08:25 +00:00
|
|
|
default_lang = self.get_lang()
|
|
|
|
results = OrderedDict()
|
|
|
|
stanzas = self.xml.findall(name)
|
|
|
|
if stanzas:
|
|
|
|
for stanza in stanzas:
|
2012-06-19 08:29:48 +00:00
|
|
|
stanza_lang = stanza.attrib.get('{%s}lang' % XML_NS,
|
|
|
|
default_lang)
|
2012-06-06 09:08:25 +00:00
|
|
|
if not lang or lang == '*' or stanza_lang == lang:
|
|
|
|
results[stanza_lang] = stanza.text
|
|
|
|
return results
|
|
|
|
|
|
|
|
def _set_sub_text(self, name, text=None, keep=False, lang=None):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Set the text contents of a sub element.
|
2010-08-24 13:37:42 +00:00
|
|
|
|
|
|
|
In case the element does not exist, a element will be created,
|
|
|
|
and its text contents will be set.
|
|
|
|
|
2010-08-26 14:08:22 +00:00
|
|
|
If the text is set to an empty string, or None, then the
|
2010-08-24 13:37:42 +00:00
|
|
|
element will be removed, unless keep is set to True.
|
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
:param name: The name or XPath expression of the element.
|
|
|
|
:param text: The new textual content of the element. If the text
|
|
|
|
is an empty string or None, the element will be removed
|
|
|
|
unless the parameter keep is True.
|
|
|
|
:param keep: Indicates if the element should be kept if its text is
|
|
|
|
removed. Defaults to False.
|
2010-08-24 13:37:42 +00:00
|
|
|
"""
|
2012-06-06 09:08:25 +00:00
|
|
|
default_lang = self.get_lang()
|
|
|
|
if lang is None:
|
|
|
|
lang = default_lang
|
2010-08-24 13:37:42 +00:00
|
|
|
|
|
|
|
if not text and not keep:
|
2012-06-06 09:08:25 +00:00
|
|
|
return self._del_sub(name, lang=lang)
|
2010-08-24 13:37:42 +00:00
|
|
|
|
2012-06-23 01:19:17 +00:00
|
|
|
path = self._fix_ns(name, split=True)
|
|
|
|
name = path[-1]
|
|
|
|
parent = self.xml
|
2010-08-24 13:37:42 +00:00
|
|
|
|
2012-06-23 01:19:17 +00:00
|
|
|
# The first goal is to find the parent of the subelement, or, if
|
|
|
|
# we can't find that, the closest grandparent element.
|
|
|
|
missing_path = []
|
|
|
|
search_order = path[:-1]
|
|
|
|
while search_order:
|
|
|
|
parent = self.xml.find('/'.join(search_order))
|
|
|
|
ename = search_order.pop()
|
|
|
|
if parent is not None:
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
missing_path.append(ename)
|
|
|
|
missing_path.reverse()
|
|
|
|
|
|
|
|
# Find all existing elements that match the desired
|
|
|
|
# element path (there may be multiples due to different
|
|
|
|
# languages values).
|
|
|
|
if parent is not None:
|
|
|
|
elements = self.xml.findall('/'.join(path))
|
|
|
|
else:
|
|
|
|
parent = self.xml
|
|
|
|
elements = []
|
|
|
|
|
|
|
|
# Insert the remaining grandparent elements that don't exist yet.
|
|
|
|
for ename in missing_path:
|
|
|
|
element = ET.Element(ename)
|
|
|
|
parent.append(element)
|
|
|
|
parent = element
|
|
|
|
|
|
|
|
# Re-use an existing element with the proper language, if one exists.
|
|
|
|
for element in elements:
|
|
|
|
elang = element.attrib.get('{%s}lang' % XML_NS, default_lang)
|
|
|
|
if not lang and elang == default_lang or lang and lang == elang:
|
|
|
|
element.text = text
|
|
|
|
return element
|
2012-06-06 09:08:25 +00:00
|
|
|
|
2012-06-23 01:19:17 +00:00
|
|
|
# No useable element exists, so create a new one.
|
|
|
|
element = ET.Element(name)
|
2010-08-24 13:37:42 +00:00
|
|
|
element.text = text
|
2012-06-23 01:19:17 +00:00
|
|
|
if lang and lang != default_lang:
|
|
|
|
element.attrib['{%s}lang' % XML_NS] = lang
|
|
|
|
parent.append(element)
|
2010-08-26 14:08:22 +00:00
|
|
|
return element
|
2010-08-24 13:37:42 +00:00
|
|
|
|
2012-06-06 09:08:25 +00:00
|
|
|
def _set_all_sub_text(self, name, values, keep=False, lang=None):
|
|
|
|
self._del_sub(name, lang)
|
|
|
|
for value_lang, value in values.items():
|
|
|
|
if not lang or lang == '*' or value_lang == lang:
|
2012-06-19 08:29:48 +00:00
|
|
|
self._set_sub_text(name, text=value,
|
|
|
|
keep=keep,
|
|
|
|
lang=value_lang)
|
2012-06-06 09:08:25 +00:00
|
|
|
|
|
|
|
def _del_sub(self, name, all=False, lang=None):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Remove sub elements that match the given name or XPath.
|
2010-08-25 14:52:07 +00:00
|
|
|
|
|
|
|
If the element is in a path, then any parent elements that become
|
|
|
|
empty after deleting the element may also be deleted if requested
|
|
|
|
by setting all=True.
|
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
:param name: The name or XPath expression for the element(s) to remove.
|
|
|
|
:param bool all: If True, remove all empty elements in the path to the
|
|
|
|
deleted element. Defaults to False.
|
2010-08-25 14:52:07 +00:00
|
|
|
"""
|
2010-08-26 22:18:00 +00:00
|
|
|
path = self._fix_ns(name, split=True)
|
2010-08-25 14:52:07 +00:00
|
|
|
original_target = path[-1]
|
|
|
|
|
2012-06-06 09:08:25 +00:00
|
|
|
default_lang = self.get_lang()
|
|
|
|
if not lang:
|
|
|
|
lang = default_lang
|
|
|
|
|
2010-08-25 14:52:07 +00:00
|
|
|
for level, _ in enumerate(path):
|
|
|
|
# Generate the paths to the target elements and their parent.
|
|
|
|
element_path = "/".join(path[:len(path) - level])
|
|
|
|
parent_path = "/".join(path[:len(path) - level - 1])
|
|
|
|
|
|
|
|
elements = self.xml.findall(element_path)
|
|
|
|
parent = self.xml.find(parent_path)
|
|
|
|
|
|
|
|
if elements:
|
|
|
|
if parent is None:
|
|
|
|
parent = self.xml
|
|
|
|
for element in elements:
|
2012-06-19 16:47:31 +00:00
|
|
|
if element.tag == original_target or not list(element):
|
2010-08-26 17:55:23 +00:00
|
|
|
# Only delete the originally requested elements, and
|
|
|
|
# any parent elements that have become empty.
|
2012-06-19 08:29:48 +00:00
|
|
|
elem_lang = element.attrib.get('{%s}lang' % XML_NS,
|
|
|
|
default_lang)
|
|
|
|
if lang == '*' or elem_lang == lang:
|
2012-06-06 09:08:25 +00:00
|
|
|
parent.remove(element)
|
2010-08-25 14:52:07 +00:00
|
|
|
if not all:
|
|
|
|
# If we don't want to delete elements up the tree, stop
|
|
|
|
# after deleting the first level of elements.
|
|
|
|
return
|
2010-08-26 14:08:22 +00:00
|
|
|
|
2010-08-25 18:40:16 +00:00
|
|
|
def match(self, xpath):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Compare a stanza object with an XPath-like expression.
|
|
|
|
|
|
|
|
If the XPath matches the contents of the stanza object, the match
|
|
|
|
is successful.
|
2010-08-25 18:40:16 +00:00
|
|
|
|
|
|
|
The XPath expression may include checks for stanza attributes.
|
2011-11-22 05:50:40 +00:00
|
|
|
For example::
|
2010-08-25 18:40:16 +00:00
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
'presence@show=xa@priority=2/status'
|
|
|
|
|
|
|
|
Would match a presence stanza whose show value is set to ``'xa'``,
|
|
|
|
has a priority value of ``'2'``, and has a status element.
|
|
|
|
|
|
|
|
:param string xpath: The XPath expression to check against. It
|
|
|
|
may be either a string or a list of element
|
|
|
|
names with attribute checks.
|
2010-08-25 18:40:16 +00:00
|
|
|
"""
|
2012-01-18 06:28:44 +00:00
|
|
|
if not isinstance(xpath, list):
|
2010-08-30 18:55:30 +00:00
|
|
|
xpath = self._fix_ns(xpath, split=True, propagate_ns=False)
|
|
|
|
|
2010-08-25 18:40:16 +00:00
|
|
|
# Extract the tag name and attribute checks for the first XPath node.
|
|
|
|
components = xpath[0].split('@')
|
|
|
|
tag = components[0]
|
|
|
|
attributes = components[1:]
|
2010-08-26 14:08:22 +00:00
|
|
|
|
2010-09-01 18:20:34 +00:00
|
|
|
if tag not in (self.name, "{%s}%s" % (self.namespace, self.name)) and \
|
2012-06-05 23:54:26 +00:00
|
|
|
tag not in self.loaded_plugins and tag not in self.plugin_attrib:
|
2010-08-25 18:40:16 +00:00
|
|
|
# The requested tag is not in this stanza, so no match.
|
|
|
|
return False
|
|
|
|
|
|
|
|
# Check the rest of the XPath against any substanzas.
|
|
|
|
matched_substanzas = False
|
|
|
|
for substanza in self.iterables:
|
|
|
|
if xpath[1:] == []:
|
|
|
|
break
|
|
|
|
matched_substanzas = substanza.match(xpath[1:])
|
2010-08-26 14:08:22 +00:00
|
|
|
if matched_substanzas:
|
2010-08-25 18:40:16 +00:00
|
|
|
break
|
|
|
|
|
|
|
|
# Check attribute values.
|
|
|
|
for attribute in attributes:
|
|
|
|
name, value = attribute.split('=')
|
|
|
|
if self[name] != value:
|
|
|
|
return False
|
|
|
|
|
2010-08-30 21:12:10 +00:00
|
|
|
# Check sub interfaces.
|
|
|
|
if len(xpath) > 1:
|
|
|
|
next_tag = xpath[1]
|
|
|
|
if next_tag in self.sub_interfaces and self[next_tag]:
|
|
|
|
return True
|
|
|
|
|
2010-08-25 18:40:16 +00:00
|
|
|
# Attempt to continue matching the XPath using the stanza's plugins.
|
|
|
|
if not matched_substanzas and len(xpath) > 1:
|
2010-08-25 18:54:09 +00:00
|
|
|
# Convert {namespace}tag@attribs to just tag
|
|
|
|
next_tag = xpath[1].split('@')[0].split('}')[-1]
|
2012-06-05 23:54:26 +00:00
|
|
|
langs = [name[1] for name in self.plugins if name[0] == next_tag]
|
|
|
|
for lang in langs:
|
2012-06-06 09:08:25 +00:00
|
|
|
plugin = self._get_plugin(next_tag, lang)
|
|
|
|
if plugin and plugin.match(xpath[1:]):
|
2012-06-05 23:54:26 +00:00
|
|
|
return True
|
|
|
|
return False
|
2010-08-25 18:40:16 +00:00
|
|
|
|
|
|
|
# Everything matched.
|
|
|
|
return True
|
|
|
|
|
2010-08-26 14:08:22 +00:00
|
|
|
def find(self, xpath):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Find an XML object in this stanza given an XPath expression.
|
2010-08-13 14:15:52 +00:00
|
|
|
|
2010-08-26 14:08:22 +00:00
|
|
|
Exposes ElementTree interface for backwards compatibility.
|
2010-08-13 14:15:52 +00:00
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
.. note::
|
2010-08-13 14:15:52 +00:00
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
Matching on attribute values is not supported in Python 2.6
|
|
|
|
or Python 3.1
|
|
|
|
|
|
|
|
:param string xpath: An XPath expression matching a single
|
|
|
|
desired element.
|
2010-08-26 14:08:22 +00:00
|
|
|
"""
|
|
|
|
return self.xml.find(xpath)
|
2010-08-13 14:15:52 +00:00
|
|
|
|
2010-08-26 14:08:22 +00:00
|
|
|
def findall(self, xpath):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Find multiple XML objects in this stanza given an XPath expression.
|
2010-08-13 14:15:52 +00:00
|
|
|
|
2010-08-26 14:08:22 +00:00
|
|
|
Exposes ElementTree interface for backwards compatibility.
|
2010-08-13 14:15:52 +00:00
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
.. note::
|
2010-08-26 14:08:22 +00:00
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
Matching on attribute values is not supported in Python 2.6
|
|
|
|
or Python 3.1.
|
|
|
|
|
|
|
|
:param string xpath: An XPath expression matching multiple
|
|
|
|
desired elements.
|
2010-08-26 14:08:22 +00:00
|
|
|
"""
|
|
|
|
return self.xml.findall(xpath)
|
|
|
|
|
|
|
|
def get(self, key, default=None):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Return the value of a stanza interface.
|
|
|
|
|
|
|
|
If the found value is None or an empty string, return the supplied
|
|
|
|
default value.
|
2010-08-26 14:08:22 +00:00
|
|
|
|
|
|
|
Allows stanza objects to be used like dictionaries.
|
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
:param string key: The name of the stanza interface to check.
|
|
|
|
:param default: Value to return if the stanza interface has a value
|
|
|
|
of ``None`` or ``""``. Will default to returning None.
|
2010-08-26 14:08:22 +00:00
|
|
|
"""
|
|
|
|
value = self[key]
|
|
|
|
if value is None or value == '':
|
|
|
|
return default
|
|
|
|
return value
|
2010-08-13 14:15:52 +00:00
|
|
|
|
|
|
|
def keys(self):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Return the names of all stanza interfaces provided by the
|
2010-08-26 14:08:22 +00:00
|
|
|
stanza object.
|
2010-08-13 14:15:52 +00:00
|
|
|
|
2010-08-26 14:08:22 +00:00
|
|
|
Allows stanza objects to be used like dictionaries.
|
|
|
|
"""
|
|
|
|
out = []
|
|
|
|
out += [x for x in self.interfaces]
|
2012-06-05 23:54:26 +00:00
|
|
|
out += [x for x in self.loaded_plugins]
|
2012-06-23 01:19:17 +00:00
|
|
|
out.append('lang')
|
2010-08-26 14:08:22 +00:00
|
|
|
if self.iterables:
|
|
|
|
out.append('substanzas')
|
2010-08-26 17:49:36 +00:00
|
|
|
return out
|
2010-08-13 14:15:52 +00:00
|
|
|
|
2010-08-26 14:08:22 +00:00
|
|
|
def append(self, item):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Append either an XML object or a substanza to this stanza object.
|
2010-08-13 14:15:52 +00:00
|
|
|
|
2010-08-26 14:08:22 +00:00
|
|
|
If a substanza object is appended, it will be added to the list
|
|
|
|
of iterable stanzas.
|
|
|
|
|
|
|
|
Allows stanza objects to be used like lists.
|
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
:param item: Either an XML object or a stanza object to add to
|
|
|
|
this stanza's contents.
|
2010-08-26 14:08:22 +00:00
|
|
|
"""
|
|
|
|
if not isinstance(item, ElementBase):
|
|
|
|
if type(item) == XML_TYPE:
|
|
|
|
return self.appendxml(item)
|
|
|
|
else:
|
|
|
|
raise TypeError
|
|
|
|
self.xml.append(item.xml)
|
|
|
|
self.iterables.append(item)
|
2012-05-05 21:01:13 +00:00
|
|
|
if item.__class__ in self.plugin_iterables:
|
|
|
|
if item.__class__.plugin_multi_attrib:
|
|
|
|
self.init_plugin(item.__class__.plugin_multi_attrib)
|
2012-10-18 19:26:17 +00:00
|
|
|
elif item.__class__ == self.plugin_tag_map.get(item.tag_name(), None):
|
|
|
|
self.init_plugin(item.plugin_attrib,
|
|
|
|
existing_xml=item.xml,
|
|
|
|
reuse=False)
|
2010-08-26 14:08:22 +00:00
|
|
|
return self
|
2010-08-13 14:15:52 +00:00
|
|
|
|
|
|
|
def appendxml(self, xml):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Append an XML object to the stanza's XML.
|
2010-08-13 14:15:52 +00:00
|
|
|
|
2010-08-26 14:08:22 +00:00
|
|
|
The added XML will not be included in the list of
|
|
|
|
iterable substanzas.
|
2010-08-13 14:15:52 +00:00
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
:param XML xml: The XML object to add to the stanza.
|
2010-08-26 14:08:22 +00:00
|
|
|
"""
|
|
|
|
self.xml.append(xml)
|
|
|
|
return self
|
2010-08-13 14:15:52 +00:00
|
|
|
|
2010-08-26 14:08:22 +00:00
|
|
|
def pop(self, index=0):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Remove and return the last substanza in the list of
|
2010-08-26 14:08:22 +00:00
|
|
|
iterable substanzas.
|
|
|
|
|
|
|
|
Allows stanza objects to be used like lists.
|
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
:param int index: The index of the substanza to remove.
|
2010-08-26 14:08:22 +00:00
|
|
|
"""
|
|
|
|
substanza = self.iterables.pop(index)
|
|
|
|
self.xml.remove(substanza.xml)
|
|
|
|
return substanza
|
|
|
|
|
|
|
|
def next(self):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Return the next iterable substanza."""
|
2010-08-26 14:08:22 +00:00
|
|
|
return self.__next__()
|
|
|
|
|
2011-01-26 16:27:41 +00:00
|
|
|
def clear(self):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Remove all XML element contents and plugins.
|
2011-01-26 16:27:41 +00:00
|
|
|
|
|
|
|
Any attribute values will be preserved.
|
|
|
|
"""
|
2012-02-20 04:27:53 +00:00
|
|
|
for child in list(self.xml):
|
2011-01-26 16:27:41 +00:00
|
|
|
self.xml.remove(child)
|
2012-02-20 04:27:53 +00:00
|
|
|
|
2011-01-26 16:27:41 +00:00
|
|
|
for plugin in list(self.plugins.keys()):
|
|
|
|
del self.plugins[plugin]
|
|
|
|
return self
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def tag_name(cls):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Return the namespaced name of the stanza's root element.
|
|
|
|
|
|
|
|
The format for the tag name is::
|
2011-01-26 16:27:41 +00:00
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
'{namespace}elementname'
|
|
|
|
|
|
|
|
For example, for the stanza ``<foo xmlns="bar" />``,
|
|
|
|
``stanza.tag_name()`` would return ``"{bar}foo"``.
|
2011-01-26 16:27:41 +00:00
|
|
|
"""
|
|
|
|
return "{%s}%s" % (cls.namespace, cls.name)
|
|
|
|
|
2012-06-23 01:19:17 +00:00
|
|
|
def get_lang(self, lang=None):
|
2012-06-05 23:54:26 +00:00
|
|
|
result = self.xml.attrib.get('{%s}lang' % XML_NS, '')
|
|
|
|
if not result and self.parent and self.parent():
|
|
|
|
return self.parent()['lang']
|
|
|
|
return result
|
|
|
|
|
|
|
|
def set_lang(self, lang):
|
|
|
|
self.del_lang()
|
|
|
|
attr = '{%s}lang' % XML_NS
|
|
|
|
if lang:
|
|
|
|
self.xml.attrib[attr] = lang
|
|
|
|
|
|
|
|
def del_lang(self):
|
|
|
|
attr = '{%s}lang' % XML_NS
|
|
|
|
if attr in self.xml.attrib:
|
|
|
|
del self.xml.attrib[attr]
|
|
|
|
|
2010-08-26 14:08:22 +00:00
|
|
|
@property
|
|
|
|
def attrib(self):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Return the stanza object itself.
|
2010-08-26 14:08:22 +00:00
|
|
|
|
|
|
|
Older implementations of stanza objects used XML objects directly,
|
2011-11-22 05:50:40 +00:00
|
|
|
requiring the use of ``.attrib`` to access attribute values.
|
2010-08-26 14:08:22 +00:00
|
|
|
|
|
|
|
Use of the dictionary syntax with the stanza object itself for
|
|
|
|
accessing stanza interfaces is preferred.
|
2011-11-22 05:50:40 +00:00
|
|
|
|
|
|
|
.. deprecated:: 1.0
|
2010-08-26 14:08:22 +00:00
|
|
|
"""
|
|
|
|
return self
|
2010-08-13 14:15:52 +00:00
|
|
|
|
2010-08-30 18:55:30 +00:00
|
|
|
def _fix_ns(self, xpath, split=False, propagate_ns=True):
|
2012-06-19 08:29:48 +00:00
|
|
|
return fix_ns(xpath, split=split,
|
|
|
|
propagate_ns=propagate_ns,
|
2012-01-18 06:28:44 +00:00
|
|
|
default_ns=self.namespace)
|
2010-08-24 12:55:37 +00:00
|
|
|
|
2010-08-26 14:08:22 +00:00
|
|
|
def __eq__(self, other):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Compare the stanza object with another to test for equality.
|
2010-08-26 14:08:22 +00:00
|
|
|
|
|
|
|
Stanzas are equal if their interfaces return the same values,
|
|
|
|
and if they are both instances of ElementBase.
|
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
:param ElementBase other: The stanza object to compare against.
|
2010-08-26 14:08:22 +00:00
|
|
|
"""
|
|
|
|
if not isinstance(other, ElementBase):
|
|
|
|
return False
|
2010-08-26 17:49:36 +00:00
|
|
|
|
|
|
|
# Check that this stanza is a superset of the other stanza.
|
2011-01-26 16:27:41 +00:00
|
|
|
values = self.values
|
2010-08-26 17:49:36 +00:00
|
|
|
for key in other.keys():
|
2010-08-26 14:08:22 +00:00
|
|
|
if key not in values or values[key] != other[key]:
|
|
|
|
return False
|
2010-08-26 17:49:36 +00:00
|
|
|
|
|
|
|
# Check that the other stanza is a superset of this stanza.
|
2011-01-26 16:27:41 +00:00
|
|
|
values = other.values
|
2010-08-26 17:49:36 +00:00
|
|
|
for key in self.keys():
|
|
|
|
if key not in values or values[key] != self[key]:
|
|
|
|
return False
|
|
|
|
|
|
|
|
# Both stanzas are supersets of each other, therefore they
|
|
|
|
# must be equal.
|
2010-08-26 14:08:22 +00:00
|
|
|
return True
|
|
|
|
|
2010-08-26 17:49:36 +00:00
|
|
|
def __ne__(self, other):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Compare the stanza object with another to test for inequality.
|
2010-08-26 17:49:36 +00:00
|
|
|
|
|
|
|
Stanzas are not equal if their interfaces return different values,
|
|
|
|
or if they are not both instances of ElementBase.
|
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
:param ElementBase other: The stanza object to compare against.
|
2010-08-26 17:49:36 +00:00
|
|
|
"""
|
|
|
|
return not self.__eq__(other)
|
|
|
|
|
2010-08-26 14:08:22 +00:00
|
|
|
def __bool__(self):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Stanza objects should be treated as True in boolean contexts.
|
2010-08-26 14:08:22 +00:00
|
|
|
|
|
|
|
Python 3.x version.
|
|
|
|
"""
|
|
|
|
return True
|
|
|
|
|
|
|
|
def __nonzero__(self):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Stanza objects should be treated as True in boolean contexts.
|
2010-08-26 14:08:22 +00:00
|
|
|
|
|
|
|
Python 2.x version.
|
|
|
|
"""
|
|
|
|
return True
|
|
|
|
|
|
|
|
def __len__(self):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Return the number of iterable substanzas in this stanza."""
|
2010-08-26 14:08:22 +00:00
|
|
|
return len(self.iterables)
|
|
|
|
|
|
|
|
def __iter__(self):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Return an iterator object for the stanza's substanzas.
|
2010-08-26 14:08:22 +00:00
|
|
|
|
|
|
|
The iterator is the stanza object itself. Attempting to use two
|
|
|
|
iterators on the same stanza at the same time is discouraged.
|
|
|
|
"""
|
|
|
|
self._index = 0
|
|
|
|
return self
|
|
|
|
|
|
|
|
def __next__(self):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Return the next iterable substanza."""
|
2010-08-26 14:08:22 +00:00
|
|
|
self._index += 1
|
|
|
|
if self._index > len(self.iterables):
|
|
|
|
self._index = 0
|
|
|
|
raise StopIteration
|
|
|
|
return self.iterables[self._index - 1]
|
|
|
|
|
|
|
|
def __copy__(self):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Return a copy of the stanza object that does not share the same
|
2010-08-26 14:08:22 +00:00
|
|
|
underlying XML object.
|
|
|
|
"""
|
|
|
|
return self.__class__(xml=copy.deepcopy(self.xml), parent=self.parent)
|
|
|
|
|
2011-03-18 21:34:07 +00:00
|
|
|
def __str__(self, top_level_ns=True):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Return a string serialization of the underlying XML object.
|
2011-03-18 21:34:07 +00:00
|
|
|
|
2011-11-22 23:25:02 +00:00
|
|
|
.. seealso:: :ref:`tostring`
|
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
:param bool top_level_ns: Display the top-most namespace.
|
|
|
|
Defaults to True.
|
2010-08-26 14:08:22 +00:00
|
|
|
"""
|
2011-01-27 23:05:05 +00:00
|
|
|
return tostring(self.xml, xmlns='',
|
2012-09-25 03:59:51 +00:00
|
|
|
top_level=True)
|
2010-08-26 14:08:22 +00:00
|
|
|
|
|
|
|
def __repr__(self):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Use the stanza's serialized XML as its representation."""
|
2010-08-26 14:08:22 +00:00
|
|
|
return self.__str__()
|
|
|
|
|
2009-12-11 01:29:46 +00:00
|
|
|
|
|
|
|
class StanzaBase(ElementBase):
|
2010-08-27 15:07:20 +00:00
|
|
|
|
|
|
|
"""
|
2011-11-22 07:17:39 +00:00
|
|
|
StanzaBase provides the foundation for all other stanza objects used
|
|
|
|
by SleekXMPP, and defines a basic set of interfaces common to nearly
|
|
|
|
all stanzas. These interfaces are the ``'id'``, ``'type'``, ``'to'``,
|
|
|
|
and ``'from'`` attributes. An additional interface, ``'payload'``, is
|
|
|
|
available to access the XML contents of the stanza. Most stanza objects
|
|
|
|
will provided more specific interfaces, however.
|
2010-08-27 15:07:20 +00:00
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
**Stanza Interfaces:**
|
|
|
|
|
|
|
|
:id: An optional id value that can be used to associate stanzas
|
|
|
|
:to: A JID object representing the recipient's JID.
|
|
|
|
:from: A JID object representing the sender's JID.
|
|
|
|
with their replies.
|
|
|
|
:type: The type of stanza, typically will be ``'normal'``,
|
|
|
|
``'error'``, ``'get'``, or ``'set'``, etc.
|
|
|
|
:payload: The XML contents of the stanza.
|
|
|
|
|
|
|
|
:param XMLStream stream: Optional :class:`sleekxmpp.xmlstream.XMLStream`
|
|
|
|
object responsible for sending this stanza.
|
|
|
|
:param XML xml: Optional XML contents to initialize stanza values.
|
|
|
|
:param string stype: Optional stanza type value.
|
|
|
|
:param sto: Optional string or :class:`sleekxmpp.xmlstream.JID`
|
|
|
|
object of the recipient's JID.
|
|
|
|
:param sfrom: Optional string or :class:`sleekxmpp.xmlstream.JID`
|
|
|
|
object of the sender's JID.
|
|
|
|
:param string sid: Optional ID value for the stanza.
|
2012-06-19 23:20:54 +00:00
|
|
|
:param parent: Optionally specify a parent stanza object will
|
|
|
|
contain this substanza.
|
2010-08-27 15:07:20 +00:00
|
|
|
"""
|
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
#: The default XMPP client namespace
|
2010-08-26 18:19:36 +00:00
|
|
|
namespace = 'jabber:client'
|
2011-11-22 05:50:40 +00:00
|
|
|
|
|
|
|
#: There is a small set of attributes which apply to all XMPP stanzas:
|
|
|
|
#: the stanza type, the to and from JIDs, the stanza ID, and, especially
|
|
|
|
#: in the case of an Iq stanza, a payload.
|
2010-08-26 18:19:36 +00:00
|
|
|
interfaces = set(('type', 'to', 'from', 'id', 'payload'))
|
2011-11-22 05:50:40 +00:00
|
|
|
|
|
|
|
#: A basic set of allowed values for the ``'type'`` interface.
|
2010-08-26 18:19:36 +00:00
|
|
|
types = set(('get', 'set', 'error', None, 'unavailable', 'normal', 'chat'))
|
|
|
|
|
|
|
|
def __init__(self, stream=None, xml=None, stype=None,
|
2012-06-19 23:20:54 +00:00
|
|
|
sto=None, sfrom=None, sid=None, parent=None):
|
2010-08-26 18:19:36 +00:00
|
|
|
self.stream = stream
|
|
|
|
if stream is not None:
|
|
|
|
self.namespace = stream.default_ns
|
2012-06-19 23:20:54 +00:00
|
|
|
ElementBase.__init__(self, xml, parent)
|
2010-08-26 18:19:36 +00:00
|
|
|
if stype is not None:
|
|
|
|
self['type'] = stype
|
|
|
|
if sto is not None:
|
|
|
|
self['to'] = sto
|
|
|
|
if sfrom is not None:
|
|
|
|
self['from'] = sfrom
|
2012-04-25 20:55:46 +00:00
|
|
|
if sid is not None:
|
|
|
|
self['id'] = sid
|
2010-08-26 18:19:36 +00:00
|
|
|
self.tag = "{%s}%s" % (self.namespace, self.name)
|
|
|
|
|
2010-10-18 01:38:22 +00:00
|
|
|
def set_type(self, value):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Set the stanza's ``'type'`` attribute.
|
2010-08-27 15:07:20 +00:00
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
Only type values contained in :attr:`types` are accepted.
|
2010-08-27 15:07:20 +00:00
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
:param string value: One of the values contained in :attr:`types`
|
2010-08-27 15:07:20 +00:00
|
|
|
"""
|
2010-08-26 18:19:36 +00:00
|
|
|
if value in self.types:
|
|
|
|
self.xml.attrib['type'] = value
|
|
|
|
return self
|
|
|
|
|
2010-10-18 01:38:22 +00:00
|
|
|
def get_to(self):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Return the value of the stanza's ``'to'`` attribute."""
|
2010-10-18 01:38:22 +00:00
|
|
|
return JID(self._get_attr('to'))
|
2010-08-27 15:07:20 +00:00
|
|
|
|
2010-10-18 01:38:22 +00:00
|
|
|
def set_to(self, value):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Set the ``'to'`` attribute of the stanza.
|
2010-08-27 15:07:20 +00:00
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
:param value: A string or :class:`sleekxmpp.xmlstream.JID` object
|
|
|
|
representing the recipient's JID.
|
2010-08-27 15:07:20 +00:00
|
|
|
"""
|
2010-10-18 01:38:22 +00:00
|
|
|
return self._set_attr('to', str(value))
|
2010-08-27 15:07:20 +00:00
|
|
|
|
2010-10-18 01:38:22 +00:00
|
|
|
def get_from(self):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Return the value of the stanza's ``'from'`` attribute."""
|
2010-10-18 01:38:22 +00:00
|
|
|
return JID(self._get_attr('from'))
|
2010-08-27 15:07:20 +00:00
|
|
|
|
2010-10-18 01:38:22 +00:00
|
|
|
def set_from(self, value):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Set the 'from' attribute of the stanza.
|
2010-08-27 15:07:20 +00:00
|
|
|
|
|
|
|
Arguments:
|
|
|
|
from -- A string or JID object representing the sender's JID.
|
|
|
|
"""
|
2010-10-18 01:38:22 +00:00
|
|
|
return self._set_attr('from', str(value))
|
2010-08-27 15:07:20 +00:00
|
|
|
|
2010-10-18 01:38:22 +00:00
|
|
|
def get_payload(self):
|
2010-08-27 15:07:20 +00:00
|
|
|
"""Return a list of XML objects contained in the stanza."""
|
2012-06-19 16:47:31 +00:00
|
|
|
return list(self.xml)
|
2010-08-26 18:19:36 +00:00
|
|
|
|
2010-10-18 01:38:22 +00:00
|
|
|
def set_payload(self, value):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Add XML content to the stanza.
|
2010-08-27 15:07:20 +00:00
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
:param value: Either an XML or a stanza object, or a list
|
|
|
|
of XML or stanza objects.
|
2010-08-27 15:07:20 +00:00
|
|
|
"""
|
2010-08-27 16:22:35 +00:00
|
|
|
if not isinstance(value, list):
|
|
|
|
value = [value]
|
|
|
|
for val in value:
|
|
|
|
self.append(val)
|
2010-08-26 18:19:36 +00:00
|
|
|
return self
|
2010-08-06 00:26:41 +00:00
|
|
|
|
2010-10-18 01:38:22 +00:00
|
|
|
def del_payload(self):
|
2010-08-27 15:07:20 +00:00
|
|
|
"""Remove the XML contents of the stanza."""
|
2010-08-26 18:19:36 +00:00
|
|
|
self.clear()
|
|
|
|
return self
|
2010-08-06 00:26:41 +00:00
|
|
|
|
2011-02-11 20:20:26 +00:00
|
|
|
def reply(self, clear=True):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Prepare the stanza for sending a reply.
|
|
|
|
|
|
|
|
Swaps the ``'from'`` and ``'to'`` attributes.
|
|
|
|
|
|
|
|
If ``clear=True``, then also remove the stanza's
|
2011-02-11 20:20:26 +00:00
|
|
|
contents to make room for the reply content.
|
2010-08-27 15:07:20 +00:00
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
For client streams, the ``'from'`` attribute is removed.
|
2011-02-11 20:20:26 +00:00
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
:param bool clear: Indicates if the stanza's contents should be
|
|
|
|
removed. Defaults to ``True``.
|
2010-08-27 15:07:20 +00:00
|
|
|
"""
|
2010-08-26 18:19:36 +00:00
|
|
|
# if it's a component, use from
|
|
|
|
if self.stream and hasattr(self.stream, "is_component") and \
|
|
|
|
self.stream.is_component:
|
|
|
|
self['from'], self['to'] = self['to'], self['from']
|
|
|
|
else:
|
|
|
|
self['to'] = self['from']
|
|
|
|
del self['from']
|
2011-02-11 20:20:26 +00:00
|
|
|
if clear:
|
|
|
|
self.clear()
|
2010-08-26 18:19:36 +00:00
|
|
|
return self
|
2010-08-06 00:26:41 +00:00
|
|
|
|
2010-08-26 18:19:36 +00:00
|
|
|
def error(self):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Set the stanza's type to ``'error'``."""
|
2010-08-26 18:19:36 +00:00
|
|
|
self['type'] = 'error'
|
|
|
|
return self
|
2010-08-06 00:26:41 +00:00
|
|
|
|
2010-08-26 18:19:36 +00:00
|
|
|
def unhandled(self):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Called if no handlers have been registered to process this stanza.
|
2010-08-27 15:07:20 +00:00
|
|
|
|
|
|
|
Meant to be overridden.
|
|
|
|
"""
|
2010-08-26 18:19:36 +00:00
|
|
|
pass
|
2010-08-06 00:26:41 +00:00
|
|
|
|
2010-08-26 18:19:36 +00:00
|
|
|
def exception(self, e):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Handle exceptions raised during stanza processing.
|
2010-08-27 15:07:20 +00:00
|
|
|
|
|
|
|
Meant to be overridden.
|
|
|
|
"""
|
2011-11-19 20:07:57 +00:00
|
|
|
log.exception('Error handling {%s}%s stanza', self.namespace,
|
|
|
|
self.name)
|
2010-08-26 18:19:36 +00:00
|
|
|
|
2011-05-27 23:59:52 +00:00
|
|
|
def send(self, now=False):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Queue the stanza to be sent on the XML stream.
|
|
|
|
|
|
|
|
:param bool now: Indicates if the queue should be skipped and the
|
|
|
|
stanza sent immediately. Useful for stream
|
|
|
|
initialization. Defaults to ``False``.
|
2011-05-27 23:59:52 +00:00
|
|
|
"""
|
2011-12-13 06:17:07 +00:00
|
|
|
self.stream.send(self, now=now)
|
2010-08-26 18:19:36 +00:00
|
|
|
|
|
|
|
def __copy__(self):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Return a copy of the stanza object that does not share the
|
2010-08-27 15:07:20 +00:00
|
|
|
same underlying XML object, but does share the same XML stream.
|
|
|
|
"""
|
|
|
|
return self.__class__(xml=copy.deepcopy(self.xml),
|
|
|
|
stream=self.stream)
|
2010-08-26 18:19:36 +00:00
|
|
|
|
2011-03-18 21:34:07 +00:00
|
|
|
def __str__(self, top_level_ns=False):
|
2011-11-22 05:50:40 +00:00
|
|
|
"""Serialize the stanza's XML to a string.
|
2011-03-18 21:34:07 +00:00
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
:param bool top_level_ns: Display the top-most namespace.
|
|
|
|
Defaults to ``False``.
|
2011-03-18 21:34:07 +00:00
|
|
|
"""
|
2012-09-25 03:59:51 +00:00
|
|
|
xmlns = self.stream.default_ns if self.stream else ''
|
|
|
|
return tostring(self.xml, xmlns=xmlns,
|
2011-01-27 23:05:05 +00:00
|
|
|
stream=self.stream,
|
2012-09-25 03:59:51 +00:00
|
|
|
top_level=(self.stream is None))
|
2011-02-14 18:49:43 +00:00
|
|
|
|
|
|
|
|
2011-11-22 05:50:40 +00:00
|
|
|
#: A JSON/dictionary version of the XML content exposed through
|
|
|
|
#: the stanza interfaces::
|
|
|
|
#:
|
|
|
|
#: >>> msg = Message()
|
|
|
|
#: >>> msg.values
|
|
|
|
#: {'body': '', 'from': , 'mucnick': '', 'mucroom': '',
|
|
|
|
#: 'to': , 'type': 'normal', 'id': '', 'subject': ''}
|
|
|
|
#:
|
|
|
|
#: Likewise, assigning to the :attr:`values` will change the XML
|
|
|
|
#: content::
|
|
|
|
#:
|
|
|
|
#: >>> msg = Message()
|
|
|
|
#: >>> msg.values = {'body': 'Hi!', 'to': 'user@example.com'}
|
|
|
|
#: >>> msg
|
|
|
|
#: '<message to="user@example.com"><body>Hi!</body></message>'
|
|
|
|
#:
|
|
|
|
#: Child stanzas are exposed as nested dictionaries.
|
|
|
|
ElementBase.values = property(ElementBase._get_stanza_values,
|
|
|
|
ElementBase._set_stanza_values)
|
|
|
|
|
|
|
|
|
2011-02-14 18:49:43 +00:00
|
|
|
# To comply with PEP8, method names now use underscores.
|
|
|
|
# Deprecated method names are re-mapped for backwards compatibility.
|
|
|
|
ElementBase.initPlugin = ElementBase.init_plugin
|
|
|
|
ElementBase._getAttr = ElementBase._get_attr
|
|
|
|
ElementBase._setAttr = ElementBase._set_attr
|
|
|
|
ElementBase._delAttr = ElementBase._del_attr
|
|
|
|
ElementBase._getSubText = ElementBase._get_sub_text
|
|
|
|
ElementBase._setSubText = ElementBase._set_sub_text
|
|
|
|
ElementBase._delSub = ElementBase._del_sub
|
|
|
|
ElementBase.getStanzaValues = ElementBase._get_stanza_values
|
|
|
|
ElementBase.setStanzaValues = ElementBase._set_stanza_values
|
|
|
|
|
|
|
|
StanzaBase.setType = StanzaBase.set_type
|
|
|
|
StanzaBase.getTo = StanzaBase.get_to
|
|
|
|
StanzaBase.setTo = StanzaBase.set_to
|
|
|
|
StanzaBase.getFrom = StanzaBase.get_from
|
|
|
|
StanzaBase.setFrom = StanzaBase.set_from
|
|
|
|
StanzaBase.getPayload = StanzaBase.get_payload
|
|
|
|
StanzaBase.setPayload = StanzaBase.set_payload
|
|
|
|
StanzaBase.delPayload = StanzaBase.del_payload
|