Mercurial > libervia-web
diff libervia/server/server.py @ 1509:106bae41f5c8
massive refactoring from camelCase -> snake_case. See backend commit log for more details
author | Goffi <goffi@goffi.org> |
---|---|
date | Sat, 08 Apr 2023 13:44:11 +0200 |
parents | ce879da7fcf7 |
children | 65e063657597 |
line wrap: on
line diff
--- a/libervia/server/server.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/server/server.py Sat Apr 08 13:44:11 2023 +0200 @@ -40,7 +40,7 @@ from sat.tools.common.utils import OrderedSet, recursive_update from sat_frontends.bridge.bridge_frontend import BridgeException from sat_frontends.bridge.dbus_bridge import ( - Bridge, + bridge, BridgeExceptionNoService, const_TIMEOUT as BRIDGE_TIMEOUT, ) @@ -98,7 +98,7 @@ notifier.startReading() return self._notifier - def _checkCallback(self, dir_path, callback, recursive): + def _check_callback(self, dir_path, callback, recursive): # Twisted doesn't add callback if a watcher was already set on a path # but in dev mode Libervia watches whole sites + internal path can be watched # by tasks, so several callbacks must be called on some paths. @@ -108,7 +108,7 @@ if recursive: for child in dir_path.walk(): if child.isdir(): - self._checkCallback(child, callback, recursive=False) + self._check_callback(child, callback, recursive=False) else: watch_id = self.notifier._isWatched(dir_path) if watch_id is None: @@ -120,7 +120,7 @@ if callback not in watch_point.callbacks: watch_point.callbacks.append(callback) - def watchDir(self, dir_path, callback, mask=DEFAULT_MASK, auto_add=False, + def watch_dir(self, dir_path, callback, mask=DEFAULT_MASK, auto_add=False, recursive=False, **kwargs): dir_path = str(dir_path) log.info(_("Watching directory {dir_path}").format(dir_path=dir_path)) @@ -131,7 +131,7 @@ self.notifier.watch( dir_path, mask=mask, autoAdd=auto_add, recursive=recursive, callbacks=callbacks) - self._checkCallback(dir_path, wrapped_callback, recursive) + self._check_callback(dir_path, wrapped_callback, recursive) class WebSession(server.Session): @@ -193,7 +193,7 @@ self.host_name = host_name self.site_name = site_name self.site_path = Path(site_path) - self.default_theme = self.getConfig('theme') + self.default_theme = self.config_get('theme') if self.default_theme is None: if not host_name: # FIXME: we use bulma theme by default for main site for now @@ -207,7 +207,7 @@ self.browser_modules = {} # template dynamic data used in all pages self.dyn_data_common = {"scripts": OrderedSet()} - for theme, data in host.renderer.getThemesData(site_name).items(): + for theme, data in host.renderer.get_themes_data(site_name).items(): # we check themes for browser metadata, and merge them here if found self.site_themes.add(theme) browser_meta = data.get('browser_meta') @@ -238,9 +238,9 @@ self.main_menu = None # map Libervia application names => data self.libervia_apps = {} - self.build_path = host.getBuildPath(site_name) + self.build_path = host.get_build_path(site_name) self.build_path.mkdir(parents=True, exist_ok=True) - self.dev_build_path = host.getBuildPath(site_name, dev=True) + self.dev_build_path = host.get_build_path(site_name, dev=True) self.dev_build_path.mkdir(parents=True, exist_ok=True) self.putChild( C.BUILD_DIR.encode(), @@ -256,14 +256,14 @@ f"files at {self.path}" ) - def getConfig(self, key, default=None, value_type=None): + def config_get(self, key, default=None, value_type=None): """Retrieve configuration for this site - params are the same as for [Libervia.getConfig] + params are the same as for [Libervia.config_get] """ - return self.host.getConfig(self, key, default, value_type) + return self.host.config_get(self, key, default, value_type) - def getFrontURL(self, theme): + def get_front_url(self, theme): return Path( '/', C.TPL_RESOURCE, @@ -271,7 +271,7 @@ C.TEMPLATE_TPL_DIR, theme) - def addResourceToPath(self, path: str, resource: web_resource.Resource) -> None: + def add_resource_to_path(self, path: str, resource: web_resource.Resource) -> None: """Add a resource to the given path A "NoResource" will be used for all intermediate segments @@ -303,8 +303,8 @@ log.info(_( "starting application {app_name}").format(app_name=app_name)) app_data = data_format.deserialise( - await self.host.bridgeCall( - "applicationStart", app_name, data_format.serialise(extra) + await self.host.bridge_call( + "application_start", app_name, data_format.serialise(extra) ) ) if app_data.get("started", False): @@ -322,7 +322,7 @@ instance_id: str ) -> None: exposed_data = self.libervia_apps[app_name] = data_format.deserialise( - await self.host.bridgeCall("applicationExposedGet", app_name, "", "") + await self.host.bridge_call("application_exposed_get", app_name, "", "") ) try: @@ -350,12 +350,12 @@ web_port, url_prefix.encode() ) - self.addResourceToPath(url_prefix, res) + self.add_resource_to_path(url_prefix, res) log.info( f"Resource for app {app_name!r} (instance {instance_id!r}) has been added" ) - async def _initRedirections(self, options): + async def _init_redirections(self, options): url_redirections = options["url_redirections_dict"] url_redirections = url_redirections.get(self.site_name, {}) @@ -410,7 +410,7 @@ new["path_args"] = [quote(a) for a in new["path_args"]] # we keep an inversed dict of page redirection # (page/path_args => redirecting URL) - # so getURL can return the redirecting URL if the same arguments + # so get_url can return the redirecting URL if the same arguments # are used # making the URL consistent args_hash = tuple(new["path_args"]) self.pages_redirects.setdefault(new_data["page"], {}).setdefault( @@ -447,7 +447,7 @@ ) continue else: - old = self._normalizeURL(old) + old = self._normalize_url(old) if isinstance(new, dict): # dict are handled differently, they contain data @@ -462,8 +462,8 @@ ) else: if new["type"] == "page": - page = self.getPageByName(new["page"]) - url = page.getURL(*new.get("path_args", [])) + page = self.get_page_by_name(new["page"]) + url = page.get_url(*new.get("path_args", [])) self.inv_redirections[url] = old continue @@ -472,13 +472,13 @@ # we handle the known URL schemes if new_url.scheme == "xmpp": - location = self.getPagePathFromURI(new) + location = self.get_page_path_from_uri(new) if location is None: log.warning( _("ignoring redirection, no page found to handle this URI: " "{uri}").format(uri=new)) continue - request_data = self._getRequestData(location) + request_data = self._get_request_data(location) self.inv_redirections[location] = old elif new_url.scheme in ("", "http", "https"): @@ -491,7 +491,7 @@ location = urllib.parse.urlunsplit( ("", "", new_url.path, new_url.query, new_url.fragment) ) - request_data = self._getRequestData(location) + request_data = self._get_request_data(location) self.inv_redirections[location] = old elif new_url.scheme == "file": @@ -512,7 +512,7 @@ ProtectedFile if new_data.get("protected", True) else static.File ) res = resource_class(path, defaultType="application/octet-stream") - self.addResourceToPath(old, res) + self.add_resource_to_path(old, res) log.info("[{host_name}] Added redirection from /{old} to file system " "path {path}".format(host_name=self.host_name, old=old, @@ -554,7 +554,7 @@ port, url_prefix.encode(), ) - self.addResourceToPath(old, res) + self.add_resource_to_path(old, res) log.info( f"[{self.host_name}] Added redirection from /{old} to reverse proxy " f"{new_url.netloc} with URL prefix {url_prefix}/" @@ -577,9 +577,9 @@ # the default root URL, if not redirected if not "" in self.redirections: - self.redirections[""] = self._getRequestData(C.LIBERVIA_PAGE_START) + self.redirections[""] = self._get_request_data(C.LIBERVIA_PAGE_START) - async def _setMenu(self, menus): + async def _set_menu(self, menus): menus = menus.get(self.site_name, []) main_menu = [] for menu in menus: @@ -623,7 +623,7 @@ else: page_name = menu try: - url = self.getPageByName(page_name).url + url = self.get_page_by_name(page_name).url except KeyError as e: log_msg = _("Can'find a named page ({msg}), please check " "menu_json in configuration.").format(msg=e.args[0]) @@ -632,7 +632,7 @@ main_menu.append((page_name, url)) self.main_menu = main_menu - def _normalizeURL(self, url, lower=True): + def _normalize_url(self, url, lower=True): """Return URL normalized for self.redirections dict @param url(unicode): URL to normalize @@ -643,7 +643,7 @@ url = url.lower() return "/".join((p for p in url.split("/") if p)) - def _getRequestData(self, uri): + def _get_request_data(self, uri): """Return data needed to redirect request @param url(unicode): destination url @@ -668,7 +668,7 @@ # XXX: splitted path case must not be changed, as it may be significant # (e.g. for blog items) return ( - self._normalizeURL(path, lower=False).split("/"), + self._normalize_url(path, lower=False).split("/"), uri, path, args, @@ -679,7 +679,7 @@ this is *NOT* a HTTP redirection, but equivalent to URL rewritting @param request(web.http.request): original request - @param request_data(tuple): data returned by self._getRequestData + @param request_data(tuple): data returned by self._get_request_data @return (web_resource.Resource): resource to use """ # recursion check @@ -702,7 +702,7 @@ if isinstance(request_data, dict): if request_data["type"] == "page": try: - page = self.getPageByName(request_data["page"]) + page = self.get_page_by_name(request_data["page"]) except KeyError: log.error( _( @@ -740,7 +740,7 @@ # we start again to look for a child with the new url return self.getChildWithDefault(path_list[0], request) - def getPageByName(self, name): + def get_page_by_name(self, name): """Retrieve page instance from its name @param name(unicode): name of the page @@ -749,7 +749,7 @@ """ return self.named_pages[name] - def getPagePathFromURI(self, uri): + def get_page_path_from_uri(self, uri): """Retrieve page URL from xmpp: URI @param uri(unicode): URI with a xmpp: scheme @@ -757,7 +757,7 @@ the URI. None is returned if no page has been registered for this URI """ - uri_data = common_uri.parseXMPPUri(uri) + uri_data = common_uri.parse_xmpp_uri(uri) try: page, cb = self.uri_callbacks[uri_data["type"], uri_data["sub_type"]] except KeyError: @@ -823,7 +823,7 @@ class WaitingRequests(dict): - def setRequest(self, request, profile, register_with_ext_jid=False): + def set_request(self, request, profile, register_with_ext_jid=False): """Add the given profile to the waiting list. @param request (server.Request): the connection request @@ -831,10 +831,10 @@ @param register_with_ext_jid (bool): True if we will try to register the profile with an external XMPP account credentials """ - dc = reactor.callLater(BRIDGE_TIMEOUT, self.purgeRequest, profile) + dc = reactor.callLater(BRIDGE_TIMEOUT, self.purge_request, profile) self[profile] = (request, dc, register_with_ext_jid) - def purgeRequest(self, profile): + def purge_request(self, profile): """Remove the given profile from the waiting list. @param profile (str): %(doc_profile)s @@ -847,7 +847,7 @@ dc.cancel() del self[profile] - def getRequest(self, profile): + def get_request(self, profile): """Get the waiting request for the given profile. @param profile (str): %(doc_profile)s @@ -855,7 +855,7 @@ """ return self[profile][0] if profile in self else None - def getRegisterWithExtJid(self, profile): + def get_register_with_ext_jid(self, profile): """Get the value of the register_with_ext_jid parameter. @param profile (str): %(doc_profile)s @@ -901,8 +901,8 @@ ## bridge ## self._bridge_retry = self.options['bridge-retries'] - self.bridge = Bridge() - self.bridge.bridgeConnect(callback=self._bridgeCb, errback=self._bridgeEb) + self.bridge = bridge() + self.bridge.bridge_connect(callback=self._bridge_cb, errback=self._bridge_eb) ## libervia app callbacks ## # mapping instance id to the callback to call on "started" signal @@ -927,16 +927,16 @@ def main_conf(self): """SafeConfigParser instance opened on configuration file (sat.conf)""" if self._main_conf is None: - self._main_conf = config.parseMainConf(log_filenames=True) + self._main_conf = config.parse_main_conf(log_filenames=True) return self._main_conf - def getConfig(self, site_root_res, key, default=None, value_type=None): + def config_get(self, site_root_res, key, default=None, value_type=None): """Retrieve configuration associated to a site Section is automatically set to site name @param site_root_res(LiberviaRootResource): resource of the site in use @param key(unicode): key to use - @param default: value to use if not found (see [config.getConfig]) + @param default: value to use if not found (see [config.config_get]) @param value_type(unicode, None): filter to use on value Note that filters are already automatically used when the key finish by a well known suffix ("_path", "_list", "_dict", or "_json") @@ -945,7 +945,7 @@ """ section = site_root_res.site_name.lower().strip() or C.CONFIG_SECTION - value = config.getConfig(self.main_conf, section, key, default=default) + value = config.config_get(self.main_conf, section, key, default=default) if value_type is not None: if value_type == 'path': v_filter = lambda v: os.path.abspath(os.path.expanduser(v)) @@ -960,10 +960,10 @@ value = v_filter(value) return value - def _namespacesGetCb(self, ns_map): + def _namespaces_get_cb(self, ns_map): self.ns_map = {str(k): str(v) for k,v in ns_map.items()} - def _namespacesGetEb(self, failure_): + def _namespaces_get_eb(self, failure_): log.error(_("Can't get namespaces map: {msg}").format(msg=failure_)) @template.contextfilter @@ -973,7 +973,7 @@ '/', C.TPL_RESOURCE, template_data.site or C.SITE_NAME_DEFAULT, C.TEMPLATE_TPL_DIR, template_data.theme, relative_url) - def _moveFirstLevelToDict(self, options, key, keys_to_keep): + def _move_first_level_to_dict(self, options, key, keys_to_keep): """Read a config option and put value at first level into u'' dict This is useful to put values for Libervia official site directly in dictionary, @@ -1001,7 +1001,7 @@ if default_dict: conf[''] = default_dict - async def checkAndConnectServiceProfile(self): + async def check_and_connect_service_profile(self): passphrase = self.options["passphrase"] if not passphrase: raise SysExit( @@ -1010,12 +1010,12 @@ "documentation.") ) try: - s_prof_connected = await self.bridgeCall("isConnected", C.SERVICE_PROFILE) + s_prof_connected = await self.bridge_call("is_connected", C.SERVICE_PROFILE) except BridgeException as e: if e.classname == "ProfileUnknownError": log.info("Service profile doesn't exist, creating it.") try: - xmpp_domain = await self.bridgeCall("getConfig", "", "xmpp_domain") + xmpp_domain = await self.bridge_call("config_get", "", "xmpp_domain") xmpp_domain = xmpp_domain.strip() if not xmpp_domain: raise SysExit( @@ -1024,8 +1024,8 @@ 'check documentation') ) service_profile_jid_s = f"{C.SERVICE_PROFILE}@{xmpp_domain}" - await self.bridgeCall( - "inBandAccountNew", + await self.bridge_call( + "in_band_account_new", service_profile_jid_s, passphrase, "", @@ -1082,14 +1082,14 @@ "do to it manually: {reason}").format(reason=e.message) ) try: - await self.bridgeCall("profileCreate", C.SERVICE_PROFILE, passphrase) - await self.bridgeCall( - "profileStartSession", passphrase, C.SERVICE_PROFILE) - await self.bridgeCall( - "setParam", "JabberID", service_profile_jid_s, "Connection", -1, + await self.bridge_call("profile_create", C.SERVICE_PROFILE, passphrase) + await self.bridge_call( + "profile_start_session", passphrase, C.SERVICE_PROFILE) + await self.bridge_call( + "param_set", "JabberID", service_profile_jid_s, "Connection", -1, C.SERVICE_PROFILE) - await self.bridgeCall( - "setParam", "Password", passphrase, "Connection", -1, + await self.bridge_call( + "param_set", "Password", passphrase, "Connection", -1, C.SERVICE_PROFILE) except BridgeException as e: raise SysExit( @@ -1104,7 +1104,7 @@ if not s_prof_connected: try: - await self.bridgeCall( + await self.bridge_call( "connect", C.SERVICE_PROFILE, passphrase, @@ -1116,21 +1116,21 @@ _("Connection of service profile failed: {reason}").format(reason=e) ) - async def backendReady(self): + async def backend_ready(self): log.info(f"Libervia Web v{self.full_version}") # settings if self.options['dev-mode']: log.info(_("Developer mode activated")) - self.media_dir = await self.bridgeCall("getConfig", "", "media_dir") - self.local_dir = await self.bridgeCall("getConfig", "", "local_dir") + self.media_dir = await self.bridge_call("config_get", "", "media_dir") + self.local_dir = await self.bridge_call("config_get", "", "local_dir") self.cache_root_dir = os.path.join(self.local_dir, C.CACHE_DIR) self.renderer = template.Renderer(self, self._front_url_filter) sites_names = list(self.renderer.sites_paths.keys()) - self._moveFirstLevelToDict(self.options, "url_redirections_dict", sites_names) - self._moveFirstLevelToDict(self.options, "menu_json", sites_names) - self._moveFirstLevelToDict(self.options, "menu_extra_json", sites_names) + self._move_first_level_to_dict(self.options, "url_redirections_dict", sites_names) + self._move_first_level_to_dict(self.options, "menu_json", sites_names) + self._move_first_level_to_dict(self.options, "menu_extra_json", sites_names) menu = self.options["menu_json"] if not '' in menu: menu[''] = C.DEFAULT_MENU @@ -1139,7 +1139,7 @@ # service profile if not self.options['build-only']: - await self.checkAndConnectServiceProfile() + await self.check_and_connect_service_profile() # restricted bridge, the one used by browser code self.restricted_bridge = RestrictedBridge(self) @@ -1153,16 +1153,16 @@ host=self, host_name='', site_name='', site_path=default_site_path, path=root_path) if self.options['dev-mode']: - self.files_watcher.watchDir( + self.files_watcher.watch_dir( default_site_path, auto_add=True, recursive=True, - callback=LiberviaPage.onFileChange, site_root=self.sat_root, + callback=LiberviaPage.on_file_change, site_root=self.sat_root, site_path=default_site_path) - LiberviaPage.importPages(self, self.sat_root) + LiberviaPage.import_pages(self, self.sat_root) tasks_manager = TasksManager(self, self.sat_root) - await tasks_manager.parseTasks() - await tasks_manager.runTasks() - # FIXME: handle _setMenu in a more generic way, taking care of external sites - await self.sat_root._setMenu(self.options["menu_json"]) + await tasks_manager.parse_tasks() + await tasks_manager.run_tasks() + # FIXME: handle _set_menu in a more generic way, taking care of external sites + await self.sat_root._set_menu(self.options["menu_json"]) self.vhost_root.default = default_root existing_vhosts = {b'': default_root} @@ -1199,48 +1199,48 @@ existing_vhosts[encoded_site_name] = res if self.options['dev-mode']: - self.files_watcher.watchDir( + self.files_watcher.watch_dir( site_path, auto_add=True, recursive=True, - callback=LiberviaPage.onFileChange, site_root=res, + callback=LiberviaPage.on_file_change, site_root=res, site_path=site_path) - LiberviaPage.importPages(self, res) + LiberviaPage.import_pages(self, res) # FIXME: default pages are accessible if not overriden by external website # while necessary for login or re-using existing pages # we may want to disable access to the page by direct URL # (e.g. /blog disabled except if called by external site) - LiberviaPage.importPages(self, res, root_path=default_site_path) + LiberviaPage.import_pages(self, res, root_path=default_site_path) tasks_manager = TasksManager(self, res) - await tasks_manager.parseTasks() - await tasks_manager.runTasks() - await res._setMenu(self.options["menu_json"]) + await tasks_manager.parse_tasks() + await tasks_manager.run_tasks() + await res._set_menu(self.options["menu_json"]) self.vhost_root.addHost(host_name.encode('utf-8'), res) templates_res = web_resource.Resource() - self.putChildAll(C.TPL_RESOURCE.encode('utf-8'), templates_res) + self.put_child_all(C.TPL_RESOURCE.encode('utf-8'), templates_res) for site_name, site_path in self.renderer.sites_paths.items(): templates_res.putChild(site_name.encode() or C.SITE_NAME_DEFAULT.encode(), static.File(site_path)) - d = self.bridgeCall("namespacesGet") - d.addCallback(self._namespacesGetCb) - d.addErrback(self._namespacesGetEb) + d = self.bridge_call("namespaces_get") + d.addCallback(self._namespaces_get_cb) + d.addErrback(self._namespaces_get_eb) # websocket if self.options["connection_type"] in ("https", "both"): - wss = websockets.LiberviaPageWSProtocol.getResource(secure=True) - self.putChildAll(b'wss', wss) + wss = websockets.LiberviaPageWSProtocol.get_resource(secure=True) + self.put_child_all(b'wss', wss) if self.options["connection_type"] in ("http", "both"): - ws = websockets.LiberviaPageWSProtocol.getResource(secure=False) - self.putChildAll(b'ws', ws) + ws = websockets.LiberviaPageWSProtocol.get_resource(secure=False) + self.put_child_all(b'ws', ws) ## following signal is needed for cache handling in Libervia pages self.bridge.register_signal( - "psEventRaw", partial(LiberviaPage.onNodeEvent, self), "plugin" + "ps_event_raw", partial(LiberviaPage.on_node_event, self), "plugin" ) self.bridge.register_signal( - "messageNew", partial(self.on_signal, "messageNew") + "message_new", partial(self.on_signal, "message_new") ) # libervia applications handling @@ -1253,28 +1253,28 @@ # Progress handling self.bridge.register_signal( - "progressStarted", partial(ProgressHandler._signal, "started") + "progress_started", partial(ProgressHandler._signal, "started") ) self.bridge.register_signal( - "progressFinished", partial(ProgressHandler._signal, "finished") + "progress_finished", partial(ProgressHandler._signal, "finished") ) self.bridge.register_signal( - "progressError", partial(ProgressHandler._signal, "error") + "progress_error", partial(ProgressHandler._signal, "error") ) # media dirs # FIXME: get rid of dirname and "/" in C.XXX_DIR - self.putChildAll(os.path.dirname(C.MEDIA_DIR).encode('utf-8'), + self.put_child_all(os.path.dirname(C.MEDIA_DIR).encode('utf-8'), ProtectedFile(self.media_dir)) self.cache_resource = web_resource.NoResource() - self.putChildAll(C.CACHE_DIR.encode('utf-8'), self.cache_resource) + self.put_child_all(C.CACHE_DIR.encode('utf-8'), self.cache_resource) self.cache_resource.putChild( b"common", ProtectedFile(str(self.cache_root_dir / Path("common")))) # redirections for root in self.roots: - await root._initRedirections(self.options) + await root._init_redirections(self.options) # no need to keep url_redirections_dict, it will not be used anymore del self.options["url_redirections_dict"] @@ -1286,15 +1286,15 @@ self.site = server.Site(wrapped) self.site.sessionFactory = WebSession - def _bridgeCb(self): + def _bridge_cb(self): del self._bridge_retry - self.bridge.getReady( + self.bridge.ready_get( lambda: self.initialised.callback(None), lambda failure: self.initialised.errback(Exception(failure)), ) - self.initialised.addCallback(lambda __: defer.ensureDeferred(self.backendReady())) + self.initialised.addCallback(lambda __: defer.ensureDeferred(self.backend_ready())) - def _bridgeEb(self, failure_): + def _bridge_eb(self, failure_): if isinstance(failure_, BridgeExceptionNoService): if self._bridge_retry: if self._bridge_retry < 0: @@ -1309,7 +1309,7 @@ ).format(retries_left=self._bridge_retry) ) time.sleep(1) - self.bridge.bridgeConnect(callback=self._bridgeCb, errback=self._bridgeEb) + self.bridge.bridge_connect(callback=self._bridge_cb, errback=self._bridge_eb) return print("Can't connect to SàT backend, are you sure it's launched ?") @@ -1332,13 +1332,13 @@ return self._version_cache except AttributeError: self._version_cache = "{} ({})".format( - version, utils.getRepositoryData(libervia) + version, utils.get_repository_data(libervia) ) return self._version_cache else: return version - def bridgeCall(self, method_name, *args, **kwargs): + def bridge_call(self, method_name, *args, **kwargs): """Call an asynchronous bridge method and return a deferred @param method_name: name of the method as a unicode @@ -1407,8 +1407,8 @@ - C.PROFILE_LOGGED_EXT_JID @raise exceptions.ConflictError: session is already active """ - register_with_ext_jid = self.waiting_profiles.getRegisterWithExtJid(profile) - self.waiting_profiles.purgeRequest(profile) + register_with_ext_jid = self.waiting_profiles.get_register_with_ext_jid(profile) + self.waiting_profiles.purge_request(profile) session = request.getSession() web_session = session_iface.IWebSession(session) if web_session.profile: @@ -1420,7 +1420,7 @@ web_session.profile = str(profile) self.prof_connected.add(profile) cache_dir = os.path.join( - self.cache_root_dir, "profiles", regex.pathEscape(profile) + self.cache_root_dir, "profiles", regex.path_escape(profile) ) # FIXME: would be better to have a global /cache URL which redirect to # profile's cache directory, without uuid @@ -1442,16 +1442,16 @@ if web_session.ws_socket is not None: web_session.ws_socket.close() # and now we disconnect the profile - self.bridgeCall("disconnect", profile) + self.bridge_call("disconnect", profile) session.notifyOnExpire(on_expire) - # FIXME: those session infos should be returned by connect or isConnected - infos = await self.bridgeCall("sessionInfosGet", profile) + # FIXME: those session infos should be returned by connect or is_connected + infos = await self.bridge_call("session_infos_get", profile) web_session.jid = jid.JID(infos["jid"]) own_bare_jid_s = web_session.jid.userhost() - own_id_raw = await self.bridgeCall( - "identityGet", own_bare_jid_s, [], True, profile) + own_id_raw = await self.bridge_call( + "identity_get", own_bare_jid_s, [], True, profile) web_session.identities[own_bare_jid_s] = data_format.deserialise(own_id_raw) web_session.backend_started = int(infos["started"]) @@ -1476,7 +1476,7 @@ @raise exceptions.PermissionError: a login is not accepted (e.g. empty password not allowed) @raise exceptions.NotReady: a profile connection is already waiting - @raise exceptions.TimeoutError: didn't received and answer from Bridge + @raise exceptions.TimeoutError: didn't received and answer from bridge @raise exceptions.InternalError: unknown error @raise ValueError(C.PROFILE_AUTH_ERROR): invalid login and/or password @raise ValueError(C.XMPP_AUTH_ERROR): invalid XMPP account password @@ -1499,7 +1499,7 @@ raise failure.Failure(exceptions.DataError("No profile_key allowed")) # FIXME: should it be cached? - new_account_domain = yield self.bridgeCall("getNewAccountDomain") + new_account_domain = yield self.bridge_call("account_domain_new_get") if login_jid.host == new_account_domain: # redirect "user@libervia.org" to the "user" profile @@ -1509,7 +1509,7 @@ login_jid = None try: - profile = yield self.bridgeCall("profileNameGet", login) + profile = yield self.bridge_call("profile_name_get", login) except Exception: # XXX: ProfileUnknownError wouldn't work, it's encapsulated # FIXME: find a better way to handle bridge errors if ( @@ -1525,7 +1525,7 @@ ) ) profile = login # FIXME: what if there is a resource? - connect_method = "asyncConnectWithXMPPCredentials" + connect_method = "credentials_xmpp_connect" register_with_ext_jid = True else: # non existing username raise failure.Failure(exceptions.ProfileUnknownError()) @@ -1551,18 +1551,18 @@ "{new_profile} requested login, but {old_profile} was already " "connected, disconnecting {old_profile}").format( old_profile=web_session.profile, new_profile=profile)) - self.purgeSession(request) + self.purge_session(request) - if self.waiting_profiles.getRequest(profile): + if self.waiting_profiles.get_request(profile): # FIXME: check if and when this can happen raise failure.Failure(exceptions.NotReady("Already waiting")) - self.waiting_profiles.setRequest(request, profile, register_with_ext_jid) + self.waiting_profiles.set_request(request, profile, register_with_ext_jid) try: - connected = yield self.bridgeCall(connect_method, profile, password) + connected = yield self.bridge_call(connect_method, profile, password) except Exception as failure_: fault = getattr(failure_, 'classname', None) - self.waiting_profiles.purgeRequest(profile) + self.waiting_profiles.purge_request(profile) if fault in ("PasswordError", "ProfileUnknownError"): log.info("Profile {profile} doesn't exist or the submitted password is " "wrong".format( profile=profile)) @@ -1611,7 +1611,7 @@ state = yield defer.ensureDeferred(self._logged(profile, request)) defer.returnValue(state) - def registerNewAccount(self, request, login, password, email): + def register_new_account(self, request, login, password, email): """Create a new account, or return error @param request(server.Request): request linked to the session @param login(unicode): new account requested login @@ -1643,7 +1643,7 @@ def registered(result): return C.REGISTRATION_SUCCEED - def registeringError(failure_): + def registering_error(failure_): # FIXME: better error handling for bridge error is needed status = failure_.value.fullname.split('.')[-1] if status == "ConflictError": @@ -1660,9 +1660,9 @@ ) return status - d = self.bridgeCall("registerSatAccount", email, password, login) + d = self.bridge_call("libervia_account_register", email, password, login) d.addCallback(registered) - d.addErrback(registeringError) + d.addErrback(registering_error) return d def addCleanup(self, callback, *args, **kwargs): @@ -1674,7 +1674,7 @@ @param **kwargs: list of keyword arguments of the callback""" self._cleanup.insert(0, (callback, args, kwargs)) - def initEb(self, failure): + def init_eb(self, failure): from twisted.application import app if failure.check(SysExit): if failure.value.message: @@ -1687,7 +1687,7 @@ reactor.stop() return failure - def _buildOnlyCb(self, __): + def _build_only_cb(self, __): log.info(_("Stopping here due to --build-only flag")) self.stop() @@ -1695,20 +1695,20 @@ """Connect the profile for Libervia and start the HTTP(S) server(s)""" self._init() if self.options['build-only']: - self.initialised.addCallback(self._buildOnlyCb) + self.initialised.addCallback(self._build_only_cb) else: - self.initialised.addCallback(self._startService) - self.initialised.addErrback(self.initEb) + self.initialised.addCallback(self._start_service) + self.initialised.addErrback(self.init_eb) ## URLs ## - def putChildSAT(self, path, resource): + def put_child_sat(self, path, resource): """Add a child to the sat resource""" if not isinstance(path, bytes): raise ValueError("path must be specified in bytes") self.sat_root.putChild(path, resource) - def putChildAll(self, path, resource): + def put_child_all(self, path, resource): """Add a child to all vhost root resources""" if not isinstance(path, bytes): raise ValueError("path must be specified in bytes") @@ -1720,7 +1720,7 @@ for root in self.roots: root.putChild(path, wrapped_res) - def getBuildPath(self, site_name: str, dev: bool=False) -> Path: + def get_build_path(self, site_name: str, dev: bool=False) -> Path: """Generate build path for a given site name @param site_name: name of the site @@ -1732,15 +1732,15 @@ """ sub_dir = C.DEV_BUILD_DIR if dev else C.PRODUCTION_BUILD_DIR build_path_elts = [ - config.getConfig(self.main_conf, "", "local_dir"), + config.config_get(self.main_conf, "", "local_dir"), C.CACHE_DIR, C.LIBERVIA_CACHE, sub_dir, - regex.pathEscape(site_name or C.SITE_NAME_DEFAULT)] + regex.path_escape(site_name or C.SITE_NAME_DEFAULT)] build_path = Path("/".join(build_path_elts)) return build_path.expanduser().resolve() - def getExtBaseURLData(self, request): + def get_ext_base_url_data(self, request): """Retrieve external base URL Data this method try to retrieve the base URL found by external user @@ -1788,7 +1788,7 @@ "", ) - def getExtBaseURL( + def get_ext_base_url( self, request: server.Request, path: str = "", @@ -1807,7 +1807,7 @@ @param scheme: if not None, will override scheme from base URL @return: external URL """ - split_result = self.getExtBaseURLData(request) + split_result = self.get_ext_base_url_data(request) return urllib.parse.urlunsplit( ( split_result.scheme if scheme is None else scheme, @@ -1818,7 +1818,7 @@ ) ) - def checkRedirection(self, vhost_root: LiberviaRootResource, url_path: str) -> str: + def check_redirection(self, vhost_root: LiberviaRootResource, url_path: str) -> str: """check is a part of the URL prefix is redirected then replace it @param vhost_root: root of this virtual host @@ -1838,12 +1838,12 @@ ## Sessions ## - def purgeSession(self, request): + def purge_session(self, request): """helper method to purge a session during request handling""" session = request.session if session is not None: log.debug(_("session purge")) - web_session = self.getSessionData(request, session_iface.IWebSession) + web_session = self.get_session_data(request, session_iface.IWebSession) socket = web_session.ws_socket if socket is not None: socket.close() @@ -1853,7 +1853,7 @@ # session during request handling request._secureSession = request._insecureSession = None - def getSessionData(self, request, *args): + def get_session_data(self, request, *args): """helper method to retrieve session data @param request(server.Request): request linked to the session @@ -1867,7 +1867,7 @@ return (iface(session) for iface in args) @defer.inlineCallbacks - def getAffiliation(self, request, service, node): + def get_affiliation(self, request, service, node): """retrieve pubsub node affiliation for current user use cache first, and request pubsub service if not cache is found @@ -1876,16 +1876,16 @@ @param node(unicode): pubsub node @return (unicode): affiliation """ - web_session = self.getSessionData(request, session_iface.IWebSession) + web_session = self.get_session_data(request, session_iface.IWebSession) if web_session.profile is None: raise exceptions.InternalError("profile must be set to use this method") - affiliation = web_session.getAffiliation(service, node) + affiliation = web_session.get_affiliation(service, node) if affiliation is not None: defer.returnValue(affiliation) else: try: - affiliations = yield self.bridgeCall( - "psAffiliationsGet", service.full(), node, web_session.profile + affiliations = yield self.bridge_call( + "ps_affiliations_get", service.full(), node, web_session.profile ) except Exception as e: log.warning( @@ -1899,24 +1899,24 @@ affiliation = affiliations[node] except KeyError: affiliation = "" - web_session.setAffiliation(service, node, affiliation) + web_session.set_affiliation(service, node, affiliation) defer.returnValue(affiliation) ## Websocket (dynamic pages) ## def get_websocket_url(self, request): - base_url_split = self.getExtBaseURLData(request) + base_url_split = self.get_ext_base_url_data(request) if base_url_split.scheme.endswith("s"): scheme = "wss" else: scheme = "ws" - return self.getExtBaseURL(request, path=scheme, scheme=scheme) + return self.get_ext_base_url(request, path=scheme, scheme=scheme) ## Various utils ## - def getHTTPDate(self, timestamp=None): + def get_http_date(self, timestamp=None): now = time.gmtime(timestamp) fmt_date = "{day_name}, %d {month_name} %Y %H:%M:%S GMT".format( day_name=C.HTTP_DAYS[now.tm_wday], month_name=C.HTTP_MONTH[now.tm_mon - 1] @@ -1925,7 +1925,7 @@ ## service management ## - def _startService(self, __=None): + def _start_service(self, __=None): """Actually start the HTTP(S) server(s) after the profile for Libervia is connected. @raise ImportError: OpenSSL is not available @@ -1933,7 +1933,7 @@ @raise OpenSSL.crypto.Error: the certificate file is invalid """ # now that we have service profile connected, we add resource for its cache - service_path = regex.pathEscape(C.SERVICE_PROFILE) + service_path = regex.path_escape(C.SERVICE_PROFILE) cache_dir = os.path.join(self.cache_root_dir, "profiles", service_path) self.cache_resource.putChild(service_path.encode('utf-8'), ProtectedFile(cache_dir)) @@ -1942,8 +1942,8 @@ if self.options["connection_type"] in ("https", "both"): try: - tls.TLSOptionsCheck(self.options) - context_factory = tls.getTLSContextFactory(self.options) + tls.tls_options_check(self.options) + context_factory = tls.get_tls_context_factory(self.options) except exceptions.ConfigError as e: log.warning( f"There is a problem in TLS settings in your configuration file: {e}") @@ -1975,7 +1975,7 @@ for callback, args, kwargs in self._cleanup: callback(*args, **kwargs) try: - yield self.bridgeCall("disconnect", C.SERVICE_PROFILE) + yield self.bridge_call("disconnect", C.SERVICE_PROFILE) except Exception: log.warning("Can't disconnect service profile")