diff sat/plugins/plugin_misc_upload.py @ 3089:e75024e41f81

plugin upload, XEP-0363: code modernisation + preparation for extension: - use of async/await syntax - fileUpload's options are now serialised, allowing non string values - (XEP-0363) Slot is now a dataclass, so it can be modified by other plugins - (XEP-0363) Moved SSL related code to the new tools.web module - (XEP-0363) added `XEP-0363_upload_size` and `XEP-0363_upload` trigger points - a Deferred is not used anymore for `progress_id`, the value is directly returned
author Goffi <goffi@goffi.org>
date Fri, 20 Dec 2019 12:28:04 +0100
parents ab2696e34d29
children 9d0df638c8b4
line wrap: on
line diff
--- a/sat/plugins/plugin_misc_upload.py	Fri Dec 20 12:28:04 2019 +0100
+++ b/sat/plugins/plugin_misc_upload.py	Fri Dec 20 12:28:04 2019 +0100
@@ -1,7 +1,6 @@
 #!/usr/bin/env python3
-# -*- coding: utf-8 -*-
 
-# SAT plugin for file tansfer
+# SAT plugin for uploading files
 # Copyright (C) 2009-2019 Jérôme Poisson (goffi@goffi.org)
 
 # This program is free software: you can redistribute it and/or modify
@@ -17,18 +16,19 @@
 # You should have received a copy of the GNU Affero General Public License
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-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
+import os
+import os.path
 from twisted.internet import defer
 from twisted.words.protocols.jabber import jid
 from twisted.words.protocols.jabber import error as jabber_error
-import os
-import os.path
+from sat.core.i18n import _, D_
+from sat.core.constants import Const as C
+from sat.tools.common import data_format
+from sat.core.log import getLogger
+from sat.core import exceptions
+from sat.tools import xml_tools
+
+log = getLogger(__name__)
 
 
 PLUGIN_INFO = {
@@ -43,7 +43,6 @@
 
 UPLOADING = D_("Please select a file to upload")
 UPLOADING_TITLE = D_("File upload")
-BOOL_OPTIONS = ("ignore_tls_errors",)
 
 
 class UploadPlugin(object):
@@ -55,7 +54,7 @@
         host.bridge.addMethod(
             "fileUpload",
             ".plugin",
-            in_sign="sssa{ss}s",
+            in_sign="sssss",
             out_sign="a{ss}",
             method=self._fileUpload,
             async_=True,
@@ -63,24 +62,17 @@
         self._upload_callbacks = []
 
     def _fileUpload(
-        self, filepath, filename, upload_jid_s="", options=None, profile=C.PROF_KEY_NONE
+        self, filepath, filename, upload_jid_s="", options='', profile=C.PROF_KEY_NONE
     ):
         client = self.host.getClient(profile)
         upload_jid = jid.JID(upload_jid_s) if upload_jid_s else None
-        if options is None:
-            options = {}
-        # we convert values that are well-known booleans
-        for bool_option in BOOL_OPTIONS:
-            try:
-                options[bool_option] = C.bool(options[bool_option])
-            except KeyError:
-                pass
+        options = data_format.deserialise(options)
 
-        return self.fileUpload(
-            client, filepath, filename or None, upload_jid, options or None
-        )
+        return defer.ensureDeferred(self.fileUpload(
+            client, filepath, filename or None, upload_jid, options
+        ))
 
-    def fileUpload(self, client, filepath, filename, upload_jid, options):
+    async def fileUpload(self, client, filepath, filename, upload_jid, options):
         """Send a file using best available method
 
         parameters are the same as for [upload]
@@ -88,16 +80,15 @@
             message
         """
 
-        def uploadCb(data):
-            progress_id, __ = data
-            return {"progress": progress_id}
-
-        def uploadEb(fail):
-            if (isinstance(fail.value, jabber_error.StanzaError)
-                and fail.value.condition == 'not-acceptable'):
-                reason = fail.value.text
+        try:
+            progress_id, __ = await self.upload(
+                client, filepath, filename, upload_jid, options)
+        except Exception as e:
+            if (isinstance(e, jabber_error.StanzaError)
+                and e.condition == 'not-acceptable'):
+                reason = e.text
             else:
-                reason = str(fail.value)
+                reason = str(e)
             msg = D_("Can't upload file: {reason}").format(reason=reason)
             log.warning(msg)
             return {
@@ -105,14 +96,11 @@
                     msg, D_("Can't upload file"), C.XMLUI_DATA_LVL_WARNING
                 ).toXml()
             }
+        else:
+            return {"progress": progress_id}
 
-        d = self.upload(client, filepath, filename, upload_jid, options)
-        d.addCallback(uploadCb)
-        d.addErrback(uploadEb)
-        return d
-
-    @defer.inlineCallbacks
-    def upload(self, client, filepath, filename=None, upload_jid=None, options=None):
+    async def upload(self, client, filepath, filename=None, upload_jid=None,
+                     options=None):
         """Send a file using best available method
 
         @param filepath(str): absolute path to the file
@@ -133,18 +121,17 @@
             raise exceptions.DataError("The given path doesn't link to a file")
         for method_name, available_cb, upload_cb, priority in self._upload_callbacks:
             try:
-                upload_jid = yield available_cb(upload_jid, client.profile)
+                upload_jid = await available_cb(client, upload_jid)
             except exceptions.NotFound:
                 continue  # no entity managing this extension found
 
             log.info(
                 "{name} method will be used to upload the file".format(name=method_name)
             )
-            progress_id_d, download_d = yield upload_cb(
-                filepath, filename, upload_jid, options, client.profile
+            progress_id, download_d = await upload_cb(
+                client, filepath, filename, upload_jid, options
             )
-            progress_id = yield progress_id_d
-            defer.returnValue((progress_id, download_d))
+            return progress_id, download_d
 
         raise exceptions.NotFound("Can't find any method to upload a file")