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

@ -102,18 +102,18 @@ class AdHocCommand(XMPPHandler):
def getName(self, xml_lang=None):
return self.label
def isAuthorised(self, requestor):
def is_authorised(self, requestor):
if "@ALL@" in self.allowed_magics:
return True
forbidden = set(self.forbidden_jids)
for group in self.forbidden_groups:
forbidden.update(self.client.roster.getJidsFromGroup(group))
forbidden.update(self.client.roster.get_jids_from_group(group))
if requestor.userhostJID() in forbidden:
return False
allowed = set(self.allowed_jids)
for group in self.allowed_groups:
try:
allowed.update(self.client.roster.getJidsFromGroup(group))
allowed.update(self.client.roster.get_jids_from_group(group))
except exceptions.UnknownGroupError:
log.warning(_("The groups [{group}] is unknown for profile [{profile}])")
.format(group=group, profile=self.client.profile))
@ -194,7 +194,7 @@ class AdHocCommand(XMPPHandler):
self.client.send(iq_elt)
del self.sessions[session_id]
def _requestEb(self, failure_, request, session_id):
def _request_eb(self, failure_, request, session_id):
if failure_.check(AdHocError):
error_constant = failure_.value.callback_error
else:
@ -203,8 +203,8 @@ class AdHocCommand(XMPPHandler):
self._sendError(error_constant, session_id, request)
def onRequest(self, command_elt, requestor, action, session_id):
if not self.isAuthorised(requestor):
def on_request(self, command_elt, requestor, action, session_id):
if not self.is_authorised(requestor):
return self._sendError(
XEP_0050.ERROR.FORBIDDEN, session_id, command_elt.parent
)
@ -220,12 +220,12 @@ class AdHocCommand(XMPPHandler):
XEP_0050.ERROR.FORBIDDEN, session_id, command_elt.parent
)
else:
session_id, session_data = self.sessions.newSession()
session_id, session_data = self.sessions.new_session()
session_data["requestor"] = requestor
if action == XEP_0050.ACTION.CANCEL:
d = defer.succeed((None, XEP_0050.STATUS.CANCELED, None, None))
else:
d = utils.asDeferred(
d = utils.as_deferred(
self.callback,
self.client,
command_elt,
@ -234,7 +234,7 @@ class AdHocCommand(XMPPHandler):
self.node,
)
d.addCallback(self._sendAnswer, session_id, command_elt.parent)
d.addErrback(self._requestEb, command_elt.parent, session_id)
d.addErrback(self._request_eb, command_elt.parent, session_id)
class XEP_0050(object):
@ -276,49 +276,49 @@ class XEP_0050(object):
log.info(_("plugin XEP-0050 initialization"))
self.host = host
self.requesting = Sessions()
host.bridge.addMethod(
"adHocRun",
host.bridge.add_method(
"ad_hoc_run",
".plugin",
in_sign="sss",
out_sign="s",
method=self._run,
async_=True,
)
host.bridge.addMethod(
"adHocList",
host.bridge.add_method(
"ad_hoc_list",
".plugin",
in_sign="ss",
out_sign="s",
method=self._listUI,
method=self._list_ui,
async_=True,
)
host.bridge.addMethod(
"adHocSequence",
host.bridge.add_method(
"ad_hoc_sequence",
".plugin",
in_sign="ssss",
out_sign="s",
method=self._sequence,
async_=True,
)
self.__requesting_id = host.registerCallback(
self._requestingEntity, with_data=True
self.__requesting_id = host.register_callback(
self._requesting_entity, with_data=True
)
host.importMenu(
host.import_menu(
(D_("Service"), D_("Commands")),
self._commandsMenu,
self._commands_menu,
security_limit=2,
help_string=D_("Execute ad-hoc commands"),
)
host.registerNamespace('commands', NS_COMMANDS)
host.register_namespace('commands', NS_COMMANDS)
def getHandler(self, client):
def get_handler(self, client):
return XEP_0050_handler(self)
def profileConnected(self, client):
def profile_connected(self, client):
# map from node to AdHocCommand instance
client._XEP_0050_commands = {}
if not client.is_component:
self.addAdHocCommand(client, self._statusCallback, _("Status"))
self.add_ad_hoc_command(client, self._status_callback, _("Status"))
def do(self, client, entity, node, action=ACTION.EXECUTE, session_id=None,
form_values=None, timeout=30):
@ -349,20 +349,20 @@ class XEP_0050(object):
d = iq_elt.send()
return d
def getCommandElt(self, iq_elt):
def get_command_elt(self, iq_elt):
try:
return next(iq_elt.elements(NS_COMMANDS, "command"))
except StopIteration:
raise exceptions.NotFound(_("Missing command element"))
def adHocError(self, error_type):
def ad_hoc_error(self, error_type):
"""Shortcut to raise an AdHocError
@param error_type(unicode): one of XEP_0050.ERROR
"""
raise AdHocError(error_type)
def _items2XMLUI(self, items, no_instructions):
def _items_2_xmlui(self, items, no_instructions):
"""Convert discovery items to XMLUI dialog """
# TODO: manage items on different jids
form_ui = xml_tools.XMLUI("form", submit_id=self.__requesting_id)
@ -374,7 +374,7 @@ class XEP_0050(object):
form_ui.addList("node", options)
return form_ui
def _getDataLvl(self, type_):
def _get_data_lvl(self, type_):
"""Return the constant corresponding to <note/> type attribute value
@param type_: note type (see XEP-0050 §4.3)
@ -389,7 +389,7 @@ class XEP_0050(object):
log.warning(_("Invalid note type [%s], using info") % type_)
return C.XMLUI_DATA_LVL_INFO
def _mergeNotes(self, notes):
def _merge_notes(self, notes):
"""Merge notes with level prefix (e.g. "ERROR: the message")
@param notes (list): list of tuple (level, message)
@ -402,8 +402,8 @@ class XEP_0050(object):
}
return ["%s%s" % (lvl_map[lvl], msg) for lvl, msg in notes]
def parseCommandAnswer(self, iq_elt):
command_elt = self.getCommandElt(iq_elt)
def parse_command_answer(self, iq_elt):
command_elt = self.get_command_elt(iq_elt)
data = {}
data["status"] = command_elt.getAttribute("status", XEP_0050.STATUS.EXECUTING)
data["session_id"] = command_elt.getAttribute("sessionid")
@ -411,7 +411,7 @@ class XEP_0050(object):
for note_elt in command_elt.elements(NS_COMMANDS, "note"):
notes.append(
(
self._getDataLvl(note_elt.getAttribute("type", "info")),
self._get_data_lvl(note_elt.getAttribute("type", "info")),
str(note_elt),
)
)
@ -419,14 +419,14 @@ class XEP_0050(object):
return command_elt, data
def _commandsAnswer2XMLUI(self, iq_elt, session_id, session_data):
def _commands_answer_2_xmlui(self, iq_elt, session_id, session_data):
"""Convert command answer to an ui for frontend
@param iq_elt: command result
@param session_id: id of the session used with the frontend
@param profile_key: %(doc_profile_key)s
"""
command_elt, answer_data = self.parseCommandAnswer(iq_elt)
command_elt, answer_data = self.parse_command_answer(iq_elt)
status = answer_data["status"]
if status in [XEP_0050.STATUS.COMPLETED, XEP_0050.STATUS.CANCELED]:
# the command session is finished, we purge our session
@ -468,68 +468,68 @@ class XEP_0050(object):
C.XMLUI_DIALOG,
dialog_opt={
C.XMLUI_DATA_TYPE: C.XMLUI_DIALOG_NOTE,
C.XMLUI_DATA_MESS: "\n".join(self._mergeNotes(notes)),
C.XMLUI_DATA_MESS: "\n".join(self._merge_notes(notes)),
C.XMLUI_DATA_LVL: dlg_level,
},
session_id=session_id,
)
if session_id is None:
xmlui = xml_tools.dataFormEltResult2XMLUI(data_elt)
xmlui = xml_tools.data_form_elt_result_2_xmlui(data_elt)
if notes:
for level, note in notes:
if level != "info":
note = f"[{level}] {note}"
xmlui.addWidget("text", note)
xmlui.add_widget("text", note)
return xmlui
form = data_form.Form.fromElement(data_elt)
# we add any present note to the instructions
form.instructions.extend(self._mergeNotes(notes))
return xml_tools.dataForm2XMLUI(form, self.__requesting_id, session_id=session_id)
form.instructions.extend(self._merge_notes(notes))
return xml_tools.data_form_2_xmlui(form, self.__requesting_id, session_id=session_id)
def _requestingEntity(self, data, profile):
def _requesting_entity(self, data, profile):
def serialise(ret_data):
if "xmlui" in ret_data:
ret_data["xmlui"] = ret_data["xmlui"].toXml()
return ret_data
d = self.requestingEntity(data, profile)
d = self.requesting_entity(data, profile)
d.addCallback(serialise)
return d
def requestingEntity(self, data, profile):
def requesting_entity(self, data, profile):
"""Request and entity and create XMLUI accordingly.
@param data: data returned by previous XMLUI (first one must come from
self._commandsMenu)
self._commands_menu)
@param profile: %(doc_profile)s
@return: callback dict result (with "xmlui" corresponding to the answering
dialog, or empty if it's finished without error)
"""
if C.bool(data.get("cancelled", C.BOOL_FALSE)):
return defer.succeed({})
data_form_values = xml_tools.XMLUIResult2DataFormResult(data)
client = self.host.getClient(profile)
data_form_values = xml_tools.xmlui_result_2_data_form_result(data)
client = self.host.get_client(profile)
# TODO: cancel, prev and next are not managed
# TODO: managed answerer errors
# TODO: manage nodes with a non data form payload
if "session_id" not in data:
# we just had the jid, we now request it for the available commands
session_id, session_data = self.requesting.newSession(profile=client.profile)
session_id, session_data = self.requesting.new_session(profile=client.profile)
entity = jid.JID(data[xml_tools.SAT_FORM_PREFIX + "jid"])
session_data["jid"] = entity
d = self.listUI(client, entity)
d = self.list_ui(client, entity)
def sendItems(xmlui):
def send_items(xmlui):
xmlui.session_id = session_id # we need to keep track of the session
return {"xmlui": xmlui}
d.addCallback(sendItems)
d.addCallback(send_items)
else:
# we have started a several forms sessions
try:
session_data = self.requesting.profileGet(
session_data = self.requesting.profile_get(
data["session_id"], client.profile
)
except KeyError:
@ -552,24 +552,24 @@ class XEP_0050(object):
# we request execute node's command
d = self.do(client, entity, session_data["node"], action=XEP_0050.ACTION.EXECUTE,
session_id=remote_id, form_values=data_form_values)
d.addCallback(self._commandsAnswer2XMLUI, session_id, session_data)
d.addCallback(self._commands_answer_2_xmlui, session_id, session_data)
d.addCallback(lambda xmlui: {"xmlui": xmlui} if xmlui is not None else {})
return d
def _commandsMenu(self, menu_data, profile):
def _commands_menu(self, menu_data, profile):
"""First XMLUI activated by menu: ask for target jid
@param profile: %(doc_profile)s
"""
form_ui = xml_tools.XMLUI("form", submit_id=self.__requesting_id)
form_ui.addText(_("Please enter target jid"), "instructions")
form_ui.changeContainer("pairs")
form_ui.change_container("pairs")
form_ui.addLabel("jid")
form_ui.addString("jid", value=self.host.getClient(profile).jid.host)
form_ui.addString("jid", value=self.host.get_client(profile).jid.host)
return {"xmlui": form_ui.toXml()}
def _statusCallback(self, client, command_elt, session_data, action, node):
def _status_callback(self, client, command_elt, session_data, action, node):
"""Ad-hoc command used to change the "show" part of status"""
actions = session_data.setdefault("actions", [])
actions.append(action)
@ -596,25 +596,25 @@ class XEP_0050(object):
answer_form = data_form.Form.fromElement(x_elt)
show = answer_form["show"]
except (KeyError, StopIteration):
self.adHocError(XEP_0050.ERROR.BAD_PAYLOAD)
self.ad_hoc_error(XEP_0050.ERROR.BAD_PAYLOAD)
if show not in SHOWS:
self.adHocError(XEP_0050.ERROR.BAD_PAYLOAD)
self.ad_hoc_error(XEP_0050.ERROR.BAD_PAYLOAD)
if show == "disconnect":
self.host.disconnect(client.profile)
else:
self.host.setPresence(show=show, profile_key=client.profile)
self.host.presence_set(show=show, profile_key=client.profile)
# job done, we can end the session
status = XEP_0050.STATUS.COMPLETED
payload = None
note = (self.NOTE.INFO, _("Status updated"))
else:
self.adHocError(XEP_0050.ERROR.INTERNAL)
self.ad_hoc_error(XEP_0050.ERROR.INTERNAL)
return (payload, status, None, note)
def _run(self, service_jid_s="", node="", profile_key=C.PROF_KEY_NONE):
client = self.host.getClient(profile_key)
client = self.host.get_client(profile_key)
service_jid = jid.JID(service_jid_s) if service_jid_s else None
d = defer.ensureDeferred(self.run(client, service_jid, node or None))
d.addCallback(lambda xmlui: xmlui.toXml())
@ -631,13 +631,13 @@ class XEP_0050(object):
"""
if service_jid is None:
service_jid = jid.JID(client.jid.host)
session_id, session_data = self.requesting.newSession(profile=client.profile)
session_id, session_data = self.requesting.new_session(profile=client.profile)
session_data["jid"] = service_jid
if node is None:
xmlui = await self.listUI(client, service_jid)
xmlui = await self.list_ui(client, service_jid)
else:
session_data["node"] = node
cb_data = await self.requestingEntity(
cb_data = await self.requesting_entity(
{"session_id": session_id}, client.profile
)
xmlui = cb_data["xmlui"]
@ -655,14 +655,14 @@ class XEP_0050(object):
d = self.host.getDiscoItems(client, to_jid, NS_COMMANDS)
return d
def _listUI(self, to_jid_s, profile_key):
client = self.host.getClient(profile_key)
def _list_ui(self, to_jid_s, profile_key):
client = self.host.get_client(profile_key)
to_jid = jid.JID(to_jid_s) if to_jid_s else None
d = self.listUI(client, to_jid, no_instructions=True)
d = self.list_ui(client, to_jid, no_instructions=True)
d.addCallback(lambda xmlui: xmlui.toXml())
return d
def listUI(self, client, to_jid, no_instructions=False):
def list_ui(self, client, to_jid, no_instructions=False):
"""Request available commands and generate XMLUI
@param to_jid(jid.JID, None): the entity answering the commands
@ -671,12 +671,12 @@ class XEP_0050(object):
@return D(xml_tools.XMLUI): UI with the commands
"""
d = self.list(client, to_jid)
d.addCallback(self._items2XMLUI, no_instructions)
d.addCallback(self._items_2_xmlui, no_instructions)
return d
def _sequence(self, sequence, node, service_jid_s="", profile_key=C.PROF_KEY_NONE):
sequence = data_format.deserialise(sequence, type_check=list)
client = self.host.getClient(profile_key)
client = self.host.get_client(profile_key)
service_jid = jid.JID(service_jid_s) if service_jid_s else None
d = defer.ensureDeferred(self.sequence(client, sequence, node, service_jid))
d.addCallback(lambda data: data_format.serialise(data))
@ -711,12 +711,12 @@ class XEP_0050(object):
session_id=session_id,
form_values=data_to_send,
)
__, answer_data = self.parseCommandAnswer(iq_result_elt)
__, answer_data = self.parse_command_answer(iq_result_elt)
session_id = answer_data.pop("session_id")
return answer_data
def addAdHocCommand(self, client, callback, label, node=None, features=None,
def add_ad_hoc_command(self, client, callback, label, node=None, features=None,
timeout=600, allowed_jids=None, allowed_groups=None,
allowed_magics=None, forbidden_jids=None, forbidden_groups=None,
):
@ -782,7 +782,7 @@ class XEP_0050(object):
commands = client._XEP_0050_commands
commands[node] = ad_hoc_command
def onCmdRequest(self, request, client):
def on_cmd_request(self, request, client):
request.handled = True
requestor = jid.JID(request["from"])
command_elt = next(request.elements(NS_COMMANDS, "command"))
@ -798,7 +798,7 @@ class XEP_0050(object):
except KeyError:
client.sendError(request, "item-not-found")
return
command.onRequest(command_elt, requestor, action, sessionid)
command.on_request(command_elt, requestor, action, sessionid)
@implementer(iwokkel.IDisco)
@ -813,7 +813,7 @@ class XEP_0050_handler(XMPPHandler):
def connectionInitialized(self):
self.xmlstream.addObserver(
CMD_REQUEST, self.plugin_parent.onCmdRequest, client=self.parent
CMD_REQUEST, self.plugin_parent.on_cmd_request, client=self.parent
)
def getDiscoInfo(self, requestor, target, nodeIdentifier=""):
@ -828,7 +828,7 @@ class XEP_0050_handler(XMPPHandler):
if nodeIdentifier == NS_COMMANDS:
commands = self.client._XEP_0050_commands
for command in list(commands.values()):
if command.isAuthorised(requestor):
if command.is_authorised(requestor):
ret.append(
disco.DiscoItem(self.parent.jid, command.node, command.getName())
) # TODO: manage name language