Mercurial > libervia-backend
diff sat/core/sat_main.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 | 7bf7677b893d |
children | 2594e1951cf7 |
line wrap: on
line diff
--- a/sat/core/sat_main.py Fri Apr 07 15:18:39 2023 +0200 +++ b/sat/core/sat_main.py Sat Apr 08 13:54:42 2023 +0200 @@ -26,7 +26,7 @@ from wokkel.data_form import Option import sat -from sat.core.i18n import _, D_, languageSwitch +from sat.core.i18n import _, D_, language_switch from sat.core import patches patches.apply() from twisted.application import service @@ -69,7 +69,7 @@ self.profiles = {} self.plugins = {} # map for short name to whole namespace, - # extended by plugins with registerNamespace + # extended by plugins with register_namespace self.ns_map = { "x-data": xmpp.NS_X_DATA, "disco#info": xmpp.NS_DISCO_INFO, @@ -84,7 +84,7 @@ bridge_name = ( os.getenv("LIBERVIA_BRIDGE_NAME") - or self.memory.getConfig("", "bridge", "dbus") + or self.memory.config_get("", "bridge", "dbus") ) bridge_module = dynamic_import.bridge(bridge_name) @@ -93,9 +93,9 @@ sys.exit(1) log.info(f"using {bridge_name} bridge") try: - self.bridge = bridge_module.Bridge() + self.bridge = bridge_module.bridge() except exceptions.BridgeInitError: - log.exception("Bridge can't be initialised, can't start Libervia Backend") + log.exception("bridge can't be initialised, can't start Libervia Backend") sys.exit(1) defer.ensureDeferred(self._post_init()) @@ -118,7 +118,7 @@ return self._version_cache except AttributeError: self._version_cache = "{} « {} » ({})".format( - version, C.APP_RELEASE_NAME, utils.getRepositoryData(sat) + version, C.APP_RELEASE_NAME, utils.get_repository_data(sat) ) return self._version_cache else: @@ -130,7 +130,7 @@ async def _post_init(self): try: - bridge_pi = self.bridge.postInit + bridge_pi = self.bridge.post_init except AttributeError: pass else: @@ -142,84 +142,84 @@ reactor.callLater(0, self.stop) return - self.bridge.register_method("getReady", lambda: self.initialised) - self.bridge.register_method("getVersion", lambda: self.full_version) - self.bridge.register_method("getFeatures", self.getFeatures) - self.bridge.register_method("profileNameGet", self.memory.getProfileName) - self.bridge.register_method("profilesListGet", self.memory.getProfilesList) - self.bridge.register_method("getEntityData", self.memory._getEntityData) - self.bridge.register_method("getEntitiesData", self.memory._getEntitiesData) - self.bridge.register_method("profileCreate", self.memory.createProfile) - self.bridge.register_method("asyncDeleteProfile", self.memory.asyncDeleteProfile) - self.bridge.register_method("profileStartSession", self.memory.startSession) + self.bridge.register_method("ready_get", lambda: self.initialised) + self.bridge.register_method("version_get", lambda: self.full_version) + self.bridge.register_method("features_get", self.features_get) + self.bridge.register_method("profile_name_get", self.memory.get_profile_name) + self.bridge.register_method("profiles_list_get", self.memory.get_profiles_list) + self.bridge.register_method("entity_data_get", self.memory._get_entity_data) + self.bridge.register_method("entities_data_get", self.memory._get_entities_data) + self.bridge.register_method("profile_create", self.memory.create_profile) + self.bridge.register_method("profile_delete_async", self.memory.profile_delete_async) + self.bridge.register_method("profile_start_session", self.memory.start_session) self.bridge.register_method( - "profileIsSessionStarted", self.memory._isSessionStarted + "profile_is_session_started", self.memory._is_session_started ) - self.bridge.register_method("profileSetDefault", self.memory.profileSetDefault) + self.bridge.register_method("profile_set_default", self.memory.profile_set_default) self.bridge.register_method("connect", self._connect) self.bridge.register_method("disconnect", self.disconnect) - self.bridge.register_method("contactGet", self._contactGet) - self.bridge.register_method("getContacts", self.getContacts) - self.bridge.register_method("getContactsFromGroup", self.getContactsFromGroup) - self.bridge.register_method("getMainResource", self.memory._getMainResource) + self.bridge.register_method("contact_get", self._contact_get) + self.bridge.register_method("contacts_get", self.contacts_get) + self.bridge.register_method("contacts_get_from_group", self.contacts_get_from_group) + self.bridge.register_method("main_resource_get", self.memory._get_main_resource) self.bridge.register_method( - "getPresenceStatuses", self.memory._getPresenceStatuses + "presence_statuses_get", self.memory._get_presence_statuses ) - self.bridge.register_method("getWaitingSub", self.memory.getWaitingSub) - self.bridge.register_method("messageSend", self._messageSend) - self.bridge.register_method("messageEncryptionStart", - self._messageEncryptionStart) - self.bridge.register_method("messageEncryptionStop", - self._messageEncryptionStop) - self.bridge.register_method("messageEncryptionGet", - self._messageEncryptionGet) - self.bridge.register_method("encryptionNamespaceGet", - self._encryptionNamespaceGet) - self.bridge.register_method("encryptionPluginsGet", self._encryptionPluginsGet) - self.bridge.register_method("encryptionTrustUIGet", self._encryptionTrustUIGet) - self.bridge.register_method("getConfig", self._getConfig) - self.bridge.register_method("setParam", self.setParam) - self.bridge.register_method("getParamA", self.memory.getStringParamA) - self.bridge.register_method("privateDataGet", self.memory._privateDataGet) - self.bridge.register_method("privateDataSet", self.memory._privateDataSet) - self.bridge.register_method("privateDataDelete", self.memory._privateDataDelete) - self.bridge.register_method("asyncGetParamA", self.memory.asyncGetStringParamA) + self.bridge.register_method("sub_waiting_get", self.memory.sub_waiting_get) + self.bridge.register_method("message_send", self._message_send) + self.bridge.register_method("message_encryption_start", + self._message_encryption_start) + self.bridge.register_method("message_encryption_stop", + self._message_encryption_stop) + self.bridge.register_method("message_encryption_get", + self._message_encryption_get) + self.bridge.register_method("encryption_namespace_get", + self._encryption_namespace_get) + self.bridge.register_method("encryption_plugins_get", self._encryption_plugins_get) + self.bridge.register_method("encryption_trust_ui_get", self._encryption_trust_ui_get) + self.bridge.register_method("config_get", self._get_config) + self.bridge.register_method("param_set", self.param_set) + self.bridge.register_method("param_get_a", self.memory.get_string_param_a) + self.bridge.register_method("private_data_get", self.memory._private_data_get) + self.bridge.register_method("private_data_set", self.memory._private_data_set) + self.bridge.register_method("private_data_delete", self.memory._private_data_delete) + self.bridge.register_method("param_get_a_async", self.memory.async_get_string_param_a) self.bridge.register_method( - "asyncGetParamsValuesFromCategory", - self.memory._getParamsValuesFromCategory, + "params_values_from_category_get_async", + self.memory._get_params_values_from_category, ) - self.bridge.register_method("getParamsUI", self.memory._getParamsUI) + self.bridge.register_method("param_ui_get", self.memory._get_params_ui) self.bridge.register_method( - "getParamsCategories", self.memory.getParamsCategories + "params_categories_get", self.memory.params_categories_get ) - self.bridge.register_method("paramsRegisterApp", self.memory.paramsRegisterApp) - self.bridge.register_method("historyGet", self.memory._historyGet) - self.bridge.register_method("setPresence", self._setPresence) + self.bridge.register_method("params_register_app", self.memory.params_register_app) + self.bridge.register_method("history_get", self.memory._history_get) + self.bridge.register_method("presence_set", self._set_presence) self.bridge.register_method("subscription", self.subscription) - self.bridge.register_method("addContact", self._addContact) - self.bridge.register_method("updateContact", self._updateContact) - self.bridge.register_method("delContact", self._delContact) - self.bridge.register_method("rosterResync", self._rosterResync) - self.bridge.register_method("isConnected", self.isConnected) - self.bridge.register_method("launchAction", self.launchCallback) - self.bridge.register_method("actionsGet", self.actionsGet) - self.bridge.register_method("progressGet", self._progressGet) - self.bridge.register_method("progressGetAll", self._progressGetAll) - self.bridge.register_method("menusGet", self.getMenus) - self.bridge.register_method("menuHelpGet", self.getMenuHelp) - self.bridge.register_method("menuLaunch", self._launchMenu) - self.bridge.register_method("discoInfos", self.memory.disco._discoInfos) - self.bridge.register_method("discoItems", self.memory.disco._discoItems) - self.bridge.register_method("discoFindByFeatures", self._findByFeatures) - self.bridge.register_method("saveParamsTemplate", self.memory.save_xml) - self.bridge.register_method("loadParamsTemplate", self.memory.load_xml) - self.bridge.register_method("sessionInfosGet", self.getSessionInfos) - self.bridge.register_method("devicesInfosGet", self._getDevicesInfos) - self.bridge.register_method("namespacesGet", self.getNamespaces) - self.bridge.register_method("imageCheck", self._imageCheck) - self.bridge.register_method("imageResize", self._imageResize) - self.bridge.register_method("imageGeneratePreview", self._imageGeneratePreview) - self.bridge.register_method("imageConvert", self._imageConvert) + self.bridge.register_method("contact_add", self._add_contact) + self.bridge.register_method("contact_update", self._update_contact) + self.bridge.register_method("contact_del", self._del_contact) + self.bridge.register_method("roster_resync", self._roster_resync) + self.bridge.register_method("is_connected", self.is_connected) + self.bridge.register_method("action_launch", self.launch_callback) + self.bridge.register_method("actions_get", self.actions_get) + self.bridge.register_method("progress_get", self._progress_get) + self.bridge.register_method("progress_get_all", self._progress_get_all) + self.bridge.register_method("menus_get", self.get_menus) + self.bridge.register_method("menu_help_get", self.get_menu_help) + self.bridge.register_method("menu_launch", self._launch_menu) + self.bridge.register_method("disco_infos", self.memory.disco._disco_infos) + self.bridge.register_method("disco_items", self.memory.disco._disco_items) + self.bridge.register_method("disco_find_by_features", self._find_by_features) + self.bridge.register_method("params_template_save", self.memory.save_xml) + self.bridge.register_method("params_template_load", self.memory.load_xml) + self.bridge.register_method("session_infos_get", self.get_session_infos) + self.bridge.register_method("devices_infos_get", self._get_devices_infos) + self.bridge.register_method("namespaces_get", self.get_namespaces) + self.bridge.register_method("image_check", self._image_check) + self.bridge.register_method("image_resize", self._image_resize) + self.bridge.register_method("image_generate_preview", self._image_generate_preview) + self.bridge.register_method("image_convert", self._image_convert) await self.memory.initialise() @@ -232,14 +232,14 @@ except Exception as e: log.error(f"Could not initialize backend: {e}") sys.exit(1) - self._addBaseMenus() + self._add_base_menus() self.initialised.callback(None) log.info(_("Backend is ready")) # profile autoconnection must be done after self.initialised is called because - # startSession waits for it. - autoconnect_dict = await self.memory.storage.getIndParamValues( + # start_session waits for it. + autoconnect_dict = await self.memory.storage.get_ind_param_values( category='Connection', name='autoconnect_backend', ) profiles_autoconnect = [p for p, v in autoconnect_dict.items() if C.bool(v)] @@ -264,9 +264,9 @@ reason = result) ) - def _addBaseMenus(self): + def _add_base_menus(self): """Add base menus""" - encryption.EncryptionHandler._importMenus(self) + encryption.EncryptionHandler._import_menus(self) def _unimport_plugin(self, plugin_path): """remove a plugin from sys.modules if it is there""" @@ -276,7 +276,7 @@ pass def _import_plugins(self): - """Import all plugins found in plugins directory""" + """import all plugins found in plugins directory""" # FIXME: module imported but cancelled should be deleted # TODO: make this more generic and reusable in tools.common # FIXME: should use imp @@ -446,7 +446,7 @@ self.plugins[import_name]._info = plugin_info # TODO: test xmppclient presence and register handler parent - def pluginsUnload(self): + def plugins_unload(self): """Call unload method on every loaded plugin, if exists @return (D): A deferred which return None when all method have been called @@ -461,11 +461,11 @@ except AttributeError: continue else: - defers_list.append(utils.asDeferred(unload)) + defers_list.append(utils.as_deferred(unload)) return defers_list def _connect(self, profile_key, password="", options=None): - profile = self.memory.getProfileName(profile_key) + profile = self.memory.get_profile_name(profile_key) return defer.ensureDeferred(self.connect(profile, password, options)) async def connect( @@ -487,16 +487,16 @@ if options is None: options = {} - await self.memory.startSession(password, profile) + await self.memory.start_session(password, profile) - if self.isConnected(profile): + if self.is_connected(profile): log.info(_("already connected !")) return True - if self.memory.isComponent(profile): - await xmpp.SatXMPPComponent.startConnection(self, profile, max_retries) + if self.memory.is_component(profile): + await xmpp.SatXMPPComponent.start_connection(self, profile, max_retries) else: - await xmpp.SatXMPPClient.startConnection(self, profile, max_retries) + await xmpp.SatXMPPClient.start_connection(self, profile, max_retries) return False @@ -504,15 +504,15 @@ """disconnect from jabber server""" # FIXME: client should not be deleted if only disconnected # it shoud be deleted only when session is finished - if not self.isConnected(profile_key): - # isConnected is checked here and not on client + if not self.is_connected(profile_key): + # is_connected is checked here and not on client # because client is deleted when session is ended log.info(_("not connected !")) return defer.succeed(None) - client = self.getClient(profile_key) - return client.entityDisconnect() + client = self.get_client(profile_key) + return client.entity_disconnect() - def getFeatures(self, profile_key=C.PROF_KEY_NONE): + def features_get(self, profile_key=C.PROF_KEY_NONE): """Get available features Return list of activated plugins and plugin specific data @@ -528,7 +528,7 @@ try: # FIXME: there is no method yet to check profile session # as soon as one is implemented, it should be used here - self.getClient(profile_key) + self.get_client(profile_key) except KeyError: log.warning("Requesting features for a profile outside a session") profile_key = C.PROF_KEY_NONE @@ -538,14 +538,14 @@ features = [] for import_name, plugin in self.plugins.items(): try: - features_d = utils.asDeferred(plugin.getFeatures, profile_key) + features_d = utils.as_deferred(plugin.features_get, profile_key) except AttributeError: features_d = defer.succeed({}) features.append(features_d) d_list = defer.DeferredList(features) - def buildFeatures(result, import_names): + def build_features(result, import_names): assert len(result) == len(import_names) ret = {} for name, (success, data) in zip(import_names, result): @@ -560,30 +560,30 @@ ret[name] = {} return ret - d_list.addCallback(buildFeatures, list(self.plugins.keys())) + d_list.addCallback(build_features, list(self.plugins.keys())) return d_list - def _contactGet(self, entity_jid_s, profile_key): - client = self.getClient(profile_key) + def _contact_get(self, entity_jid_s, profile_key): + client = self.get_client(profile_key) entity_jid = jid.JID(entity_jid_s) - return defer.ensureDeferred(self.getContact(client, entity_jid)) + return defer.ensureDeferred(self.get_contact(client, entity_jid)) - async def getContact(self, client, entity_jid): + async def get_contact(self, client, entity_jid): # we want to be sure that roster has been received await client.roster.got_roster - item = client.roster.getItem(entity_jid) + item = client.roster.get_item(entity_jid) if item is None: raise exceptions.NotFound(f"{entity_jid} is not in roster!") - return (client.roster.getAttributes(item), list(item.groups)) + return (client.roster.get_attributes(item), list(item.groups)) - def getContacts(self, profile_key): - client = self.getClient(profile_key) + def contacts_get(self, profile_key): + client = self.get_client(profile_key) def got_roster(__): ret = [] - for item in client.roster.getItems(): # we get all items for client's roster + for item in client.roster.get_items(): # we get all items for client's roster # and convert them to expected format - attr = client.roster.getAttributes(item) + attr = client.roster.get_attributes(item) # we use full() and not userhost() because jid with resources are allowed # in roster, even if it's not common. ret.append([item.entity.full(), attr, list(item.groups)]) @@ -591,11 +591,11 @@ return client.roster.got_roster.addCallback(got_roster) - def getContactsFromGroup(self, group, profile_key): - client = self.getClient(profile_key) - return [jid_.full() for jid_ in client.roster.getJidsFromGroup(group)] + def contacts_get_from_group(self, group, profile_key): + client = self.get_client(profile_key) + return [jid_.full() for jid_ in client.roster.get_jids_from_group(group)] - def purgeEntity(self, profile): + def purge_entity(self, profile): """Remove reference to a profile client/component and purge cache the garbage collector can then free the memory @@ -605,7 +605,7 @@ except KeyError: log.error(_("Trying to remove reference to a client not referenced")) else: - self.memory.purgeProfileSession(profile) + self.memory.purge_profile_session(profile) def startService(self): self._init() @@ -613,7 +613,7 @@ def stopService(self): log.info("Salut aussi à Rantanplan") - return self.pluginsUnload() + return self.plugins_unload() def run(self): log.debug(_("running app")) @@ -625,16 +625,16 @@ ## Misc methods ## - def getJidNStream(self, profile_key): + def get_jid_n_stream(self, profile_key): """Convenient method to get jid and stream from profile key @return: tuple (jid, xmlstream) from profile, can be None""" - # TODO: deprecate this method (getClient is enough) - profile = self.memory.getProfileName(profile_key) - if not profile or not self.profiles[profile].isConnected(): + # TODO: deprecate this method (get_client is enough) + profile = self.memory.get_profile_name(profile_key) + if not profile or not self.profiles[profile].is_connected(): return (None, None) return (self.profiles[profile].jid, self.profiles[profile].xmlstream) - def getClient(self, profile_key: str) -> xmpp.SatXMPPClient: + def get_client(self, profile_key: str) -> xmpp.SatXMPPClient: """Convenient method to get client from profile key @return: the client @@ -642,7 +642,7 @@ @raise exceptions.NotFound: client is not available This happen if profile has not been used yet """ - profile = self.memory.getProfileName(profile_key) + profile = self.memory.get_profile_name(profile_key) if not profile: raise exceptions.ProfileKeyUnknown try: @@ -650,7 +650,7 @@ except KeyError: raise exceptions.NotFound(profile_key) - def getClients(self, profile_key): + def get_clients(self, profile_key): """Convenient method to get list of clients from profile key Manage list through profile_key like C.PROF_KEY_ALL @@ -660,7 +660,7 @@ if not profile_key: raise exceptions.DataError(_("profile_key must not be empty")) try: - profile = self.memory.getProfileName(profile_key, True) + profile = self.memory.get_profile_name(profile_key, True) except exceptions.ProfileUnknownError: return [] if profile == C.PROF_KEY_ALL: @@ -669,16 +669,16 @@ raise exceptions.ProfileKeyUnknown return [self.profiles[profile]] - def _getConfig(self, section, name): + def _get_config(self, section, name): """Get the main configuration option @param section: section of the config file (None or '' for DEFAULT) @param name: name of the option @return: unicode representation of the option """ - return str(self.memory.getConfig(section, name, "")) + return str(self.memory.config_get(section, name, "")) - def logErrback(self, failure_, msg=_("Unexpected error: {failure_}")): + def log_errback(self, failure_, msg=_("Unexpected error: {failure_}")): """Generic errback logging @param msg(unicode): error message ("failure_" key will be use for format) @@ -689,41 +689,41 @@ # namespaces - def registerNamespace(self, short_name, namespace): + def register_namespace(self, short_name, namespace): """associate a namespace to a short name""" if short_name in self.ns_map: raise exceptions.ConflictError("this short name is already used") log.debug(f"registering namespace {short_name} => {namespace}") self.ns_map[short_name] = namespace - def getNamespaces(self): + def get_namespaces(self): return self.ns_map - def getNamespace(self, short_name): + def get_namespace(self, short_name): try: return self.ns_map[short_name] except KeyError: raise exceptions.NotFound("namespace {short_name} is not registered" .format(short_name=short_name)) - def getSessionInfos(self, profile_key): + def get_session_infos(self, profile_key): """compile interesting data on current profile session""" - client = self.getClient(profile_key) + client = self.get_client(profile_key) data = { "jid": client.jid.full(), "started": str(int(client.started)) } return defer.succeed(data) - def _getDevicesInfos(self, bare_jid, profile_key): - client = self.getClient(profile_key) + def _get_devices_infos(self, bare_jid, profile_key): + client = self.get_client(profile_key) if not bare_jid: bare_jid = None - d = defer.ensureDeferred(self.getDevicesInfos(client, bare_jid)) + d = defer.ensureDeferred(self.get_devices_infos(client, bare_jid)) d.addCallback(lambda data: data_format.serialise(data)) return d - async def getDevicesInfos(self, client, bare_jid=None): + async def get_devices_infos(self, client, bare_jid=None): """compile data on an entity devices @param bare_jid(jid.JID, None): bare jid of entity to check @@ -737,7 +737,7 @@ bare_jid = own_jid else: bare_jid = jid.JID(bare_jid) - resources = self.memory.getAllResources(client, bare_jid) + resources = self.memory.get_all_resources(client, bare_jid) if bare_jid == own_jid: # our own jid is not stored in memory's cache resources.add(client.jid.resource) @@ -745,7 +745,7 @@ for resource in resources: res_jid = copy.copy(bare_jid) res_jid.resource = resource - cache_data = self.memory.getEntityData(client, res_jid) + cache_data = self.memory.entity_data_get(client, res_jid) res_data = { "resource": resource, } @@ -760,7 +760,7 @@ "statuses": presence.statuses, } - disco = await self.getDiscoInfos(client, res_jid) + disco = await self.get_disco_infos(client, res_jid) for (category, type_), name in disco.identities.items(): identities = res_data.setdefault('identities', []) @@ -776,22 +776,22 @@ # images - def _imageCheck(self, path): + def _image_check(self, path): report = image.check(self, path) return data_format.serialise(report) - def _imageResize(self, path, width, height): + def _image_resize(self, path, width, height): d = image.resize(path, (width, height)) d.addCallback(lambda new_image_path: str(new_image_path)) return d - def _imageGeneratePreview(self, path, profile_key): - client = self.getClient(profile_key) - d = defer.ensureDeferred(self.imageGeneratePreview(client, Path(path))) + def _image_generate_preview(self, path, profile_key): + client = self.get_client(profile_key) + d = defer.ensureDeferred(self.image_generate_preview(client, Path(path))) d.addCallback(lambda preview_path: str(preview_path)) return d - async def imageGeneratePreview(self, client, path): + async def image_generate_preview(self, client, path): """Helper method to generate in cache a preview of an image @param path(Path): path to the image @@ -807,11 +807,11 @@ path_hash = hashlib.sha256(str(path).encode()).hexdigest() uid = f"{path.stem}_{path_hash}_preview" filename = f"{uid}{path.suffix.lower()}" - metadata = client.cache.getMetadata(uid=uid) + metadata = client.cache.get_metadata(uid=uid) if metadata is not None: preview_path = metadata['path'] else: - with client.cache.cacheData( + with client.cache.cache_data( source='HOST_PREVIEW', uid=uid, filename=filename) as cache_f: @@ -824,16 +824,16 @@ return preview_path - def _imageConvert(self, source, dest, extra, profile_key): - client = self.getClient(profile_key) if profile_key else None + def _image_convert(self, source, dest, extra, profile_key): + client = self.get_client(profile_key) if profile_key else None source = Path(source) dest = None if not dest else Path(dest) extra = data_format.deserialise(extra) - d = defer.ensureDeferred(self.imageConvert(client, source, dest, extra)) + d = defer.ensureDeferred(self.image_convert(client, source, dest, extra)) d.addCallback(lambda dest_path: str(dest_path)) return d - async def imageConvert(self, client, source, dest=None, extra=None): + async def image_convert(self, client, source, dest=None, extra=None): """Helper method to convert an image from one format to an other @param client(SatClient, None): client to use for caching @@ -861,12 +861,12 @@ cache = self.common_cache else: cache = client.cache - metadata = cache.getMetadata(uid=uid) + metadata = cache.get_metadata(uid=uid) if metadata is not None: # there is already a conversion for this image in cache return metadata['path'] else: - with cache.cacheData( + with cache.cache_data( source='HOST_IMAGE_CONVERT', uid=uid, filename=filename) as cache_f: @@ -900,69 +900,69 @@ @param component: if True, path will be prefixed with C.COMPONENTS_DIR @return: path """ - local_dir = self.memory.getConfig("", "local_dir") + local_dir = self.memory.config_get("", "local_dir") if not local_dir: raise exceptions.InternalError("local_dir must be set") path_elts = [] if component: path_elts.append(C.COMPONENTS_DIR) - path_elts.append(regex.pathEscape(dir_name)) + path_elts.append(regex.path_escape(dir_name)) if extra_path: - path_elts.extend([regex.pathEscape(p) for p in extra_path]) + path_elts.extend([regex.path_escape(p) for p in extra_path]) if client is not None: - path_elts.append(regex.pathEscape(client.profile)) + path_elts.append(regex.path_escape(client.profile)) local_path = Path(*path_elts) local_path.mkdir(0o700, parents=True, exist_ok=True) return local_path ## Client management ## - def setParam(self, name, value, category, security_limit, profile_key): + def param_set(self, name, value, category, security_limit, profile_key): """set wanted paramater and notice observers""" - self.memory.setParam(name, value, category, security_limit, profile_key) + self.memory.param_set(name, value, category, security_limit, profile_key) - def isConnected(self, profile_key): + def is_connected(self, profile_key): """Return connection status of profile @param profile_key: key_word or profile name to determine profile name @return: True if connected """ - profile = self.memory.getProfileName(profile_key) + profile = self.memory.get_profile_name(profile_key) if not profile: log.error(_("asking connection status for a non-existant profile")) raise exceptions.ProfileUnknownError(profile_key) if profile not in self.profiles: return False - return self.profiles[profile].isConnected() + return self.profiles[profile].is_connected() ## Encryption ## - def registerEncryptionPlugin(self, *args, **kwargs): - return encryption.EncryptionHandler.registerPlugin(*args, **kwargs) + def register_encryption_plugin(self, *args, **kwargs): + return encryption.EncryptionHandler.register_plugin(*args, **kwargs) - def _messageEncryptionStart(self, to_jid_s, namespace, replace=False, + def _message_encryption_start(self, to_jid_s, namespace, replace=False, profile_key=C.PROF_KEY_NONE): - client = self.getClient(profile_key) + client = self.get_client(profile_key) to_jid = jid.JID(to_jid_s) return defer.ensureDeferred( client.encryption.start(to_jid, namespace or None, replace)) - def _messageEncryptionStop(self, to_jid_s, profile_key=C.PROF_KEY_NONE): - client = self.getClient(profile_key) + def _message_encryption_stop(self, to_jid_s, profile_key=C.PROF_KEY_NONE): + client = self.get_client(profile_key) to_jid = jid.JID(to_jid_s) return defer.ensureDeferred( client.encryption.stop(to_jid)) - def _messageEncryptionGet(self, to_jid_s, profile_key=C.PROF_KEY_NONE): - client = self.getClient(profile_key) + def _message_encryption_get(self, to_jid_s, profile_key=C.PROF_KEY_NONE): + client = self.get_client(profile_key) to_jid = jid.JID(to_jid_s) session_data = client.encryption.getSession(to_jid) - return client.encryption.getBridgeData(session_data) + return client.encryption.get_bridge_data(session_data) - def _encryptionNamespaceGet(self, name): - return encryption.EncryptionHandler.getNSFromName(name) + def _encryption_namespace_get(self, name): + return encryption.EncryptionHandler.get_ns_from_name(name) - def _encryptionPluginsGet(self): + def _encryption_plugins_get(self): plugins = encryption.EncryptionHandler.getPlugins() ret = [] for p in plugins: @@ -974,20 +974,20 @@ }) return data_format.serialise(ret) - def _encryptionTrustUIGet(self, to_jid_s, namespace, profile_key): - client = self.getClient(profile_key) + def _encryption_trust_ui_get(self, to_jid_s, namespace, profile_key): + client = self.get_client(profile_key) to_jid = jid.JID(to_jid_s) d = defer.ensureDeferred( - client.encryption.getTrustUI(to_jid, namespace=namespace or None)) + client.encryption.get_trust_ui(to_jid, namespace=namespace or None)) d.addCallback(lambda xmlui: xmlui.toXml()) return d ## XMPP methods ## - def _messageSend( + def _message_send( self, to_jid_s, message, subject=None, mess_type="auto", extra_s="", profile_key=C.PROF_KEY_NONE): - client = self.getClient(profile_key) + client = self.get_client(profile_key) to_jid = jid.JID(to_jid_s) return client.sendMessage( to_jid, @@ -997,25 +997,25 @@ data_format.deserialise(extra_s) ) - def _setPresence(self, to="", show="", statuses=None, profile_key=C.PROF_KEY_NONE): - return self.setPresence(jid.JID(to) if to else None, show, statuses, profile_key) + def _set_presence(self, to="", show="", statuses=None, profile_key=C.PROF_KEY_NONE): + return self.presence_set(jid.JID(to) if to else None, show, statuses, profile_key) - def setPresence(self, to_jid=None, show="", statuses=None, + def presence_set(self, to_jid=None, show="", statuses=None, profile_key=C.PROF_KEY_NONE): """Send our presence information""" if statuses is None: statuses = {} - profile = self.memory.getProfileName(profile_key) + profile = self.memory.get_profile_name(profile_key) assert profile priority = int( - self.memory.getParamA("Priority", "Connection", profile_key=profile) + self.memory.param_get_a("Priority", "Connection", profile_key=profile) ) self.profiles[profile].presence.available(to_jid, show, statuses, priority) # XXX: FIXME: temporary fix to work around openfire 3.7.0 bug (presence is not # broadcasted to generating resource) if "" in statuses: statuses[C.PRESENCE_STATUSES_DEFAULT] = statuses.pop("") - self.bridge.presenceUpdate( + self.bridge.presence_update( self.profiles[profile].jid.full(), show, int(priority), statuses, profile ) @@ -1024,7 +1024,7 @@ @param subs_type: subsciption type (cf RFC 3921) @param raw_jid: unicode entity's jid @param profile_key: profile""" - profile = self.memory.getProfileName(profile_key) + profile = self.memory.get_profile_name(profile_key) assert profile to_jid = jid.JID(raw_jid) log.debug( @@ -1040,22 +1040,22 @@ elif subs_type == "unsubscribed": self.profiles[profile].presence.unsubscribed(to_jid) - def _addContact(self, to_jid_s, profile_key): - return self.addContact(jid.JID(to_jid_s), profile_key) + def _add_contact(self, to_jid_s, profile_key): + return self.contact_add(jid.JID(to_jid_s), profile_key) - def addContact(self, to_jid, profile_key): + def contact_add(self, to_jid, profile_key): """Add a contact in roster list""" - profile = self.memory.getProfileName(profile_key) + profile = self.memory.get_profile_name(profile_key) assert profile # presence is sufficient, as a roster push will be sent according to # RFC 6121 §3.1.2 self.profiles[profile].presence.subscribe(to_jid) - def _updateContact(self, to_jid_s, name, groups, profile_key): - client = self.getClient(profile_key) - return self.updateContact(client, jid.JID(to_jid_s), name, groups) + def _update_contact(self, to_jid_s, name, groups, profile_key): + client = self.get_client(profile_key) + return self.contact_update(client, jid.JID(to_jid_s), name, groups) - def updateContact(self, client, to_jid, name, groups): + def contact_update(self, client, to_jid, name, groups): """update a contact in roster list""" roster_item = RosterItem(to_jid) roster_item.name = name or u'' @@ -1064,18 +1064,18 @@ return return client.roster.setItem(roster_item) - def _delContact(self, to_jid_s, profile_key): - return self.delContact(jid.JID(to_jid_s), profile_key) + def _del_contact(self, to_jid_s, profile_key): + return self.contact_del(jid.JID(to_jid_s), profile_key) - def delContact(self, to_jid, profile_key): + def contact_del(self, to_jid, profile_key): """Remove contact from roster list""" - profile = self.memory.getProfileName(profile_key) + profile = self.memory.get_profile_name(profile_key) assert profile self.profiles[profile].presence.unsubscribe(to_jid) # is not asynchronous return self.profiles[profile].roster.removeItem(to_jid) - def _rosterResync(self, profile_key): - client = self.getClient(profile_key) + def _roster_resync(self, profile_key): + client = self.get_client(profile_key) return client.roster.resync() ## Discovery ## @@ -1085,39 +1085,39 @@ def hasFeature(self, *args, **kwargs): return self.memory.disco.hasFeature(*args, **kwargs) - def checkFeature(self, *args, **kwargs): - return self.memory.disco.checkFeature(*args, **kwargs) + def check_feature(self, *args, **kwargs): + return self.memory.disco.check_feature(*args, **kwargs) - def checkFeatures(self, *args, **kwargs): - return self.memory.disco.checkFeatures(*args, **kwargs) + def check_features(self, *args, **kwargs): + return self.memory.disco.check_features(*args, **kwargs) - def hasIdentity(self, *args, **kwargs): - return self.memory.disco.hasIdentity(*args, **kwargs) + def has_identity(self, *args, **kwargs): + return self.memory.disco.has_identity(*args, **kwargs) - def getDiscoInfos(self, *args, **kwargs): - return self.memory.disco.getInfos(*args, **kwargs) + def get_disco_infos(self, *args, **kwargs): + return self.memory.disco.get_infos(*args, **kwargs) def getDiscoItems(self, *args, **kwargs): - return self.memory.disco.getItems(*args, **kwargs) + return self.memory.disco.get_items(*args, **kwargs) - def findServiceEntity(self, *args, **kwargs): - return self.memory.disco.findServiceEntity(*args, **kwargs) + def find_service_entity(self, *args, **kwargs): + return self.memory.disco.find_service_entity(*args, **kwargs) - def findServiceEntities(self, *args, **kwargs): - return self.memory.disco.findServiceEntities(*args, **kwargs) + def find_service_entities(self, *args, **kwargs): + return self.memory.disco.find_service_entities(*args, **kwargs) - def findFeaturesSet(self, *args, **kwargs): - return self.memory.disco.findFeaturesSet(*args, **kwargs) + def find_features_set(self, *args, **kwargs): + return self.memory.disco.find_features_set(*args, **kwargs) - def _findByFeatures(self, namespaces, identities, bare_jids, service, roster, own_jid, + def _find_by_features(self, namespaces, identities, bare_jids, service, roster, own_jid, local_device, profile_key): - client = self.getClient(profile_key) + client = self.get_client(profile_key) identities = [tuple(i) for i in identities] if identities else None - return defer.ensureDeferred(self.findByFeatures( + return defer.ensureDeferred(self.find_by_features( client, namespaces, identities, bare_jids, service, roster, own_jid, local_device)) - async def findByFeatures( + async def find_by_features( self, client: xmpp.SatXMPPEntity, namespaces: List[str], @@ -1164,10 +1164,10 @@ found_own = {} found_roster = {} if service: - services_jids = await self.findFeaturesSet(client, namespaces) + services_jids = await self.find_features_set(client, namespaces) services_jids = list(services_jids) # we need a list to map results below services_infos = await defer.DeferredList( - [self.getDiscoInfos(client, service_jid) for service_jid in services_jids] + [self.get_disco_infos(client, service_jid) for service_jid in services_jids] ) for idx, (success, infos) in enumerate(services_infos): @@ -1190,7 +1190,7 @@ if own_jid: to_find.append((found_own, [client.jid.userhostJID()])) if roster: - to_find.append((found_roster, client.roster.getJids())) + to_find.append((found_roster, client.roster.get_jids())) for found, jids in to_find: full_jids = [] @@ -1206,7 +1206,7 @@ resources = [None] else: try: - resources = self.memory.getAvailableResources(client, jid_) + resources = self.memory.get_available_resources(client, jid_) except exceptions.UnknownEntityError: continue if not resources and jid_ == client.jid.userhostJID() and own_jid: @@ -1220,7 +1220,7 @@ continue full_jids.append(full_jid) - disco_defers.append(self.getDiscoInfos(client, full_jid)) + disco_defers.append(self.get_disco_infos(client, full_jid)) d_list = defer.DeferredList(disco_defers) # XXX: 10 seconds may be too low for slow connections (e.g. mobiles) @@ -1251,18 +1251,18 @@ ## Generic HMI ## - def _killAction(self, keep_id, client): + def _kill_action(self, keep_id, client): log.debug("Killing action {} for timeout".format(keep_id)) client.actions[keep_id] - def actionNew( + def action_new( self, action_data, security_limit=C.NO_SECURITY_LIMIT, keep_id=None, profile=C.PROF_KEY_NONE, ): - """Shortcut to bridge.actionNew which generate and id and keep for retrieval + """Shortcut to bridge.action_new which generate and id and keep for retrieval @param action_data(dict): action data (see bridge documentation) @param security_limit: %(doc_security_limit)s @@ -1273,44 +1273,44 @@ """ id_ = str(uuid.uuid4()) if keep_id is not None: - client = self.getClient(profile) - action_timer = reactor.callLater(60 * 30, self._killAction, keep_id, client) + client = self.get_client(profile) + action_timer = reactor.callLater(60 * 30, self._kill_action, keep_id, client) client.actions[keep_id] = (action_data, id_, security_limit, action_timer) - self.bridge.actionNew(action_data, id_, security_limit, profile) + self.bridge.action_new(action_data, id_, security_limit, profile) - def actionsGet(self, profile): + def actions_get(self, profile): """Return current non answered actions @param profile: %(doc_profile)s """ - client = self.getClient(profile) + client = self.get_client(profile) return [action_tuple[:-1] for action_tuple in client.actions.values()] - def registerProgressCb( + def register_progress_cb( self, progress_id, callback, metadata=None, profile=C.PROF_KEY_NONE ): """Register a callback called when progress is requested for id""" if metadata is None: metadata = {} - client = self.getClient(profile) + client = self.get_client(profile) if progress_id in client._progress_cb: raise exceptions.ConflictError("Progress ID is not unique !") client._progress_cb[progress_id] = (callback, metadata) - def removeProgressCb(self, progress_id, profile): + def remove_progress_cb(self, progress_id, profile): """Remove a progress callback""" - client = self.getClient(profile) + client = self.get_client(profile) try: del client._progress_cb[progress_id] except KeyError: log.error(_("Trying to remove an unknow progress callback")) - def _progressGet(self, progress_id, profile): - data = self.progressGet(progress_id, profile) + def _progress_get(self, progress_id, profile): + data = self.progress_get(progress_id, profile) return {k: str(v) for k, v in data.items()} - def progressGet(self, progress_id, profile): + def progress_get(self, progress_id, profile): """Return a dict with progress information @param progress_id(unicode): unique id of the progressing element @@ -1321,22 +1321,22 @@ if id doesn't exists (may be a finished progression), and empty dict is returned """ - client = self.getClient(profile) + client = self.get_client(profile) try: data = client._progress_cb[progress_id][0](progress_id, profile) except KeyError: data = {} return data - def _progressGetAll(self, profile_key): - progress_all = self.progressGetAll(profile_key) + def _progress_get_all(self, profile_key): + progress_all = self.progress_get_all(profile_key) for profile, progress_dict in progress_all.items(): for progress_id, data in progress_dict.items(): for key, value in data.items(): data[key] = str(value) return progress_all - def progressGetAllMetadata(self, profile_key): + def progress_get_all_metadata(self, profile_key): """Return all progress metadata at once @param profile_key: %(doc_profile)s @@ -1344,9 +1344,9 @@ returned @return (dict[dict[dict]]): a dict which map profile to progress_dict progress_dict map progress_id to progress_data - progress_metadata is the same dict as sent by [progressStarted] + progress_metadata is the same dict as sent by [progress_started] """ - clients = self.getClients(profile_key) + clients = self.get_clients(profile_key) progress_all = {} for client in clients: profile = client.profile @@ -1359,16 +1359,16 @@ progress_dict[progress_id] = progress_metadata return progress_all - def progressGetAll(self, profile_key): + def progress_get_all(self, profile_key): """Return all progress status at once @param profile_key: %(doc_profile)s if C.PROF_KEY_ALL is used, all progress status from all profiles are returned @return (dict[dict[dict]]): a dict which map profile to progress_dict progress_dict map progress_id to progress_data - progress_data is the same dict as returned by [progressGet] + progress_data is the same dict as returned by [progress_get] """ - clients = self.getClients(profile_key) + clients = self.get_clients(profile_key) progress_all = {} for client in clients: profile = client.profile @@ -1378,7 +1378,7 @@ progress_dict[progress_id] = progress_cb(progress_id, profile) return progress_all - def registerCallback(self, callback, *args, **kwargs): + def register_callback(self, callback, *args, **kwargs): """Register a callback. @param callback(callable): method to call @@ -1399,23 +1399,23 @@ if "one_shot" in kwargs: # One Shot callback are removed after 30 min - def purgeCallback(): + def purge_callback(): try: self.removeCallback(callback_id) except KeyError: pass - reactor.callLater(1800, purgeCallback) + reactor.callLater(1800, purge_callback) return callback_id def removeCallback(self, callback_id): """ Remove a previously registered callback - @param callback_id: id returned by [registerCallback] """ + @param callback_id: id returned by [register_callback] """ log.debug("Removing callback [%s]" % callback_id) del self._cb_map[callback_id] - def launchCallback(self, callback_id, data=None, profile_key=C.PROF_KEY_NONE): + def launch_callback(self, callback_id, data=None, profile_key=C.PROF_KEY_NONE): """Launch a specific callback @param callback_id: id of the action (callback) to launch @@ -1430,10 +1430,10 @@ """ # FIXME: security limit need to be checked here try: - client = self.getClient(profile_key) + client = self.get_client(profile_key) except exceptions.NotFound: # client is not available yet - profile = self.memory.getProfileName(profile_key) + profile = self.memory.get_profile_name(profile_key) if not profile: raise exceptions.ProfileUnknownError( _("trying to launch action with a non-existant profile") @@ -1468,11 +1468,11 @@ if kwargs.pop("one_shot", False): self.removeCallback(callback_id) - return utils.asDeferred(callback, *args, **kwargs) + return utils.as_deferred(callback, *args, **kwargs) # Menus management - def _getMenuCanonicalPath(self, path): + def _get_menu_canonical_path(self, path): """give canonical form of path canonical form is a tuple of the path were every element is stripped and lowercase @@ -1481,7 +1481,7 @@ """ return tuple((p.lower().strip() for p in path)) - def importMenu(self, path, callback, security_limit=C.NO_SECURITY_LIMIT, + def import_menu(self, path, callback, security_limit=C.NO_SECURITY_LIMIT, help_string="", type_=C.MENU_GLOBAL): r"""register a new menu for frontends @@ -1491,9 +1491,9 @@ untranslated/lower case path can be used to identity a menu, for this reason it must be unique independently of case. @param callback(callable): method to be called when menuitem is selected, callable - or a callback id (string) as returned by [registerCallback] + or a callback id (string) as returned by [register_callback] @param security_limit(int): %(doc_security_limit)s - /!\ security_limit MUST be added to data in launchCallback if used #TODO + /!\ security_limit MUST be added to data in launch_callback if used #TODO @param help_string(unicode): string used to indicate what the menu do (can be show as a tooltip). /!\ use D_() instead of _() for translations @@ -1517,7 +1517,7 @@ """ if callable(callback): - callback_id = self.registerCallback(callback, with_data=True) + callback_id = self.register_callback(callback, with_data=True) elif isinstance(callback, str): # The callback is already registered callback_id = callback @@ -1535,7 +1535,7 @@ _("A menu with the same path and type already exists") ) - path_canonical = self._getMenuCanonicalPath(path) + path_canonical = self._get_menu_canonical_path(path) menu_key = (type_, path_canonical) if menu_key in self._menus_paths: @@ -1558,7 +1558,7 @@ return callback_id - def getMenus(self, language="", security_limit=C.NO_SECURITY_LIMIT): + def get_menus(self, language="", security_limit=C.NO_SECURITY_LIMIT): """Return all menus registered @param language: language used for translation, or empty string for default @@ -1582,20 +1582,20 @@ or menu_security_limit > security_limit ): continue - languageSwitch(language) + language_switch(language) path_i18n = [_(elt) for elt in path] - languageSwitch() + language_switch() extra = {} # TODO: manage extra data like icon ret.append((menu_id, type_, path, path_i18n, extra)) return ret - def _launchMenu(self, menu_type, path, data=None, security_limit=C.NO_SECURITY_LIMIT, + def _launch_menu(self, menu_type, path, data=None, security_limit=C.NO_SECURITY_LIMIT, profile_key=C.PROF_KEY_NONE): - client = self.getClient(profile_key) - return self.launchMenu(client, menu_type, path, data, security_limit) + client = self.get_client(profile_key) + return self.launch_menu(client, menu_type, path, data, security_limit) - def launchMenu(self, client, menu_type, path, data=None, + def launch_menu(self, client, menu_type, path, data=None, security_limit=C.NO_SECURITY_LIMIT): """launch action a menu action @@ -1606,7 +1606,7 @@ """ # FIXME: manage security_limit here # defaut security limit should be high instead of C.NO_SECURITY_LIMIT - canonical_path = self._getMenuCanonicalPath(path) + canonical_path = self._get_menu_canonical_path(path) menu_key = (menu_type, canonical_path) try: callback_id = self._menus_paths[menu_key] @@ -1616,9 +1616,9 @@ path=canonical_path, menu_type=menu_type ) ) - return self.launchCallback(callback_id, data, client.profile) + return self.launch_callback(callback_id, data, client.profile) - def getMenuHelp(self, menu_id, language=""): + def get_menu_help(self, menu_id, language=""): """return the help string of the menu @param menu_id: id of the menu (same as callback_id) @@ -1630,7 +1630,7 @@ menu_data = self._menus[menu_id] except KeyError: raise exceptions.DataError("Trying to access an unknown menu") - languageSwitch(language) + language_switch(language) help_string = _(menu_data["help_string"]) - languageSwitch() + language_switch() return help_string