diff sat/plugins/plugin_xep_0033.py @ 2624:56f94936df1e

code style reformatting using black
author Goffi <goffi@goffi.org>
date Wed, 27 Jun 2018 20:14:46 +0200
parents 26edcf3a30eb
children 378188abe941
line wrap: on
line diff
--- a/sat/plugins/plugin_xep_0033.py	Wed Jun 27 07:51:29 2018 +0200
+++ b/sat/plugins/plugin_xep_0033.py	Wed Jun 27 20:14:46 2018 +0200
@@ -20,6 +20,7 @@
 from sat.core.i18n import _
 from sat.core.constants import Const as C
 from sat.core.log import getLogger
+
 log = getLogger(__name__)
 from sat.core import exceptions
 from wokkel import disco, iwokkel
@@ -27,6 +28,7 @@
 from twisted.words.protocols.jabber.jid import JID
 from twisted.python import failure
 import copy
+
 try:
     from twisted.words.protocols.xmlstream import XMPPHandler
 except ImportError:
@@ -61,7 +63,7 @@
     C.PI_DEPENDENCIES: [],
     C.PI_MAIN: "XEP_0033",
     C.PI_HANDLER: "yes",
-    C.PI_DESCRIPTION: _("""Implementation of Extended Stanza Addressing""")
+    C.PI_DESCRIPTION: _("""Implementation of Extended Stanza Addressing"""),
 }
 
 
@@ -69,38 +71,65 @@
     """
     Implementation for XEP 0033
     """
+
     def __init__(self, host):
         log.info(_("Extended Stanza Addressing plugin initialization"))
         self.host = host
         self.internal_data = {}
-        host.trigger.add("sendMessage", self.sendMessageTrigger, trigger.TriggerManager.MIN_PRIORITY)
+        host.trigger.add(
+            "sendMessage", self.sendMessageTrigger, trigger.TriggerManager.MIN_PRIORITY
+        )
         host.trigger.add("MessageReceived", self.messageReceivedTrigger)
 
-    def sendMessageTrigger(self, client, mess_data, pre_xml_treatments, post_xml_treatments):
+    def sendMessageTrigger(
+        self, client, mess_data, pre_xml_treatments, post_xml_treatments
+    ):
         """Process the XEP-0033 related data to be sent"""
         profile = client.profile
 
         def treatment(mess_data):
-            if not 'address' in mess_data['extra']:
+            if not "address" in mess_data["extra"]:
                 return mess_data
 
             def discoCallback(entities):
                 if not entities:
-                    log.warning(_("XEP-0033 is being used but the server doesn't support it!"))
-                    raise failure.Failure(exceptions.CancelError(u'Cancelled by XEP-0033'))
+                    log.warning(
+                        _("XEP-0033 is being used but the server doesn't support it!")
+                    )
+                    raise failure.Failure(
+                        exceptions.CancelError(u"Cancelled by XEP-0033")
+                    )
                 if mess_data["to"] not in entities:
-                    expected = _(' or ').join([entity.userhost() for entity in entities])
-                    log.warning(_(u"Stanzas using XEP-0033 should be addressed to %(expected)s, not %(current)s!") % {'expected': expected, 'current': mess_data["to"]})
-                    log.warning(_(u"TODO: addressing has been fixed by the backend... fix it in the frontend!"))
+                    expected = _(" or ").join([entity.userhost() for entity in entities])
+                    log.warning(
+                        _(
+                            u"Stanzas using XEP-0033 should be addressed to %(expected)s, not %(current)s!"
+                        )
+                        % {"expected": expected, "current": mess_data["to"]}
+                    )
+                    log.warning(
+                        _(
+                            u"TODO: addressing has been fixed by the backend... fix it in the frontend!"
+                        )
+                    )
                     mess_data["to"] = list(entities)[0].userhostJID()
-                element = mess_data['xml'].addElement('addresses', NS_ADDRESS)
-                entries = [entry.split(':') for entry in mess_data['extra']['address'].split('\n') if entry != '']
+                element = mess_data["xml"].addElement("addresses", NS_ADDRESS)
+                entries = [
+                    entry.split(":")
+                    for entry in mess_data["extra"]["address"].split("\n")
+                    if entry != ""
+                ]
                 for type_, jid_ in entries:
