diff sat/plugins/plugin_xep_0096.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_0096.py	Wed Jun 27 07:51:29 2018 +0200
+++ b/sat/plugins/plugin_xep_0096.py	Wed Jun 27 20:14:46 2018 +0200
@@ -20,6 +20,7 @@
 from sat.core.i18n import _, D_
 from sat.core.constants import Const as C
 from sat.core.log import getLogger
+
 log = getLogger(__name__)
 from sat.core import exceptions
 from sat.tools import xml_tools
@@ -43,7 +44,7 @@
     C.PI_DEPENDENCIES: ["XEP-0020", "XEP-0095", "XEP-0065", "XEP-0047", "FILE"],
     C.PI_MAIN: "XEP_0096",
     C.PI_HANDLER: "no",
-    C.PI_DESCRIPTION: _("""Implementation of SI File Transfer""")
+    C.PI_DESCRIPTION: _("""Implementation of SI File Transfer"""),
 }
 
 
@@ -53,13 +54,19 @@
     def __init__(self, host):
         log.info(_("Plugin XEP_0096 initialization"))
         self.host = host
-        self.managed_stream_m = [self.host.plugins["XEP-0065"].NAMESPACE,
-                                 self.host.plugins["XEP-0047"].NAMESPACE]  # Stream methods managed
+        self.managed_stream_m = [
+            self.host.plugins["XEP-0065"].NAMESPACE,
+            self.host.plugins["XEP-0047"].NAMESPACE,
+        ]  # Stream methods managed
         self._f = self.host.plugins["FILE"]
-        self._f.register(NS_SI_FT, self.sendFile, priority=0, method_name=u"Stream Initiation")
+        self._f.register(
+            NS_SI_FT, self.sendFile, priority=0, method_name=u"Stream Initiation"
+        )
         self._si = self.host.plugins["XEP-0095"]
         self._si.registerSIProfile(SI_PROFILE_NAME, self._transferRequest)
-        host.bridge.addMethod("siSendFile", ".plugin", in_sign='sssss', out_sign='s', method=self._sendFile)
+        host.bridge.addMethod(
+            "siSendFile", ".plugin", in_sign="sssss", out_sign="s", method=self._sendFile
+        )
 
     def unload(self):
         self._si.unregisterSIProfile(SI_PROFILE_NAME)
@@ -72,7 +79,7 @@
         """
         if message is not None:
             log.warning(message)
-        self._si.sendError(client, iq_elt, 'bad-request')
+        self._si.sendError(client, iq_elt, "bad-request")
 
     def _parseRange(self, parent_elt, file_size):
         """find and parse <range/> element
@@ -84,7 +91,7 @@
             - range_length
         """
         try:
-            range_elt = parent_elt.elements(NS_SI_FT, 'range').next()
+            range_elt = parent_elt.elements(NS_SI_FT, "range").next()
         except StopIteration:
             range_ = False
             range_offset = None
@@ -93,17 +100,17 @@
             range_ = True
 
             try:
-                range_offset = int(range_elt['offset'])
+                range_offset = int(range_elt["offset"])
             except KeyError:
                 range_offset = 0
 
             try:
-                range_length = int(range_elt['length'])
+                range_length = int(range_elt["length"])
             except KeyError:
                 range_length = file_size
 
             if range_offset != 0 or range_length != file_size:
-                raise NotImplementedError # FIXME
+                raise NotImplementedError  # FIXME
 
         return range_, range_offset, range_length
 
@@ -116,17 +123,21 @@
         @param si_elt(domish.Element): request
         """
         log.info(_("XEP-0096 file transfer requested"))
-        peer_jid = jid.JID(iq_elt['from'])
+        peer_jid = jid.JID(iq_elt["from"])
 
         try:
             file_elt = si_elt.elements(NS_SI_FT, "file").next()
         except StopIteration:
-            return self._badRequest(client, iq_elt, "No <file/> element found in SI File Transfer request")
+            return self._badRequest(
+                client, iq_elt, "No <file/> element found in SI File Transfer request"
+            )
 
         try:
             feature_elt = self.host.plugins["XEP-0020"].getFeatureElt(si_elt)
         except exceptions.NotFound:
-            return self._badRequest(client, iq_elt, "No <feature/> element found in SI File Transfer request")
+            return self._badRequest(
+                client, iq_elt, "No <feature/> element found in SI File Transfer request"
+            )
 
         try:
             filename = file_elt["name"]
@@ -137,12 +148,16 @@
         file_date = file_elt.getAttribute("date")
         file_hash = file_elt.getAttribute("hash")
 
-        log.info(u"File proposed: name=[{name}] size={size}".format(name=filename, size=file_size))
+        log.info(
+            u"File proposed: name=[{name}] size={size}".format(
+                name=filename, size=file_size
+            )
+        )
 
         try:
-            file_desc = unicode(file_elt.elements(NS_SI_FT, 'desc').next())
+            file_desc = unicode(file_elt.elements(NS_SI_FT, "desc").next())
         except StopIteration:
