diff src/plugins/plugin_xep_0277.py @ 1421:16b1ba7ccaaa

plugins xep-0277: some methods reordering to make the plugin more readable
author Goffi <goffi@goffi.org>
date Thu, 23 Apr 2015 10:25:47 +0200
parents be2df1ddea8e
children e8c8e467964b
line wrap: on
line diff
--- a/src/plugins/plugin_xep_0277.py	Wed Apr 22 20:21:55 2015 +0200
+++ b/src/plugins/plugin_xep_0277.py	Thu Apr 23 10:25:47 2015 +0200
@@ -75,25 +75,27 @@
                               async=True,
                               doc={})
 
-    def parseCommentUrl(self, node_url):
-        """Determine the fields comments_service and comments_node of a microblog data
-        from the href attribute of an entry's link element. For example this input:
-        xmpp:sat-pubsub.libervia.org?node=urn%3Axmpp%3Acomments%3A_c5c4a142-2279-4b2a-ba4c-1bc33aa87634__urn%3Axmpp%3Agroupblog%3Asouliane%40libervia.org
-        will return (JID(u'sat-pubsub.libervia.org'), 'urn:xmpp:comments:_c5c4a142-2279-4b2a-ba4c-1bc33aa87634__urn:xmpp:groupblog:souliane@libervia.org')
-        @return: a tuple (JID, str)
-        """
-        parsed_url = urlparse.urlparse(node_url, 'xmpp')
-        service = jid.JID(parsed_url.path)
-        queries = parsed_url.query.split(';')
-        parsed_queries = dict()
-        for query in queries:
-            parsed_queries.update(urlparse.parse_qs(query))
-        node = parsed_queries.get('node', [''])[0]
+    ## plugin management methods ##
+
+    def microblogCB(self, itemsEvent, profile):
+        """Callback to "MICROBLOG" PEP event."""
+        def manageItem(microblog_data):
+            self.host.bridge.personalEvent(itemsEvent.sender.full(), "MICROBLOG", microblog_data, profile)
+
+        for item in itemsEvent.items:
+            self.item2mbdata(item).addCallbacks(manageItem, lambda failure: None)
 
-        if not node:
-            raise exceptions.DataError('Invalid comments link')
+    ## data/item transformation ##
 
-        return (service, node)
+    def _getDomishInnerContent(self, elt):
+        """Return the inner content of a domish.Element."""
+        result = ''
+        for child in elt.children:
+            try:
+                result += child.toXml()  # child id a domish.Element
+            except AttributeError:
+                result += child  # child is unicode
+        return result
 
     def _removeXHTMLMarkups(self, xhtml):
         """Remove XHTML markups from the given string.
@@ -109,8 +111,10 @@
     @defer.inlineCallbacks
     def item2mbdata(self, item):
         """Convert an XML Item to microblog data used in bridge API
+
         @param item: domish.Element of microblog item
-        @return: microblog data (dictionary)"""
+        @return: microblog data (dictionary)
+        """
 
         def xpath(elt, path):
             """Return the XPATH result of an entry element or its descendance."""
@@ -142,12 +146,23 @@
 
         for key in ['title', 'content']:  # process the textual elements
             for attr_elt in xpath(entry_elt, key):
-                attr_content = self._getLXMLInnerContent(attr_elt)
+                # Return the inner content of a lxml.etree.Element. It is not
+                # trivial because the lxml tostring method would return the full
+                # content including elt's tag and attributes, and elt.getchildren()
+                # would skip a text value which is not within an element...
+                attr_content = self._getDomishInnerContent(ElementParser()(etree.tostring(attr_elt)))
                 if not attr_content.strip():
                     continue  # element with empty value
                 content_type = attr_elt.get('type', 'text').lower()
                 if content_type == 'xhtml':
-                    text = self._decapsulateExtraNS(attr_content)
+                    # Check for XHTML namespace and decapsulate the content so the user
+                    # who wants to modify an entry will see the text that he entered. Also
+                    # this avoids successive encapsulation with a new <div>...</div> at
+                    # each modification (encapsulation is done in self.data2entry)
+                    elt = ElementParser()(attr_content)
+                    if elt.uri != NS_XHTML:
+                        raise exceptions.DataError(_('Content of type XHTML must declare its namespace!'))
+                    text = self._getDomishInnerContent(elt)
                     microblog_data['%s_xhtml' % key] = yield self.host.plugins["TEXT-SYNTAXES"].clean_xhtml(text)
                 else:
                     microblog_data[key] = attr_content
