diff sat/plugins/plugin_comp_ap_gateway/http_server.py @ 4037:524856bd7b19

massive refactoring to switch from camelCase to snake_case: historically, Libervia (SàT before) was using camelCase as allowed by PEP8 when using a pre-PEP8 code, to use the same coding style as in Twisted. However, snake_case is more readable and it's better to follow PEP8 best practices, so it has been decided to move on full snake_case. Because Libervia has a huge codebase, this ended with a ugly mix of camelCase and snake_case. To fix that, this patch does a big refactoring by renaming every function and method (including bridge) that are not coming from Twisted or Wokkel, to use fully snake_case. This is a massive change, and may result in some bugs.
author Goffi <goffi@goffi.org>
date Sat, 08 Apr 2023 13:54:42 +0200
parents 78b5f356900c
children
line wrap: on
line diff
--- a/sat/plugins/plugin_comp_ap_gateway/http_server.py	Fri Apr 07 15:18:39 2023 +0200
+++ b/sat/plugins/plugin_comp_ap_gateway/http_server.py	Sat Apr 08 13:54:42 2023 +0200
@@ -66,7 +66,7 @@
         self._seen_digest = deque(maxlen=50)
         super().__init__()
 
-    def responseCode(
+    def response_code(
         self,
         request: "HTTPRequest",
         http_code: int,
@@ -77,17 +77,17 @@
             log.warning(msg)
         request.setResponseCode(http_code, None if msg is None else msg.encode())
 
-    def _onRequestError(self, failure_: failure.Failure, request: "HTTPRequest") -> None:
+    def _on_request_error(self, failure_: failure.Failure, request: "HTTPRequest") -> None:
         exc = failure_.value
         if isinstance(exc, exceptions.NotFound):
-            self.responseCode(
+            self.response_code(
                 request,
                 http.NOT_FOUND,
                 str(exc)
             )
         else:
             log.exception(f"Internal error: {failure_.value}")
-            self.responseCode(
+            self.response_code(
                 request,
                 http.INTERNAL_SERVER_ERROR,
                 f"internal error: {failure_.value}"
@@ -107,7 +107,7 @@
                 http.BAD_REQUEST, "Bad Request" , "Invalid webfinger resource"
             ).render(request)
 
-        actor_url = self.apg.buildAPURL(TYPE_ACTOR, account)
+        actor_url = self.apg.build_apurl(TYPE_ACTOR, account)
 
         resp = {
             "aliases": [actor_url],
@@ -124,7 +124,7 @@
         request.write(json.dumps(resp).encode())
         request.finish()
 
-    async def handleUndoActivity(
+    async def handle_undo_activity(
         self,
         request: "HTTPRequest",
         data: dict,
@@ -136,7 +136,7 @@
     ) -> None:
         if node is None:
             node = self.apg._m.namespace
-        client = await self.apg.getVirtualClient(signing_actor)
+        client = await self.apg.get_virtual_client(signing_actor)
         object_ = data.get("object")
         if isinstance(object_, str):
             # we check first if it's not a cached object
@@ -149,10 +149,10 @@
             # because we'll undo the activity, we can remove it from cache
             await self.apg.client._ap_storage.remove(ap_cache_key)
         else:
-            objects = await self.apg.apGetList(data, "object")
+            objects = await self.apg.ap_get_list(data, "object")
         for obj in objects:
             type_ = obj.get("type")
-            actor = await self.apg.apGetSenderActor(obj)
+            actor = await self.apg.ap_get_sender_actor(obj)
             if actor != signing_actor:
                 log.warning(f"ignoring object not attributed to signing actor: {data}")
                 continue
@@ -163,7 +163,7 @@
                 except KeyError:
                     log.warning(f'ignoring invalid object, missing "object" key: {data}')
                     continue
-                if not self.apg.isLocalURL(target_account):
+                if not self.apg.is_local_url(target_account):
                     log.warning(f"ignoring unfollow request to non local actor: {data}")
                     continue
                 await self.apg._p.unsubscribe(
@@ -175,17 +175,17 @@
             elif type_ == "Announce":
                 # we can use directly the Announce object, as only the "id" field is
                 # needed
-                await self.apg.newAPDeleteItem(client, None, node, obj)
+                await self.apg.new_ap_delete_item(client, None, node, obj)
             elif type_ == TYPE_LIKE:
-                await self.handleAttachmentItem(client, obj, {"noticed": False})
+                await self.handle_attachment_item(client, obj, {"noticed": False})
             elif type_ == TYPE_REACTION:
-                await self.handleAttachmentItem(client, obj, {
+                await self.handle_attachment_item(client, obj, {
                     "reactions": {"operation": "update", "remove": [obj["content"]]}
                 })
             else:
                 log.warning(f"Unmanaged undo type: {type_!r}")
 
-    async def handleFollowActivity(
+    async def handle_follow_activity(
         self,
         request: "HTTPRequest",
         data: dict,
@@ -197,14 +197,14 @@
     ) -> None:
         if node is None:
             node = self.apg._m.namespace
-        client = await self.apg.getVirtualClient(signing_actor)
+        client = await self.apg.get_virtual_client(signing_actor)
         try:
             subscription = await self.apg._p.subscribe(
                 client,
                 account_jid,
                 node,
                 # subscriptions from AP are always public
-                options=self.apg._pps.setPublicOpt()
+                options=self.apg._pps.set_public_opt()
             )
         except pubsub.SubscriptionPending:
             log.info(f"subscription to node {node!r} of {account_jid} is pending")
@@ -213,15 +213,15 @@
             if subscription.state != "subscribed":
                 # other states should raise an Exception
                 raise exceptions.InternalError('"subscribed" state was expected')
-            inbox = await self.apg.getAPInboxFromId(signing_actor, use_shared=False)
-            actor_id = self.apg.buildAPURL(TYPE_ACTOR, ap_account)
+            inbox = await self.apg.get_ap_inbox_from_id(signing_actor, use_shared=False)
+            actor_id = self.apg.build_apurl(TYPE_ACTOR, ap_account)
             accept_data = self.apg.create_activity(
                 "Accept", actor_id, object_=data
             )
-            await self.apg.signAndPost(inbox, actor_id, accept_data)
+            await self.apg.sign_and_post(inbox, actor_id, accept_data)
         await self.apg._c.synchronise(client, account_jid, node, resync=False)
 
-    async def handleAcceptActivity(
+    async def handle_accept_activity(
         self,
         request: "HTTPRequest",
         data: dict,
@@ -233,12 +233,12 @@
     ) -> None:
         if node is None:
             node = self.apg._m.namespace
-        client = await self.apg.getVirtualClient(signing_actor)
-        objects = await self.apg.apGetList(data, "object")
+        client = await self.apg.get_virtual_client(signing_actor)
+        objects = await self.apg.ap_get_list(data, "object")
         for obj in objects:
             type_ = obj.get("type")
             if type_ == "Follow":
-                follow_node = await self.apg.host.memory.storage.getPubsubNode(
+                follow_node = await self.apg.host.memory.storage.get_pubsub_node(
                     client, client.jid, node, with_subscriptions=True
                 )
                 if follow_node is None:
@@ -270,7 +270,7 @@
             else:
                 log.warning(f"Unmanaged accept type: {type_!r}")
 
-    async def handleDeleteActivity(
+    async def handle_delete_activity(
         self,
         request: "HTTPRequest",
         data: dict,
@@ -282,12 +282,12 @@
     ):
         if node is None:
             node = self.apg._m.namespace
-        client = await self.apg.getVirtualClient(signing_actor)
-        objects = await self.apg.apGetList(data, "object")
+        client = await self.apg.get_virtual_client(signing_actor)
+        objects = await self.apg.ap_get_list(data, "object")
         for obj in objects:
-            await self.apg.newAPDeleteItem(client, account_jid, node, obj)
+            await self.apg.new_ap_delete_item(client, account_jid, node, obj)
 
-    async def handleNewAPItems(
+    async def handle_new_ap_items(
         self,
         request: "HTTPRequest",
         data: dict,
@@ -298,7 +298,7 @@
     ):
         """Helper method to handle workflow for new AP items
 
-        accept globally the same parameter as for handleCreateActivity
+        accept globally the same parameter as for handle_create_activity
         @param repeated: if True, the item is an item republished from somewhere else
         """
         if "_repeated" in data:
@@ -307,25 +307,25 @@
                 f"happen. Ignoring object from {signing_actor}\n{data}"
             )
             raise exceptions.DataError("unexpected field in item")
-        client = await self.apg.getVirtualClient(signing_actor)
-        objects = await self.apg.apGetList(data, "object")
+        client = await self.apg.get_virtual_client(signing_actor)
+        objects = await self.apg.ap_get_list(data, "object")
         for obj in objects:
             if node is None:
                 if obj.get("type") == TYPE_EVENT:
                     node = self.apg._events.namespace
                 else:
                     node = self.apg._m.namespace
-            sender = await self.apg.apGetSenderActor(obj)
+            sender = await self.apg.ap_get_sender_actor(obj)
             if repeated:
                 # we don't check sender when item is repeated, as it should be different
                 # from post author in this case
-                sender_jid = await self.apg.getJIDFromId(sender)
-                repeater_jid = await self.apg.getJIDFromId(signing_actor)
+                sender_jid = await self.apg.get_jid_from_id(sender)
+                repeater_jid = await self.apg.get_jid_from_id(signing_actor)
                 repeated_item_id = obj["id"]
-                if self.apg.isLocalURL(repeated_item_id):
+                if self.apg.is_local_url(repeated_item_id):
                     # the repeated object is from XMPP, we need to parse the URL to find
                     # the right ID
-                    url_type, url_args = self.apg.parseAPURL(repeated_item_id)
+                    url_type, url_args = self.apg.parse_apurl(repeated_item_id)
                     if url_type != "item":
                         raise exceptions.DataError(
                             "local URI is not an item: {repeated_id}"
@@ -339,7 +339,7 @@
                             "local URI is invalid: {repeated_id}"
                         )
                     else:
-                        url_jid, url_node = await self.apg.getJIDAndNode(url_account)
+                        url_jid, url_node = await self.apg.get_jid_and_node(url_account)
                         if ((url_jid != sender_jid
                              or url_node and url_node != self.apg._m.namespace)):
                             raise exceptions.DataError(
@@ -352,7 +352,7 @@
                 obj["_repeated"] = {
                     "by": repeater_jid.full(),
                     "at": data.get("published"),
-                    "uri": uri.buildXMPPUri(
+                    "uri": uri.build_xmpp_uri(
                         "pubsub",
                         path=sender_jid.full(),
                         node=self.apg._m.namespace,
@@ -369,9 +369,9 @@
                     )
                     continue
 
-            await self.apg.newAPItem(client, account_jid, node, obj)
+            await self.apg.new_ap_item(client, account_jid, node, obj)
 
-    async def handleCreateActivity(
+    async def handle_create_activity(
         self,
         request: "HTTPRequest",
         data: dict,
@@ -381,9 +381,9 @@
         ap_url: str,
         signing_actor: str
     ):
-        await self.handleNewAPItems(request, data, account_jid, node, signing_actor)
+        await self.handle_new_ap_items(request, data, account_jid, node, signing_actor)
 
-    async def handleUpdateActivity(
+    async def handle_update_activity(
         self,
         request: "HTTPRequest",
         data: dict,
@@ -395,9 +395,9 @@
     ):
         # Update is the same as create: the item ID stays the same, thus the item will be
         # overwritten
-        await self.handleNewAPItems(request, data, account_jid, node, signing_actor)
+        await self.handle_new_ap_items(request, data, account_jid, node, signing_actor)
 
-    async def handleAnnounceActivity(
+    async def handle_announce_activity(
         self,
         request: "HTTPRequest",
         data: dict,
@@ -408,7 +408,7 @@
         signing_actor: str
     ):
         # we create a new item
-        await self.handleNewAPItems(
+        await self.handle_new_ap_items(
             request,
             data,
             account_jid,
@@ -417,7 +417,7 @@
             repeated=True
         )
 
-    async def handleAttachmentItem(
+    async def handle_attachment_item(
         self,
         client: SatXMPPEntity,
         data: dict,
@@ -447,10 +447,10 @@
         await client._ap_storage.aset(f"{ST_AP_CACHE}{data['id']}", data)
 
         for target_id in target_ids:
-            if not self.apg.isLocalURL(target_id):
+            if not self.apg.is_local_url(target_id):
                 log.debug(f"ignoring non local target ID: {target_id}")
                 continue
-            url_type, url_args = self.apg.parseAPURL(target_id)
+            url_type, url_args = self.apg.parse_apurl(target_id)
             if url_type != TYPE_ITEM:
                 log.warning(f"unexpected local URL for attachment on item {target_id}")
                 continue
@@ -458,20 +458,20 @@
                 account, item_id = url_args
             except ValueError:
                 raise ValueError(f"invalid URL: {target_id}")
-            author_jid, item_node = await self.apg.getJIDAndNode(account)
+            author_jid, item_node = await self.apg.get_jid_and_node(account)
             if item_node is None:
                 item_node = self.apg._m.namespace
-            attachment_node = self.apg._pa.getAttachmentNodeName(
+            attachment_node = self.apg._pa.get_attachment_node_name(
                 author_jid, item_node, item_id
             )
-            cached_node = await self.apg.host.memory.storage.getPubsubNode(
+            cached_node = await self.apg.host.memory.storage.get_pubsub_node(
                 client,
                 author_jid,
                 attachment_node,
                 with_subscriptions=True,
                 create=True
             )
-            found_items, __ = await self.apg.host.memory.storage.getItems(
+            found_items, __ = await self.apg.host.memory.storage.get_items(
                 cached_node, item_ids=[client.jid.userhost()]
             )
             if not found_items:
@@ -487,16 +487,16 @@
                 None
             )
             # we reparse the element, as there can be other attachments
-            attachments_data = self.apg._pa.items2attachmentData(client, [item_elt])
+            attachments_data = self.apg._pa.items_2_attachment_data(client, [item_elt])
             # and we update the cache
-            await self.apg.host.memory.storage.cachePubsubItems(
+            await self.apg.host.memory.storage.cache_pubsub_items(
                 client,
                 cached_node,
                 [item_elt],
                 attachments_data or [{}]
             )
 
-            if self.apg.isVirtualJID(author_jid):
+            if self.apg.is_virtual_jid(author_jid):
                 # the attachment is on t a virtual pubsub service (linking to an AP item),
                 # we notify all subscribers
                 for subscription in cached_node.subscriptions:
@@ -509,11 +509,11 @@
                     )
             else:
                 # the attachment is on an XMPP item, we publish it to the attachment node
-                await self.apg._p.sendItems(
+                await self.apg._p.send_items(
                     client, author_jid, attachment_node, [item_elt]
                 )
 
-    async def handleLikeActivity(
+    async def handle_like_activity(
         self,
         request: "HTTPRequest",
         data: dict,
@@ -523,10 +523,10 @@
         ap_url: str,
         signing_actor: str
     ) -> None:
-        client = await self.apg.getVirtualClient(signing_actor)
-        await self.handleAttachmentItem(client, data, {"noticed": True})
+        client = await self.apg.get_virtual_client(signing_actor)
+        await self.handle_attachment_item(client, data, {"noticed": True})
 
-    async def handleEmojireactActivity(
+    async def handle_emojireact_activity(
         self,
         request: "HTTPRequest",
         data: dict,
@@ -536,12 +536,12 @@
         ap_url: str,
         signing_actor: str
     ) -> None:
-        client = await self.apg.getVirtualClient(signing_actor)
-        await self.handleAttachmentItem(client, data, {
+        client = await self.apg.get_virtual_client(signing_actor)
+        await self.handle_attachment_item(client, data, {
             "reactions": {"operation": "update", "add": [data["content"]]}
         })
 
-    async def handleJoinActivity(
+    async def handle_join_activity(
         self,
         request: "HTTPRequest",
         data: dict,
@@ -551,10 +551,10 @@
         ap_url: str,
         signing_actor: str
     ) -> None:
-        client = await self.apg.getVirtualClient(signing_actor)
-        await self.handleAttachmentItem(client, data, {"rsvp": {"attending": "yes"}})
+        client = await self.apg.get_virtual_client(signing_actor)
+        await self.handle_attachment_item(client, data, {"rsvp": {"attending": "yes"}})
 
-    async def handleLeaveActivity(
+    async def handle_leave_activity(
         self,
         request: "HTTPRequest",
         data: dict,
@@ -564,10 +564,10 @@
         ap_url: str,
         signing_actor: str
     ) -> None:
-        client = await self.apg.getVirtualClient(signing_actor)
-        await self.handleAttachmentItem(client, data, {"rsvp": {"attending": "no"}})
+        client = await self.apg.get_virtual_client(signing_actor)
+        await self.handle_attachment_item(client, data, {"rsvp": {"attending": "no"}})
 
-    async def APActorRequest(
+    async def ap_actor_request(
         self,
         request: "HTTPRequest",
         data: Optional[dict],
@@ -577,24 +577,24 @@
         ap_url: str,
         signing_actor: Optional[str]
     ) -> dict:
-        inbox = self.apg.buildAPURL(TYPE_INBOX, ap_account)
-        shared_inbox = self.apg.buildAPURL(TYPE_SHARED_INBOX)
-        outbox = self.apg.buildAPURL(TYPE_OUTBOX, ap_account)
-        followers = self.apg.buildAPURL(TYPE_FOLLOWERS, ap_account)
-        following = self.apg.buildAPURL(TYPE_FOLLOWING, ap_account)
+        inbox = self.apg.build_apurl(TYPE_INBOX, ap_account)
+        shared_inbox = self.apg.build_apurl(TYPE_SHARED_INBOX)
+        outbox = self.apg.build_apurl(TYPE_OUTBOX, ap_account)
+        followers = self.apg.build_apurl(TYPE_FOLLOWERS, ap_account)
+        following = self.apg.build_apurl(TYPE_FOLLOWING, ap_account)
 
         # we have to use AP account as preferredUsername because it is used to retrieve
         # actor handle (see https://socialhub.activitypub.rocks/t/how-to-retrieve-user-server-tld-handle-from-actors-url/2196)
         preferred_username = ap_account.split("@", 1)[0]
 
-        identity_data = await self.apg._i.getIdentity(self.apg.client, account_jid)
+        identity_data = await self.apg._i.get_identity(self.apg.client, account_jid)
         if node and node.startswith(self.apg._events.namespace):
             events = outbox
         else:
-            events_account = await self.apg.getAPAccountFromJidAndNode(
+            events_account = await self.apg.get_ap_account_from_jid_and_node(
                 account_jid, self.apg._events.namespace
             )
-            events = self.apg.buildAPURL(TYPE_OUTBOX, events_account)
+            events = self.apg.build_apurl(TYPE_OUTBOX, events_account)
 
         actor_data = {
             "@context": [
@@ -636,7 +636,7 @@
             except KeyError:
                 log.error(f"incomplete avatar data: {identity_data!r}")
             else:
-                avatar_url = self.apg.buildAPURL("avatar", filename)
+                avatar_url = self.apg.build_apurl("avatar", filename)
                 actor_data["icon"] = {
                     "type": "Image",
                     "url": avatar_url,
@@ -645,14 +645,14 @@
 
         return actor_data
 
-    def getCanonicalURL(self, request: "HTTPRequest") -> str:
+    def get_canonical_url(self, request: "HTTPRequest") -> str:
         return parse.urljoin(
             f"https://{self.apg.public_url}",
             request.path.decode().rstrip("/")
-        # we unescape "@" for the same reason as in [APActorRequest]
+        # we unescape "@" for the same reason as in [ap_actor_request]
         ).replace("%40", "@")
 
-    def queryData2RSMRequest(
+    def query_data_2_rsm_request(
         self,
         query_data: Dict[str, List[str]]
     ) -> rsm.RSMRequest:
@@ -673,7 +673,7 @@
                     return rsm.RSMRequest(**kwargs)
         raise ValueError(f"Invalid query data: {query_data!r}")
 
-    async def APOutboxPageRequest(
+    async def ap_outbox_page_request(
         self,
         request: "HTTPRequest",
         data: Optional[dict],
@@ -690,18 +690,18 @@
         url_keys = sorted(set(query_data) & {"page", "index", "before", "after"})
         query_data = {k: query_data[k] for k in url_keys}
         try:
-            items, metadata = await self.apg._p.getItems(
+            items, metadata = await self.apg._p.get_items(
                 client=self.apg.client,
                 service=account_jid,
                 node=node,
-                rsm_request=self.queryData2RSMRequest(query_data),
+                rsm_request=self.query_data_2_rsm_request(query_data),
                 extra = {C.KEY_USE_CACHE: False}
             )
         except error.StanzaError as e:
             log.warning(f"Can't get data from pubsub node {node} at {account_jid}: {e}")
             return {}
 
-        base_url = self.getCanonicalURL(request)
+        base_url = self.get_canonical_url(request)
         url = f"{base_url}?{parse.urlencode(query_data, True)}"
         if node and node.startswith(self.apg._events.namespace):
             ordered_items = [
@@ -753,7 +753,7 @@
 
         return ret_data
 
-    async def APOutboxRequest(
+    async def ap_outbox_request(
         self,
         request: "HTTPRequest",
         data: Optional[dict],
@@ -769,7 +769,7 @@
         parsed_url = parse.urlparse(request.uri.decode())
         query_data = parse.parse_qs(parsed_url.query)
         if query_data:
-            return await self.APOutboxPageRequest(
+            return await self.ap_outbox_page_request(
                 request, data, account_jid, node, ap_account, ap_url, query_data
             )
 
@@ -779,7 +779,7 @@
         # The current workaround is to do a request as if RSM was available, and actually
         # check its availability according to result.
         try:
-            __, metadata = await self.apg._p.getItems(
+            __, metadata = await self.apg._p.get_items(
                 client=self.apg.client,
                 service=account_jid,
                 node=node,
@@ -799,7 +799,7 @@
             )
             items_count = 20
 
-        url = self.getCanonicalURL(request)
+        url = self.get_canonical_url(request)
         url_first_page = f"{url}?{parse.urlencode({'page': 'first'})}"
         url_last_page = f"{url}?{parse.urlencode({'page': 'last'})}"
         return {
@@ -811,7 +811,7 @@
             "last": url_last_page,
         }
 
-    async def APInboxRequest(
+    async def ap_inbox_request(
         self,
         request: "HTTPRequest",
         data: Optional[dict],
@@ -824,26 +824,26 @@
         assert data is not None
         if signing_actor is None:
             raise exceptions.InternalError("signing_actor must be set for inbox requests")
-        await self.checkSigningActor(data, signing_actor)
+        await self.check_signing_actor(data, signing_actor)
         activity_type = (data.get("type") or "").lower()
         if not activity_type in ACTIVITY_TYPES_LOWER:
-            return self.responseCode(
+            return self.response_code(
                 request,
                 http.UNSUPPORTED_MEDIA_TYPE,
                 f"request is not an activity, ignoring"
             )
 
         if account_jid is None and activity_type not in ACTIVIY_NO_ACCOUNT_ALLOWED:
-            return self.responseCode(
+            return self.response_code(
                 request,
                 http.UNSUPPORTED_MEDIA_TYPE,
                 f"{activity_type.title()!r} activity must target an account"
             )
 
         try:
-            method = getattr(self, f"handle{activity_type.title()}Activity")
+            method = getattr(self, f"handle_{activity_type}_activity")
         except AttributeError:
-            return self.responseCode(
+            return self.response_code(
                 request,
                 http.UNSUPPORTED_MEDIA_TYPE,
                 f"{activity_type.title()} activity is not yet supported"
@@ -853,7 +853,7 @@
                 request, data, account_jid, node, ap_account, ap_url, signing_actor
             )
 
-    async def APFollowersRequest(
+    async def ap_followers_request(
         self,
         request: "HTTPRequest",
         data: Optional[dict],
@@ -866,20 +866,20 @@
         if node is None:
             node = self.apg._m.namespace
         client = self.apg.client
-        subscribers = await self.apg._pps.getPublicNodeSubscriptions(
+        subscribers = await self.apg._pps.get_public_node_subscriptions(
             client, account_jid, node
         )
         followers = []
         for subscriber in subscribers.keys():
-            if self.apg.isVirtualJID(subscriber):
+            if self.apg.is_virtual_jid(subscriber):
                 # the subscriber is an AP user subscribed with this gateway
                 ap_account = self.apg._e.unescape(subscriber.user)
             else:
                 # regular XMPP user
-                ap_account = await self.apg.getAPAccountFromJidAndNode(subscriber, node)
+                ap_account = await self.apg.get_ap_account_from_jid_and_node(subscriber, node)
             followers.append(ap_account)
 
-        url = self.getCanonicalURL(request)
+        url = self.get_canonical_url(request)
         return {
           "@context": ["https://www.w3.org/ns/activitystreams"],
           "type": "OrderedCollection",
@@ -892,7 +892,7 @@
           }
         }
 
-    async def APFollowingRequest(
+    async def ap_following_request(
         self,
         request: "HTTPRequest",
         data: Optional[dict],
@@ -909,17 +909,17 @@
         following = []
         for sub_dict in subscriptions:
             service = jid.JID(sub_dict["service"])
-            if self.apg.isVirtualJID(service):
+            if self.apg.is_virtual_jid(service):
                 # the subscription is to an AP actor with this gateway
                 ap_account = self.apg._e.unescape(service.user)
             else:
                 # regular XMPP user
-                ap_account = await self.apg.getAPAccountFromJidAndNode(
+                ap_account = await self.apg.get_ap_account_from_jid_and_node(
                     service, sub_dict["node"]
                 )
             following.append(ap_account)
 
-        url = self.getCanonicalURL(request)
+        url = self.get_canonical_url(request)
         return {
           "@context": ["https://www.w3.org/ns/activitystreams"],
           "type": "OrderedCollection",
@@ -953,7 +953,7 @@
             to_log.append(f"  headers:\n{headers}")
         return to_log
 
-    async def APRequest(
+    async def ap_request(
         self,
         request: "HTTPRequest",
         data: Optional[dict] = None,
@@ -967,13 +967,13 @@
             f"https://{self.apg.public_url}",
             path
         )
-        request_type, extra_args = self.apg.parseAPURL(ap_url)
+        request_type, extra_args = self.apg.parse_apurl(ap_url)
         if ((MEDIA_TYPE_AP not in (request.getHeader("accept") or "")
              and request_type in self.apg.html_redirect)):
             # this is not a AP request, and we have a redirections for it
             kw = {}
             if extra_args:
-                kw["jid"], kw["node"] = await self.apg.getJIDAndNode(extra_args[0])
+                kw["jid"], kw["node"] = await self.apg.get_jid_and_node(extra_args[0])
                 kw["jid_user"] = kw["jid"].user
                 if kw["node"] is None:
                     kw["node"] = self.apg._m.namespace
@@ -1007,7 +1007,7 @@
         if len(extra_args) == 0:
             if request_type != "shared_inbox":
                 raise exceptions.DataError(f"Invalid request type: {request_type!r}")
-            ret_data = await self.APInboxRequest(
+            ret_data = await self.ap_inbox_request(
                 request, data, None, None, None, ap_url, signing_actor
             )
         elif request_type == "avatar":
@@ -1017,14 +1017,14 @@
             avatar_path = self.apg.host.common_cache.getPath(avatar_filename)
             return static.File(str(avatar_path)).render(request)
         elif request_type == "item":
-            ret_data = await self.apg.apGetLocalObject(ap_url)
+            ret_data = await self.apg.ap_get_local_object(ap_url)
             if "@context" not in ret_data:
                 ret_data["@context"] = [NS_AP]
         else:
             if len(extra_args) > 1:
                 log.warning(f"unexpected extra arguments: {extra_args!r}")
             ap_account = extra_args[0]
-            account_jid, node = await self.apg.getJIDAndNode(ap_account)
+            account_jid, node = await self.apg.get_jid_and_node(ap_account)
             if request_type not in AP_REQUEST_TYPES.get(
                     request.method.decode().upper(), []
             ):
@@ -1046,12 +1046,12 @@
             log.info("\n".join(to_log))
         request.finish()
 
-    async def APPostRequest(self, request: "HTTPRequest") -> None:
+    async def ap_post_request(self, request: "HTTPRequest") -> None:
         try:
             data = json.load(request.content)
             if not isinstance(data, dict):
                 log.warning(f"JSON data should be an object (uri={request.uri.decode()})")
-                self.responseCode(
+                self.response_code(
                     request,
                     http.BAD_REQUEST,
                     f"invalid body, was expecting a JSON object"
@@ -1059,7 +1059,7 @@
                 request.finish()
                 return
         except (json.JSONDecodeError, ValueError) as e:
-            self.responseCode(
+            self.response_code(
                 request,
                 http.BAD_REQUEST,
                 f"invalid json in inbox request: {e}"
@@ -1081,14 +1081,14 @@
             pass
 
         try:
-            signing_actor = await self.checkSignature(request)
+            signing_actor = await self.check_signature(request)
         except exceptions.EncryptionError as e:
             if self.apg.verbose:
                 to_log = self._get_to_log(request)
                 to_log.append(f"  body: {request.content.read()!r}")
                 request.content.seek(0)
                 log.info("\n".join(to_log))
-            self.responseCode(
+            self.response_code(
                 request,
                 http.FORBIDDEN,
                 f"invalid signature: {e}"
@@ -1096,7 +1096,7 @@
             request.finish()
             return
         except Exception as e:
-            self.responseCode(
+            self.response_code(
                 request,
                 http.INTERNAL_SERVER_ERROR,
                 f"Can't check signature: {e}"
@@ -1115,27 +1115,27 @@
 
         # default response code, may be changed, e.g. in case of exception
         try:
-            return await self.APRequest(request, data, signing_actor)
+            return await self.ap_request(request, data, signing_actor)
         except Exception as e:
-            self._onRequestError(failure.Failure(e), request)
+            self._on_request_error(failure.Failure(e), request)
 
-    async def checkSigningActor(self, data: dict, signing_actor: str) -> None:
+    async def check_signing_actor(self, data: dict, signing_actor: str) -> None:
         """That that signing actor correspond to actor declared in data
 
         @param data: request payload
         @param signing_actor: actor ID of the signing entity, as returned by
-            checkSignature
+            check_signature
         @raise exceptions.NotFound: no actor found in data
         @raise exceptions.EncryptionError: signing actor doesn't match actor in data
         """
-        actor = await self.apg.apGetSenderActor(data)
+        actor = await self.apg.ap_get_sender_actor(data)
 
         if signing_actor != actor:
             raise exceptions.EncryptionError(
                 f"signing actor ({signing_actor}) doesn't match actor in data ({actor})"
             )
 
-    async def checkSignature(self, request: "HTTPRequest") -> str:
+    async def check_signature(self, request: "HTTPRequest") -> str:
         """Check and validate HTTP signature
 
         @return: id of the signing actor
@@ -1242,7 +1242,7 @@
                         raise exceptions.EncryptionError(
                             "Only SHA-256 algorithm is currently supported for digest"
                         )
-                    __, computed_digest = self.apg.getDigest(body)
+                    __, computed_digest = self.apg.get_digest(body)
                     if given_digest != computed_digest:
                         raise exceptions.EncryptionError(
                             f"SHA-256 given and computed digest differ:\n"
@@ -1275,7 +1275,7 @@
             raise exceptions.EncryptionError("Signature has expired")
 
         try:
-            return await self.apg.checkSignature(
+            return await self.apg.check_signature(
                 sign_data["signature"],
                 key_id,
                 headers
@@ -1287,7 +1287,7 @@
                 "Using workaround for (request-target) encoding bug in signature, "
                 "see https://github.com/mastodon/mastodon/issues/18871"
             )
-            return await self.apg.checkSignature(
+            return await self.apg.check_signature(
                 sign_data["signature"],
                 key_id,
                 headers
@@ -1303,8 +1303,8 @@
             defer.ensureDeferred(self.webfinger(request))
             return server.NOT_DONE_YET
         elif path.startswith(self.apg.ap_path):
-            d = defer.ensureDeferred(self.APRequest(request))
-            d.addErrback(self._onRequestError, request)
+            d = defer.ensureDeferred(self.ap_request(request))
+            d.addErrback(self._on_request_error, request)
             return server.NOT_DONE_YET
 
         return web_resource.NoResource().render(request)
@@ -1313,7 +1313,7 @@
         path = request.path.decode().lstrip("/")
         if not path.startswith(self.apg.ap_path):
             return web_resource.NoResource().render(request)
-        defer.ensureDeferred(self.APPostRequest(request))
+        defer.ensureDeferred(self.ap_post_request(request))
         return server.NOT_DONE_YET