diff libervia/backend/plugins/plugin_xep_0363.py @ 4270:0d7bb4df2343

Reformatted code base using black.
author Goffi <goffi@goffi.org>
date Wed, 19 Jun 2024 18:44:57 +0200
parents 72b95cdc3432
children
line wrap: on
line diff
--- a/libervia/backend/plugins/plugin_xep_0363.py	Tue Jun 18 12:06:45 2024 +0200
+++ b/libervia/backend/plugins/plugin_xep_0363.py	Wed Jun 19 18:44:57 2024 +0200
@@ -57,12 +57,13 @@
 
 NS_HTTP_UPLOAD = "urn:xmpp:http:upload:0"
 IQ_HTTP_UPLOAD_REQUEST = C.IQ_GET + '/request[@xmlns="' + NS_HTTP_UPLOAD + '"]'
-ALLOWED_HEADERS = ('authorization', 'cookie', 'expires')
+ALLOWED_HEADERS = ("authorization", "cookie", "expires")
 
 
 @dataclass
 class Slot:
     """Upload slot"""
+
     put: str
     get: str
     headers: list
@@ -81,7 +82,7 @@
 
 
 class XEP_0363:
-    Slot=Slot
+    Slot = Slot
 
     def __init__(self, host):
         log.info(_("plugin HTTP File Upload initialization"))
@@ -136,11 +137,11 @@
     async def get_http_upload_entity(self, client, upload_jid=None):
         """Get HTTP upload capable entity
 
-         upload_jid is checked, then its components
-         @param upload_jid(None, jid.JID): entity to check
-         @return(D(jid.JID)): first HTTP upload capable entity
-         @raise exceptions.NotFound: no entity found
-         """
+        upload_jid is checked, then its components
+        @param upload_jid(None, jid.JID): entity to check
+        @return(D(jid.JID)): first HTTP upload capable entity
+        @raise exceptions.NotFound: no entity found
+        """
         try:
             entity = client.http_upload_service
         except AttributeError:
@@ -155,17 +156,25 @@
 
         return entity
 
-    def _file_http_upload(self, filepath, filename="", upload_jid="",
-                        ignore_tls_errors=False, profile=C.PROF_KEY_NONE):
+    def _file_http_upload(
+        self,
+        filepath,
+        filename="",
+        upload_jid="",
+        ignore_tls_errors=False,
+        profile=C.PROF_KEY_NONE,
+    ):
         assert os.path.isabs(filepath) and os.path.isfile(filepath)
         client = self.host.get_client(profile)
-        return defer.ensureDeferred(self.file_http_upload(
-            client,
-            filepath,
-            filename or None,
-            jid.JID(upload_jid) if upload_jid else None,
-            {"ignore_tls_errors": ignore_tls_errors},
-        ))
+        return defer.ensureDeferred(
+            self.file_http_upload(
+                client,
+                filepath,
+                filename or None,
+                jid.JID(upload_jid) if upload_jid else None,
+                {"ignore_tls_errors": ignore_tls_errors},
+            )
+        )
 
     async def file_http_upload(
         self,
@@ -173,7 +182,7 @@
         filepath: Path,
         filename: Optional[str] = None,
         upload_jid: Optional[jid.JID] = None,
-        extra: Optional[dict] = None
+        extra: Optional[dict] = None,
     ) -> Tuple[str, defer.Deferred]:
         """Upload a file through HTTP
 
@@ -200,13 +209,18 @@
         #: this trigger can be used to modify the filename or size requested when geting
         #: the slot, it is notably useful with encryption.
         self.host.trigger.point(
-            "XEP-0363_upload_pre_slot", client, extra, file_metadata,
-            triggers_no_cancel=True
+            "XEP-0363_upload_pre_slot",
+            client,
+            extra,
+            file_metadata,
+            triggers_no_cancel=True,
         )
         try:
             slot = await self.get_slot(
-                client, file_metadata["filename"], file_metadata["size"],
-                upload_jid=upload_jid
+                client,
+                file_metadata["filename"],
+                file_metadata["size"],
+                upload_jid=upload_jid,
             )
         except Exception as e:
             log.warning(_("Can't get upload slot: {reason}").format(reason=e))
