changeset 1451:9b88b19b1ca8

plugins xep-0060, xep-0277: added methods to serialise getItems result (before bridge transmission): serItemsData is used for normal callbacks, and serItemsDataD for callbacks which return deferred. These methods simplifly the code by making the re-use of getItems more easy.
author Goffi <goffi@goffi.org>
date Sat, 15 Aug 2015 22:20:56 +0200
parents 7797dda847ae
children 5116d70ddd1c
files src/plugins/plugin_xep_0060.py src/plugins/plugin_xep_0277.py
diffstat 2 files changed, 54 insertions(+), 6 deletions(-) [+]
line wrap: on
line diff
--- a/src/plugins/plugin_xep_0060.py	Sat Aug 15 22:20:43 2015 +0200
+++ b/src/plugins/plugin_xep_0060.py	Sat Aug 15 22:20:56 2015 +0200
@@ -25,6 +25,7 @@
 from sat.tools import sat_defer
 
 from twisted.words.protocols.jabber import jid
+from twisted.internet import defer
 from wokkel import disco
 from wokkel import pubsub
 from wokkel import rsm
@@ -201,6 +202,53 @@
 
     ## methods to manage several stanzas/jids at once ##
 
+    def serItemsData(self, items_data, item_cb=lambda item: item.toXml()):
+        """Helper method to serialise result from [getItems]
+
+        the items_data must be a tuple(list[domish.Element], dict[unicode, unicode])
+        as returned by [getItems]. metadata values are then casted to unicode and
+        each item is passed to items_cb
+        @param items_data(tuple): tuple returned by [getItems]
+        @param item_cb(callable): method to transform each item
+        @return (tuple): a serialised form ready to go throught bridge
+        """
+        items, metadata = items_data
+        return [item_cb(item) for item in items], {key: unicode(value) for key, value in metadata.iteritems()}
+
+    def serItemsDataD(self, items_data, item_cb):
+        """Helper method to serialise result from [getItems], deferred version
+
+        the items_data must be a tuple(list[domish.Element], dict[unicode, unicode])
+        as returned by [getItems]. metadata values are then casted to unicode and
+        each item is passed to items_cb
+        An errback is added to item_cb, and when it is fired the value is filtered from final items
+        @param items_data(tuple): tuple returned by [getItems]
+        @param item_cb(callable): method to transform each item (must return a deferred)
+        @return (tuple): a deferred which fire a serialised form ready to go throught bridge
+        """
+        items, metadata = items_data
+        def eb(failure):
+            log.warning("Error while serialising/parsing item: {}".format(unicode(failure.value)))
+        d = defer.gatherResults([item_cb(item).addErrback(eb) for item in items])
+        def finishSerialisation(serialised_items):
+            return [item for item in serialised_items if item is not None], {key: unicode(value) for key, value in metadata.iteritems()}
+        d.addCallback(finishSerialisation)
+        return d
+
+    def serDList(self, results, failure_result=None):
+        """Serialise a DeferredList result
+
+        @param results: DeferredList results
+        @param failure_result: value to use as value for failed Deferred
+            (default: empty tuple)
+        @return (list): list with:
+            - failure: empty in case of success, else error message
+            - result
+        """
+        if failure_result is None:
+            failure_result = ()
+        return [('', result) if success else (unicode(result.result) or UNSPECIFIED, failure_result) for success, result in results]
+
     # subscribe #
 
     def _manySubscribeRTResult(self, session_id, profile_key=C.PROF_KEY_DEFAULT):
--- a/src/plugins/plugin_xep_0277.py	Sat Aug 15 22:20:43 2015 +0200
+++ b/src/plugins/plugin_xep_0277.py	Sat Aug 15 22:20:56 2015 +0200
@@ -61,6 +61,7 @@
     def __init__(self, host):
         log.info(_("Microblogging plugin initialization"))
         self.host = host
+        self._p = self.host.plugins["XEP-0060"] # this facilitate the access to pubsub plugin
         self.host.plugins["XEP-0163"].addPEPEvent("MICROBLOG", NS_MICROBLOG, self.microblogCB, self.sendMicroblog, notify=False)
         host.bridge.addMethod("getLastMicroblogs", ".plugin",
                               in_sign='sis', out_sign='(aa{ss}a{ss})',
@@ -310,7 +311,7 @@
             log.error("Microblog data's content value must not be empty")
             raise failure.Failure(exceptions.DataError('empty content'))
         item = yield self.data2entry(data, profile)
-        ret = yield self.host.plugins["XEP-0060"].publish(None, NS_MICROBLOG, [item], profile_key=profile)
+        ret = yield self._p.publish(None, NS_MICROBLOG, [item], profile_key=profile)
         defer.returnValue(ret)
 
     ## get ##
@@ -373,8 +374,7 @@
         if not _jid:
             log.error(_("Can't find profile's jid"))
             return
-        C = self.host.plugins["XEP-0060"]
-        _options = {C.OPT_ACCESS_MODEL: access, C.OPT_PERSIST_ITEMS: 1, C.OPT_MAX_ITEMS: -1, C.OPT_DELIVER_PAYLOADS: 1, C.OPT_SEND_ITEM_SUBSCRIBE: 1}
+        _options = {self._p.OPT_ACCESS_MODEL: access, self._p.OPT_PERSIST_ITEMS: 1, self._p.OPT_MAX_ITEMS: -1, self._p.OPT_DELIVER_PAYLOADS: 1, self._p.OPT_SEND_ITEM_SUBSCRIBE: 1}
 
         def cb(result):
             #Node is created with right permission
@@ -396,10 +396,10 @@
                 fatal_err(s_error)
 
         def create_node():
-            return self.host.plugins["XEP-0060"].createNode(_jid.userhostJID(), NS_MICROBLOG, _options, profile_key=profile_key)
+            return self._p.createNode(_jid.userhostJID(), NS_MICROBLOG, _options, profile_key=profile_key)
 
         def change_node_options():
-            return self.host.plugins["XEP-0060"].setOptions(_jid.userhostJID(), NS_MICROBLOG, _jid.userhostJID(), _options, profile_key=profile_key)
+            return self._p.setOptions(_jid.userhostJID(), NS_MICROBLOG, _jid.userhostJID(), _options, profile_key=profile_key)
 
         create_node().addCallback(cb).addErrback(err_cb)
 
@@ -466,5 +466,5 @@
         @return (str): session id
         """
         client, node_data = self._getClientAndNodeData(publishers_type, publishers, profile_key)
-        return self.host.plugins["XEP-0060"].subscribeToMany(node_data, client.jid.userhostJID(), profile_key=profile_key)
+        return self._p.subscribeToMany(node_data, client.jid.userhostJID(), profile_key=profile_key)