-                    element.addChild(domish.Element((None, 'address'), None, {'type': type_, 'jid': jid_}))
+                    element.addChild(
+                        domish.Element(
+                            (None, "address"), None, {"type": type_, "jid": jid_}
+                        )
+                    )
                 # when the prosody plugin is completed, we can immediately return mess_data from here
                 self.sendAndStoreMessage(mess_data, entries, profile)
                 log.debug("XEP-0033 took over")
-                raise failure.Failure(exceptions.CancelError(u'Cancelled by XEP-0033'))
+                raise failure.Failure(exceptions.CancelError(u"Cancelled by XEP-0033"))
+
             d = self.host.findFeaturesSet(client, [NS_ADDRESS])
             d.addCallbacks(discoCallback, lambda dummy: discoCallback(None))
             return d
@@ -122,6 +151,7 @@
         - change the messageNew signal to eventually pass more than one recipient
         """
         client = self.host.getClient(profile)
+
         def send(mess_data, skip_send=False):
             d = defer.Deferred()
             if not skip_send:
@@ -133,13 +163,13 @@
 
         def discoCallback(entities, to_jid_s):
             history_data = copy.deepcopy(mess_data)
-            history_data['to'] = JID(to_jid_s)
-            history_data['xml']['to'] = to_jid_s
+            history_data["to"] = JID(to_jid_s)
+            history_data["xml"]["to"] = to_jid_s
             if entities:
                 if entities not in self.internal_data[timestamp]:
                     sent_data = copy.deepcopy(mess_data)
-                    sent_data['to'] = JID(JID(to_jid_s).host)
-                    sent_data['xml']['to'] = JID(to_jid_s).host
+                    sent_data["to"] = JID(JID(to_jid_s).host)
+                    sent_data["xml"]["to"] = JID(to_jid_s).host
                     send(sent_data)
                     self.internal_data[timestamp].append(entities)
                 # we still need to fill the history and signal the echo...
@@ -156,8 +186,12 @@
         defer_list = []
         for type_, jid_ in entries:
             d = defer.Deferred()
-            d.addCallback(self.host.findFeaturesSet, client=client, jid_=JID(JID(jid_).host))
-            d.addCallbacks(discoCallback, errback, callbackArgs=[jid_], errbackArgs=[jid_])
+            d.addCallback(
+                self.host.findFeaturesSet, client=client, jid_=JID(JID(jid_).host)
+            )
+            d.addCallbacks(
+                discoCallback, errback, callbackArgs=[jid_], errbackArgs=[jid_]
+            )
             d.callback([NS_ADDRESS])
             defer_list.append(d)
         d = defer.Deferred().addCallback(lambda dummy: self.internal_data.pop(timestamp))
@@ -165,17 +199,21 @@
 
     def messageReceivedTrigger(self, client, message, post_treat):
         """In order to save the addressing information in the history"""
+
         def post_treat_addr(data, addresses):
-            data['extra']['addresses'] = ""
+            data["extra"]["addresses"] = ""
             for address in addresses:
                 # Depending how message has been constructed, we could get here
                 # some noise like "\n        " instead of an address element.
                 if isinstance(address, domish.Element):
-                    data['extra']['addresses'] += '%s:%s\n' % (address['type'], address['jid'])
+                    data["extra"]["addresses"] += "%s:%s\n" % (
+                        address["type"],
+                        address["jid"],
+                    )
             return data
 
         try:
-            addresses = message.elements(NS_ADDRESS, 'addresses').next()
+            addresses = message.elements(NS_ADDRESS, "addresses").next()
         except StopIteration:
             pass  # no addresses
         else:
@@ -194,8 +232,8 @@
         self.host = plugin_parent.host
         self.profile = profile
 
-    def getDiscoInfo(self, requestor, target, nodeIdentifier=''):
+    def getDiscoInfo(self, requestor, target, nodeIdentifier=""):
         return [disco.DiscoFeature(NS_ADDRESS)]
 
-    def getDiscoItems(self, requestor, target, nodeIdentifier=''):
+    def getDiscoItems(self, requestor, target, nodeIdentifier=""):
         return []