-            file_desc = ''
+            file_desc = ""
 
         try:
             range_, range_offset, range_length = self._parseRange(file_elt, file_size)
@@ -150,7 +165,9 @@
             return self._badRequest(client, iq_elt, "Malformed SI File Transfer request")
 
         try:
-            stream_method = self.host.plugins["XEP-0020"].negotiate(feature_elt, 'stream-method', self.managed_stream_m, namespace=None)
+            stream_method = self.host.plugins["XEP-0020"].negotiate(
+                feature_elt, "stream-method", self.managed_stream_m, namespace=None
+            )
         except KeyError:
             return self._badRequest(client, iq_elt, "No stream method found")
 
@@ -160,16 +177,30 @@
             elif stream_method == self.host.plugins["XEP-0047"].NAMESPACE:
                 plugin = self.host.plugins["XEP-0047"]
             else:
-                log.error(u"Unknown stream method, this should not happen at this stage, cancelling transfer")
+                log.error(
+                    u"Unknown stream method, this should not happen at this stage, cancelling transfer"
+                )
         else:
             log.warning(u"Can't find a valid stream method")
-            self._si.sendError(client, iq_elt, 'not-acceptable')
+            self._si.sendError(client, iq_elt, "not-acceptable")
             return
 
-        #if we are here, the transfer can start, we just need user's agreement
-        data = {"name": filename, "peer_jid": peer_jid, "size": file_size, "date": file_date, "hash": file_hash, "desc": file_desc,
-                "range": range_, "range_offset": range_offset, "range_length": range_length,
-                "si_id": si_id, "progress_id": si_id, "stream_method": stream_method, "stream_plugin": plugin}
+        # if we are here, the transfer can start, we just need user's agreement
+        data = {
+            "name": filename,
+            "peer_jid": peer_jid,
+            "size": file_size,
+            "date": file_date,
+            "hash": file_hash,
+            "desc": file_desc,
+            "range": range_,
+            "range_offset": range_offset,
+            "range_length": range_length,
+            "si_id": si_id,
+            "progress_id": si_id,
+            "stream_method": stream_method,
+            "stream_plugin": plugin,
+        }
 
         d = self._f.getDestDir(client, peer_jid, data, data, stream_object=True)
         d.addCallback(self.confirmationCb, client, iq_elt, data)
@@ -183,7 +214,7 @@
         """
         if not accepted:
             log.info(u"File transfer declined")
-            self._si.sendError(client, iq_elt, 'forbidden')
+            self._si.sendError(client, iq_elt, "forbidden")
             return
         # data, timeout, stream_method, failed_methods = client._xep_0096_waiting_for_approval[sid]
         # can_range = data['can_range'] == "True"
@@ -207,12 +238,16 @@
 
         # file_obj = self._getFileObject(dest_path, can_range)
         # range_offset = file_obj.tell()
-        d = data['stream_plugin'].createSession(client, data['stream_object'], data['peer_jid'], data['si_id'])
+        d = data["stream_plugin"].createSession(
+            client, data["stream_object"], data["peer_jid"], data["si_id"]
+        )
         d.addCallback(self._transferCb, client, data)
         d.addErrback(self._transferEb, client, data)
 
-        #we can send the iq result
-        feature_elt = self.host.plugins["XEP-0020"].chooseOption({'stream-method': data['stream_method']}, namespace=None)
+        # we can send the iq result
+        feature_elt = self.host.plugins["XEP-0020"].chooseOption(
+            {"stream-method": data["stream_method"]}, namespace=None
+        )
         misc_elts = []
         misc_elts.append(domish.Element((SI_PROFILE, "file")))
         # if can_range:
@@ -227,9 +262,9 @@
 
         @param data: session data
         """
-        #TODO: check hash
-        data['stream_object'].close()
-        log.info(u'Transfer {si_id} successfuly finished'.format(**data))
+        # TODO: check hash
+        data["stream_object"].close()
+        log.info(u"Transfer {si_id} successfuly finished".format(**data))
 
     def _transferEb(self, failure, client, data):
         """Called when something went wrong with the transfer
@@ -237,12 +272,18 @@
         @param id: stream id
         @param data: session data
         """
-        log.warning(u'Transfer {si_id} failed: {reason}'.format(reason=unicode(failure.value), **data))
-        data['stream_object'].close()
+        log.warning(
+            u"Transfer {si_id} failed: {reason}".format(
+                reason=unicode(failure.value), **data
+            )
+        )
+        data["stream_object"].close()
 
     def _sendFile(self, peer_jid_s, filepath, name, desc, profile=C.PROF_KEY_NONE):
         client = self.host.getClient(profile)
-        return self.sendFile(client, jid.JID(peer_jid_s), filepath, name or None, desc or None)
+        return self.sendFile(
+            client, jid.JID(peer_jid_s), filepath, name or None, desc or None
+        )
 
     def sendFile(self, client, peer_jid, filepath, name=None, desc=None, extra=None):
         """Send a file using XEP-0096
@@ -255,23 +296,27 @@
         @param extra: not used here
         @return: an unique id to identify the transfer
         """
