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

Reformatted code base using black.
author Goffi <goffi@goffi.org>
date Wed, 19 Jun 2024 18:44:57 +0200
parents 49019947cc76
children
line wrap: on
line diff
--- a/libervia/backend/plugins/plugin_comp_ap_gateway/pubsub_service.py	Tue Jun 18 12:06:45 2024 +0200
+++ b/libervia/backend/plugins/plugin_comp_ap_gateway/pubsub_service.py	Wed Jun 19 18:44:57 2024 +0200
@@ -37,11 +37,7 @@
 from libervia.backend.tools.web import download_file
 from libervia.backend.memory.sqla_mapping import PubsubSub, SubscriptionState
 
-from .constants import (
-    TYPE_ACTOR,
-    ST_AVATAR,
-    MAX_AVATAR_SIZE
-)
+from .constants import TYPE_ACTOR, ST_AVATAR, MAX_AVATAR_SIZE
 
 
 log = getLogger(__name__)
@@ -52,13 +48,14 @@
     {"var": "pubsub#max_items", "value": "max"},
     {"var": "pubsub#access_model", "type": "list-single", "value": "open"},
     {"var": "pubsub#publish_model", "type": "list-single", "value": "open"},
-
 ]
 
 NODE_CONFIG_VALUES = {c["var"]: c["value"] for c in NODE_CONFIG}
 NODE_OPTIONS = {c["var"]: {} for c in NODE_CONFIG}
 for c in NODE_CONFIG:
-    NODE_OPTIONS[c["var"]].update({k:v for k,v in c.items() if k not in ("var", "value")})
+    NODE_OPTIONS[c["var"]].update(
+        {k: v for k, v in c.items() if k not in ("var", "value")}
+    )
 
 
 class APPubsubService(rsm.PubSubService):
@@ -88,34 +85,30 @@
             in requestor
         """
         if not recipient.user:
-            raise error.StanzaError(
-                "item-not-found",
-                text="No user part specified"
-            )
+            raise error.StanzaError("item-not-found", text="No user part specified")
         requestor_actor_id = self.apg.build_apurl(TYPE_ACTOR, requestor.userhost())
         recipient_account = self.apg._e.unescape(recipient.user)
-        recipient_actor_id = await self.apg.get_ap_actor_id_from_account(recipient_account)
+        recipient_actor_id = await self.apg.get_ap_actor_id_from_account(
+            recipient_account
+        )
         inbox = await self.apg.get_ap_inbox_from_id(recipient_actor_id, use_shared=False)
         return requestor_actor_id, recipient_actor_id, inbox
 
-
     @ensure_deferred
     async def publish(self, requestor, service, nodeIdentifier, items):
         if self.apg.local_only and not self.apg.is_local(requestor):
             raise error.StanzaError(
-                "forbidden",
-                "Only local users can publish on this gateway."
+                "forbidden", "Only local users can publish on this gateway."
             )
         if not service.user:
             raise error.StanzaError(
                 "bad-request",
-                "You must specify an ActivityPub actor account in JID user part."
+                "You must specify an ActivityPub actor account in JID user part.",
             )
         ap_account = self.apg._e.unescape(service.user)
         if ap_account.count("@") != 1:
             raise error.StanzaError(
-                "bad-request",
-                f"{ap_account!r} is not a valid ActivityPub actor account."
+                "bad-request", f"{ap_account!r} is not a valid ActivityPub actor account."
             )
 
         client = self.apg.client.get_virtual_client(requestor)
@@ -130,21 +123,17 @@
             cached_node = await self.host.memory.storage.get_pubsub_node(
                 client, service, nodeIdentifier, with_subscriptions=True, create=True
             )
-            await self.host.memory.storage.cache_pubsub_items(
-                client,
-                cached_node,
-                items
-            )
+            await self.host.memory.storage.cache_pubsub_items(client, cached_node, items)
             for subscription in cached_node.subscriptions:
                 if subscription.state != SubscriptionState.SUBSCRIBED:
                     continue
                 self.notifyPublish(
-                    service,
-                    nodeIdentifier,
-                    [(subscription.subscriber, None, items)]
+                    service, nodeIdentifier, [(subscription.subscriber, None, items)]
                 )
 
-    async def ap_following_2_elt(self, requestor_actor_id: str, ap_item: dict) -> domish.Element:
+    async def ap_following_2_elt(
+        self, requestor_actor_id: str, ap_item: dict
+    ) -> domish.Element:
         """Convert actor ID from following collection to XMPP item
 
         @param requestor_actor_id: ID of the actor doing the request.