@@ -198,41 +213,6 @@
 
         defer.returnValue(microblog_data)
 
-    def _getLXMLInnerContent(self, elt):
-        """Return the inner content of a lxml.etree.Element. It is not
-        trivial because the lxml tostring method would return the full
-        content including elt's tag and attributes, and elt.getchildren()
-        would skip a text value which is not within an element..."""
-        return self._getDomishInnerContent(ElementParser()(etree.tostring(elt)))
-
-    def _getDomishInnerContent(self, elt):
-        """Return the inner content of a domish.Element."""
-        result = ''
-        for child in elt.children:
-            try:
-                result += child.toXml()  # child id a domish.Element
-            except AttributeError:
-                result += child  # child is unicode
-        return result
-
-    def _decapsulateExtraNS(self, text):
-        """Check for XHTML namespace and decapsulate the content so the user
-        who wants to modify an entry will see the text that he entered. Also
-        this avoids successive encapsulation with a new <div>...</div> at
-        each modification (encapsulation is done in self.data2entry)"""
-        elt = ElementParser()(text)
-        if elt.uri != NS_XHTML:
-            raise exceptions.DataError(_('Content of type XHTML must declare its namespace!'))
-        return self._getDomishInnerContent(elt)
-
-    def microblogCB(self, itemsEvent, profile):
-        """Callback to "MICROBLOG" PEP event."""
-        def manageItem(microblog_data):
-            self.host.bridge.personalEvent(itemsEvent.sender.full(), "MICROBLOG", microblog_data, profile)
-
-        for item in itemsEvent.items:
-            self.item2mbdata(item).addCallbacks(manageItem, lambda failure: None)
-
     @defer.inlineCallbacks
     def data2entry(self, data, profile):
         """Convert a data dict to en entry usable to create an item
@@ -297,6 +277,8 @@
         item = pubsub.Item(id=entry_id, payload=_entry_elt)
         defer.returnValue(item)
 
+    ## publish ##
+
     @defer.inlineCallbacks
     def sendMicroblog(self, data, profile):
         """Send XEP-0277's microblog data
@@ -314,6 +296,8 @@
         ret = yield self.host.plugins["XEP-0060"].publish(None, NS_MICROBLOG, [item], profile_key=profile)
         defer.returnValue(ret)
 
+    ## get ##
+
     def getLastMicroblogs(self, pub_jid, max_items=10, profile_key=C.PROF_KEY_NONE):
         """Get the last published microblogs
 
@@ -328,6 +312,28 @@
         d.addCallback(lambda res: ([value for (success, value) in res[0] if success], res[1]))
         return d
 
+    def parseCommentUrl(self, node_url):
+        """Determine the fields comments_service and comments_node of a microblog data
+        from the href attribute of an entry's link element. For example this input:
+        xmpp:sat-pubsub.libervia.org?node=urn%3Axmpp%3Acomments%3A_c5c4a142-2279-4b2a-ba4c-1bc33aa87634__urn%3Axmpp%3Agroupblog%3Asouliane%40libervia.org
+        will return (JID(u'sat-pubsub.libervia.org'), 'urn:xmpp:comments:_c5c4a142-2279-4b2a-ba4c-1bc33aa87634__urn:xmpp:groupblog:souliane@libervia.org')
+        @return: a tuple (JID, str)
+        """
+        parsed_url = urlparse.urlparse(node_url, 'xmpp')
+        service = jid.JID(parsed_url.path)
+        queries = parsed_url.query.split(';')
+        parsed_queries = dict()
+        for query in queries:
+            parsed_queries.update(urlparse.parse_qs(query))
+        node = parsed_queries.get('node', [''])[0]
+
+        if not node:
+            raise exceptions.DataError('Invalid comments link')
+
+        return (service, node)
+
+    ## configure ##
+
     def setMicroblogAccess(self, access="presence", profile_key=C.PROF_KEY_NONE):
         """Create a microblog node on PEP with given access