-        feature_elt = self.host.plugins["XEP-0020"].proposeFeatures({'stream-method': self.managed_stream_m}, namespace=None)
+        feature_elt = self.host.plugins["XEP-0020"].proposeFeatures(
+            {"stream-method": self.managed_stream_m}, namespace=None
+        )
 
         file_transfer_elts = []
 
         statinfo = os.stat(filepath)
-        file_elt = domish.Element((SI_PROFILE, 'file'))
-        file_elt['name'] = name or os.path.basename(filepath)
-        assert '/' not in file_elt['name']
+        file_elt = domish.Element((SI_PROFILE, "file"))
+        file_elt["name"] = name or os.path.basename(filepath)
+        assert "/" not in file_elt["name"]
         size = statinfo.st_size
-        file_elt['size'] = str(size)
+        file_elt["size"] = str(size)
         if desc:
-            file_elt.addElement('desc', content=desc)
+            file_elt.addElement("desc", content=desc)
         file_transfer_elts.append(file_elt)
 
-        file_transfer_elts.append(domish.Element((None, 'range')))
+        file_transfer_elts.append(domish.Element((None, "range")))
 
-        sid, offer_d = self._si.proposeStream(client, peer_jid, SI_PROFILE, feature_elt, file_transfer_elts)
+        sid, offer_d = self._si.proposeStream(
+            client, peer_jid, SI_PROFILE, feature_elt, file_transfer_elts
+        )
         args = [filepath, sid, size, client]
         offer_d.addCallbacks(self._fileCb, self._fileEb, args, None, args)
         return sid
@@ -285,7 +330,9 @@
             log.warning(u"No <feature/> element found in result while expected")
             return
 
-        choosed_options = self.host.plugins["XEP-0020"].getChoosedOptions(feature_elt, namespace=None)
+        choosed_options = self.host.plugins["XEP-0020"].getChoosedOptions(
+            feature_elt, namespace=None
+        )
         try:
             stream_method = choosed_options["stream-method"]
         except KeyError:
@@ -307,45 +354,46 @@
             log.warning(u"Invalid stream method received")
             return
 
-        stream_object = stream.FileStreamObject(self.host,
-                                                client,
-                                                filepath,
-                                                uid=sid,
-                                                size=size,
-                                                )
-        d = plugin.startStream(client, stream_object, jid.JID(iq_elt['from']), sid)
+        stream_object = stream.FileStreamObject(
+            self.host, client, filepath, uid=sid, size=size
+        )
+        d = plugin.startStream(client, stream_object, jid.JID(iq_elt["from"]), sid)
         d.addCallback(self._sendCb, client, sid, stream_object)
         d.addErrback(self._sendEb, client, sid, stream_object)
 
     def _fileEb(self, failure, filepath, sid, size, client):
         if failure.check(error.StanzaError):
             stanza_err = failure.value
-            if stanza_err.code == '403' and stanza_err.condition == 'forbidden':
-                from_s = stanza_err.stanza['from']
+            if stanza_err.code == "403" and stanza_err.condition == "forbidden":
+                from_s = stanza_err.stanza["from"]
                 log.info(u"File transfer refused by {}".format(from_s))
                 msg = D_(u"The contact {} has refused your file").format(from_s)
                 title = D_(u"File refused")
                 xml_tools.quickNote(self.host, client, msg, title, C.XMLUI_DATA_LVL_INFO)
             else:
                 log.warning(_(u"Error during file transfer"))
-                msg = D_(u"Something went wrong during the file transfer session initialisation: {reason}").format(reason=unicode(stanza_err))
+                msg = D_(
+                    u"Something went wrong during the file transfer session initialisation: {reason}"
+                ).format(reason=unicode(stanza_err))
                 title = D_(u"File transfer error")
                 xml_tools.quickNote(self.host, client, msg, title, C.XMLUI_DATA_LVL_ERROR)
         elif failure.check(exceptions.DataError):
-            log.warning(u'Invalid stanza received')
+            log.warning(u"Invalid stanza received")
         else:
-            log.error(u'Error while proposing stream: {}'.format(failure))
+            log.error(u"Error while proposing stream: {}".format(failure))
 
     def _sendCb(self, dummy, client, sid, stream_object):
-        log.info(_(u'transfer {sid} successfuly finished [{profile}]').format(
-            sid=sid,
-            profile=client.profile))
+        log.info(
+            _(u"transfer {sid} successfuly finished [{profile}]").format(
+                sid=sid, profile=client.profile
+            )
+        )
         stream_object.close()
 
     def _sendEb(self, failure, client, sid, stream_object):
-        log.warning(_(u'transfer {sid} failed [{profile}]: {reason}').format(
-            sid=sid,
-            profile=client.profile,
-            reason=unicode(failure.value),
-            ))
+        log.warning(
+            _(u"transfer {sid} failed [{profile}]: {reason}").format(
+                sid=sid, profile=client.profile, reason=unicode(failure.value)
+            )
+        )
         stream_object.close()