@@ -159,9 +148,7 @@
         return item_elt
 
     async def ap_follower_2_elt(
-        self,
-        requestor_actor_id: str,
-        ap_item: dict
+        self, requestor_actor_id: str, ap_item: dict
     ) -> domish.Element:
         """Convert actor ID from followers collection to XMPP item
 
@@ -175,9 +162,7 @@
         return item_elt
 
     async def generate_v_card(
-        self,
-        requestor_actor_id: str,
-        ap_account: str
+        self, requestor_actor_id: str, ap_account: str
     ) -> domish.Element:
         """Generate vCard4 (XEP-0292) item element from ap_account's metadata
 
@@ -186,8 +171,7 @@
         @return: <item> with the <vcard> element
         """
         actor_data = await self.apg.get_ap_actor_data_from_account(
-            requestor_actor_id,
-            ap_account
+            requestor_actor_id, ap_account
         )
         identity_data = {}
 
@@ -212,10 +196,7 @@
         return item_elt
 
     async def get_avatar_data(
-        self,
-        client: SatXMPPEntity,
-        requestor_actor_id: str,
-        ap_account: str
+        self, client: SatXMPPEntity, requestor_actor_id: str, ap_account: str
     ) -> dict[str, Any]:
         """Retrieve actor's avatar if any, cache it and file actor_data
 
@@ -259,27 +240,21 @@
                 avatar_data = {
                     "path": dest_path,
                     "filename": filename,
-                    'media_type': image.guess_type(dest_path),
+                    "media_type": image.guess_type(dest_path),
                 }
 
-                await self.apg._i.cache_avatar(
-                    self.apg.IMPORT_NAME,
-                    avatar_data
-                )
+                await self.apg._i.cache_avatar(self.apg.IMPORT_NAME, avatar_data)
         else:
             avatar_data = {
-            "cache_uid": cache["uid"],
-            "path": cache["path"],
-            "media_type": cache["mime_type"]
-        }
+                "cache_uid": cache["uid"],
+                "path": cache["path"],
+                "media_type": cache["mime_type"],
+            }
 
         return avatar_data
 
     async def generate_avatar_metadata(
-        self,
-        client: SatXMPPEntity,
-        requestor_actor_id: str,
-        ap_account: str
+        self, client: SatXMPPEntity, requestor_actor_id: str, ap_account: str
     ) -> domish.Element:
         """Generate the metadata element for user avatar
 
@@ -308,14 +283,11 @@
         """
         if not itemIdentifiers:
             avatar_data = await self.get_avatar_data(
-                client,
-                requestor_actor_id,
-                ap_account
+                client, requestor_actor_id, ap_account
             )
             if "base64" not in avatar_data:
                 await threads.deferToThread(
-                    self._blocking_b_6_4_encode_avatar,
-                    avatar_data
+                    self._blocking_b_6_4_encode_avatar, avatar_data
                 )
         else:
             if len(itemIdentifiers) > 1:
@@ -327,10 +299,7 @@
             cache_data = self.apg.host.common_cache.get_metadata(item_id)
             if cache_data is None:
                 raise error.StanzaError("item-not-found")
-            avatar_data = {
-                "cache_uid": item_id,
-                "path": cache_data["path"]
-            }
+            avatar_data = {"cache_uid": item_id, "path": cache_data["path"]}
             await threads.deferToThread(self._blocking_b_6_4_encode_avatar, avatar_data)
 
         return self.apg._a.build_item_data_elt(avatar_data)
@@ -343,7 +312,7 @@
         node: str,
         maxItems: Optional[int],
         itemIdentifiers: Optional[List[str]],
-        rsm_req: Optional[rsm.RSMRequest]
+        rsm_req: Optional[rsm.RSMRequest],
     ) -> Tuple[List[domish.Element], Optional[rsm.RSMResponse]]:
         if not service.user:
             return [], None
@@ -353,8 +322,7 @@
             return [], None
 
         requestor_actor_id = self.apg.build_apurl(
-            TYPE_ACTOR,
-            await self.apg.get_ap_account_from_jid_and_node(service, node)
+            TYPE_ACTOR, await self.apg.get_ap_account_from_jid_and_node(service, node)
         )
 
         # cached_node may be pre-filled with some nodes (e.g. attachments nodes),
@@ -379,17 +347,12 @@
             return [item_elt], None
         elif node == self.apg._a.namespace_metadata:
             item_elt = await self.generate_avatar_metadata(
-                self.apg.client,
-                requestor_actor_id,
-                ap_account
+                self.apg.client, requestor_actor_id, ap_account
             )
             return [item_elt], None
         elif node == self.apg._a.namespace_data:
             item_elt = await self.generate_avatar_data(
-                self.apg.client,
-                requestor_actor_id,
-                ap_account,
-                itemIdentifiers
+                self.apg.client, requestor_actor_id, ap_account, itemIdentifiers
             )
             return [item_elt], None
         elif self.apg._pa.is_attachment_node(node):