@@ -214,9 +228,12 @@
         else:
             log.debug(f"Got upload slot: {slot}")
             sat_file = self.host.plugins["FILE"].File(
-                self.host, client, filepath, uid=extra.get("progress_id"),
+                self.host,
+                client,
+                filepath,
+                uid=extra.get("progress_id"),
                 size=file_metadata["size"],
-                auto_end_signals=False
+                auto_end_signals=False,
             )
             progress_id = sat_file.uid
 
@@ -230,14 +247,19 @@
             headers = {"User-Agent": [C.APP_NAME.encode("utf-8")]}
 
             for name, value in slot.headers:
-                name = name.encode('utf-8')
-                value = value.encode('utf-8')
+                name = name.encode("utf-8")
+                value = value.encode("utf-8")
                 headers[name] = [value]
 
-
             await self.host.trigger.async_point(
-                "XEP-0363_upload", client, extra, sat_file, file_producer, slot,
-                triggers_no_cancel=True)
+                "XEP-0363_upload",
+                client,
+                extra,
+                sat_file,
+                file_producer,
+                slot,
+                triggers_no_cancel=True,
+            )
 
             download_d = agent.request(
                 b"PUT",
@@ -286,8 +308,9 @@
             sat_file.progress_error(msg)
         raise failure_
 
-    def _get_slot(self, filename, size, content_type, upload_jid,
-                 profile_key=C.PROF_KEY_NONE):
+    def _get_slot(
+        self, filename, size, content_type, upload_jid, profile_key=C.PROF_KEY_NONE
+    ):
         """Get an upload slot
 
         This method can be used when uploading is done by the frontend
@@ -299,10 +322,15 @@
         """
         client = self.host.get_client(profile_key)
         filename = filename.replace("/", "_")
-        d = defer.ensureDeferred(self.get_slot(
-            client, filename, size, content_type or None,
-            jid.JID(upload_jid) if upload_jid else None
-        ))
+        d = defer.ensureDeferred(
+            self.get_slot(
+                client,
+                filename,
+                size,
+                content_type or None,
+                jid.JID(upload_jid) if upload_jid else None,
+            )
+        )
         d.addCallback(lambda slot: (slot.get, slot.put, slot.headers))
         return d
 
@@ -330,7 +358,8 @@
             except AttributeError:
                 found_entity = await self.get_http_upload_entity(client)
                 return await self.get_slot(
-                    client, filename, size, content_type, found_entity)
+                    client, filename, size, content_type, found_entity
+                )
             else:
                 if upload_jid is None:
                     raise exceptions.NotFound("No HTTP upload entity found")
@@ -348,9 +377,9 @@
         try:
             slot_elt = next(iq_result_elt.elements(NS_HTTP_UPLOAD, "slot"))
             put_elt = next(slot_elt.elements(NS_HTTP_UPLOAD, "put"))
-            put_url = put_elt['url']
+            put_url = put_elt["url"]
             get_elt = next(slot_elt.elements(NS_HTTP_UPLOAD, "get"))
-            get_url = get_elt['url']
+            get_url = get_elt["url"]
         except (StopIteration, KeyError):
             raise exceptions.DataError("Incorrect stanza received from server")
 
@@ -360,14 +389,18 @@
                 name = header_elt["name"]
                 value = str(header_elt)
             except KeyError:
-                log.warning(_("Invalid header element: {xml}").format(
-                    iq_result_elt.toXml()))
+                log.warning(
+                    _("Invalid header element: {xml}").format(iq_result_elt.toXml())
+                )
                 continue
