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.
This commit is contained in:
Goffi 2023-04-08 13:54:42 +02:00
commit 6a6f15707a

View file

@ -30,7 +30,7 @@ from sat.core.log import getLogger
from sat.core.core_types import SatXMPPEntity
from sat.core import exceptions
from sat.tools.common import uri, data_format, date_utils
from sat.tools.utils import asDeferred, xmpp_date
from sat.tools.utils import as_deferred, xmpp_date
log = getLogger(__name__)
@ -58,27 +58,27 @@ class PubsubAttachments:
def __init__(self, host):
log.info(_("XEP-0470 (Pubsub Attachments) plugin initialization"))
host.registerNamespace("pubsub-attachments", NS_PUBSUB_ATTACHMENTS)
host.register_namespace("pubsub-attachments", NS_PUBSUB_ATTACHMENTS)
self.host = host
self._p = host.plugins["XEP-0060"]
self.handlers: Dict[Tuple[str, str], dict[str, Any]] = {}
host.trigger.add("XEP-0277_send", self.onMBSend)
host.trigger.add("XEP-0277_send", self.on_mb_send)
self.register_attachment_handler(
"noticed", NS_PUBSUB_ATTACHMENTS, self.noticedGet, self.noticedSet
"noticed", NS_PUBSUB_ATTACHMENTS, self.noticed_get, self.noticed_set
)
self.register_attachment_handler(
"reactions", NS_PUBSUB_ATTACHMENTS, self.reactionsGet, self.reactionsSet
"reactions", NS_PUBSUB_ATTACHMENTS, self.reactions_get, self.reactions_set
)
host.bridge.addMethod(
"psAttachmentsGet",
host.bridge.add_method(
"ps_attachments_get",
".plugin",
in_sign="sssasss",
out_sign="(ss)",
method=self._get,
async_=True,
)
host.bridge.addMethod(
"psAttachmentsSet",
host.bridge.add_method(
"ps_attachments_set",
".plugin",
in_sign="ss",
out_sign="",
@ -86,7 +86,7 @@ class PubsubAttachments:
async_=True,
)
def getHandler(self, client):
def get_handler(self, client):
return PubsubAttachments_Handler()
def register_attachment_handler(
@ -125,9 +125,9 @@ class PubsubAttachments:
"set": set_cb
}
def getAttachmentNodeName(self, service: jid.JID, node: str, item: str) -> str:
def get_attachment_node_name(self, service: jid.JID, node: str, item: str) -> str:
"""Generate name to use for attachment node"""
target_item_uri = uri.buildXMPPUri(
target_item_uri = uri.build_xmpp_uri(
"pubsub",
path=service.userhost(),
node=node,
@ -135,17 +135,17 @@ class PubsubAttachments:
)
return f"{NS_PUBSUB_ATTACHMENTS}/{target_item_uri}"
def isAttachmentNode(self, node: str) -> bool:
def is_attachment_node(self, node: str) -> bool:
"""Return True if node name is an attachment node"""
return node.startswith(f"{NS_PUBSUB_ATTACHMENTS}/")
def attachmentNode2Item(self, node: str) -> Tuple[jid.JID, str, str]:
def attachment_node_2_item(self, node: str) -> Tuple[jid.JID, str, str]:
"""Retrieve service, node and item from attachement node's name"""
if not self.isAttachmentNode(node):
if not self.is_attachment_node(node):
raise ValueError("this is not an attachment node!")
prefix_len = len(f"{NS_PUBSUB_ATTACHMENTS}/")
item_uri = node[prefix_len:]
parsed_uri = uri.parseXMPPUri(item_uri)
parsed_uri = uri.parse_xmpp_uri(item_uri)
if parsed_uri["type"] != "pubsub":
raise ValueError(f"unexpected URI type, it must be a pubsub URI: {item_uri}")
try:
@ -156,7 +156,7 @@ class PubsubAttachments:
item = parsed_uri["item"]
return (service, node, item)
async def onMBSend(
async def on_mb_send(
self,
client: SatXMPPEntity,
service: jid.JID,
@ -203,16 +203,16 @@ class PubsubAttachments:
node_config.fields["pubsub#publish_model"].value = "open"
except KeyError:
log.warning("pubsub#publish_model field is missing")
attachment_node = self.getAttachmentNodeName(service, node, item_id)
attachment_node = self.get_attachment_node_name(service, node, item_id)
# we use the same options as target node
try:
await self._p.createIfNewNode(
await self._p.create_if_new_node(
client, service, attachment_node, options=dict(node_config)
)
except Exception as e:
log.warning(f"Can't create attachment node {attachment_node}: {e}")
def items2attachmentData(
def items_2_attachment_data(
self,
client: SatXMPPEntity,
items: List[domish.Element]
@ -267,11 +267,11 @@ class PubsubAttachments:
extra_s: str,
profile_key: str
) -> defer.Deferred:
client = self.host.getClient(profile_key)
client = self.host.get_client(profile_key)
extra = data_format.deserialise(extra_s)
senders = [jid.JID(s) for s in senders_s]
d = defer.ensureDeferred(
self.getAttachments(client, jid.JID(service_s), node, item, senders)
self.get_attachments(client, jid.JID(service_s), node, item, senders)
)
d.addCallback(
lambda ret:
@ -280,7 +280,7 @@ class PubsubAttachments:
)
return d
async def getAttachments(
async def get_attachments(
self,
client: SatXMPPEntity,
service: jid.JID,
@ -298,21 +298,21 @@ class PubsubAttachments:
entities will be retrieved.
If None, attachments from all entities will be retrieved
@param extra: extra data, will be used as ``extra`` argument when doing
``getItems`` call.
``get_items`` call.
@return: A tuple with:
- the list of attachments data, one item per found sender. The attachments
data are dict containing attachment, no ``extra`` field is used here
(contrarily to attachments data used with ``set_attachements``).
- metadata returned by the call to ``getItems``
- metadata returned by the call to ``get_items``
"""
if extra is None:
extra = {}
attachment_node = self.getAttachmentNodeName(service, node, item)
attachment_node = self.get_attachment_node_name(service, node, item)
item_ids = [e.userhost() for e in senders] if senders else None
items, metadata = await self._p.getItems(
items, metadata = await self._p.get_items(
client, service, attachment_node, item_ids=item_ids, extra=extra
)
list_data = self.items2attachmentData(client, items)
list_data = self.items_2_attachment_data(client, items)
return list_data, metadata
@ -321,7 +321,7 @@ class PubsubAttachments:
attachments_s: str,
profile_key: str
) -> None:
client = self.host.getClient(profile_key)
client = self.host.get_client(profile_key)
attachments = data_format.deserialise(attachments_s) or {}
return defer.ensureDeferred(self.set_attachements(client, attachments))
@ -378,7 +378,7 @@ class PubsubAttachments:
former_elt = next(attachments_elt.elements(namespace, name))
except StopIteration:
former_elt = None
new_elt = await asDeferred(
new_elt = await as_deferred(
handler["set"], client, attachments_data, former_elt
)
if new_elt != former_elt:
@ -417,9 +417,9 @@ class PubsubAttachments:
raise ValueError(
'data must have "service", "node" and "id" set'
)
attachment_node = self.getAttachmentNodeName(service, node, item)
attachment_node = self.get_attachment_node_name(service, node, item)
try:
items, __ = await self._p.getItems(
items, __ = await self._p.get_items(
client, service, attachment_node, item_ids=[client.jid.userhost()]
)
except exceptions.NotFound:
@ -437,7 +437,7 @@ class PubsubAttachments:
)
try:
await self._p.sendItems(client, service, attachment_node, [item_elt])
await self._p.send_items(client, service, attachment_node, [item_elt])
except error.StanzaError as e:
if e.condition == "item-not-found":
# the node doesn't exist, we can't publish attachments
@ -462,11 +462,11 @@ class PubsubAttachments:
@param node: node of target item (used to get attachment node's name)
@param item: name of target item (used to get attachment node's name)
"""
attachment_node = self.getAttachmentNodeName(service, node, item)
attachment_node = self.get_attachment_node_name(service, node, item)
await self._p.subscribe(client, service, attachment_node)
def setTimestamp(self, attachment_elt: domish.Element, data: dict) -> None:
def set_timestamp(self, attachment_elt: domish.Element, data: dict) -> None:
"""Check if a ``timestamp`` attribute is set, parse it, and fill data
@param attachments_elt: element where the ``timestamp`` attribute may be set
@ -482,7 +482,7 @@ class PubsubAttachments:
else:
data["timestamp"] = timestamp
def noticedGet(
def noticed_get(
self,
client: SatXMPPEntity,
attachments_elt: domish.Element,
@ -498,10 +498,10 @@ class PubsubAttachments:
noticed_data = {
"noticed": True
}
self.setTimestamp(noticed_elt, noticed_data)
self.set_timestamp(noticed_elt, noticed_data)
data["noticed"] = noticed_data
def noticedSet(
def noticed_set(
self,
client: SatXMPPEntity,
data: Dict[str, Any],
@ -525,7 +525,7 @@ class PubsubAttachments:
else:
return None
def reactionsGet(
def reactions_get(
self,
client: SatXMPPEntity,
attachments_elt: domish.Element,
@ -542,10 +542,10 @@ class PubsubAttachments:
reactions = reactions_data["reactions"]
for reaction_elt in reactions_elt.elements(NS_PUBSUB_ATTACHMENTS, "reaction"):
reactions.append(str(reaction_elt))
self.setTimestamp(reactions_elt, reactions_data)
self.set_timestamp(reactions_elt, reactions_data)
data["reactions"] = reactions_data
def reactionsSet(
def reactions_set(
self,
client: SatXMPPEntity,
data: Dict[str, Any],