Mercurial > libervia-backend
diff sat/core/xmpp.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 | c23cad65ae99 |
line wrap: on
line diff
--- a/sat/core/xmpp.py Fri Apr 07 15:18:39 2023 +0200 +++ b/sat/core/xmpp.py Sat Apr 08 13:54:42 2023 +0200 @@ -89,20 +89,20 @@ class SatXMPPEntity(core_types.SatXMPPEntity): """Common code for Client and Component""" - # profile is added there when startConnection begins and removed when it is finished + # profile is added there when start_connection begins and removed when it is finished profiles_connecting = set() def __init__(self, host_app, profile, max_retries): factory = self.factory - # we monkey patch clientConnectionLost to handle networkEnabled/networkDisabled + # we monkey patch clientConnectionLost to handle network_enabled/network_disabled # and to allow plugins to tune reconnection mechanism clientConnectionFailed_ori = factory.clientConnectionFailed clientConnectionLost_ori = factory.clientConnectionLost factory.clientConnectionFailed = partial( - self.connectionTerminated, term_type="failed", cb=clientConnectionFailed_ori) + self.connection_terminated, term_type="failed", cb=clientConnectionFailed_ori) factory.clientConnectionLost = partial( - self.connectionTerminated, term_type="lost", cb=clientConnectionLost_ori) + self.connection_terminated, term_type="lost", cb=clientConnectionLost_ori) factory.maxRetries = max_retries factory.maxDelay = 30 @@ -129,41 +129,41 @@ ## initialisation ## - async def _callConnectionTriggers(self, connection_timer): + async def _call_connection_triggers(self, connection_timer): """Call conneting trigger prepare connected trigger @param plugins(iterable): plugins to use @return (list[object, callable]): plugin to trigger tuples with: - plugin instance - - profileConnected* triggers (to call after connection) + - profile_connected* triggers (to call after connection) """ plugin_conn_cb = [] - for plugin in self._getPluginsList(): + for plugin in self._get_plugins_list(): # we check if plugin handle client mode if plugin.is_handler: - plugin.getHandler(self).setHandlerParent(self) + plugin.get_handler(self).setHandlerParent(self) - # profileConnecting/profileConnected methods handling + # profile_connecting/profile_connected methods handling timer = connection_timer[plugin] = { "total": 0 } # profile connecting is called right now (before actually starting client) - connecting_cb = getattr(plugin, "profileConnecting", None) + connecting_cb = getattr(plugin, "profile_connecting", None) if connecting_cb is not None: connecting_start = time.time() - await utils.asDeferred(connecting_cb, self) + await utils.as_deferred(connecting_cb, self) timer["connecting"] = time.time() - connecting_start timer["total"] += timer["connecting"] # profile connected is called after client is ready and roster is got - connected_cb = getattr(plugin, "profileConnected", None) + connected_cb = getattr(plugin, "profile_connected", None) if connected_cb is not None: plugin_conn_cb.append((plugin, connected_cb)) return plugin_conn_cb - def _getPluginsList(self): + def _get_plugins_list(self): """Return list of plugin to use need to be implemented by subclasses @@ -172,10 +172,10 @@ """ raise NotImplementedError - def _createSubProtocols(self): + def _create_sub_protocols(self): return - def entityConnected(self): + def entity_connected(self): """Called once connection is done may return a Deferred, to perform initialisation tasks @@ -189,12 +189,12 @@ timer: Dict[str, float] ) -> None: connected_start = time.time() - await utils.asDeferred(callback, entity) + await utils.as_deferred(callback, entity) timer["connected"] = time.time() - connected_start timer["total"] += timer["connected"] @classmethod - async def startConnection(cls, host, profile, max_retries): + async def start_connection(cls, host, profile, max_retries): """instantiate the entity and start the connection""" # FIXME: reconnection doesn't seems to be handled correclty # (client is deleted then recreated from scratch) @@ -208,7 +208,7 @@ try: try: port = int( - host.memory.getParamA( + host.memory.param_get_a( C.FORCE_PORT_PARAM, "Connection", profile_key=profile ) ) @@ -218,11 +218,11 @@ None ) # will use default value 5222 or be retrieved from a DNS SRV record - password = await host.memory.asyncGetParamA( + password = await host.memory.param_get_a_async( "Password", "Connection", profile_key=profile ) - entity_jid_s = await host.memory.asyncGetParamA( + entity_jid_s = await host.memory.param_get_a_async( "JabberID", "Connection", profile_key=profile) entity_jid = jid.JID(entity_jid_s) @@ -231,13 +231,13 @@ # server returned one, as it will then stay stable in case of # reconnection. we only do that for client and if there is a user part, to # let server decide for anonymous login - resource_dict = await host.memory.storage.getPrivates( + resource_dict = await host.memory.storage.get_privates( "core:xmpp", ["resource"] , profile=profile) try: resource = resource_dict["resource"] except KeyError: resource = f"{C.APP_NAME_FILE}.{shortuuid.uuid()}" - await host.memory.storage.setPrivateValue( + await host.memory.storage.set_private_value( "core:xmpp", "resource", resource, profile=profile) log.info(_("We'll use the stable resource {resource}").format( @@ -245,7 +245,7 @@ entity_jid.resource = resource if profile in host.profiles: - if host.profiles[profile].isConnected(): + if host.profiles[profile].is_connected(): raise exceptions.InternalError( f"There is already a connected profile of name {profile!r} in " f"host") @@ -254,14 +254,14 @@ del host.profiles[profile] entity = host.profiles[profile] = cls( host, profile, entity_jid, password, - host.memory.getParamA(C.FORCE_SERVER_PARAM, "Connection", + host.memory.param_get_a(C.FORCE_SERVER_PARAM, "Connection", profile_key=profile) or None, port, max_retries, ) - await entity.encryption.loadSessions() + await entity.encryption.load_sessions() - entity._createSubProtocols() + entity._create_sub_protocols() entity.fallBack = SatFallbackHandler(host) entity.fallBack.setHandlerParent(entity) @@ -275,15 +275,15 @@ log.debug(_("setting plugins parents")) connection_timer: Dict[str, Dict[str, float]] = {} - plugin_conn_cb = await entity._callConnectionTriggers(connection_timer) + plugin_conn_cb = await entity._call_connection_triggers(connection_timer) entity.startService() await entity.conn_deferred - await defer.maybeDeferred(entity.entityConnected) + await defer.maybeDeferred(entity.entity_connected) - # Call profileConnected callback for all plugins, + # Call profile_connected callback for all plugins, # and print error message if any of them fails conn_cb_list = [] for plugin, callback in plugin_conn_cb: @@ -296,7 +296,7 @@ ) list_d = defer.DeferredList(conn_cb_list) - def logPluginResults(results): + def log_plugin_results(results): if not results: log.info("no plugin loaded") return @@ -347,22 +347,22 @@ ) await list_d.addCallback( - logPluginResults + log_plugin_results ) # FIXME: we should have a timeout here, and a way to know if a plugin freeze # TODO: mesure launch time of each plugin finally: cls.profiles_connecting.remove(profile) - def _disconnectionCb(self, __): + def _disconnection_cb(self, __): self._connected_d = None - def _disconnectionEb(self, failure_): + def _disconnection_eb(self, failure_): log.error(_("Error while disconnecting: {}".format(failure_))) def _authd(self, xmlstream): super(SatXMPPEntity, self)._authd(xmlstream) log.debug(_("{profile} identified").format(profile=self.profile)) - self.streamInitialized() + self.stream_initialized() def _finish_connection(self, __): if self.conn_deferred.called: @@ -371,14 +371,14 @@ else: self.conn_deferred.callback(None) - def streamInitialized(self): + def stream_initialized(self): """Called after _authd""" log.debug(_("XML stream is initialized")) if not self.host_app.trigger.point("xml_init", self): return - self.postStreamInit() + self.post_stream_init() - def postStreamInit(self): + def post_stream_init(self): """Workflow after stream initalisation.""" log.info( _("********** [{profile}] CONNECTED **********").format(profile=self.profile) @@ -387,9 +387,9 @@ # the following Deferred is used to know when we are connected # so we need to be set it to None when connection is lost self._connected_d = defer.Deferred() - self._connected_d.addCallback(self._cleanConnection) - self._connected_d.addCallback(self._disconnectionCb) - self._connected_d.addErrback(self._disconnectionEb) + self._connected_d.addCallback(self._clean_connection) + self._connected_d.addCallback(self._disconnection_cb) + self._connected_d.addErrback(self._disconnection_eb) # we send the signal to the clients self.host_app.bridge.connected(self.jid.full(), self.profile) @@ -421,7 +421,7 @@ ## connection ## - def connectionTerminated(self, connector, reason, term_type, cb): + def connection_terminated(self, connector, reason, term_type, cb): """Display disconnection reason, and call factory method This method is monkey patched to factory, allowing plugins to handle finely @@ -453,7 +453,7 @@ return return cb(connector, reason) - def networkDisabled(self): + def network_disabled(self): """Indicate that network has been completely disabled In other words, internet is not available anymore and transport must be stopped. @@ -466,7 +466,7 @@ if self.xmlstream is not None: self.xmlstream.transport.abortConnection() - def networkEnabled(self): + def network_enabled(self): """Indicate that network has been (re)enabled This happens when e.g. user activate WIFI connection. @@ -475,7 +475,7 @@ connector = self._saved_connector network_disabled = self._network_disabled except AttributeError: - # connection has not been stopped by networkDisabled + # connection has not been stopped by network_disabled # we don't have to restart it log.debug(f"no connection to restart [{self.profile}]") return @@ -496,12 +496,12 @@ self.host_app.trigger.point( "stream_hooks", self, receive_hooks, send_hooks) for hook in receive_hooks: - xs.addHook(C.STREAM_HOOK_RECEIVE, hook) + xs.add_hook(C.STREAM_HOOK_RECEIVE, hook) for hook in send_hooks: - xs.addHook(C.STREAM_HOOK_SEND, hook) + xs.add_hook(C.STREAM_HOOK_SEND, hook) super(SatXMPPEntity, self)._connected(xs) - def disconnectProfile(self, reason): + def disconnect_profile(self, reason): if self._connected_d is not None: self.host_app.bridge.disconnected( self.profile @@ -516,7 +516,7 @@ log.debug("continueTrying not set, purging entity") self._connected_d.callback(None) # and we remove references to this client - self.host_app.purgeEntity(self.profile) + self.host_app.purge_entity(self.profile) if not self.conn_deferred.called: if reason is None: @@ -535,7 +535,7 @@ try: # with invalid certificate, we should not retry to connect # so we delete saved connector to avoid reconnection if - # networkEnabled is called. + # network_enabled is called. del self._saved_connector except AttributeError: pass @@ -547,21 +547,21 @@ super(SatXMPPEntity, self)._disconnected(reason) if not self.host_app.trigger.point("disconnected", self, reason): return - self.disconnectProfile(reason) + self.disconnect_profile(reason) @defer.inlineCallbacks - def _cleanConnection(self, __): + def _clean_connection(self, __): """method called on disconnection - used to call profileDisconnected* triggers + used to call profile_disconnected* triggers """ - trigger_name = "profileDisconnected" - for plugin in self._getPluginsList(): + trigger_name = "profile_disconnected" + for plugin in self._get_plugins_list(): disconnected_cb = getattr(plugin, trigger_name, None) if disconnected_cb is not None: yield disconnected_cb(self) - def isConnected(self): + def is_connected(self): """Return True is client is fully connected client is considered fully connected if transport is started and all plugins @@ -574,7 +574,7 @@ return self._connected_d is not None and transport_connected - def entityDisconnect(self): + def entity_disconnect(self): if not self.host_app.trigger.point("disconnecting", self): return log.info(_("Disconnecting...")) @@ -609,7 +609,7 @@ ).toResponse(iq_elt) self.xmlstream.send(iq_error_elt) - def generateMessageXML( + def generate_message_xml( self, data: core_types.MessageData, post_xml_treatments: Optional[defer.Deferred] = None @@ -666,9 +666,9 @@ @property def is_admin(self) -> bool: """True if a client is an administrator with extra privileges""" - return self.host_app.memory.isAdmin(self.profile) + return self.host_app.memory.is_admin(self.profile) - def addPostXmlCallbacks(self, post_xml_treatments): + def add_post_xml_callbacks(self, post_xml_treatments): """Used to add class level callbacks at the end of the workflow @param post_xml_treatments(D): the same Deferred as in sendMessage trigger @@ -685,20 +685,20 @@ # (out of band transmission for instance). # e2e should have a priority of 0 here, and out of band transmission # a lower priority - if not (await self.host_app.trigger.asyncPoint("send", self, obj)): + if not (await self.host_app.trigger.async_point("send", self, obj)): return super().send(obj) def send(self, obj): defer.ensureDeferred(self.a_send(obj)) - async def sendMessageData(self, mess_data): + async def send_message_data(self, mess_data): """Convenient method to send message data to stream This method will send mess_data[u'xml'] to stream, but a trigger is there The trigger can't be cancelled, it's a good place for e2e encryption which don't handle full stanza encryption - This trigger can return a Deferred (it's an asyncPoint) + This trigger can return a Deferred (it's an async_point) @param mess_data(dict): message data as constructed by onMessage workflow @return (dict): mess_data (so it can be used in a deferred chain) """ @@ -707,7 +707,7 @@ # This is intented for e2e encryption which doesn't do full stanza # encryption (e.g. OTR) # This trigger point can't cancel the method - await self.host_app.trigger.asyncPoint("sendMessageData", self, mess_data, + await self.host_app.trigger.async_point("send_message_data", self, mess_data, triggers_no_cancel=True) await self.a_send(mess_data["xml"]) return mess_data @@ -762,7 +762,7 @@ elif not data["to"].resource: # we may have a groupchat message, we check if the we know this jid try: - entity_type = self.host_app.memory.getEntityDatum( + entity_type = self.host_app.memory.get_entity_datum( self, data["to"], C.ENTITY_TYPE ) # FIXME: should entity_type manage resources ? @@ -783,7 +783,7 @@ if not no_trigger and not send_only: # is the session encrypted? If so we indicate it in data - self.encryption.setEncryptionFlag(data) + self.encryption.set_encryption_flag(data) if not self.host_app.trigger.point( "sendMessage" + self.trigger_suffix, @@ -797,27 +797,27 @@ log.debug(_("Sending message (type {type}, to {to})") .format(type=data["type"], to=to_jid.full())) - pre_xml_treatments.addCallback(lambda __: self.generateMessageXML(data, post_xml_treatments)) + pre_xml_treatments.addCallback(lambda __: self.generate_message_xml(data, post_xml_treatments)) pre_xml_treatments.addCallback(lambda __: post_xml_treatments) - pre_xml_treatments.addErrback(self._cancelErrorTrap) + pre_xml_treatments.addErrback(self._cancel_error_trap) post_xml_treatments.addCallback( - lambda __: defer.ensureDeferred(self.sendMessageData(data)) + lambda __: defer.ensureDeferred(self.send_message_data(data)) ) if send_only: log.debug(_("Triggers, storage and echo have been inhibited by the " "'send_only' parameter")) else: - self.addPostXmlCallbacks(post_xml_treatments) - post_xml_treatments.addErrback(self._cancelErrorTrap) - post_xml_treatments.addErrback(self.host_app.logErrback) + self.add_post_xml_callbacks(post_xml_treatments) + post_xml_treatments.addErrback(self._cancel_error_trap) + post_xml_treatments.addErrback(self.host_app.log_errback) pre_xml_treatments.callback(data) return pre_xml_treatments - def _cancelErrorTrap(self, failure): + def _cancel_error_trap(self, failure): """A message sending can be cancelled by a plugin treatment""" failure.trap(exceptions.CancelError) - def isMessagePrintable(self, mess_data): + def is_message_printable(self, mess_data): """Return True if a message contain payload to show in frontends""" return ( mess_data["message"] or mess_data["subject"] @@ -825,7 +825,7 @@ or mess_data["type"] == C.MESS_TYPE_INFO ) - async def messageAddToHistory(self, data): + async def message_add_to_history(self, data): """Store message into database (for local history) @param data: message data dictionnary @@ -836,22 +836,22 @@ # and they will be added then # we need a message to store - if self.isMessagePrintable(data): - await self.host_app.memory.addToHistory(self, data) + if self.is_message_printable(data): + await self.host_app.memory.add_to_history(self, data) else: log.warning( "No message found" ) # empty body should be managed by plugins before this point return data - def messageGetBridgeArgs(self, data): + def message_get_bridge_args(self, data): """Generate args to use with bridge from data dict""" return (data["uid"], data["timestamp"], data["from"].full(), data["to"].full(), data["message"], data["subject"], data["type"], data_format.serialise(data["extra"])) - def messageSendToBridge(self, data): + def message_send_to_bridge(self, data): """Send message to bridge, so frontends can display it @param data: message data dictionnary @@ -862,11 +862,11 @@ # and they will be added the # we need a message to send something - if self.isMessagePrintable(data): + if self.is_message_printable(data): # We send back the message, so all frontends are aware of it - self.host_app.bridge.messageNew( - *self.messageGetBridgeArgs(data), + self.host_app.bridge.message_new( + *self.message_get_bridge_args(data), profile=self.profile ) else: @@ -913,7 +913,7 @@ # for now we consider Android devices to be always phones self.identities = [disco.DiscoIdentity("client", "phone", C.APP_NAME)] - hosts_map = host_app.memory.getConfig(None, "hosts_dict", {}) + hosts_map = host_app.memory.config_get(None, "hosts_dict", {}) if host is None and user_jid.host in hosts_map: host_data = hosts_map[user_jid.host] if isinstance(host_data, str): @@ -934,7 +934,7 @@ .format(host_ori=user_jid.host, host=host, port=port) ) - self.check_certificate = host_app.memory.getParamA( + self.check_certificate = host_app.memory.param_get_a( "check_certificate", "Connection", profile_key=profile) if self.check_certificate: @@ -954,19 +954,19 @@ "somebody may be spying on you. If you have no good reason to disable " "certificate validation, please activate \"Check certificate\" in your " "settings in \"Connection\" tab.")) - xml_tools.quickNote(host_app, self, msg, _("Security notice"), + xml_tools.quick_note(host_app, self, msg, _("Security notice"), level = C.XMLUI_DATA_LVL_WARNING) @property def server_jid(self): return jid.JID(self.jid.host) - def _getPluginsList(self): + def _get_plugins_list(self): for p in self.host_app.plugins.values(): if C.PLUG_MODE_CLIENT in p._info["modes"]: yield p - def _createSubProtocols(self): + def _create_sub_protocols(self): self.messageProt = SatMessageProtocol(self.host_app) self.messageProt.setHandlerParent(self) @@ -977,26 +977,26 @@ self.presence.setHandlerParent(self) @classmethod - async def startConnection(cls, host, profile, max_retries): + async def start_connection(cls, host, profile, max_retries): try: - await super(SatXMPPClient, cls).startConnection(host, profile, max_retries) + await super(SatXMPPClient, cls).start_connection(host, profile, max_retries) except exceptions.CancelError as e: - log.warning(f"startConnection cancelled: {e}") + log.warning(f"start_connection cancelled: {e}") return entity = host.profiles[profile] # we finally send our presence entity.presence.available() - def entityConnected(self): + def entity_connected(self): # we want to be sure that we got the roster return self.roster.got_roster - def addPostXmlCallbacks(self, post_xml_treatments): - post_xml_treatments.addCallback(self.messageProt.completeAttachments) + def add_post_xml_callbacks(self, post_xml_treatments): + post_xml_treatments.addCallback(self.messageProt.complete_attachments) post_xml_treatments.addCallback( - lambda ret: defer.ensureDeferred(self.messageAddToHistory(ret)) + lambda ret: defer.ensureDeferred(self.message_add_to_history(ret)) ) - post_xml_treatments.addCallback(self.messageSendToBridge) + post_xml_treatments.addCallback(self.message_send_to_bridge) def feedback( self, @@ -1015,7 +1015,7 @@ """ if extra is None: extra = {} - self.host_app.bridge.messageNew( + self.host_app.bridge.message_new( uid=str(uuid.uuid4()), timestamp=time.time(), from_jid=self.jid.full(), @@ -1028,7 +1028,7 @@ ) def _finish_connection(self, __): - d = self.roster.requestRoster() + d = self.roster.request_roster() d.addCallback(lambda __: super(SatXMPPClient, self)._finish_connection(__)) @@ -1057,7 +1057,7 @@ port = C.XMPP_COMPONENT_PORT ## entry point ## - entry_point = host_app.memory.getEntryPoint(profile) + entry_point = host_app.memory.get_entry_point(profile) try: self.entry_plugin = host_app.plugins[entry_point] except KeyError: @@ -1090,11 +1090,11 @@ def is_admin(self) -> bool: return False - def _createSubProtocols(self): + def _create_sub_protocols(self): self.messageProt = SatMessageProtocol(self.host_app) self.messageProt.setHandlerParent(self) - def _buildDependencies(self, current, plugins, required=True): + def _build_dependencies(self, current, plugins, required=True): """build recursively dependencies needed for a plugin this method build list of plugin needed for a component and raises @@ -1128,7 +1128,7 @@ # plugins are already loaded as dependencies # so we know they are in self.host_app.plugins dep = self.host_app.plugins[import_name] - self._buildDependencies(dep, plugins) + self._build_dependencies(dep, plugins) for import_name in current._info.get(C.PI_RECOMMENDATIONS, []): # here plugins are only recommendations, @@ -1137,21 +1137,21 @@ dep = self.host_app.plugins[import_name] except KeyError: continue - self._buildDependencies(dep, plugins, required=False) + self._build_dependencies(dep, plugins, required=False) if current not in plugins: # current can be required for several plugins and so # it can already be present in the list plugins.append(current) - def _getPluginsList(self): + def _get_plugins_list(self): # XXX: for component we don't launch all plugins triggers # but only the ones from which there is a dependency plugins = [] - self._buildDependencies(self.entry_plugin, plugins) + self._build_dependencies(self.entry_plugin, plugins) return plugins - def entityConnected(self): + def entity_connected(self): # we can now launch entry point try: start_cb = self.entry_plugin.componentStart @@ -1160,13 +1160,13 @@ else: return start_cb(self) - def addPostXmlCallbacks(self, post_xml_treatments): + def add_post_xml_callbacks(self, post_xml_treatments): if self.sendHistory: post_xml_treatments.addCallback( - lambda ret: defer.ensureDeferred(self.messageAddToHistory(ret)) + lambda ret: defer.ensureDeferred(self.message_add_to_history(ret)) ) - def getOwnerFromJid(self, to_jid: jid.JID) -> jid.JID: + def get_owner_from_jid(self, to_jid: jid.JID) -> jid.JID: """Retrieve "owner" of a component resource from the destination jid of the request This method needs plugin XEP-0106 for unescaping, if you use it you must add the @@ -1187,7 +1187,7 @@ # only user part is specified, we use our own host to build the full jid return jid.JID(None, (user, self.host, None)) - def getOwnerAndPeer(self, iq_elt: domish.Element) -> Tuple[jid.JID, jid.JID]: + def get_owner_and_peer(self, iq_elt: domish.Element) -> Tuple[jid.JID, jid.JID]: """Retrieve owner of a component jid, and the jid of the requesting peer "owner" is found by either unescaping full jid from node, or by combining node @@ -1198,14 +1198,14 @@ """ to_jid = jid.JID(iq_elt['to']) if to_jid.user: - owner = self.getOwnerFromJid(to_jid) + owner = self.get_owner_from_jid(to_jid) else: owner = jid.JID(iq_elt["from"]).userhostJID() peer_jid = jid.JID(iq_elt["from"]) return peer_jid, owner - def getVirtualClient(self, jid_: jid.JID) -> SatXMPPEntity: + def get_virtual_client(self, jid_: jid.JID) -> SatXMPPEntity: """Get client for this component with a specified jid This is needed to perform operations with a virtual JID corresponding to a virtual @@ -1229,13 +1229,13 @@ def client(self): return self.parent - def normalizeNS(self, elt: domish.Element, namespace: Optional[str]) -> None: + def normalize_ns(self, elt: domish.Element, namespace: Optional[str]) -> None: if elt.uri == namespace: elt.defaultUri = elt.uri = C.NS_CLIENT for child in elt.elements(): - self.normalizeNS(child, namespace) + self.normalize_ns(child, namespace) - def parseMessage(self, message_elt): + def parse_message(self, message_elt): """Parse a message XML and return message_data @param message_elt(domish.Element): raw <message> xml @@ -1245,13 +1245,13 @@ """ if message_elt.name != "message": log.warning(_( - "parseMessage used with a non <message/> stanza, ignoring: {xml}" + "parse_message used with a non <message/> stanza, ignoring: {xml}" .format(xml=message_elt.toXml()))) return {} if message_elt.uri == None: # xmlns may be None when wokkel element parsing strip out root namespace - self.normalizeNS(message_elt, None) + self.normalize_ns(message_elt, None) elif message_elt.uri != C.NS_CLIENT: log.warning(_( "received <message> with a wrong namespace: {xml}" @@ -1297,7 +1297,7 @@ received_timestamp = message_elt._received_timestamp except AttributeError: # message_elt._received_timestamp should have been set in onMessage - # but if parseMessage is called directly, it can be missing + # but if parse_message is called directly, it can be missing log.debug("missing received timestamp for {message_elt}".format( message_elt=message_elt)) received_timestamp = time.time() @@ -1316,7 +1316,7 @@ self.host.trigger.point("message_parse", client, message_elt, data) return data - def _onMessageStartWorkflow(self, cont, client, message_elt, post_treat): + def _on_message_start_workflow(self, cont, client, message_elt, post_treat): """Parse message and do post treatments It is the first callback called after messageReceived trigger @@ -1327,16 +1327,16 @@ """ if not cont: return - data = self.parseMessage(message_elt) - post_treat.addCallback(self.completeAttachments) - post_treat.addCallback(self.skipEmptyMessage) + data = self.parse_message(message_elt) + post_treat.addCallback(self.complete_attachments) + post_treat.addCallback(self.skip_empty_message) if not client.is_component or client.receiveHistory: post_treat.addCallback( - lambda ret: defer.ensureDeferred(self.addToHistory(ret)) + lambda ret: defer.ensureDeferred(self.add_to_history(ret)) ) if not client.is_component: - post_treat.addCallback(self.bridgeSignal, data) - post_treat.addErrback(self.cancelErrorTrap) + post_treat.addCallback(self.bridge_signal, data) + post_treat.addErrback(self.cancel_error_trap) post_treat.callback(data) def onMessage(self, message_elt): @@ -1348,18 +1348,18 @@ log.debug(_("got message from: {from_}").format(from_=message_elt["from"])) if self.client.is_component and message_elt.uri == component.NS_COMPONENT_ACCEPT: # we use client namespace all the time to simplify parsing - self.normalizeNS(message_elt, component.NS_COMPONENT_ACCEPT) + self.normalize_ns(message_elt, component.NS_COMPONENT_ACCEPT) # plugin can add their treatments to this deferred post_treat = defer.Deferred() - d = self.host.trigger.asyncPoint( + d = self.host.trigger.async_point( "messageReceived", client, message_elt, post_treat ) - d.addCallback(self._onMessageStartWorkflow, client, message_elt, post_treat) + d.addCallback(self._on_message_start_workflow, client, message_elt, post_treat) - def completeAttachments(self, data): + def complete_attachments(self, data): """Complete missing metadata of attachments""" for attachment in data['extra'].get(C.KEY_ATTACHMENTS, []): if "name" not in attachment and "url" in attachment: @@ -1374,24 +1374,24 @@ return data - def skipEmptyMessage(self, data): + def skip_empty_message(self, data): if not data["message"] and not data["extra"] and not data["subject"]: raise failure.Failure(exceptions.CancelError("Cancelled empty message")) return data - async def addToHistory(self, data): + async def add_to_history(self, data): if data.pop("history", None) == C.HISTORY_SKIP: log.debug("history is skipped as requested") data["extra"]["history"] = C.HISTORY_SKIP else: # we need a message to store - if self.parent.isMessagePrintable(data): - return await self.host.memory.addToHistory(self.parent, data) + if self.parent.is_message_printable(data): + return await self.host.memory.add_to_history(self.parent, data) else: log.debug("not storing empty message to history: {data}" .format(data=data)) - def bridgeSignal(self, __, data): + def bridge_signal(self, __, data): try: data["extra"]["received_timestamp"] = str(data["received_timestamp"]) data["extra"]["delay_sender"] = data["delay_sender"] @@ -1400,8 +1400,8 @@ if self.client.encryption.isEncrypted(data): data["extra"]["encrypted"] = True if data is not None: - if self.parent.isMessagePrintable(data): - self.host.bridge.messageNew( + if self.parent.is_message_printable(data): + self.host.bridge.message_new( data["uid"], data["timestamp"], data["from"].full(), @@ -1417,7 +1417,7 @@ data=data)) return data - def cancelErrorTrap(self, failure_): + def cancel_error_trap(self, failure_): """A message sending can be cancelled by a plugin treatment""" failure_.trap(exceptions.CancelError) @@ -1433,7 +1433,7 @@ self._groups = {} # map from groups to jids: key=group value=set of jids def __contains__(self, entity_jid): - return self.isJidInRoster(entity_jid) + return self.is_jid_in_roster(entity_jid) @property def versioning(self): @@ -1449,7 +1449,7 @@ """ return persistent.PersistentDict(NS_ROSTER_VER, self.parent.profile) - def _registerItem(self, item): + def _register_item(self, item): """Register item in local cache item must be already registered in self._jids before this method is called @@ -1477,7 +1477,7 @@ self._groups.setdefault(group, set()).add(item.entity) @defer.inlineCallbacks - def _cacheRoster(self, version): + def _cache_roster(self, version): """Serialise local roster and save it to storage @param version(unicode): version of roster in local cache @@ -1501,10 +1501,10 @@ yield roster_cache.clear() self._jids.clear() self._groups.clear() - yield self.requestRoster() + yield self.request_roster() @defer.inlineCallbacks - def requestRoster(self): + def request_roster(self): """Ask the server for Roster list """ if self.versioning: log.info(_("our server support roster versioning, we use it")) @@ -1526,7 +1526,7 @@ roster_item_elt = generic.parseXml(roster_item_elt_s.encode('utf-8')) roster_item = xmppim.RosterItem.fromElement(roster_item_elt) self._jids[roster_jid] = roster_item - self._registerItem(roster_item) + self._register_item(roster_item) else: log.warning(_("our server doesn't support roster versioning")) version = None @@ -1553,8 +1553,8 @@ ) self.removeItem(item.entity) # FIXME: to be checked else: - self._registerItem(item) - yield self._cacheRoster(roster.version) + self._register_item(item) + yield self._cache_roster(roster.version) if not self.got_roster.called: # got_roster may already be called if we use resync() @@ -1567,7 +1567,7 @@ """ return xmppim.RosterClientProtocol.removeItem(self, to_jid) - def getAttributes(self, item): + def get_attributes(self, item): """Return dictionary of attributes as used in bridge from a RosterItem @param item: RosterItem @@ -1602,9 +1602,9 @@ except KeyError: pass # no previous item registration (or it's been cleared) self._jids[entity] = item - self._registerItem(item) - self.host.bridge.newContact( - entity.full(), self.getAttributes(item), list(item.groups), + self._register_item(item) + self.host.bridge.contact_new( + entity.full(), self.get_attributes(item), list(item.groups), self.parent.profile ) @@ -1645,13 +1645,13 @@ ) # then we send the bridge signal - self.host.bridge.contactDeleted(entity.full(), self.parent.profile) + self.host.bridge.contact_deleted(entity.full(), self.parent.profile) - def getGroups(self): + def get_groups(self): """Return a list of groups""" return list(self._groups.keys()) - def getItem(self, entity_jid): + def get_item(self, entity_jid): """Return RosterItem for a given jid @param entity_jid(jid.JID): jid of the contact @@ -1660,18 +1660,18 @@ """ return self._jids.get(entity_jid, None) - def getJids(self): + def get_jids(self): """Return all jids of the roster""" return list(self._jids.keys()) - def isJidInRoster(self, entity_jid): + def is_jid_in_roster(self, entity_jid): """Return True if jid is in roster""" if not isinstance(entity_jid, jid.JID): raise exceptions.InternalError( f"a JID is expected, not {type(entity_jid)}: {entity_jid!r}") return entity_jid in self._jids - def isSubscribedFrom(self, entity_jid: jid.JID) -> bool: + def is_subscribed_from(self, entity_jid: jid.JID) -> bool: """Return True if entity is authorised to see our presence""" try: item = self._jids[entity_jid.userhostJID()] @@ -1679,7 +1679,7 @@ return False return item.subscriptionFrom - def isSubscribedTo(self, entity_jid: jid.JID) -> bool: + def is_subscribed_to(self, entity_jid: jid.JID) -> bool: """Return True if we are subscribed to entity""" try: item = self._jids[entity_jid.userhostJID()] @@ -1687,17 +1687,17 @@ return False return item.subscriptionTo - def getItems(self): + def get_items(self): """Return all items of the roster""" return list(self._jids.values()) - def getJidsFromGroup(self, group): + def get_jids_from_group(self, group): try: return self._groups[group] except KeyError: raise exceptions.UnknownGroupError(group) - def getJidsSet(self, type_, groups=None): + def get_jids_set(self, type_, groups=None): """Helper method to get a set of jids @param type_(unicode): one of: @@ -1710,22 +1710,22 @@ raise ValueError("groups must not be set for {} type".format(C.ALL)) if type_ == C.ALL: - return set(self.getJids()) + return set(self.get_jids()) elif type_ == C.GROUP: jids = set() for group in groups: - jids.update(self.getJidsFromGroup(group)) + jids.update(self.get_jids_from_group(group)) return jids else: raise ValueError("Unexpected type_ {}".format(type_)) - def getNick(self, entity_jid): + def get_nick(self, entity_jid): """Return a nick name for an entity return nick choosed by user if available else return user part of entity_jid """ - item = self.getItem(entity_jid) + item = self.get_item(entity_jid) if item is None: return entity_jid.user else: @@ -1761,12 +1761,12 @@ ): return - self.host.memory.setPresenceStatus( + self.host.memory.set_presence_status( entity, show or "", int(priority), statuses, self.parent.profile ) # now it's time to notify frontends - self.host.bridge.presenceUpdate( + self.host.bridge.presence_update( entity.full(), show or "", int(priority), statuses, self.parent.profile ) @@ -1791,7 +1791,7 @@ # if the entity is not known yet in this session or is already unavailable, # there is no need to send an unavailable signal try: - presence = self.host.memory.getEntityDatum( + presence = self.host.memory.get_entity_datum( self.client, entity, "presence" ) except (KeyError, exceptions.UnknownEntityError): @@ -1799,7 +1799,7 @@ pass else: if presence.show != C.PRESENCE_UNAVAILABLE: - self.host.bridge.presenceUpdate( + self.host.bridge.presence_update( entity.full(), C.PRESENCE_UNAVAILABLE, 0, @@ -1807,7 +1807,7 @@ self.parent.profile, ) - self.host.memory.setPresenceStatus( + self.host.memory.set_presence_status( entity, C.PRESENCE_UNAVAILABLE, 0, statuses, self.parent.profile ) @@ -1822,7 +1822,7 @@ if priority is None: try: priority = int( - self.host.memory.getParamA( + self.host.memory.param_get_a( "Priority", "Connection", profile_key=self.parent.profile ) ) @@ -1851,8 +1851,8 @@ def subscribed(self, entity): yield self.parent.roster.got_roster xmppim.PresenceClientProtocol.subscribed(self, entity) - self.host.memory.delWaitingSub(entity.userhost(), self.parent.profile) - item = self.parent.roster.getItem(entity) + self.host.memory.del_waiting_sub(entity.userhost(), self.parent.profile) + item = self.parent.roster.get_item(entity) if ( not item or not item.subscriptionTo ): # we automatically subscribe to 'to' presence @@ -1861,7 +1861,7 @@ def unsubscribed(self, entity): xmppim.PresenceClientProtocol.unsubscribed(self, entity) - self.host.memory.delWaitingSub(entity.userhost(), self.parent.profile) + self.host.memory.del_waiting_sub(entity.userhost(), self.parent.profile) def subscribedReceived(self, entity): log.debug(_("subscription approved for [%s]") % entity.userhost()) @@ -1875,14 +1875,14 @@ def subscribeReceived(self, entity): log.debug(_("subscription request from [%s]") % entity.userhost()) yield self.parent.roster.got_roster - item = self.parent.roster.getItem(entity) + item = self.parent.roster.get_item(entity) if item and item.subscriptionTo: # We automatically accept subscription if we are already subscribed to # contact presence log.debug(_("sending automatic subscription acceptance")) self.subscribed(entity) else: - self.host.memory.addWaitingSub( + self.host.memory.add_waiting_sub( "subscribe", entity.userhost(), self.parent.profile ) self.host.bridge.subscribe( @@ -1893,10 +1893,10 @@ def unsubscribeReceived(self, entity): log.debug(_("unsubscription asked for [%s]") % entity.userhost()) yield self.parent.roster.got_roster - item = self.parent.roster.getItem(entity) + item = self.parent.roster.get_item(entity) if item and item.subscriptionFrom: # we automatically remove contact log.debug(_("automatic contact deletion")) - self.host.delContact(entity, self.parent.profile) + self.host.contact_del(entity, self.parent.profile) self.host.bridge.subscribe("unsubscribe", entity.userhost(), self.parent.profile)