@@ -410,7 +373,7 @@
                 raise error.StanzaError(
                     "feature-not-implemented",
                     text=f"AP Gateway {C.APP_VERSION} only supports "
-                    f"{self.apg._m.namespace} node for now"
+                    f"{self.apg._m.namespace} node for now",
                 )
             collection_name = "outbox"
             use_cache = True
@@ -444,18 +407,26 @@
             if rsm_req is None:
                 if maxItems is None:
                     maxItems = 20
-                kwargs.update({
-                    "max_items": maxItems,
-                    "chronological_pagination": False,
-                })
+                kwargs.update(
+                    {
+                        "max_items": maxItems,
+                        "chronological_pagination": False,
+                    }
+                )
             else:
-                if len(
-                    [v for v in (rsm_req.after, rsm_req.before, rsm_req.index)
-                     if v is not None]
-                ) > 1:
+                if (
+                    len(
+                        [
+                            v
+                            for v in (rsm_req.after, rsm_req.before, rsm_req.index)
+                            if v is not None
+                        ]
+                    )
+                    > 1
+                ):
                     raise error.StanzaError(
                         "bad-request",
-                        text="You can't use after, before and index at the same time"
+                        text="You can't use after, before and index at the same time",
                     )
                 kwargs.update({"max_items": rsm_req.max})
                 if rsm_req.after is not None:
@@ -476,25 +447,21 @@
                 try:
                     parent_data = await self.apg.ap_get(parent_item, requestor_actor_id)
                     collection = await self.apg.ap_get_object(
-                        requestor_actor_id,
-                        parent_data.get("object", {}),
-                        "replies"
+                        requestor_actor_id, parent_data.get("object", {}), "replies"
                     )
                 except Exception as e:
-                    raise error.StanzaError(
-                        "item-not-found",
-                        text=str(e)
-                    )
+                    raise error.StanzaError("item-not-found", text=str(e))
             else:
                 actor_data = await self.apg.get_ap_actor_data_from_account(
-                    requestor_actor_id,
-                    ap_account
+                    requestor_actor_id, ap_account
                 )
-                collection = await self.apg.ap_get_object(requestor_actor_id, actor_data, collection_name)
+                collection = await self.apg.ap_get_object(
+                    requestor_actor_id, actor_data, collection_name
+                )
             if not collection:
                 raise error.StanzaError(
                     "item-not-found",
-                    text=f"No collection found for node {node!r} (account: {ap_account})"
+                    text=f"No collection found for node {node!r} (account: {ap_account})",
                 )
 
             kwargs["parser"] = parser
@@ -528,17 +495,15 @@
         else:
             try:
                 subscription = next(
-                    s for s in node.subscriptions
+                    s
+                    for s in node.subscriptions
                     if s.subscriber == requestor.userhostJID()
                 )
             except StopIteration:
                 subscription = None
 
         if subscription is None:
-            subscription = PubsubSub(
-                subscriber=requestor.userhostJID(),
-                state=sub_state
-            )
+            subscription = PubsubSub(subscriber=requestor.userhostJID(), state=sub_state)
             node.subscriptions.append(subscription)
             await self.host.memory.storage.add(node)
         else:
@@ -586,11 +551,7 @@
         data = self.apg.create_activity(
             "Undo",
             req_actor_id,
-            self.apg.create_activity(
-                "Follow",
-                req_actor_id,
-                recip_actor_id
-            )
+            self.apg.create_activity("Follow", req_actor_id, recip_actor_id),
         )
 
         resp = await self.apg.sign_and_post(inbox, req_actor_id, data)
@@ -602,10 +563,7 @@
         return NODE_OPTIONS
 
     def getConfiguration(
-        self,
-        requestor: jid.JID,
-        service: jid.JID,
-        nodeIdentifier: str
+        self, requestor: jid.JID, service: jid.JID, nodeIdentifier: str
     ) -> defer.Deferred:
         return defer.succeed(NODE_CONFIG_VALUES)
 
@@ -615,12 +573,9 @@
         service: jid.JID,
         nodeIdentifier: str,
         pep: bool = False,
-        recipient: Optional[jid.JID] = None
+        recipient: Optional[jid.JID] = None,
     ) -> Optional[dict]:
         if not nodeIdentifier:
             return None
-        info = {
-            "type": "leaf",
-            "meta-data": NODE_CONFIG
-        }
+        info = {"type": "leaf", "meta-data": NODE_CONFIG}
         return info