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

@ -71,33 +71,33 @@ class XEP_0234:
def __init__(self, host):
log.info(_("plugin Jingle File Transfer initialization"))
self.host = host
host.registerNamespace("jingle-ft", NS_JINGLE_FT)
host.register_namespace("jingle-ft", NS_JINGLE_FT)
self._j = host.plugins["XEP-0166"] # shortcut to access jingle
self._j.registerApplication(NS_JINGLE_FT, self)
self._j.register_application(NS_JINGLE_FT, self)
self._f = host.plugins["FILE"]
self._f.register(self, priority=10000)
self._hash = self.host.plugins["XEP-0300"]
host.bridge.addMethod(
"fileJingleSend",
host.bridge.add_method(
"file_jingle_send",
".plugin",
in_sign="ssssa{ss}s",
out_sign="",
method=self._fileSend,
method=self._file_send,
async_=True,
)
host.bridge.addMethod(
"fileJingleRequest",
host.bridge.add_method(
"file_jingle_request",
".plugin",
in_sign="sssssa{ss}s",
out_sign="s",
method=self._fileJingleRequest,
method=self._file_jingle_request,
async_=True,
)
def getHandler(self, client):
def get_handler(self, client):
return XEP_0234_handler()
def getProgressId(self, session, content_name):
def get_progress_id(self, session, content_name):
"""Return a unique progress ID
@param session(dict): jingle session
@ -106,7 +106,7 @@ class XEP_0234:
"""
return "{}_{}".format(session["id"], content_name)
async def canHandleFileSend(self, client, peer_jid, filepath):
async def can_handle_file_send(self, client, peer_jid, filepath):
if peer_jid.resource:
return await self.host.hasFeature(client, NS_JINGLE_FT, peer_jid)
else:
@ -115,7 +115,7 @@ class XEP_0234:
# generic methods
def buildFileElement(
def build_file_element(
self, client, name=None, file_hash=None, hash_algo=None, size=None,
mime_type=None, desc=None, modified=None, transfer_range=None, path=None,
namespace=None, file_elt=None, **kwargs):
@ -168,11 +168,11 @@ class XEP_0234:
range_elt["length"] = transfer_range.length
if file_hash is not None:
if not file_hash:
file_elt.addChild(self._hash.buildHashUsedElt())
file_elt.addChild(self._hash.build_hash_used_elt())
else:
file_elt.addChild(self._hash.buildHashElt(file_hash, hash_algo))
file_elt.addChild(self._hash.build_hash_elt(file_hash, hash_algo))
elif hash_algo is not None:
file_elt.addChild(self._hash.buildHashUsedElt(hash_algo))
file_elt.addChild(self._hash.build_hash_used_elt(hash_algo))
self.host.trigger.point(
"XEP-0234_buildFileElement", client, file_elt, extra_args=kwargs)
if kwargs:
@ -180,8 +180,8 @@ class XEP_0234:
log.debug("ignored keyword: {}".format(kw))
return file_elt
def buildFileElementFromDict(self, client, file_data, **kwargs):
"""like buildFileElement but get values from a file_data dict
def build_file_element_from_dict(self, client, file_data, **kwargs):
"""like build_file_element but get values from a file_data dict
@param file_data(dict): metadata to use
@param **kwargs: data to override
@ -195,9 +195,9 @@ class XEP_0234:
)
except KeyError:
pass
return self.buildFileElement(client, **file_data)
return self.build_file_element(client, **file_data)
async def parseFileElement(
async def parse_file_element(
self, client, file_elt, file_data=None, given=False, parent_elt=None,
keep_empty_range=False):
"""Parse a <file> element and file dictionary accordingly
@ -248,7 +248,7 @@ class XEP_0234:
name = "--"
file_data["name"] = name
elif name is not None and ("/" in name or "\\" in name):
file_data["name"] = regex.pathEscape(name)
file_data["name"] = regex.path_escape(name)
try:
file_data["mime_type"] = str(
@ -284,7 +284,7 @@ class XEP_0234:
prefix = "given_" if given else ""
hash_algo_key, hash_key = "hash_algo", prefix + "file_hash"
try:
file_data[hash_algo_key], file_data[hash_key] = self._hash.parseHashElt(
file_data[hash_algo_key], file_data[hash_key] = self._hash.parse_hash_elt(
file_elt
)
except exceptions.NotFound:
@ -296,7 +296,7 @@ class XEP_0234:
# bridge methods
def _fileSend(
def _file_send(
self,
peer_jid,
filepath,
@ -305,8 +305,8 @@ class XEP_0234:
extra=None,
profile=C.PROF_KEY_NONE,
):
client = self.host.getClient(profile)
return defer.ensureDeferred(self.fileSend(
client = self.host.get_client(profile)
return defer.ensureDeferred(self.file_send(
client,
jid.JID(peer_jid),
filepath,
@ -315,7 +315,7 @@ class XEP_0234:
extra or None,
))
async def fileSend(
async def file_send(
self, client, peer_jid, filepath, name, file_desc=None, extra=None
):
"""Send a file using jingle file transfer
@ -351,11 +351,11 @@ class XEP_0234:
)
return await progress_id_d
def _fileJingleRequest(
def _file_jingle_request(
self, peer_jid, filepath, name="", file_hash="", hash_algo="", extra=None,
profile=C.PROF_KEY_NONE):
client = self.host.getClient(profile)
return defer.ensureDeferred(self.fileJingleRequest(
client = self.host.get_client(profile)
return defer.ensureDeferred(self.file_jingle_request(
client,
jid.JID(peer_jid),
filepath,
@ -365,7 +365,7 @@ class XEP_0234:
extra or None,
))
async def fileJingleRequest(
async def file_jingle_request(
self, client, peer_jid, filepath, name=None, file_hash=None, hash_algo=None,
extra=None):
"""Request a file using jingle file transfer
@ -407,12 +407,12 @@ class XEP_0234:
# jingle callbacks
def jingleDescriptionElt(
def jingle_description_elt(
self, client, session, content_name, filepath, name, extra, progress_id_d
):
return domish.Element((NS_JINGLE_FT, "description"))
def jingleSessionInit(
def jingle_session_init(
self, client, session, content_name, filepath, name, extra, progress_id_d
):
if extra is None:
@ -424,13 +424,13 @@ class XEP_0234:
keys=", ".join(EXTRA_ALLOWED)
)
)
progress_id_d.callback(self.getProgressId(session, content_name))
progress_id_d.callback(self.get_progress_id(session, content_name))
content_data = session["contents"][content_name]
application_data = content_data["application_data"]
assert "file_path" not in application_data
application_data["file_path"] = filepath
file_data = application_data["file_data"] = {}
desc_elt = self.jingleDescriptionElt(
desc_elt = self.jingle_description_elt(
client, session, content_name, filepath, name, extra, progress_id_d)
file_elt = desc_elt.addElement("file")
@ -449,7 +449,7 @@ class XEP_0234:
file_data["namespace"] = extra["namespace"]
if "path" in extra:
file_data["path"] = extra["path"]
self.buildFileElementFromDict(
self.build_file_element_from_dict(
client, file_data, file_elt=file_elt, file_hash="")
else:
# we request a file
@ -462,16 +462,16 @@ class XEP_0234:
file_data["file_hash"] = file_hash
file_data["hash_algo"] = extra["hash_algo"]
else:
file_data["hash_algo"] = self._hash.getDefaultAlgo()
file_data["hash_algo"] = self._hash.get_default_algo()
if "namespace" in extra:
file_data["namespace"] = extra["namespace"]
if "path" in extra:
file_data["path"] = extra["path"]
self.buildFileElementFromDict(client, file_data, file_elt=file_elt)
self.build_file_element_from_dict(client, file_data, file_elt=file_elt)
return desc_elt
async def jingleRequestConfirmation(
async def jingle_request_confirmation(
self, client, action, session, content_name, desc_elt
):
"""This method request confirmation for a jingle session"""
@ -485,11 +485,11 @@ class XEP_0234:
file_elt = next(desc_elt.elements(NS_JINGLE_FT, "file"))
except StopIteration:
raise failure.Failure(exceptions.DataError)
file_data = {"progress_id": self.getProgressId(session, content_name)}
file_data = {"progress_id": self.get_progress_id(session, content_name)}
if senders == self._j.ROLE_RESPONDER:
# we send the file
return await self._fileSendingRequestConf(
return await self._file_sending_request_conf(
client, session, content_data, content_name, file_data, file_elt
)
else:
@ -498,16 +498,16 @@ class XEP_0234:
client, session, content_data, content_name, file_data, file_elt
)
async def _fileSendingRequestConf(
async def _file_sending_request_conf(
self, client, session, content_data, content_name, file_data, file_elt
):
"""parse file_elt, and handle file retrieving/permission checking"""
await self.parseFileElement(client, file_elt, file_data)
await self.parse_file_element(client, file_elt, file_data)
content_data["application_data"]["file_data"] = file_data
finished_d = content_data["finished_d"] = defer.Deferred()
# confirmed_d is a deferred returning confimed value (only used if cont is False)
cont, confirmed_d = self.host.trigger.returnPoint(
cont, confirmed_d = self.host.trigger.return_point(
"XEP-0234_fileSendingRequest",
client,
session,
@ -521,7 +521,7 @@ class XEP_0234:
if confirmed:
args = [client, session, content_name, content_data]
finished_d.addCallbacks(
self._finishedCb, self._finishedEb, args, None, args
self._finished_cb, self._finished_eb, args, None, args
)
return confirmed
@ -532,18 +532,18 @@ class XEP_0234:
self, client, session, content_data, content_name, file_data, file_elt
):
"""parse file_elt, and handle user permission/file opening"""
await self.parseFileElement(client, file_elt, file_data, given=True)
await self.parse_file_element(client, file_elt, file_data, given=True)
try:
hash_algo, file_data["given_file_hash"] = self._hash.parseHashElt(file_elt)
hash_algo, file_data["given_file_hash"] = self._hash.parse_hash_elt(file_elt)
except exceptions.NotFound:
try:
hash_algo = self._hash.parseHashUsedElt(file_elt)
hash_algo = self._hash.parse_hash_used_elt(file_elt)
except exceptions.NotFound:
raise failure.Failure(exceptions.DataError)
if hash_algo is not None:
file_data["hash_algo"] = hash_algo
file_data["hash_hasher"] = hasher = self._hash.getHasher(hash_algo)
file_data["hash_hasher"] = hasher = self._hash.get_hasher(hash_algo)
file_data["data_cb"] = lambda data: hasher.update(data)
try:
@ -564,21 +564,21 @@ class XEP_0234:
# deferred to track end of transfer
finished_d = content_data["finished_d"] = defer.Deferred()
confirmed = await self._f.getDestDir(
confirmed = await self._f.get_dest_dir(
client, session["peer_jid"], content_data, file_data, stream_object=True
)
if confirmed:
await self.host.trigger.asyncPoint(
await self.host.trigger.async_point(
"XEP-0234_file_receiving_request_conf",
client, session, content_data, file_elt
)
args = [client, session, content_name, content_data]
finished_d.addCallbacks(
self._finishedCb, self._finishedEb, args, None, args
self._finished_cb, self._finished_eb, args, None, args
)
return confirmed
async def jingleHandler(self, client, action, session, content_name, desc_elt):
async def jingle_handler(self, client, action, session, content_name, desc_elt):
content_data = session["contents"][content_name]
application_data = content_data["application_data"]
if action in (self._j.A_ACCEPTED_ACK,):
@ -608,8 +608,8 @@ class XEP_0234:
size = None
# XXX: hash security is not critical here, so we just take the higher
# mandatory one
hasher = file_data["hash_hasher"] = self._hash.getHasher()
progress_id = self.getProgressId(session, content_name)
hasher = file_data["hash_hasher"] = self._hash.get_hasher()
progress_id = self.get_progress_id(session, content_name)
try:
content_data["stream_object"] = stream.FileStreamObject(
self.host,
@ -621,7 +621,7 @@ class XEP_0234:
data_cb=lambda data: hasher.update(data),
)
except Exception as e:
self.host.bridge.progressError(
self.host.bridge.progress_error(
progress_id, C.PROGRESS_ERROR_FAILED, client.profile
)
await self._j.terminate(
@ -632,19 +632,19 @@ class XEP_0234:
size = file_data["size"]
# XXX: hash security is not critical here, so we just take the higher
# mandatory one
hasher = file_data["hash_hasher"] = self._hash.getHasher()
hasher = file_data["hash_hasher"] = self._hash.get_hasher()
content_data["stream_object"] = stream.FileStreamObject(
self.host,
client,
file_path,
uid=self.getProgressId(session, content_name),
uid=self.get_progress_id(session, content_name),
size=size,
data_cb=lambda data: hasher.update(data),
)
finished_d = content_data["finished_d"] = defer.Deferred()
args = [client, session, content_name, content_data]
finished_d.addCallbacks(self._finishedCb, self._finishedEb, args, None, args)
await self.host.trigger.asyncPoint(
finished_d.addCallbacks(self._finished_cb, self._finished_eb, args, None, args)
await self.host.trigger.async_point(
"XEP-0234_jingle_handler",
client, session, content_data, desc_elt
)
@ -652,7 +652,7 @@ class XEP_0234:
log.warning("FIXME: unmanaged action {}".format(action))
return desc_elt
def jingleSessionInfo(self, client, action, session, content_name, jingle_elt):
def jingle_session_info(self, client, action, session, content_name, jingle_elt):
"""Called on session-info action
manage checksum, and ignore <received/> element
@ -681,7 +681,7 @@ class XEP_0234:
file_elt = next(elt.elements(NS_JINGLE_FT, "file"))
except StopIteration:
raise exceptions.DataError
algo, file_data["given_file_hash"] = self._hash.parseHashElt(file_elt)
algo, file_data["given_file_hash"] = self._hash.parse_hash_elt(file_elt)
if algo != file_data.get("hash_algo"):
log.warning(
"Hash algorithm used in given hash ({peer_algo}) doesn't correspond to the one we have used ({our_algo}) [{profile}]".format(
@ -691,21 +691,21 @@ class XEP_0234:
)
)
else:
self._receiverTryTerminate(
self._receiver_try_terminate(
client, session, content_name, content_data
)
else:
raise NotImplementedError
def jingleTerminate(self, client, action, session, content_name, jingle_elt):
def jingle_terminate(self, client, action, session, content_name, jingle_elt):
if jingle_elt.decline:
# progress is the only way to tell to frontends that session has been declined
progress_id = self.getProgressId(session, content_name)
self.host.bridge.progressError(
progress_id = self.get_progress_id(session, content_name)
self.host.bridge.progress_error(
progress_id, C.PROGRESS_ERROR_DECLINED, client.profile
)
elif not jingle_elt.success:
progress_id = self.getProgressId(session, content_name)
progress_id = self.get_progress_id(session, content_name)
first_child = jingle_elt.firstChildElement()
if first_child is not None:
reason = first_child.name
@ -713,25 +713,25 @@ class XEP_0234:
reason = f"{reason} - {jingle_elt.text}"
else:
reason = C.PROGRESS_ERROR_FAILED
self.host.bridge.progressError(
self.host.bridge.progress_error(
progress_id, reason, client.profile
)
def _sendCheckSum(self, client, session, content_name, content_data):
def _send_check_sum(self, client, session, content_name, content_data):
"""Send the session-info with the hash checksum"""
file_data = content_data["application_data"]["file_data"]
hasher = file_data["hash_hasher"]
hash_ = hasher.hexdigest()
log.debug("Calculated hash: {}".format(hash_))
iq_elt, jingle_elt = self._j.buildSessionInfo(client, session)
iq_elt, jingle_elt = self._j.build_session_info(client, session)
checksum_elt = jingle_elt.addElement((NS_JINGLE_FT, "checksum"))
checksum_elt["creator"] = content_data["creator"]
checksum_elt["name"] = content_name
file_elt = checksum_elt.addElement("file")
file_elt.addChild(self._hash.buildHashElt(hash_))
file_elt.addChild(self._hash.build_hash_elt(hash_))
iq_elt.send()
def _receiverTryTerminate(
def _receiver_try_terminate(
self, client, session, content_name, content_data, last_try=False
):
"""Try to terminate the session
@ -753,7 +753,7 @@ class XEP_0234:
profile=client.profile
)
)
self._j.delayedContentTerminate(client, session, content_name)
self._j.delayed_content_terminate(client, session, content_name)
content_data["stream_object"].close()
return True
return False
@ -775,7 +775,7 @@ class XEP_0234:
algo=file_data["hash_algo"], given=given_hash, our=hash_
)
self._j.delayedContentTerminate(client, session, content_name)
self._j.delayed_content_terminate(client, session, content_name)
content_data["stream_object"].close(progress_metadata, error)
# we may have the last_try timer still active, so we try to cancel it
try:
@ -784,19 +784,19 @@ class XEP_0234:
pass
return True
def _finishedCb(self, __, client, session, content_name, content_data):
def _finished_cb(self, __, client, session, content_name, content_data):
log.info("File transfer terminated")
if content_data["senders"] != session["role"]:
# we terminate the session only if we are the receiver,
# as recommanded in XEP-0234 §2 (after example 6)
content_data["transfer_finished"] = True
if not self._receiverTryTerminate(
if not self._receiver_try_terminate(
client, session, content_name, content_data
):
# we have not received the hash yet, we wait 5 more seconds
content_data["last_try_timer"] = reactor.callLater(
5,
self._receiverTryTerminate,
self._receiver_try_terminate,
client,
session,
content_name,
@ -805,13 +805,13 @@ class XEP_0234:
)
else:
# we are the sender, we send the checksum
self._sendCheckSum(client, session, content_name, content_data)
self._send_check_sum(client, session, content_name, content_data)
content_data["stream_object"].close()
def _finishedEb(self, failure, client, session, content_name, content_data):
def _finished_eb(self, failure, client, session, content_name, content_data):
log.warning("Error while streaming file: {}".format(failure))
content_data["stream_object"].close()
self._j.contentTerminate(
self._j.content_terminate(
client, session, content_name, reason=self._j.REASON_FAILED_TRANSPORT
)