-            name = name.replace('\n', '')
-            value = value.replace('\n', '')
+            name = name.replace("\n", "")
+            value = value.replace("\n", "")
             if name.lower() not in ALLOWED_HEADERS:
-                log.warning(_('Ignoring unauthorised header "{name}": {xml}')
-                    .format(name=name, xml = iq_result_elt.toXml()))
+                log.warning(
+                    _('Ignoring unauthorised header "{name}": {xml}').format(
+                        name=name, xml=iq_result_elt.toXml()
+                    )
+                )
                 continue
             headers.append((name, value))
 
@@ -376,17 +409,17 @@
     # component
 
     def on_component_request(self, iq_elt, client):
-        iq_elt.handled=True
+        iq_elt.handled = True
         defer.ensureDeferred(self.handle_component_request(client, iq_elt))
 
     async def handle_component_request(self, client, iq_elt):
         try:
             request_elt = next(iq_elt.elements(NS_HTTP_UPLOAD, "request"))
             request = UploadRequest(
-                from_=jid.JID(iq_elt['from']),
-                filename=parse.quote(request_elt['filename'].replace('/', '_'), safe=''),
-                size=int(request_elt['size']),
-                content_type=request_elt.getAttribute('content-type')
+                from_=jid.JID(iq_elt["from"]),
+                filename=parse.quote(request_elt["filename"].replace("/", "_"), safe=""),
+                size=int(request_elt["size"]),
+                content_type=request_elt.getAttribute("content-type"),
             )
         except (StopIteration, KeyError, ValueError):
             client.sendError(iq_elt, "bad-request")
@@ -411,19 +444,21 @@
                     break
         else:
             log.warning(
-                _("no service can handle HTTP Upload request: {elt}")
-                .format(elt=iq_elt.toXml()))
+                _("no service can handle HTTP Upload request: {elt}").format(
+                    elt=iq_elt.toXml()
+                )
+            )
             if err is None:
                 err = error.StanzaError("feature-not-implemented")
             client.send(err.toResponse(iq_elt))
             return
 
         iq_result_elt = xmlstream.toResponse(iq_elt, "result")
-        slot_elt = iq_result_elt.addElement((NS_HTTP_UPLOAD, 'slot'))
-        put_elt = slot_elt.addElement('put')
-        put_elt['url'] = slot.put
-        get_elt = slot_elt.addElement('get')
-        get_elt['url'] = slot.get
+        slot_elt = iq_result_elt.addElement((NS_HTTP_UPLOAD, "slot"))
+        put_elt = slot_elt.addElement("put")
+        put_elt["url"] = slot.put
+        get_elt = slot_elt.addElement("get")
+        get_elt["url"] = slot.get
         client.send(iq_result_elt)
 
 
@@ -434,16 +469,21 @@
         self.plugin_parent = plugin_parent
 
     def connectionInitialized(self):
-        if ((self.parent.is_component
-             and PLUGIN_INFO[C.PI_IMPORT_NAME] in self.parent.enabled_features)):
+        if (
+            self.parent.is_component
+            and PLUGIN_INFO[C.PI_IMPORT_NAME] in self.parent.enabled_features
+        ):
             self.xmlstream.addObserver(
-                IQ_HTTP_UPLOAD_REQUEST, self.plugin_parent.on_component_request,
-                client=self.parent
+                IQ_HTTP_UPLOAD_REQUEST,
+                self.plugin_parent.on_component_request,
+                client=self.parent,
             )
 
     def getDiscoInfo(self, requestor, target, nodeIdentifier=""):
-        if ((self.parent.is_component
-             and not PLUGIN_INFO[C.PI_IMPORT_NAME] in self.parent.enabled_features)):
+        if (
+            self.parent.is_component
+            and not PLUGIN_INFO[C.PI_IMPORT_NAME] in self.parent.enabled_features
+        ):
             return []
         else:
             return [disco.DiscoFeature(NS_HTTP_UPLOAD)]