# HG changeset patch # User Goffi # Date 1680954251 -7200 # Node ID 106bae41f5c86de4be0f74213fa074837cabb107 # Parent ec3ad9abf9f946b21e0d8fcda647ff502bec5bc5 massive refactoring from camelCase -> snake_case. See backend commit log for more details diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/_bridge/page_meta.py --- a/libervia/pages/_bridge/page_meta.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/_bridge/page_meta.py Sat Apr 08 13:44:11 2023 +0200 @@ -14,20 +14,20 @@ on_data_post = "continue" # bridge method allowed when no profile is connected -NO_SESSION_ALLOWED = ("getContacts", "identitiesBaseGet", "identitiesGet") +NO_SESSION_ALLOWED = ("contacts_get", "identities_base_get", "identities_get") def parse_url(self, request): - self.getPathArgs(request, ["method_name"], min_args=1) + self.get_path_args(request, ["method_name"], min_args=1) async def render(self, request): if request.method != b'POST': log.warning(f"Bad method used with _bridge endpoint: {request.method.decode()}") - return self.pageError(request, C.HTTP_BAD_REQUEST) - data = self.getRData(request) - profile = self.getProfile(request) - self.checkCSRF(request) + return self.page_error(request, C.HTTP_BAD_REQUEST) + data = self.get_r_data(request) + profile = self.get_profile(request) + self.check_csrf(request) method_name = data["method_name"] if profile is None: if method_name in NO_SESSION_ALLOWED: @@ -35,7 +35,7 @@ profile = C.SERVICE_PROFILE else: log.warning("_bridge endpoint accessed without authorisation") - return self.pageError(request, C.HTTP_UNAUTHORIZED) + return self.page_error(request, C.HTTP_UNAUTHORIZED) method_data = json.load(request.content) try: bridge_method = getattr(self.host.restricted_bridge, method_name) @@ -44,7 +44,7 @@ "{profile!r} is trying to access a bridge method not implemented in " "RestrictedBridge: {method_name}").format( profile=profile, method_name=method_name)) - return self.pageError(request, C.HTTP_BAD_REQUEST) + return self.page_error(request, C.HTTP_BAD_REQUEST) try: args, kwargs = method_data['args'], method_data['kwargs'] @@ -52,14 +52,14 @@ log.warning(_( "{profile!r} has sent a badly formatted method call: {method_data}" ).format(profile=profile, method_data=method_data)) - return self.pageError(request, C.HTTP_BAD_REQUEST) + return self.page_error(request, C.HTTP_BAD_REQUEST) if "profile" in kwargs or "profile_key" in kwargs: log.warning(_( '"profile" key should not be in method kwargs, hack attempt? ' "profile={profile}, method_data={method_data}" ).format(profile=profile, method_data=method_data)) - return self.pageError(request, C.HTTP_BAD_REQUEST) + return self.page_error(request, C.HTTP_BAD_REQUEST) try: ret = await bridge_method(*args, **kwargs, profile=profile) diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/_browser/__init__.py --- a/libervia/pages/_browser/__init__.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/_browser/__init__.py Sat Apr 08 13:44:11 2023 +0200 @@ -1,5 +1,5 @@ import bridge -# we create a Bridge instance to receive signals -bridge.Bridge() +# we create a bridge instance to receive signals +bridge.bridge() diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/_browser/aio_bridge.py --- a/libervia/pages/_browser/aio_bridge.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/_browser/aio_bridge.py Sat Apr 08 13:44:11 2023 +0200 @@ -25,7 +25,7 @@ return self.classname == other -class Bridge: +class bridge: def __getattr__(self, attr): return lambda *args, **kwargs: self.call(attr, *args, **kwargs) diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/_browser/bridge.py --- a/libervia/pages/_browser/bridge.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/_browser/bridge.py Sat Apr 08 13:44:11 2023 +0200 @@ -243,12 +243,12 @@ }) -class Bridge: +class bridge: bc: BroadcastChannel | None = None def __init__(self) -> None: - if Bridge.bc is None: - Bridge.bc = BroadcastChannel() + if bridge.bc is None: + bridge.bc = BroadcastChannel() def __getattr__(self, attr): return lambda *args, **kwargs: self.call(attr, *args, **kwargs) diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/_browser/cache.py --- a/libervia/pages/_browser/cache.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/_browser/cache.py Sat Apr 08 13:44:11 2023 +0200 @@ -2,10 +2,10 @@ from browser.local_storage import storage from javascript import JSON from dialog import notification -from bridge import Bridge +from bridge import bridge session_uuid = window.session_uuid -bridge = Bridge() +bridge = bridge() # XXX: we don't use browser.object_storage because it is affected by # https://github.com/brython-dev/brython/issues/1467 and mixing local_storage.storage @@ -51,7 +51,7 @@ del self._completed_count self.update() - def getContactsCb(self, contacts): + def get_contacts_cb(self, contacts): print("roster received") roster = self._cache['roster'] for contact_jid, attributes, groups in contacts: @@ -61,7 +61,7 @@ } self._store_if_complete() - def identitiesBaseGetCb(self, identities_raw): + def identities_base_get_cb(self, identities_raw): print("base identities received") identities = JSON.parse(identities_raw) self._cache['identities'].update(identities) @@ -81,13 +81,13 @@ } self._completed_count = 2 print("requesting roster to backend") - bridge.getContacts( - callback=self.getContactsCb, + bridge.contacts_get( + callback=self.get_contacts_cb, errback=lambda e: self.request_failed(e, "Can't get contacts: {exc}") ) print("requesting base identities to backend") - bridge.identitiesBaseGet( - callback=self.identitiesBaseGetCb, + bridge.identities_base_get( + callback=self.identities_base_get_cb, errback=lambda e: self.request_failed(e, "Can't get base identities: {exc}") ) @@ -103,7 +103,7 @@ """Check that identities for entities exist, request them otherwise""" to_get = {e for e in entities if e not in self._cache['identities']} if to_get: - bridge.identitiesGet( + bridge.identities_get( list(to_get), ['avatar', 'nicknames'], callback=lambda identities: self._fill_identities_cb( diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/_browser/editor.py --- a/libervia/pages/_browser/editor.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/_browser/editor.py Sat Apr 08 13:44:11 2023 +0200 @@ -4,11 +4,11 @@ from browser.local_storage import storage from browser.object_storage import ObjectStorage from javascript import JSON -from aio_bridge import Bridge, BridgeException +from aio_bridge import bridge, BridgeException from template import Template import dialog -bridge = Bridge() +bridge = bridge() object_storage = ObjectStorage(storage) profile = window.profile @@ -214,7 +214,7 @@ data['tags'] = [t.strip() for t in tags.split(',') if t.strip()] try: preview_data = JSON.parse( - await bridge.mbPreview("", "", JSON.stringify(data)) + await bridge.mb_preview("", "", JSON.stringify(data)) ) except BridgeException as e: dialog.notification.show( diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/_browser/invitation.py --- a/libervia/pages/_browser/invitation.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/_browser/invitation.py Sat Apr 08 13:44:11 2023 +0200 @@ -1,11 +1,11 @@ from browser import document, window, timer -from bridge import Bridge +from bridge import bridge from template import Template import dialog from cache import cache import javascript -bridge = Bridge() +bridge = bridge() # we use JS RegExp because Python's re is really long to import in Brython # FIXME: this is a naive JID regex, a more accurate should be used instead jid_re = javascript.RegExp.new(r"^\w+@\w+\.\w+") @@ -78,7 +78,7 @@ path = self.invitation_data["path"] album_name = path.rsplit('/')[-1] print(f"inviting {entity_jid}") - bridge.FISInvite( + bridge.fis_invite( entity_jid, service, "photos", @@ -98,7 +98,7 @@ if namespace: extra["namespace"] = namespace print(f"inviting {entity_jid}") - bridge.psInvite( + bridge.ps_invite( entity_jid, service, node, @@ -241,7 +241,7 @@ level="success", ) - def invitationSimpleCreateCb(self, invitation_data, email, name): + def invitation_simple_create_cb(self, invitation_data, email, name): invitee_jid = invitation_data['jid'] self._invite_jid( invitee_jid, @@ -259,12 +259,12 @@ def invite_by_email(self, email, name): guest_url_tpl = f'{window.URL.new("/g", document.baseURI).href}/{{uuid}}' - bridge.invitationSimpleCreate( + bridge.invitation_simple_create( email, name, guest_url_tpl, '', - callback=lambda data: self.invitationSimpleCreateCb(data, email, name), + callback=lambda data: self.invitation_simple_create_cb(data, email, name), errback=lambda e: window.alert(f"can't send email invitation: {e}") ) @@ -306,7 +306,7 @@ ## affiliations - def _addAffiliationBindings(self, entity_jid, affiliation_elt): + def _add_affiliation_bindings(self, entity_jid, affiliation_elt): for elt in affiliation_elt.select(".click_to_delete"): elt.bind( "click", @@ -353,7 +353,7 @@ "identities": cache.identities, }) document['affiliations'] <= affiliation_elt - self._addAffiliationBindings(entity_jid, affiliation_elt) + self._add_affiliation_bindings(entity_jid, affiliation_elt) def _on_affiliation_remove_success(self, affiliation_elt, entity_jid): affiliation_elt.remove() @@ -363,7 +363,7 @@ if self.invitation_type == 'photos': path = self.invitation_data["path"] service = self.invitation_data["service"] - bridge.FISAffiliationsSet( + bridge.fis_affiliations_set( service, "", path, @@ -376,7 +376,7 @@ elif self.invitation_type == 'pubsub': service = self.invitation_data["service"] node = self.invitation_data["node"] - bridge.psNodeAffiliationsSet( + bridge.ps_node_affiliations_set( service, node, {entity_jid: "none"}, @@ -400,13 +400,13 @@ "identities": cache.identities, }) affiliation_elt.replaceWith(new_affiliation_elt) - self._addAffiliationBindings(entity_jid, new_affiliation_elt) + self._add_affiliation_bindings(entity_jid, new_affiliation_elt) def _on_affiliation_set_ok(self, entity_jid, name, affiliation_elt, affiliation): if self.invitation_type == 'pubsub': service = self.invitation_data["service"] node = self.invitation_data["node"] - bridge.psNodeAffiliationsSet( + bridge.ps_node_affiliations_set( service, node, {entity_jid: affiliation}, diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/_browser/template.py --- a/libervia/pages/_browser/template.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/_browser/template.py Sat Apr 08 13:44:11 2023 +0200 @@ -12,7 +12,7 @@ 'autoescape': True, 'trimBlocks': True, 'lstripBlocks': True, - 'web': {'useCache': True}, + 'web': {'use_cache': True}, }) nunjucks.installJinjaCompat() diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/blog/edit/page_meta.py --- a/libervia/pages/blog/edit/page_meta.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/blog/edit/page_meta.py Sat Apr 08 13:44:11 2023 +0200 @@ -12,11 +12,11 @@ async def on_data_post(self, request): - profile = self.getProfile(request) + profile = self.get_profile(request) if profile is None: - self.pageError(request, C.HTTP_FORBIDDEN) - request_data = self.getRData(request) - title, tags, body = self.getPostedData(request, ('title', 'tags', 'body')) + self.page_error(request, C.HTTP_FORBIDDEN) + request_data = self.get_r_data(request) + title, tags, body = self.get_posted_data(request, ('title', 'tags', 'body')) mb_data = {"content_rich": body, "allow_comments": True} title = title.strip() if title: @@ -25,12 +25,12 @@ if tags: mb_data["tags"] = tags - await self.host.bridgeCall( - 'mbSend', + await self.host.bridge_call( + 'mb_send', "", "", data_format.serialise(mb_data), profile ) - request_data["post_redirect_page"] = self.getPageByName("blog") + request_data["post_redirect_page"] = self.get_page_by_name("blog") diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/blog/page_meta.py --- a/libervia/pages/blog/page_meta.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/blog/page_meta.py Sat Apr 08 13:44:11 2023 +0200 @@ -16,11 +16,11 @@ async def prepare_render(self, request): - profile = self.getProfile(request) + profile = self.get_profile(request) template_data = request.template_data if profile is not None: - __, entities_own, entities_roster = await self.host.bridgeCall( - "discoFindByFeatures", + __, entities_own, entities_roster = await self.host.bridge_call( + "disco_find_by_features", [], [("pubsub", "pep")], True, @@ -34,17 +34,17 @@ list(entities_own.keys()) + list(entities_roster.keys()) ) entities_url = template_data["entities_url"] = {} - identities = self.host.getSessionData( + identities = self.host.get_session_data( request, session_iface.IWebSession ).identities d_list = {} for entity_jid_s in entities: - entities_url[entity_jid_s] = self.getPageByName("blog_view").getURL( + entities_url[entity_jid_s] = self.get_page_by_name("blog_view").get_url( entity_jid_s ) if entity_jid_s not in identities: - d_list[entity_jid_s] = self.host.bridgeCall( - "identityGet", + d_list[entity_jid_s] = self.host.bridge_call( + "identity_get", entity_jid_s, [], True, @@ -59,14 +59,14 @@ else: identities[entity_jid_s] = data_format.deserialise(identity_raw) - template_data["url_blog_edit"] = self.getSubPageURL(request, "blog_edit") + template_data["url_blog_edit"] = self.get_sub_page_url(request, "blog_edit") def on_data_post(self, request): - jid_str = self.getPostedData(request, "jid") + jid_str = self.get_posted_data(request, "jid") try: jid_ = jid.JID(jid_str) except RuntimeError: - self.pageError(request, C.HTTP_BAD_REQUEST) - url = self.getPageByName("blog_view").getURL(jid_.full()) - self.HTTPRedirect(request, url) + self.page_error(request, C.HTTP_BAD_REQUEST) + url = self.get_page_by_name("blog_view").get_url(jid_.full()) + self.http_redirect(request, url) diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/blog/view/atom.xml/page_meta.py --- a/libervia/pages/blog/view/atom.xml/page_meta.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/blog/view/atom.xml/page_meta.py Sat Apr 08 13:44:11 2023 +0200 @@ -11,26 +11,26 @@ async def prepare_render(self, request): request.setHeader("Content-Type", "application/atom+xml; charset=utf-8") - data = self.getRData(request) + data = self.get_r_data(request) service, node = data["service"], data.get("node") - self.checkCache( + self.check_cache( request, C.CACHE_PUBSUB, service=service, node=node, short="microblog" ) data["show_comments"] = False template_data = request.template_data - blog_page = self.getPageByName("blog_view") + blog_page = self.get_page_by_name("blog_view") await blog_page.prepare_render(self, request) items = data["blog_items"]['items'] - template_data["request_uri"] = self.host.getExtBaseURL( + template_data["request_uri"] = self.host.get_ext_base_url( request, request.path.decode("utf-8") ) - template_data["xmpp_uri"] = uri.buildXMPPUri( + template_data["xmpp_uri"] = uri.build_xmpp_uri( "pubsub", subtype="microblog", path=service.full(), node=node ) - blog_view = self.getPageByName("blog_view") - template_data["http_uri"] = self.host.getExtBaseURL( - request, blog_view.getURL(service.full(), node) + blog_view = self.get_page_by_name("blog_view") + template_data["http_uri"] = self.host.get_ext_base_url( + request, blog_view.get_url(service.full(), node) ) if items: template_data["updated"] = items[0]['updated'] diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/blog/view/page_meta.py --- a/libervia/pages/blog/view/page_meta.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/blog/view/page_meta.py Sat Apr 08 13:44:11 2023 +0200 @@ -30,7 +30,7 @@ args = [uri_data['path'], uri_data['node']] if 'item' in uri_data: args.extend(['id', uri_data['item']]) - return self.getURL(*args) + return self.get_url(*args) def parse_url(self, request): """URL is /[service]/[node]/[filter_keyword]/[item]|[other] @@ -41,10 +41,10 @@ id: next value is a item id tag: next value is a blog tag """ - data = self.getRData(request) + data = self.get_r_data(request) try: - service = self.nextPath(request) + service = self.next_path(request) except IndexError: data['service'] = '' else: @@ -52,16 +52,16 @@ data["service"] = jid.JID(service) except Exception: log.warning(_("bad service entered: {}").format(service)) - self.pageError(request, C.HTTP_BAD_REQUEST) + self.page_error(request, C.HTTP_BAD_REQUEST) try: - node = self.nextPath(request) + node = self.next_path(request) except IndexError: node = '@' data['node'] = '' if node == '@' else node try: - filter_kw = data['filter_keyword'] = self.nextPath(request) + filter_kw = data['filter_keyword'] = self.next_path(request) except IndexError: filter_kw = '@' else: @@ -70,28 +70,28 @@ pass elif filter_kw == 'id': try: - data['item'] = self.nextPath(request) + data['item'] = self.next_path(request) except IndexError: - self.pageError(request, C.HTTP_BAD_REQUEST) + self.page_error(request, C.HTTP_BAD_REQUEST) # we get one more argument in case text has been added to have a nice URL try: - self.nextPath(request) + self.next_path(request) except IndexError: pass elif filter_kw == 'tag': try: - data['tag'] = self.nextPath(request) + data['tag'] = self.next_path(request) except IndexError: - self.pageError(request, C.HTTP_BAD_REQUEST) + self.page_error(request, C.HTTP_BAD_REQUEST) else: # invalid filter keyword log.warning(_("invalid filter keyword: {filter_kw}").format( filter_kw=filter_kw)) - self.pageError(request, C.HTTP_BAD_REQUEST) + self.page_error(request, C.HTTP_BAD_REQUEST) # if URL is parsed here, we'll have atom.xml available and we need to # add the link to the page - atom_url = self.getURLByPath( + atom_url = self.get_url_by_path( SubPage('blog_view'), service, node, @@ -107,10 +107,10 @@ def add_breadcrumb(self, request, breadcrumbs): - data = self.getRData(request) + data = self.get_r_data(request) breadcrumbs.append({ "label": D_("Feed"), - "url": self.getURL(data["service"].full(), data.get("node", "@")) + "url": self.get_url(data["service"].full(), data.get("node", "@")) }) if "item" in data: breadcrumbs.append({ @@ -118,7 +118,7 @@ }) -async def appendComments( +async def append_comments( self, request: server.Request, blog_items: dict, @@ -133,10 +133,10 @@ """ if _seen is None: _seen = set() - await self.fillMissingIdentities( + await self.fill_missing_identities( request, [i['author_jid'] for i in blog_items['items']]) extra: Dict[str, Any] = {C.KEY_ORDER_BY: C.ORDER_BY_CREATION} - if not self.useCache(request): + if not self.use_cache(request): extra[C.KEY_USE_CACHE] = False for blog_item in blog_items['items']: for comment_data in blog_item['comments']: @@ -153,7 +153,7 @@ else: _seen.add(service_node) try: - comments_data = await self.host.bridgeCall('mbGet', + comments_data = await self.host.bridge_call('mb_get', service, node, C.NO_LIMIT, @@ -177,9 +177,9 @@ comment_data["items"] = [] continue comment_data['items'] = comments['items'] - await appendComments(self, request, comments, profile, _seen=_seen) + await append_comments(self, request, comments, profile, _seen=_seen) -async def getBlogItems( +async def get_blog_items( self, request: server.Request, service: jid.JID, @@ -193,9 +193,9 @@ items_id = [item_id] else: items_id = [] - if not self.useCache(request): + if not self.use_cache(request): extra[C.KEY_USE_CACHE] = False - blog_data = await self.host.bridgeCall('mbGet', + blog_data = await self.host.bridge_call('mb_get', service.userhost(), node, C.NO_LIMIT, @@ -205,7 +205,7 @@ except Exception as e: # FIXME: need a better way to test errors in bridge errback if "forbidden" in str(e): - self.pageError(request, 401) + self.page_error(request, 401) else: log.warning(_("can't retrieve blog for [{service}]: {msg}".format( service = service.userhost(), msg=e))) @@ -216,7 +216,7 @@ return blog_data async def prepare_render(self, request): - data = self.getRData(request) + data = self.get_r_data(request) template_data = request.template_data page_max = data.get("page_max", 10) # if the comments are not explicitly hidden, we show them @@ -226,7 +226,7 @@ data.get('item'), data.get('show_comments', True) ) - profile = self.getProfile(request) + profile = self.get_profile(request) if profile is None: profile = C.SERVICE_PROFILE profile_connected = False @@ -237,15 +237,15 @@ if item_id: extra = {} else: - extra = self.getPubsubExtra(request, page_max=page_max) + extra = self.get_pubsub_extra(request, page_max=page_max) tag = data.get('tag') if tag: extra[f'mam_filter_{C.MAM_FILTER_CATEGORY}'] = tag - self.handleSearch(request, extra) + self.handle_search(request, extra) ## main data ## # we get data from backend/XMPP here - blog_items = await getBlogItems(self, request, service, node, item_id, extra, profile) + blog_items = await get_blog_items(self, request, service, node, item_id, extra, profile) ## navigation ## # no let's fill service, node and pagination URLs @@ -257,13 +257,13 @@ if blog_items: if item_id: - template_data["previous_page_url"] = self.getURL( + template_data["previous_page_url"] = self.get_url( service.full(), node, before=item_id, page_max=1 ) - template_data["next_page_url"] = self.getURL( + template_data["next_page_url"] = self.get_url( service.full(), node, after=item_id, @@ -275,33 +275,33 @@ } blog_items["complete"] = False else: - self.setPagination(request, blog_items) + self.set_pagination(request, blog_items) else: if item_id: # if item id has been specified in URL and it's not found, # we must return an error - self.pageError(request, C.HTTP_NOT_FOUND) + self.page_error(request, C.HTTP_NOT_FOUND) ## identities ## # identities are used to show nice nickname or avatars - await self.fillMissingIdentities(request, [i['author_jid'] for i in blog_items['items']]) + await self.fill_missing_identities(request, [i['author_jid'] for i in blog_items['items']]) ## Comments ## # if comments are requested, we need to take them if show_comments: - await appendComments(self, request, blog_items, profile) + await append_comments(self, request, blog_items, profile) ## URLs ## # We will fill items_http_uri and tags_http_uri in template_data with suitable urls # if we know the profile, we use it instead of service + blog (nicer url) if target_profile is None: - blog_base_url_item = self.getPageByName('blog_view').getURL(service.full(), node or '@', 'id') - blog_base_url_tag = self.getPageByName('blog_view').getURL(service.full(), node or '@', 'tag') + blog_base_url_item = self.get_page_by_name('blog_view').get_url(service.full(), node or '@', 'id') + blog_base_url_tag = self.get_page_by_name('blog_view').get_url(service.full(), node or '@', 'tag') else: - blog_base_url_item = self.getURLByNames([('user', [target_profile]), ('user_blog', ['id'])]) - blog_base_url_tag = self.getURLByNames([('user', [target_profile]), ('user_blog', ['tag'])]) + blog_base_url_item = self.get_url_by_names([('user', [target_profile]), ('user_blog', ['id'])]) + blog_base_url_tag = self.get_url_by_names([('user', [target_profile]), ('user_blog', ['tag'])]) # we also set the background image if specified by user - bg_img = await self.host.bridgeCall('asyncGetParamA', 'Background', 'Blog page', 'value', -1, template_data['target_profile']) + bg_img = await self.host.bridge_call('param_get_a_async', 'Background', 'Blog page', 'value', -1, template_data['target_profile']) if bg_img: template_data['dynamic_style'] = safe(""" :root { @@ -327,7 +327,7 @@ # item's id is already user friendly. # TODO: to be removed, this is only kept for a transition period until # user friendly item IDs are more common. - text = regex.urlFriendlyText(item.get('title', item['content'])) + text = regex.url_friendly_text(item.get('title', item['content'])) if text: blog_url = blog_canonical_url + '/' + text else: @@ -335,11 +335,11 @@ else: blog_url = blog_canonical_url - items_http_uri[item['id']] = self.host.getExtBaseURL(request, blog_url) + items_http_uri[item['id']] = self.host.get_ext_base_url(request, blog_url) for tag in item['tags']: if tag not in tags_http_uri: tag_url = '/'.join([blog_base_url_tag, utils.quote(tag)]) - tags_http_uri[tag] = self.host.getExtBaseURL(request, tag_url) + tags_http_uri[tag] = self.host.get_ext_base_url(request, tag_url) # if True, page should display a comment box template_data['allow_commenting'] = data.get('allow_commenting', profile_connected) @@ -350,31 +350,31 @@ uri_args['node'] = node if item_id: uri_args['item'] = item_id - template_data['xmpp_uri'] = uri.buildXMPPUri( + template_data['xmpp_uri'] = uri.build_xmpp_uri( 'pubsub', subtype='microblog', **uri_args ) async def on_data_post(self, request): - profile = self.getProfile(request) + profile = self.get_profile(request) if profile is None: - self.pageError(request, C.HTTP_FORBIDDEN) - type_ = self.getPostedData(request, 'type') + self.page_error(request, C.HTTP_FORBIDDEN) + type_ = self.get_posted_data(request, 'type') if type_ == 'comment': - service, node, body = self.getPostedData(request, ('service', 'node', 'body')) + service, node, body = self.get_posted_data(request, ('service', 'node', 'body')) if not body: - self.pageError(request, C.HTTP_BAD_REQUEST) + self.page_error(request, C.HTTP_BAD_REQUEST) comment_data = {"content_rich": body} try: - await self.host.bridgeCall('mbSend', + await self.host.bridge_call('mb_send', service, node, data_format.serialise(comment_data), profile) except Exception as e: if "forbidden" in str(e): - self.pageError(request, 401) + self.page_error(request, 401) else: raise e else: diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/calendar/page_meta.py --- a/libervia/pages/calendar/page_meta.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/calendar/page_meta.py Sat Apr 08 13:44:11 2023 +0200 @@ -20,13 +20,13 @@ async def prepare_render(self, request): - profile = self.getProfile(request) + profile = self.get_profile(request) template_data = request.template_data - # template_data["url_event_new"] = self.getSubPageURL(request, "event_new") + # template_data["url_event_new"] = self.get_sub_page_url(request, "event_new") if profile is not None: try: events = data_format.deserialise( - await self.host.bridgeCall("eventsGet", "", "", [], "", profile), + await self.host.bridge_call("events_get", "", "", [], "", profile), type_check=list ) except Exception as e: @@ -44,7 +44,7 @@ calendar_end = template_data["calendar_end"] = datetime.datetime.combine( today_local, datetime.time.max, tzinfo=local_tz ).timestamp() - self.exposeToScripts( + self.expose_to_scripts( request, calendar_start=calendar_start, calendar_end=calendar_end, diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/chat/page_meta.py --- a/libervia/pages/chat/page_meta.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/chat/page_meta.py Sat Apr 08 13:44:11 2023 +0200 @@ -19,13 +19,13 @@ def parse_url(self, request): - rdata = self.getRData(request) + rdata = self.get_r_data(request) try: - target_jid_s = self.nextPath(request) + target_jid_s = self.next_path(request) except IndexError: # not chat jid, we redirect to jid selection page - self.pageRedirect("chat_select", request) + self.page_redirect("chat_select", request) try: target_jid = jid.JID(target_jid_s) @@ -35,7 +35,7 @@ log.warning( _("bad chat jid entered: {jid} ({msg})").format(jid=target_jid, msg=e) ) - self.pageError(request, C.HTTP_BAD_REQUEST) + self.page_error(request, C.HTTP_BAD_REQUEST) else: rdata["target"] = target_jid @@ -43,18 +43,18 @@ @defer.inlineCallbacks def prepare_render(self, request): #  FIXME: bug on room filtering (currently display messages from all rooms) - session = self.host.getSessionData(request, session_iface.IWebSession) + session = self.host.get_session_data(request, session_iface.IWebSession) template_data = request.template_data - rdata = self.getRData(request) + rdata = self.get_r_data(request) target_jid = rdata["target"] profile = session.profile profile_jid = session.jid - disco = yield self.host.bridgeCall("discoInfos", target_jid.host, "", True, profile) + disco = yield self.host.bridge_call("disco_infos", target_jid.host, "", True, profile) if "conference" in [i[0] for i in disco[1]]: chat_type = C.CHAT_GROUP - join_ret = yield self.host.bridgeCall( - "mucJoin", target_jid.userhost(), "", "", profile + join_ret = yield self.host.bridge_call( + "muc_join", target_jid.userhost(), "", "", profile ) (already_joined, room_jid_s, @@ -73,9 +73,9 @@ rdata["chat_type"] = chat_type template_data["own_jid"] = own_jid - self.registerSignal(request, "messageNew") - history = yield self.host.bridgeCall( - "historyGet", + self.register_signal(request, "message_new") + history = yield self.host.bridge_call( + "history_get", profile_jid.userhost(), target_jid.userhost(), 20, @@ -86,8 +86,8 @@ authors = {m[2] for m in history} identities = session.identities for author in authors: - id_raw = yield self.host.bridgeCall( - "identityGet", author, [], True, profile) + id_raw = yield self.host.bridge_call( + "identity_get", author, [], True, profile) identities[author] = data_format.deserialise(id_raw) template_data["messages"] = data_objects.Messages(history) @@ -97,8 +97,8 @@ def on_data(self, request, data): - session = self.host.getSessionData(request, session_iface.IWebSession) - rdata = self.getRData(request) + session = self.host.get_session_data(request, session_iface.IWebSession) + rdata = self.get_r_data(request) target = rdata["target"] data_type = data.get("type", "") if data_type == "msg": @@ -109,8 +109,8 @@ else C.MESS_TYPE_CHAT ) log.debug("message received: {}".format(message)) - self.host.bridgeCall( - "messageSend", + self.host.bridge_call( + "message_send", target.full(), {"": message}, {}, diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/chat/select/page_meta.py --- a/libervia/pages/chat/select/page_meta.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/chat/select/page_meta.py Sat Apr 08 13:44:11 2023 +0200 @@ -17,23 +17,23 @@ @defer.inlineCallbacks def prepare_render(self, request): - profile = self.getProfile(request) + profile = self.get_profile(request) template_data = request.template_data rooms = template_data["rooms"] = [] - bookmarks = yield self.host.bridgeCall("bookmarksList", "muc", "all", profile) + bookmarks = yield self.host.bridge_call("bookmarks_list", "muc", "all", profile) for bm_values in list(bookmarks.values()): for room_jid, room_data in bm_values.items(): - url = self.getPageByName("chat").getURL(room_jid) + url = self.get_page_by_name("chat").get_url(room_jid) rooms.append(data_objects.Room(room_jid, name=room_data.get("name"), url=url)) rooms.sort(key=lambda r: r.name) @defer.inlineCallbacks def on_data_post(self, request): - jid_ = self.getPostedData(request, "jid") + jid_ = self.get_posted_data(request, "jid") if "@" not in jid_: - profile = self.getProfile(request) - service = yield self.host.bridgeCall("mucGetService", "", profile) + profile = self.get_profile(request) + service = yield self.host.bridge_call("muc_get_service", "", profile) if service: muc_jid = jid.JID(service) muc_jid.user = jid_ @@ -41,5 +41,5 @@ else: log.warning(_("Invalid jid received: {jid}".format(jid=jid_))) defer.returnValue(C.POST_NO_CONFIRM) - url = self.getPageByName("chat").getURL(jid_) - self.HTTPRedirect(request, url) + url = self.get_page_by_name("chat").get_url(jid_) + self.http_redirect(request, url) diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/embed/page_meta.py --- a/libervia/pages/embed/page_meta.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/embed/page_meta.py Sat Apr 08 13:44:11 2023 +0200 @@ -11,13 +11,13 @@ def parse_url(self, request): - self.getPathArgs(request, ["app_name"], min_args=1) - data = self.getRData(request) + self.get_path_args(request, ["app_name"], min_args=1) + data = self.get_r_data(request) app_name = data["app_name"] try: app_data = self.vhost_root.libervia_apps[app_name] except KeyError: - self.pageError(request, C.HTTP_BAD_REQUEST) + self.page_error(request, C.HTTP_BAD_REQUEST) template_data = request.template_data template_data['full_screen_body'] = True try: diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/events/_browser/__init__.py --- a/libervia/pages/events/_browser/__init__.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/events/_browser/__init__.py Sat Apr 08 13:44:11 2023 +0200 @@ -1,9 +1,9 @@ from browser import DOMNode, document, aio from javascript import JSON -from aio_bridge import Bridge, BridgeException +from aio_bridge import bridge, BridgeException import dialog -bridge = Bridge() +bridge = bridge() async def on_delete(evt): @@ -23,7 +23,7 @@ return try: - await bridge.interestRetract("", item['interest_id']) + await bridge.interest_retract("", item['interest_id']) except BridgeException as e: dialog.notification.show( f"Can't remove list {item['name']!r} from personal interests: {e}", @@ -35,7 +35,7 @@ item_elt.bind("transitionend", lambda evt: item_elt.remove()) if item.get("creator", False): try: - await bridge.psNodeDelete( + await bridge.ps_node_delete( item['service'], item['node'], ) diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/events/admin/page_meta.py --- a/libervia/pages/events/admin/page_meta.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/events/admin/page_meta.py Sat Apr 08 13:44:11 2023 +0200 @@ -21,7 +21,7 @@ def parse_url(self, request): - self.getPathArgs( + self.get_path_args( request, ("event_service", "event_node", "event_id"), min_args=2, @@ -31,7 +31,7 @@ async def prepare_render(self, request): - data = self.getRData(request) + data = self.get_r_data(request) template_data = request.template_data ## Event ## @@ -39,8 +39,8 @@ event_service = template_data["event_service"] = data["event_service"] event_node = template_data["event_node"] = data["event_node"] event_id = template_data["event_id"] = data["event_id"] - profile = self.getProfile(request) - event_timestamp, event_data = await self.host.bridgeCall( + profile = self.get_profile(request) + event_timestamp, event_data = await self.host.bridge_call( "eventGet", event_service.userhost() if event_service else "", event_node, @@ -62,8 +62,8 @@ % html.escape(background_image, True) ) template_data["event"] = event_data - invitees = await self.host.bridgeCall( - "eventInviteesList", + invitees = await self.host.bridge_call( + "event_invitees_list", event_data["invitees_service"], event_data["invitees_node"], profile, @@ -92,30 +92,30 @@ # we now need blog items, using blog common page # this will fill the "items" template data - blog_page = self.getPageByName("blog_view") + blog_page = self.get_page_by_name("blog_view") await blog_page.prepare_render(self, request) async def on_data_post(self, request): - profile = self.getProfile(request) + profile = self.get_profile(request) if not profile: log.error("got post data without profile") - self.pageError(request, C.HTTP_INTERNAL_ERROR) - type_ = self.getPostedData(request, "type") + self.page_error(request, C.HTTP_INTERNAL_ERROR) + type_ = self.get_posted_data(request, "type") if type_ == "blog": - service, node, title, body, lang = self.getPostedData( + service, node, title, body, lang = self.get_posted_data( request, ("service", "node", "title", "body", "language") ) if not body.strip(): - self.pageError(request, C.HTTP_BAD_REQUEST) + self.page_error(request, C.HTTP_BAD_REQUEST) data = {"content": body} if title: data["title"] = title if lang: data["language"] = lang try: - comments = bool(self.getPostedData(request, "comments").strip()) + comments = bool(self.get_posted_data(request, "comments").strip()) except KeyError: pass else: @@ -123,15 +123,15 @@ data["allow_comments"] = True try: - await self.host.bridgeCall( - "mbSend", service, node, data_format.serialise(data), profile) + await self.host.bridge_call( + "mb_send", service, node, data_format.serialise(data), profile) except Exception as e: if "forbidden" in str(e): - self.pageError(request, C.HTTP_FORBIDDEN) + self.page_error(request, C.HTTP_FORBIDDEN) else: raise e elif type_ == "event": - service, node, event_id, jids, emails = self.getPostedData( + service, node, event_id, jids, emails = self.get_posted_data( request, ("service", "node", "event_id", "jids", "emails") ) for invitee_jid_s in jids.split(): @@ -142,8 +142,8 @@ _("this is not a valid jid: {jid}").format(jid=invitee_jid_s) ) continue - await self.host.bridgeCall( - "eventInvite", invitee_jid.userhost(), service, node, event_id, profile + await self.host.bridge_call( + "event_invite", invitee_jid.userhost(), service, node, event_id, profile ) for email_addr in emails.split(): if not REG_EMAIL_RE.match(email_addr): @@ -153,8 +153,8 @@ ) ) continue - await self.host.bridgeCall( - "eventInviteByEmail", + await self.host.bridge_call( + "event_invite_by_email", service, node, event_id, diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/events/new/page_meta.py --- a/libervia/pages/events/new/page_meta.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/events/new/page_meta.py Sat Apr 08 13:44:11 2023 +0200 @@ -16,9 +16,9 @@ @defer.inlineCallbacks def on_data_post(self, request): - request_data = self.getRData(request) - profile = self.getProfile(request) - title, location, body, date, main_img, bg_img = self.getPostedData( + request_data = self.get_r_data(request) + profile = self.get_profile(request) + title, location, body, date, main_img, bg_img = self.get_posted_data( request, ("name", "location", "body", "date", "main_image", "bg_image") ) timestamp = date_utils.date_parse(date) @@ -29,11 +29,11 @@ if not value: continue if not value.startswith("http"): - self.pageError(request, C.HTTP_BAD_REQUEST) + self.page_error(request, C.HTTP_BAD_REQUEST) data[var] = value data["register"] = C.BOOL_TRUE - node = yield self.host.bridgeCall("eventCreate", timestamp, data, "", "", "", profile) + node = yield self.host.bridge_call("event_create", timestamp, data, "", "", "", profile) log.info("Event node created at {node}".format(node=node)) - request_data["post_redirect_page"] = (self.getPageByName("event_admin"), "@", node) + request_data["post_redirect_page"] = (self.get_page_by_name("event_admin"), "@", node) defer.returnValue(C.POST_NO_CONFIRM) diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/events/page_meta.py --- a/libervia/pages/events/page_meta.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/events/page_meta.py Sat Apr 08 13:44:11 2023 +0200 @@ -17,13 +17,13 @@ async def prepare_render(self, request): - profile = self.getProfile(request) + profile = self.get_profile(request) template_data = request.template_data - template_data["url_event_new"] = self.getSubPageURL(request, "event_new") + template_data["url_event_new"] = self.get_sub_page_url(request, "event_new") if profile is not None: try: events = data_format.deserialise( - await self.host.bridgeCall("eventsGet", "", "", [], "", profile), + await self.host.bridge_call("events_get", "", "", [], "", profile), type_check=list ) except Exception as e: @@ -35,13 +35,13 @@ for event in events: if C.bool(event.get("creator", C.BOOL_FALSE)): own_events.append(event) - event["url"] = self.getSubPageURL( + event["url"] = self.get_sub_page_url( request, "event_admin", ) else: other_events.append(event) - event["url"] = self.getSubPageURL( + event["url"] = self.get_sub_page_url( request, "event_rsvp", ) diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/events/rsvp/page_meta.py --- a/libervia/pages/events/rsvp/page_meta.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/events/rsvp/page_meta.py Sat Apr 08 13:44:11 2023 +0200 @@ -20,7 +20,7 @@ def parse_url(self, request): - self.getPathArgs( + self.get_path_args( request, ("event_service", "event_node", "event_id"), min_args=2, @@ -32,15 +32,15 @@ @defer.inlineCallbacks def prepare_render(self, request): template_data = request.template_data - data = self.getRData(request) - profile = self.getProfile(request) + data = self.get_r_data(request) + profile = self.get_profile(request) ## Event ## event_service = data["event_service"] event_node = data["event_node"] event_id = data["event_id"] - event_timestamp, event_data = yield self.host.bridgeCall( + event_timestamp, event_data = yield self.host.bridge_call( "eventGet", event_service.userhost() if event_service else "", event_node, @@ -62,8 +62,8 @@ % html.escape(background_image, True) ) template_data["event"] = event_data - event_invitee_data = yield self.host.bridgeCall( - "eventInviteeGet", + event_invitee_data = yield self.host.bridge_call( + "event_invitee_get", event_data["invitees_service"], event_data["invitees_node"], '', @@ -80,22 +80,22 @@ # we now need blog items, using blog common page # this will fill the "items" template data - blog_page = self.getPageByName("blog_view") + blog_page = self.get_page_by_name("blog_view") yield blog_page.prepare_render(self, request) @defer.inlineCallbacks def on_data_post(self, request): - type_ = self.getPostedData(request, "type") + type_ = self.get_posted_data(request, "type") if type_ == "comment": - blog_page = self.getPageByName("blog_view") + blog_page = self.get_page_by_name("blog_view") yield blog_page.on_data_post(self, request) elif type_ == "attendance": - profile = self.getProfile(request) - service, node, attend, guests = self.getPostedData( + profile = self.get_profile(request) + service, node, attend, guests = self.get_posted_data( request, ("service", "node", "attend", "guests") ) data = {"attend": attend, "guests": guests} - yield self.host.bridgeCall("eventInviteeSet", service, node, data, profile) + yield self.host.bridge_call("event_invitee_set", service, node, data, profile) else: log.warning(_("Unhandled data type: {}").format(type_)) diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/events/view/page_meta.py --- a/libervia/pages/events/view/page_meta.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/events/view/page_meta.py Sat Apr 08 13:44:11 2023 +0200 @@ -21,26 +21,26 @@ @defer.inlineCallbacks def prepare_render(self, request): template_data = request.template_data - guest_session = self.host.getSessionData(request, session_iface.ISATGuestSession) + guest_session = self.host.get_session_data(request, session_iface.ISATGuestSession) try: event_uri = guest_session.data["event_uri"] except KeyError: log.warning(_("event URI not found, can't render event page")) - self.pageError(request, C.HTTP_SERVICE_UNAVAILABLE) + self.page_error(request, C.HTTP_SERVICE_UNAVAILABLE) - data = self.getRData(request) + data = self.get_r_data(request) ## Event ## - event_uri_data = uri.parseXMPPUri(event_uri) + event_uri_data = uri.parse_xmpp_uri(event_uri) if event_uri_data["type"] != "pubsub": - self.pageError(request, C.HTTP_SERVICE_UNAVAILABLE) + self.page_error(request, C.HTTP_SERVICE_UNAVAILABLE) event_service = template_data["event_service"] = jid.JID(event_uri_data["path"]) event_node = template_data["event_node"] = event_uri_data["node"] event_id = template_data["event_id"] = event_uri_data.get("item", "") - profile = self.getProfile(request) - event_timestamp, event_data = yield self.host.bridgeCall( + profile = self.get_profile(request) + event_timestamp, event_data = yield self.host.bridge_call( "eventGet", event_service.userhost(), event_node, event_id, profile ) try: @@ -58,8 +58,8 @@ % html.escape(background_image, True) ) template_data["event"] = event_data - event_invitee_data = yield self.host.bridgeCall( - "eventInviteeGet", + event_invitee_data = yield self.host.bridge_call( + "event_invitee_get", event_data["invitees_service"], event_data["invitees_node"], '', @@ -76,22 +76,22 @@ # we now need blog items, using blog common page # this will fill the "items" template data - blog_page = self.getPageByName("blog_view") + blog_page = self.get_page_by_name("blog_view") yield blog_page.prepare_render(self, request) @defer.inlineCallbacks def on_data_post(self, request): - type_ = self.getPostedData(request, "type") + type_ = self.get_posted_data(request, "type") if type_ == "comment": - blog_page = self.getPageByName("blog_view") + blog_page = self.get_page_by_name("blog_view") yield blog_page.on_data_post(self, request) elif type_ == "attendance": - profile = self.getProfile(request) - service, node, attend, guests = self.getPostedData( + profile = self.get_profile(request) + service, node, attend, guests = self.get_posted_data( request, ("service", "node", "attend", "guests") ) data = {"attend": attend, "guests": guests} - yield self.host.bridgeCall("eventInviteeSet", service, node, data, profile) + yield self.host.bridge_call("event_invitee_set", service, node, data, profile) else: log.warning(_("Unhandled data type: {}").format(type_)) diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/files/list/page_meta.py --- a/libervia/pages/files/list/page_meta.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/files/list/page_meta.py Sat Apr 08 13:44:11 2023 +0200 @@ -19,38 +19,38 @@ def parse_url(self, request): - self.getPathArgs(request, ["service", "*path"], min_args=1, service="jid", path="") + self.get_path_args(request, ["service", "*path"], min_args=1, service="jid", path="") def add_breadcrumb(self, request, breadcrumbs): - data = self.getRData(request) + data = self.get_r_data(request) breadcrumbs.append({ "label": data["service"], - "url": self.getURL(data["service"].full()), + "url": self.get_url(data["service"].full()), "icon": "server", }) for idx, p in enumerate(data["path"]): breadcrumbs.append({ "label": p, - "url": self.getURL(data["service"].full(), *data["path"][:idx+1]), + "url": self.get_url(data["service"].full(), *data["path"][:idx+1]), "icon": "folder-open-empty", }) async def prepare_render(self, request): - data = self.getRData(request) + data = self.get_r_data(request) thumb_limit = data.get("thumb_limit", 400) template_data = request.template_data service, path_elts = data["service"], data["path"] path = Path('/', *path_elts) - profile = self.getProfile(request) or C.SERVICE_PROFILE - session_data = self.host.getSessionData( + profile = self.get_profile(request) or C.SERVICE_PROFILE + session_data = self.host.get_session_data( request, session_iface.IWebSession ) try: - files_data = await self.host.bridgeCall( - "FISList", service.full(), str(path), {}, profile) + files_data = await self.host.bridge_call( + "fis_list", service.full(), str(path), {}, profile) except BridgeException as e: if e.condition == 'item-not-found': log.debug( @@ -70,7 +70,7 @@ if file_data["type"] == C.FILE_TYPE_DIRECTORY: page = self elif file_data["type"] == C.FILE_TYPE_FILE: - page = self.getPageByName("files_view") + page = self.get_page_by_name("files_view") # we set URL for the last thumbnail which has a size below thumb_limit try: @@ -90,12 +90,12 @@ raise ValueError( "unexpected file type: {file_type}".format(file_type=file_data["type"]) ) - file_data["url"] = page.getURL(service.full(), *dir_path) + file_data["url"] = page.get_url(service.full(), *dir_path) ## comments ## comments_url = file_data.get("comments_url") if comments_url: - parsed_url = uri.parseXMPPUri(comments_url) + parsed_url = uri.parse_xmpp_uri(comments_url) comments_service = file_data["comments_service"] = parsed_url["path"] comments_node = file_data["comments_node"] = parsed_url["node"] try: @@ -105,7 +105,7 @@ except KeyError: comments_count = None if comments_count and data.get("retrieve_comments", False): - file_data["comments"] = await pages_tools.retrieveComments( + file_data["comments"] = await pages_tools.retrieve_comments( self, comments_service, comments_node, profile=profile ) @@ -113,8 +113,8 @@ # TODO: some caching? What if affiliation changes? try: - affiliations = await self.host.bridgeCall( - "FISAffiliationsGet", service.full(), "", str(path), profile + affiliations = await self.host.bridge_call( + "fis_affiliations_get", service.full(), "", str(path), profile ) except BridgeException as e: if e.condition == 'item-not-found': @@ -134,7 +134,7 @@ if directory_affiliation == "owner": # we need to transtype dict items to str because with some bridges (D-Bus) # we have a specific type which can't be exposed - self.exposeToScripts( + self.expose_to_scripts( request, affiliations={str(e): str(a) for e, a in affiliations.items()} ) @@ -142,11 +142,11 @@ template_data["directory_affiliation"] = directory_affiliation template_data["files_data"] = files_data template_data["path"] = path - self.exposeToScripts( + self.expose_to_scripts( request, directory_affiliation=str(directory_affiliation), files_service=service.full(), files_path=str(path), ) if path_elts: - template_data["parent_url"] = self.getURL(service.full(), *path_elts[:-1]) + template_data["parent_url"] = self.get_url(service.full(), *path_elts[:-1]) diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/files/page_meta.py --- a/libervia/pages/files/page_meta.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/files/page_meta.py Sat Apr 08 13:44:11 2023 +0200 @@ -14,11 +14,11 @@ async def prepare_render(self, request): - profile = self.getProfile(request) + profile = self.get_profile(request) template_data = request.template_data namespace = self.host.ns_map["fis"] - entities_services, entities_own, entities_roster = await self.host.bridgeCall( - "discoFindByFeatures", [namespace], [], False, True, True, True, False, profile + entities_services, entities_own, entities_roster = await self.host.bridge_call( + "disco_find_by_features", [namespace], [], False, True, True, True, False, profile ) tpl_service_entities = template_data["disco_service_entities"] = {} tpl_own_entities = template_data["disco_own_entities"] = {} @@ -37,16 +37,16 @@ tpl_entities[entity_jid] = identities = {} for cat, type_, name in entity_ids: identities.setdefault(cat, {}).setdefault(type_, []).append(name) - entities_url[entity_jid] = self.getPageByName("files_list").getURL( + entities_url[entity_jid] = self.get_page_by_name("files_list").get_url( entity_jid.full() ) def on_data_post(self, request): - jid_str = self.getPostedData(request, "jid") + jid_str = self.get_posted_data(request, "jid") try: jid_ = jid.JID(jid_str) except RuntimeError: - self.pageError(request, C.HTTP_BAD_REQUEST) - url = self.getPageByName("files_list").getURL(jid_.full()) - self.HTTPRedirect(request, url) + self.page_error(request, C.HTTP_BAD_REQUEST) + url = self.get_page_by_name("files_list").get_url(jid_.full()) + self.http_redirect(request, url) diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/files/view/page_meta.py --- a/libervia/pages/files/view/page_meta.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/files/view/page_meta.py Sat Apr 08 13:44:11 2023 +0200 @@ -18,7 +18,7 @@ def parse_url(self, request): - self.getPathArgs(request, ["service", "*path"], min_args=2, service="jid", path="") + self.get_path_args(request, ["service", "*path"], min_args=2, service="jid", path="") def cleanup(__, tmp_dir, dest_path): @@ -33,8 +33,8 @@ async def render(self, request): - data = self.getRData(request) - profile = self.getProfile(request) + data = self.get_r_data(request) + profile = self.get_profile(request) service, path_elts = data["service"], data["path"] basename = path_elts[-1] dir_elts = path_elts[:-1] @@ -42,8 +42,8 @@ tmp_dir = tempfile.mkdtemp() dest_path = os.path.join(tmp_dir, basename) request.notifyFinish().addCallback(cleanup, tmp_dir, dest_path) - progress_id = await self.host.bridgeCall( - "fileJingleRequest", + progress_id = await self.host.bridge_call( + "file_jingle_request", service.full(), dest_path, basename, @@ -55,4 +55,4 @@ log.debug("file requested") await ProgressHandler(self.host, progress_id, profile).register() log.debug("file downloaded") - self.delegateToResource(request, static.File(dest_path)) + self.delegate_to_resource(request, static.File(dest_path)) diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/forums/list/page_meta.py --- a/libervia/pages/forums/list/page_meta.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/forums/list/page_meta.py Sat Apr 08 13:44:11 2023 +0200 @@ -16,7 +16,7 @@ def parse_url(self, request): - self.getPathArgs( + self.get_path_args( request, ["service", "node", "forum_key"], service="@jid", @@ -31,36 +31,36 @@ pass -def getLinks(self, forums): +def get_links(self, forums): for forum in forums: try: uri = forum["uri"] except KeyError: pass else: - uri = xmpp_uri.parseXMPPUri(uri) + uri = xmpp_uri.parse_xmpp_uri(uri) service = uri["path"] node = uri["node"] - forum["http_url"] = self.getPageByName("forum_topics").getURL(service, node) + forum["http_url"] = self.get_page_by_name("forum_topics").get_url(service, node) if "sub-forums" in forum: - getLinks(self, forum["sub-forums"]) + get_links(self, forum["sub-forums"]) async def prepare_render(self, request): - data = self.getRData(request) + data = self.get_r_data(request) template_data = request.template_data service, node, key = data["service"], data["node"], data["forum_key"] - profile = self.getProfile(request) or C.SERVICE_PROFILE + profile = self.get_profile(request) or C.SERVICE_PROFILE try: - forums_raw = await self.host.bridgeCall( - "forumsGet", service.full() if service else "", node, key, profile + forums_raw = await self.host.bridge_call( + "forums_get", service.full() if service else "", node, key, profile ) except Exception as e: log.warning(_("Can't retrieve forums: {msg}").format(msg=e)) forums = [] else: forums = json.loads(forums_raw) - getLinks(self, forums) + get_links(self, forums) template_data["forums"] = forums diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/forums/page_meta.py --- a/libervia/pages/forums/page_meta.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/forums/page_meta.py Sat Apr 08 13:44:11 2023 +0200 @@ -1,3 +1,3 @@ def prepare_render(self, request): - self.pageRedirect("forums", request, skip_parse_url=False) + self.page_redirect("forums", request, skip_parse_url=False) diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/forums/topics/new/page_meta.py --- a/libervia/pages/forums/topics/new/page_meta.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/forums/topics/new/page_meta.py Sat Apr 08 13:44:11 2023 +0200 @@ -26,26 +26,26 @@ async def on_data_post(self, request): - profile = self.getProfile(request) + profile = self.get_profile(request) if profile is None: - self.pageError(request, C.HTTP_FORBIDDEN) - rdata = self.getRData(request) + self.page_error(request, C.HTTP_FORBIDDEN) + rdata = self.get_r_data(request) service = rdata["service"].full() if rdata["service"] else "" node = rdata["node"] - title, body = self.getPostedData(request, ("title", "body")) + title, body = self.get_posted_data(request, ("title", "body")) title = title.strip() body = body.strip() if not title or not body: - self.pageError(request, C.HTTP_BAD_REQUEST) + self.page_error(request, C.HTTP_BAD_REQUEST) topic_data = {"title": title, "content": body} try: - await self.host.bridgeCall( - "forumTopicCreate", service, node, topic_data, profile + await self.host.bridge_call( + "forum_topic_create", service, node, topic_data, profile ) except Exception as e: if "forbidden" in str(e): - self.pageError(request, 401) + self.page_error(request, 401) else: raise e - rdata["post_redirect_page"] = (self.getPageByName("forum_topics"), service, node) + rdata["post_redirect_page"] = (self.get_page_by_name("forum_topics"), service, node) diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/forums/topics/page_meta.py --- a/libervia/pages/forums/topics/page_meta.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/forums/topics/page_meta.py Sat Apr 08 13:44:11 2023 +0200 @@ -17,73 +17,73 @@ def parse_url(self, request): - self.getPathArgs(request, ["service", "node"], 2, service="jid") + self.get_path_args(request, ["service", "node"], 2, service="jid") def add_breadcrumb(self, request, breadcrumbs): - data = self.getRData(request) + data = self.get_r_data(request) breadcrumbs.append({ "label": label, - "url": self.getURL(data["service"].full(), data["node"]) + "url": self.get_url(data["service"].full(), data["node"]) }) async def prepare_render(self, request): - profile = self.getProfile(request) or C.SERVICE_PROFILE - data = self.getRData(request) + profile = self.get_profile(request) or C.SERVICE_PROFILE + data = self.get_r_data(request) service, node = data["service"], data["node"] request.template_data.update({"service": service, "node": node}) template_data = request.template_data page_max = data.get("page_max", 20) - extra = self.getPubsubExtra(request, page_max=page_max) - topics, metadata = await self.host.bridgeCall( - "forumTopicsGet", + extra = self.get_pubsub_extra(request, page_max=page_max) + topics, metadata = await self.host.bridge_call( + "forum_topics_get", service.full(), node, extra, profile ) metadata = data_format.deserialise(metadata) - self.setPagination(request, metadata) - identities = self.host.getSessionData( + self.set_pagination(request, metadata) + identities = self.host.get_session_data( request, session_iface.IWebSession ).identities for topic in topics: - parsed_uri = xmpp_uri.parseXMPPUri(topic["uri"]) + parsed_uri = xmpp_uri.parse_xmpp_uri(topic["uri"]) author = topic["author"] - topic["http_uri"] = self.getPageByName("forum_view").getURL( + topic["http_uri"] = self.get_page_by_name("forum_view").get_url( parsed_uri["path"], parsed_uri["node"] ) if author not in identities: - id_raw = await self.host.bridgeCall( - "identityGet", author, [], True, profile + id_raw = await self.host.bridge_call( + "identity_get", author, [], True, profile ) identities[topic["author"]] = data_format.deserialise(id_raw) template_data["topics"] = topics - template_data["url_topic_new"] = self.getSubPageURL(request, "forum_topic_new") + template_data["url_topic_new"] = self.get_sub_page_url(request, "forum_topic_new") async def on_data_post(self, request): - profile = self.getProfile(request) + profile = self.get_profile(request) if profile is None: - self.pageError(request, C.HTTP_FORBIDDEN) - type_ = self.getPostedData(request, "type") + self.page_error(request, C.HTTP_FORBIDDEN) + type_ = self.get_posted_data(request, "type") if type_ == "new_topic": - service, node, title, body = self.getPostedData( + service, node, title, body = self.get_posted_data( request, ("service", "node", "title", "body") ) if not title or not body: - self.pageError(request, C.HTTP_BAD_REQUEST) + self.page_error(request, C.HTTP_BAD_REQUEST) topic_data = {"title": title, "content": body} try: - await self.host.bridgeCall( - "forumTopicCreate", service, node, topic_data, profile + await self.host.bridge_call( + "forum_topic_create", service, node, topic_data, profile ) except Exception as e: if "forbidden" in str(e): - self.pageError(request, 401) + self.page_error(request, 401) else: raise e else: diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/forums/view/page_meta.py --- a/libervia/pages/forums/view/page_meta.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/forums/view/page_meta.py Sat Apr 08 13:44:11 2023 +0200 @@ -15,36 +15,36 @@ def parse_url(self, request): - self.getPathArgs(request, ["service", "node"], 2, service="jid") + self.get_path_args(request, ["service", "node"], 2, service="jid") async def prepare_render(self, request): - data = self.getRData(request) + data = self.get_r_data(request) data["show_comments"] = False - blog_page = self.getPageByName("blog_view") + blog_page = self.get_page_by_name("blog_view") request.args[b"before"] = [b""] request.args[b"reverse"] = [b"1"] await blog_page.prepare_render(self, request) - request.template_data["login_url"] = self.getPageRedirectURL(request) + request.template_data["login_url"] = self.get_page_redirect_url(request) async def on_data_post(self, request): - profile = self.getProfile(request) + profile = self.get_profile(request) if profile is None: - self.pageError(request, C.HTTP_FORBIDDEN) - type_ = self.getPostedData(request, "type") + self.page_error(request, C.HTTP_FORBIDDEN) + type_ = self.get_posted_data(request, "type") if type_ == "comment": - service, node, body = self.getPostedData(request, ("service", "node", "body")) + service, node, body = self.get_posted_data(request, ("service", "node", "body")) if not body: - self.pageError(request, C.HTTP_BAD_REQUEST) + self.page_error(request, C.HTTP_BAD_REQUEST) mb_data = {"content_rich": body} try: - await self.host.bridgeCall( - "mbSend", service, node, data_format.serialise(mb_data), profile) + await self.host.bridge_call( + "mb_send", service, node, data_format.serialise(mb_data), profile) except Exception as e: if "forbidden" in str(e): - self.pageError(request, 401) + self.page_error(request, 401) else: raise e else: diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/g/page_meta.py --- a/libervia/pages/g/page_meta.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/g/page_meta.py Sat Apr 08 13:44:11 2023 +0200 @@ -18,11 +18,11 @@ if a session already exists for an other guest/profile, it will be purged """ try: - invitation_id = self.nextPath(request) + invitation_id = self.next_path(request) except IndexError: - self.pageError(request) + self.page_error(request) - web_session, guest_session = self.host.getSessionData( + web_session, guest_session = self.host.get_session_data( request, session_iface.IWebSession, session_iface.ISATGuestSession ) current_id = guest_session.id @@ -33,8 +33,8 @@ "killing guest session [{old_id}] because it is connecting with an other ID [{new_id}]" ).format(old_id=current_id, new_id=invitation_id) ) - self.host.purgeSession(request) - web_session, guest_session = self.host.getSessionData( + self.host.purge_session(request) + web_session, guest_session = self.host.get_session_data( request, session_iface.IWebSession, session_iface.ISATGuestSession ) current_id = None # FIXME: id not reset here @@ -47,8 +47,8 @@ "killing current profile session [{profile}] because a guest id is used" ).format(profile=profile) ) - self.host.purgeSession(request) - web_session, guest_session = self.host.getSessionData( + self.host.purge_session(request) + web_session, guest_session = self.host.get_session_data( request, session_iface.IWebSession, session_iface.ISATGuestSession ) profile = None @@ -56,9 +56,9 @@ if current_id is None: log.debug(_("checking invitation [{id}]").format(id=invitation_id)) try: - data = await self.host.bridgeCall("invitationGet", invitation_id) + data = await self.host.bridge_call("invitation_get", invitation_id) except Exception: - self.pageError(request, C.HTTP_FORBIDDEN) + self.page_error(request, C.HTTP_FORBIDDEN) else: guest_session.id = invitation_id guest_session.data = data @@ -76,7 +76,7 @@ log.warning(_("Can't connect profile: {msg}").format(msg=e)) # FIXME: no good error code correspond # maybe use a custom one? - self.pageError(request, code=C.HTTP_SERVICE_UNAVAILABLE) + self.page_error(request, code=C.HTTP_SERVICE_UNAVAILABLE) log.info( _( @@ -94,13 +94,13 @@ if "language" in data: template_data["locale"] = data["language"] -def handleEventInterest(self, interest): +def handle_event_interest(self, interest): if C.bool(interest.get("creator", C.BOOL_FALSE)): page_name = "event_admin" else: page_name = "event_rsvp" - interest["url"] = self.getPageByName(page_name).getURL( + interest["url"] = self.get_page_by_name(page_name).get_url( interest.get("service", ""), interest.get("node", ""), interest.get("item"), @@ -109,7 +109,7 @@ if "thumb_url" not in interest and "image" in interest: interest["thumb_url"] = interest["image"] -def handleFISInterest(self, interest): +def handle_fis_interest(self, interest): path = interest.get('path', '') path_args = [p for p in path.split('/') if p] subtype = interest.get('subtype') @@ -122,18 +122,18 @@ log.warning("unknown interest subtype: {subtype}".format(subtype=subtype)) return False - interest["url"] = self.getPageByName(page_name).getURL( + interest["url"] = self.get_page_by_name(page_name).get_url( interest['service'], *path_args) async def prepare_render(self, request): template_data = request.template_data - profile = self.getProfile(request) + profile = self.get_profile(request) # interests template_data['interests_map'] = interests_map = {} try: - interests = await self.host.bridgeCall( - "interestsList", "", "", "", profile) + interests = await self.host.bridge_call( + "interests_list", "", "", "", profile) except Exception: log.warning(_("Can't get interests list for {profile}").format( profile=profile)) @@ -143,8 +143,8 @@ # the data. If it returns False, the interest is skipped ns_data = {} - for short_name, cb in (('event', handleEventInterest), - ('fis', handleFISInterest), + for short_name, cb in (('event', handle_event_interest), + ('fis', handle_fis_interest), ): try: namespace = self.host.ns_map[short_name] @@ -164,9 +164,9 @@ interests_map.setdefault(key, []).append(interest) # main URI - guest_session = self.host.getSessionData(request, session_iface.ISATGuestSession) + guest_session = self.host.get_session_data(request, session_iface.ISATGuestSession) main_uri = guest_session.data.get("event_uri") if main_uri: - include_url = self.getPagePathFromURI(main_uri) + include_url = self.get_page_path_from_uri(main_uri) if include_url is not None: template_data["include_url"] = include_url diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/lists/_browser/__init__.py --- a/libervia/pages/lists/_browser/__init__.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/lists/_browser/__init__.py Sat Apr 08 13:44:11 2023 +0200 @@ -1,9 +1,9 @@ from browser import DOMNode, document, aio from javascript import JSON -from aio_bridge import Bridge, BridgeException +from aio_bridge import bridge, BridgeException import dialog -bridge = Bridge() +bridge = bridge() async def on_delete(evt): @@ -23,7 +23,7 @@ return try: - await bridge.interestRetract("", item['id']) + await bridge.interest_retract("", item['id']) except BridgeException as e: dialog.notification.show( f"Can't remove list {item['name']!r} from personal interests: {e}", @@ -35,7 +35,7 @@ item_elt.bind("transitionend", lambda evt: item_elt.remove()) if item.get("creator", False): try: - await bridge.psNodeDelete( + await bridge.ps_node_delete( item['service'], item['node'], ) diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/lists/create/page_meta.py --- a/libervia/pages/lists/create/page_meta.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/lists/create/page_meta.py Sat Apr 08 13:44:11 2023 +0200 @@ -12,20 +12,20 @@ def parse_url(self, request): - self.getPathArgs(request, ["template_id"]) - data = self.getRData(request) + self.get_path_args(request, ["template_id"]) + data = self.get_r_data(request) if data["template_id"]: - self.HTTPRedirect( + self.http_redirect( request, - self.getPageByName("list_create_from_tpl").getURL(data["template_id"]) + self.get_page_by_name("list_create_from_tpl").get_url(data["template_id"]) ) async def prepare_render(self, request): template_data = request.template_data - profile = self.getProfile(request) - tpl_raw = await self.host.bridgeCall( - "listTemplatesNamesGet", + profile = self.get_profile(request) + tpl_raw = await self.host.bridge_call( + "list_templates_names_get", "", profile, ) @@ -35,7 +35,7 @@ { "icon": tpl["icon"], "name": tpl["name"], - "url": self.getURL(tpl["id"]), + "url": self.get_url(tpl["id"]), } for tpl in lists_templates ] diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/lists/create_from_tpl/page_meta.py --- a/libervia/pages/lists/create_from_tpl/page_meta.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/lists/create_from_tpl/page_meta.py Sat Apr 08 13:44:11 2023 +0200 @@ -15,18 +15,18 @@ def parse_url(self, request): - self.getPathArgs(request, ["template_id"]) + self.get_path_args(request, ["template_id"]) async def prepare_render(self, request): - data = self.getRData(request) + data = self.get_r_data(request) template_id = data["template_id"] if not template_id: - self.pageError(request, C.HTTP_BAD_REQUEST) + self.page_error(request, C.HTTP_BAD_REQUEST) template_data = request.template_data - profile = self.getProfile(request) - tpl_raw = await self.host.bridgeCall( - "listTemplateGet", + profile = self.get_profile(request) + tpl_raw = await self.host.bridge_call( + "list_template_get", template_id, "", profile, @@ -36,20 +36,20 @@ template_data["list_template"] = template async def on_data_post(self, request): - data = self.getRData(request) + data = self.get_r_data(request) template_id = data['template_id'] - name, access = self.getPostedData(request, ('name', 'access')) + name, access = self.get_posted_data(request, ('name', 'access')) if access == 'private': access_model = 'whitelist' elif access == 'public': access_model = 'open' else: log.warning(f"Unknown access for template creation: {access}") - self.pageError(request, C.HTTP_BAD_REQUEST) - profile = self.getProfile(request) + self.page_error(request, C.HTTP_BAD_REQUEST) + profile = self.get_profile(request) try: - service, node = await self.host.bridgeCall( - "listTemplateCreate", template_id, name, access_model, profile + service, node = await self.host.bridge_call( + "list_template_create", template_id, name, access_model, profile ) except BridgeException as e: if e.condition == "conflict": @@ -58,7 +58,7 @@ log.error(f"Can't create list from template: {e}") raise e data["post_redirect_page"] = ( - self.getPageByName("lists"), + self.get_page_by_name("lists"), service, node or "@", ) diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/lists/edit/page_meta.py --- a/libervia/pages/lists/edit/page_meta.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/lists/edit/page_meta.py Sat Apr 08 13:44:11 2023 +0200 @@ -16,22 +16,22 @@ def parse_url(self, request): - self.getPathArgs(request, ["service", "node", "item_id"], service="jid", node="@") - data = self.getRData(request) + self.get_path_args(request, ["service", "node", "item_id"], service="jid", node="@") + data = self.get_r_data(request) if data["item_id"] is None: log.warning(_("no list item id specified")) - self.pageError(request, C.HTTP_BAD_REQUEST) + self.page_error(request, C.HTTP_BAD_REQUEST) @defer.inlineCallbacks def prepare_render(self, request): - data = self.getRData(request) + data = self.get_r_data(request) template_data = request.template_data service, node, item_id = ( data.get("service", ""), data.get("node", ""), data["item_id"], ) - profile = self.getProfile(request) + profile = self.get_profile(request) # we don't ignore "author" below to keep it when a list item is edited # by node owner/admin and "consistent publisher" is activated @@ -44,8 +44,8 @@ "updated", "comments_uri", ) - list_raw = yield self.host.bridgeCall( - "listGet", + list_raw = yield self.host.bridge_call( + "list_get", service.full() if service else "", node, C.NO_LIMIT, @@ -71,41 +71,41 @@ wid = list_item.widgets['body'] if wid.type == "xhtmlbox": wid.type = "textbox" - wid.value = yield self.host.bridgeCall( - "syntaxConvert", wid.value, C.SYNTAX_XHTML, "markdown", + wid.value = yield self.host.bridge_call( + "syntax_convert", wid.value, C.SYNTAX_XHTML, "markdown", False, profile) template_data["new_list_item_xmlui"] = list_item async def on_data_post(self, request): - data = self.getRData(request) + data = self.get_r_data(request) service = data["service"] node = data["node"] item_id = data["item_id"] - posted_data = self.getAllPostedData(request) + posted_data = self.get_all_posted_data(request) if not posted_data["title"] or not posted_data["body"]: - self.pageError(request, C.HTTP_BAD_REQUEST) + self.page_error(request, C.HTTP_BAD_REQUEST) try: posted_data["labels"] = [l.strip() for l in posted_data["labels"][0].split(",")] except (KeyError, IndexError): pass - profile = self.getProfile(request) + profile = self.get_profile(request) # we convert back body to XHTML - body = await self.host.bridgeCall( - "syntaxConvert", posted_data['body'][0], "markdown", C.SYNTAX_XHTML, + body = await self.host.bridge_call( + "syntax_convert", posted_data['body'][0], "markdown", C.SYNTAX_XHTML, False, profile) posted_data['body'] = ['
{body}
'.format(ns=C.NS_XHTML, body=body)] extra = {'update': True} - await self.host.bridgeCall( - "listSet", service.full(), node, posted_data, "", item_id, + await self.host.bridge_call( + "list_set", service.full(), node, posted_data, "", item_id, data_format.serialise(extra), profile ) data["post_redirect_page"] = ( - self.getPageByName("list_view"), + self.get_page_by_name("list_view"), service.full(), node or "@", item_id diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/lists/new/page_meta.py --- a/libervia/pages/lists/new/page_meta.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/lists/new/page_meta.py Sat Apr 08 13:44:11 2023 +0200 @@ -13,14 +13,14 @@ def parse_url(self, request): - self.getPathArgs(request, ["service", "node"], service="jid", node="@") + self.get_path_args(request, ["service", "node"], service="jid", node="@") async def prepare_render(self, request): - data = self.getRData(request) + data = self.get_r_data(request) template_data = request.template_data service, node = data.get("service", ""), data.get("node", "") - profile = self.getProfile(request) - schema = await self.host.bridgeCall("listSchemaGet", service.full(), node, profile) + profile = self.get_profile(request) + schema = await self.host.bridge_call("list_schema_get", service.full(), node, profile) data["schema"] = schema # following fields are handled in backend ignore = ( @@ -49,41 +49,41 @@ if wid.type == "xhtmlbox": # same as for list_edit, we have to convert for now wid.type = "textbox" - wid.value = await self.host.bridgeCall( - "syntaxConvert", wid.value, C.SYNTAX_XHTML, "markdown", + wid.value = await self.host.bridge_call( + "syntax_convert", wid.value, C.SYNTAX_XHTML, "markdown", False, profile) template_data["new_list_item_xmlui"] = xmlui_obj async def on_data_post(self, request): - data = self.getRData(request) + data = self.get_r_data(request) service = data["service"] node = data["node"] - posted_data = self.getAllPostedData(request) + posted_data = self.get_all_posted_data(request) if (("title" in posted_data and not posted_data["title"]) or ("body" in posted_data and not posted_data["body"])): - self.pageError(request, C.HTTP_BAD_REQUEST) + self.page_error(request, C.HTTP_BAD_REQUEST) try: posted_data["labels"] = [l.strip() for l in posted_data["labels"][0].split(",")] except (KeyError, IndexError): pass - profile = self.getProfile(request) + profile = self.get_profile(request) # we convert back body to XHTML if "body" in posted_data: - body = await self.host.bridgeCall( - "syntaxConvert", posted_data['body'][0], "markdown", C.SYNTAX_XHTML, + body = await self.host.bridge_call( + "syntax_convert", posted_data['body'][0], "markdown", C.SYNTAX_XHTML, False, profile) posted_data['body'] = ['
{body}
'.format(ns=C.NS_XHTML, body=body)] - await self.host.bridgeCall( - "listSet", service.full(), node, posted_data, "", "", "", profile + await self.host.bridge_call( + "list_set", service.full(), node, posted_data, "", "", "", profile ) # we don't want to redirect to creation page on success, but to list overview data["post_redirect_page"] = ( - self.getPageByName("lists"), + self.get_page_by_name("lists"), service.full(), node or "@", ) diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/lists/page_meta.py --- a/libervia/pages/lists/page_meta.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/lists/page_meta.py Sat Apr 08 13:44:11 2023 +0200 @@ -14,9 +14,9 @@ template = "list/discover.html" async def prepare_render(self, request): - profile = self.getProfile(request) + profile = self.get_profile(request) template_data = request.template_data - template_data["url_list_create"] = self.getPageByName("list_create").url + template_data["url_list_create"] = self.get_page_by_name("list_create").url lists_directory_config = self.host.options["lists_directory_json"] lists_directory = request.template_data["lists_directory"] = [] @@ -26,7 +26,7 @@ service = list_data["service"] node = list_data["node"] name = list_data["name"] - url = self.getPageByName("lists").getURL(service, node) + url = self.get_page_by_name("lists").get_url(service, node) lists_directory.append({"name": name, "url": url, "from_config": True}) except KeyError as e: log.warning("Missing field in lists_directory_json: {msg}".format(msg=e)) @@ -35,7 +35,7 @@ if profile is not None: try: - lists_list_raw = await self.host.bridgeCall("listsList", "", "", profile) + lists_list_raw = await self.host.bridge_call("lists_list", "", "", profile) except Exception as e: log.warning( _("Can't get list of registered lists for {profile}: {reason}") @@ -46,7 +46,7 @@ for list_data in lists_list: service = list_data["service"] node = list_data["node"] - list_data["url"] = self.getPageByName("lists").getURL(service, node) + list_data["url"] = self.get_page_by_name("lists").get_url(service, node) list_data["from_config"] = False lists_directory.append(list_data) @@ -61,11 +61,11 @@ def on_data_post(self, request): - jid_str = self.getPostedData(request, "jid") + jid_str = self.get_posted_data(request, "jid") try: jid_ = jid.JID(jid_str) except RuntimeError: - self.pageError(request, C.HTTP_BAD_REQUEST) + self.page_error(request, C.HTTP_BAD_REQUEST) # for now we just use default node - url = self.getPageByName("lists").getURL(jid_.full(), "@") - self.HTTPRedirect(request, url) + url = self.get_page_by_name("lists").get_url(jid_.full(), "@") + self.http_redirect(request, url) diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/lists/view/_browser/__init__.py --- a/libervia/pages/lists/view/_browser/__init__.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/lists/view/_browser/__init__.py Sat Apr 08 13:44:11 2023 +0200 @@ -1,11 +1,11 @@ from browser import window, document, aio, bind from invitation import InvitationManager from javascript import JSON -from aio_bridge import Bridge, BridgeException +from aio_bridge import bridge, BridgeException import dialog -bridge = Bridge() +bridge = bridge() lists_ns = window.lists_ns pubsub_service = window.pubsub_service pubsub_node = window.pubsub_node @@ -54,7 +54,7 @@ item_elt.classList.remove("selected_for_deletion") if confirmed: try: - await bridge.psItemRetract(pubsub_service, pubsub_node, item["id"], True) + await bridge.ps_item_retract(pubsub_service, pubsub_node, item["id"], True) except Exception as e: dialog.notification.show( f"Can't delete list item: {e}", @@ -105,7 +105,7 @@ return item_elt.dataset.item = JSON.stringify(item) try: - await bridge.listSet( + await bridge.list_set( pubsub_service, pubsub_node, # FIXME: value type should be consistent, or we should serialise diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/lists/view/page_meta.py --- a/libervia/pages/lists/view/page_meta.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/lists/view/page_meta.py Sat Apr 08 13:44:11 2023 +0200 @@ -15,41 +15,41 @@ def parse_url(self, request): - self.getPathArgs(request, ["service", "node"], service="jid") - data = self.getRData(request) + self.get_path_args(request, ["service", "node"], service="jid") + data = self.get_r_data(request) service, node = data["service"], data["node"] if node is None: - self.HTTPRedirect(request, self.getPageByName("lists_disco").url) + self.http_redirect(request, self.get_page_by_name("lists_disco").url) if node == "@": node = data["node"] = "" template_data = request.template_data - template_data["url_list_items"] = self.getURL(service.full(), node or "@") - template_data["url_list_new"] = self.getPageByName("list_new").getURL( + template_data["url_list_items"] = self.get_url(service.full(), node or "@") + template_data["url_list_new"] = self.get_page_by_name("list_new").get_url( service.full(), node or "@") async def prepare_render(self, request): - data = self.getRData(request) + data = self.get_r_data(request) template_data = request.template_data service, node = data["service"], data["node"] - submitted_node = await self.host.bridgeCall( - "psSchemaSubmittedNodeGet", + submitted_node = await self.host.bridge_call( + "ps_schema_submitted_node_get", node or self.host.ns_map["tickets"] ) - profile = self.getProfile(request) or C.SERVICE_PROFILE + profile = self.get_profile(request) or C.SERVICE_PROFILE - self.checkCache(request, C.CACHE_PUBSUB, service=service, node=node, short="tickets") + self.check_cache(request, C.CACHE_PUBSUB, service=service, node=node, short="tickets") try: - lists_types = self.getPageData(request, "lists_types") + lists_types = self.get_page_data(request, "lists_types") if lists_types is None: lists_types = {} - self.setPageData(request, "lists_types", lists_types) + self.set_page_data(request, "lists_types", lists_types) list_type = lists_types[(service, node)] except KeyError: ns_tickets_type = self.host.ns_map["tickets_type"] - schema_raw = await self.host.bridgeCall( - "psSchemaDictGet", + schema_raw = await self.host.bridge_call( + "ps_schema_dict_get", service.full(), submitted_node, profile @@ -71,12 +71,12 @@ data["list_type"] = template_data["list_type"] = list_type - extra = self.getPubsubExtra(request) + extra = self.get_pubsub_extra(request) extra["labels_as_list"] = C.BOOL_TRUE - self.handleSearch(request, extra) + self.handle_search(request, extra) - list_raw = await self.host.bridgeCall( - "listGet", + list_raw = await self.host.bridge_call( + "list_get", service.full() if service else "", node, C.NO_LIMIT, @@ -87,8 +87,8 @@ ) if profile != C.SERVICE_PROFILE: try: - affiliations = await self.host.bridgeCall( - "psNodeAffiliationsGet", + affiliations = await self.host.bridge_call( + "ps_node_affiliations_get", service.full() if service else "", submitted_node, profile @@ -99,10 +99,10 @@ ) template_data["owner"] = False else: - is_owner = affiliations.get(self.getJid(request).userhost()) == 'owner' + is_owner = affiliations.get(self.get_jid(request).userhost()) == 'owner' template_data["owner"] = is_owner if is_owner: - self.exposeToScripts( + self.expose_to_scripts( request, affiliations={str(e): str(a) for e, a in affiliations.items()} ) @@ -113,12 +113,12 @@ template_data["list_items"] = [ template_xmlui.create(self.host, x) for x in list_items ] - view_url = self.getPageByName('list_view').getURL(service.full(), node or '@') + view_url = self.get_page_by_name('list_view').get_url(service.full(), node or '@') template_data["on_list_item_click"] = data_objects.OnClick( url=f"{view_url}/{{item.id}}" ) - self.setPagination(request, metadata) - self.exposeToScripts( + self.set_pagination(request, metadata) + self.expose_to_scripts( request, lists_ns=self.host.ns_map["tickets"], pubsub_service=service.full(), @@ -128,22 +128,22 @@ async def on_data_post(self, request): - data = self.getRData(request) - profile = self.getProfile(request) + data = self.get_r_data(request) + profile = self.get_profile(request) service = data["service"] node = data["node"] - list_type = self.getPostedData(request, ("type",)) + list_type = self.get_posted_data(request, ("type",)) if list_type == "grocery": - name, quantity = self.getPostedData(request, ("name", "quantity")) + name, quantity = self.get_posted_data(request, ("name", "quantity")) if not name: - self.pageError(request, C.HTTP_BAD_REQUEST) + self.page_error(request, C.HTTP_BAD_REQUEST) item_data = { "name": [name], } if quantity: item_data["quantity"] = [quantity] - await self.host.bridgeCall( - "listSet", service.full(), node, item_data, "", "", "", profile + await self.host.bridge_call( + "list_set", service.full(), node, item_data, "", "", "", profile ) return C.POST_NO_CONFIRM else: diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/lists/view_item/_browser/__init__.py --- a/libervia/pages/lists/view_item/_browser/__init__.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/lists/view_item/_browser/__init__.py Sat Apr 08 13:44:11 2023 +0200 @@ -1,5 +1,5 @@ from browser import document, window, aio -from aio_bridge import Bridge +from aio_bridge import bridge import dialog try: @@ -9,7 +9,7 @@ except AttributeError: can_delete = False else: - bridge = Bridge() + bridge = bridge() can_delete = True @@ -29,7 +29,7 @@ else: print(f"deleting comment node at [{comments_service}] {comments_node!r}") try: - await bridge.psNodeDelete(comments_service, comments_node) + await bridge.ps_node_delete(comments_service, comments_node) except Exception as e: dialog.notification.show( f"Can't delete comment node: {e}", @@ -38,7 +38,7 @@ print(f"deleting list item {pubsub_item!r} at [{pubsub_service}] {pubsub_node!r}") try: - await bridge.psItemRetract(pubsub_service, pubsub_node, pubsub_item, True) + await bridge.ps_item_retract(pubsub_service, pubsub_node, pubsub_item, True) except Exception as e: dialog.notification.show( f"Can't delete list item: {e}", diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/lists/view_item/page_meta.py --- a/libervia/pages/lists/view_item/page_meta.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/lists/view_item/page_meta.py Sat Apr 08 13:44:11 2023 +0200 @@ -20,16 +20,16 @@ def parse_url(self, request): - self.getPathArgs(request, ["service", "node", "item_id"], service="jid", node="@") - data = self.getRData(request) + self.get_path_args(request, ["service", "node", "item_id"], service="jid", node="@") + data = self.get_r_data(request) if data["item_id"] is None: log.warning(_("no list item id specified")) - self.pageError(request, C.HTTP_BAD_REQUEST) + self.page_error(request, C.HTTP_BAD_REQUEST) def add_breadcrumb(self, request, breadcrumbs): - data = self.getRData(request) - list_url = self.getPageByName("lists").getURL(data["service"].full(), + data = self.get_r_data(request) + list_url = self.get_page_by_name("lists").get_url(data["service"].full(), data.get("node") or "@") breadcrumbs.append({ "label": D_("List"), @@ -41,23 +41,23 @@ async def prepare_render(self, request): - data = self.getRData(request) + data = self.get_r_data(request) template_data = request.template_data - session = self.host.getSessionData(request, session_iface.IWebSession) + session = self.host.get_session_data(request, session_iface.IWebSession) service, node, item_id = ( data.get("service", ""), data.get("node", ""), data["item_id"], ) namespace = node or self.host.ns_map["tickets"] - node = await self.host.bridgeCall("psSchemaSubmittedNodeGet", namespace) + node = await self.host.bridge_call("ps_schema_submitted_node_get", namespace) - profile = self.getProfile(request) + profile = self.get_profile(request) if profile is None: profile = C.SERVICE_PROFILE - list_raw = await self.host.bridgeCall( - "listGet", + list_raw = await self.host.bridge_call( + "list_get", service.full() if service else "", node, C.NO_LIMIT, @@ -75,12 +75,12 @@ pass else: if comments_uri: - uri_data = uri.parseXMPPUri(comments_uri) + uri_data = uri.parse_xmpp_uri(comments_uri) template_data["comments_node"] = comments_node = uri_data["node"] template_data["comments_service"] = comments_service = uri_data["path"] try: - comments = data_format.deserialise(await self.host.bridgeCall( - "mbGet", comments_service, comments_node, C.NO_LIMIT, [], + comments = data_format.deserialise(await self.host.bridge_call( + "mb_get", comments_service, comments_node, C.NO_LIMIT, [], data_format.serialise({}), profile )) except BridgeException as e: @@ -93,8 +93,8 @@ raise e else: template_data["comments"] = comments - template_data["login_url"] = self.getPageRedirectURL(request) - self.exposeToScripts( + template_data["login_url"] = self.get_page_redirect_url(request) + self.expose_to_scripts( request, comments_node=comments_node, comments_service=comments_service, @@ -107,16 +107,16 @@ is_publisher = publisher.userhostJID() == session.jid.userhostJID() affiliation = None if not is_publisher: - affiliation = await self.host.getAffiliation(request, service, node) + affiliation = await self.host.get_affiliation(request, service, node) if is_publisher or affiliation == "owner": - self.exposeToScripts( + self.expose_to_scripts( request, pubsub_service = service.full(), pubsub_node = node, pubsub_item = item_id, ) template_data["can_modify"] = True - template_data["url_list_item_edit"] = self.getURLByPath( + template_data["url_list_item_edit"] = self.get_url_by_path( SubPage("list_edit"), service.full(), node or "@", @@ -128,13 +128,13 @@ uri_args['node'] = node if item_id: uri_args['item'] = item_id - template_data['xmpp_uri'] = uri.buildXMPPUri('pubsub', **uri_args) + template_data['xmpp_uri'] = uri.build_xmpp_uri('pubsub', **uri_args) async def on_data_post(self, request): - type_ = self.getPostedData(request, "type") + type_ = self.get_posted_data(request, "type") if type_ == "comment": - blog_page = self.getPageByName("blog_view") + blog_page = self.get_page_by_name("blog_view") await blog_page.on_data_post(self, request) else: log.warning(_("Unhandled data type: {}").format(type_)) diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/login/logged/page_meta.py --- a/libervia/pages/login/logged/page_meta.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/login/logged/page_meta.py Sat Apr 08 13:44:11 2023 +0200 @@ -13,6 +13,6 @@ def prepare_render(self, request): template_data = request.template_data - session_data = self.host.getSessionData(request, session_iface.IWebSession) + session_data = self.host.get_session_data(request, session_iface.IWebSession) template_data["guest_session"] = session_data.guest template_data["session_started"] = session_data.started diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/login/page_meta.py --- a/libervia/pages/login/page_meta.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/login/page_meta.py Sat Apr 08 13:44:11 2023 +0200 @@ -21,13 +21,13 @@ template_data = request.template_data #  we redirect to logged page if a session is active - profile = self.getProfile(request) + profile = self.get_profile(request) if profile is not None: - self.pageRedirect("/login/logged", request) + self.page_redirect("/login/logged", request) # login error message - session_data = self.host.getSessionData(request, session_iface.IWebSession) - login_error = session_data.popPageData(self, "login_error") + session_data = self.host.get_session_data(request, session_iface.IWebSession) + login_error = session_data.pop_page_data(self, "login_error") if login_error is not None: template_data["S_C"] = C # we need server constants in template template_data["login_error"] = login_error @@ -37,10 +37,10 @@ # register page url if self.host.options["allow_registration"]: - template_data["register_url"] = self.getPageRedirectURL(request, "register") + template_data["register_url"] = self.get_page_redirect_url(request, "register") #  if login is set, we put it in template to prefill field - template_data["login"] = session_data.popPageData(self, "login") + template_data["login"] = session_data.pop_page_data(self, "login") def login_error(self, request, error_const): @@ -49,23 +49,23 @@ @param error_const(unicode): one of login error constant @return C.POST_NO_CONFIRM: avoid confirm message """ - session_data = self.host.getSessionData(request, session_iface.IWebSession) - session_data.setPageData(self, "login_error", error_const) + session_data = self.host.get_session_data(request, session_iface.IWebSession) + session_data.set_page_data(self, "login_error", error_const) return C.POST_NO_CONFIRM async def on_data_post(self, request): - profile = self.getProfile(request) - type_ = self.getPostedData(request, "type") + profile = self.get_profile(request) + type_ = self.get_posted_data(request, "type") if type_ == "disconnect": if profile is None: log.warning(_("Disconnect called when no profile is logged")) - self.pageError(request, C.HTTP_BAD_REQUEST) + self.page_error(request, C.HTTP_BAD_REQUEST) else: - self.host.purgeSession(request) + self.host.purge_session(request) return C.POST_NO_CONFIRM elif type_ == "login": - login, password = self.getPostedData(request, ("login", "password")) + login, password = self.get_posted_data(request, ("login", "password")) try: status = await self.host.connect(request, login, password) except exceptions.ProfileUnknownError: @@ -85,8 +85,8 @@ else: if status in (C.PROFILE_LOGGED, C.PROFILE_LOGGED_EXT_JID, C.SESSION_ACTIVE): # Profile has been logged correctly - self.redirectOrContinue(request) + self.redirect_or_continue(request) else: log.error(_("Unhandled status: {status}".format(status=status))) else: - self.pageError(request, C.HTTP_BAD_REQUEST) + self.page_error(request, C.HTTP_BAD_REQUEST) diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/merge-requests/disco/page_meta.py --- a/libervia/pages/merge-requests/disco/page_meta.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/merge-requests/disco/page_meta.py Sat Apr 08 13:44:11 2023 +0200 @@ -22,7 +22,7 @@ service = handler_data["service"] node = handler_data["node"] name = handler_data["name"] - url = self.getPageByName("merge-requests").getURL(service, node) + url = self.get_page_by_name("merge-requests").get_url(service, node) handlers.append({"name": name, "url": url}) except KeyError as e: log.warning("Missing field in mr_handlers_json: {msg}".format(msg=e)) @@ -31,11 +31,11 @@ def on_data_post(self, request): - jid_str = self.getPostedData(request, "jid") + jid_str = self.get_posted_data(request, "jid") try: jid_ = jid.JID(jid_str) except RuntimeError: - self.pageError(request, C.HTTP_BAD_REQUEST) + self.page_error(request, C.HTTP_BAD_REQUEST) # for now we just use default node - url = self.getPageByName("merge-requests").getURL(jid_.full(), "@") - self.HTTPRedirect(request, url) + url = self.get_page_by_name("merge-requests").get_url(jid_.full(), "@") + self.http_redirect(request, url) diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/merge-requests/edit/page_meta.py --- a/libervia/pages/merge-requests/edit/page_meta.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/merge-requests/edit/page_meta.py Sat Apr 08 13:44:11 2023 +0200 @@ -17,24 +17,24 @@ def parse_url(self, request): try: - item_id = self.nextPath(request) + item_id = self.next_path(request) except IndexError: log.warning(_("no list item id specified")) - self.pageError(request, C.HTTP_BAD_REQUEST) + self.page_error(request, C.HTTP_BAD_REQUEST) - data = self.getRData(request) + data = self.get_r_data(request) data["list_item_id"] = item_id async def prepare_render(self, request): - data = self.getRData(request) + data = self.get_r_data(request) template_data = request.template_data service, node, list_item_id = ( data.get("service", ""), data.get("node", ""), data["list_item_id"], ) - profile = self.getProfile(request) + profile = self.get_profile(request) ignore = ( "publisher", @@ -48,8 +48,8 @@ "type", ) merge_requests = data_format.deserialise( - await self.host.bridgeCall( - "mergeRequestsGet", + await self.host.bridge_call( + "merge_requests_get", service.full() if service else "", node, C.NO_LIMIT, @@ -76,37 +76,37 @@ wid = list_item.widgets['body'] if wid.type == "xhtmlbox": wid.type = "textbox" - wid.value = await self.host.bridgeCall( - "syntaxConvert", wid.value, C.SYNTAX_XHTML, "markdown", + wid.value = await self.host.bridge_call( + "syntax_convert", wid.value, C.SYNTAX_XHTML, "markdown", False, profile) template_data["new_list_item_xmlui"] = list_item async def on_data_post(self, request): - data = self.getRData(request) + data = self.get_r_data(request) service = data["service"] node = data["node"] list_item_id = data["list_item_id"] - posted_data = self.getAllPostedData(request) + posted_data = self.get_all_posted_data(request) if not posted_data["title"] or not posted_data["body"]: - self.pageError(request, C.HTTP_BAD_REQUEST) + self.page_error(request, C.HTTP_BAD_REQUEST) try: posted_data["labels"] = [l.strip() for l in posted_data["labels"][0].split(",")] except (KeyError, IndexError): pass - profile = self.getProfile(request) + profile = self.get_profile(request) # we convert back body to XHTML - body = await self.host.bridgeCall( - "syntaxConvert", posted_data['body'][0], "markdown", C.SYNTAX_XHTML, + body = await self.host.bridge_call( + "syntax_convert", posted_data['body'][0], "markdown", C.SYNTAX_XHTML, False, profile) posted_data['body'] = ['
{body}
'.format(ns=C.NS_XHTML, body=body)] extra = {'update': True} - await self.host.bridgeCall( - "mergeRequestSet", + await self.host.bridge_call( + "merge_request_set", service.full(), node, "", @@ -119,7 +119,7 @@ ) # we don't want to redirect to edit page on success, but to list overview data["post_redirect_page"] = ( - self.getPageByName("merge-requests"), + self.get_page_by_name("merge-requests"), service.full(), node or "@", ) diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/merge-requests/page_meta.py --- a/libervia/pages/merge-requests/page_meta.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/merge-requests/page_meta.py Sat Apr 08 13:44:11 2023 +0200 @@ -16,32 +16,32 @@ def parse_url(self, request): - self.getPathArgs(request, ["service", "node"], service="jid") - data = self.getRData(request) + self.get_path_args(request, ["service", "node"], service="jid") + data = self.get_r_data(request) service, node = data["service"], data["node"] if node is None: - self.pageRedirect("merge-requests_disco", request) + self.page_redirect("merge-requests_disco", request) if node == "@": node = data["node"] = "" - self.checkCache( + self.check_cache( request, C.CACHE_PUBSUB, service=service, node=node, short="merge-requests" ) template_data = request.template_data - template_data["url_list_items"] = self.getPageByName("merge-requests").getURL( + template_data["url_list_items"] = self.get_page_by_name("merge-requests").get_url( service.full(), node ) - template_data["url_list_new"] = self.getSubPageURL(request, "merge-requests_new") + template_data["url_list_new"] = self.get_sub_page_url(request, "merge-requests_new") async def prepare_render(self, request): - data = self.getRData(request) + data = self.get_r_data(request) template_data = request.template_data service, node = data["service"], data["node"] - profile = self.getProfile(request) or C.SERVICE_PROFILE + profile = self.get_profile(request) or C.SERVICE_PROFILE merge_requests = data_format.deserialise( - await self.host.bridgeCall( - "mergeRequestsGet", + await self.host.bridge_call( + "merge_requests_get", service.full() if service else "", node, C.NO_LIMIT, @@ -56,5 +56,5 @@ template_xmlui.create(self.host, x) for x in merge_requests['items'] ] template_data["on_list_item_click"] = data_objects.OnClick( - url=self.getSubPageURL(request, "merge-requests_view") + "/{item.id}" + url=self.get_sub_page_url(request, "merge-requests_view") + "/{item.id}" ) diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/merge-requests/view/page_meta.py --- a/libervia/pages/merge-requests/view/page_meta.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/merge-requests/view/page_meta.py Sat Apr 08 13:44:11 2023 +0200 @@ -19,32 +19,32 @@ def parse_url(self, request): try: - item_id = self.nextPath(request) + item_id = self.next_path(request) except IndexError: log.warning(_("no list item id specified")) - self.pageError(request, C.HTTP_BAD_REQUEST) + self.page_error(request, C.HTTP_BAD_REQUEST) - data = self.getRData(request) + data = self.get_r_data(request) data["list_item_id"] = item_id async def prepare_render(self, request): - data = self.getRData(request) + data = self.get_r_data(request) template_data = request.template_data - session = self.host.getSessionData(request, session_iface.IWebSession) + session = self.host.get_session_data(request, session_iface.IWebSession) service, node, list_item_id = ( data.get("service", ""), data.get("node", ""), data["list_item_id"], ) - profile = self.getProfile(request) + profile = self.get_profile(request) if profile is None: profile = C.SERVICE_PROFILE merge_requests = data_format.deserialise( - await self.host.bridgeCall( - "mergeRequestsGet", + await self.host.bridge_call( + "merge_requests_get", service.full() if service else "", node, C.NO_LIMIT, @@ -61,15 +61,15 @@ template_data["patches"] = merge_requests['items_patches'][0] comments_uri = list_item.widgets["comments_uri"].value if comments_uri: - uri_data = uri.parseXMPPUri(comments_uri) + uri_data = uri.parse_xmpp_uri(comments_uri) template_data["comments_node"] = comments_node = uri_data["node"] template_data["comments_service"] = comments_service = uri_data["path"] - template_data["comments"] = data_format.deserialise(await self.host.bridgeCall( - "mbGet", comments_service, comments_node, C.NO_LIMIT, [], + template_data["comments"] = data_format.deserialise(await self.host.bridge_call( + "mb_get", comments_service, comments_node, C.NO_LIMIT, [], data_format.serialise({}), profile )) - template_data["login_url"] = self.getPageRedirectURL(request) + template_data["login_url"] = self.get_page_redirect_url(request) if session.connected: # we set edition URL only if user is the publisher or the node owner @@ -78,9 +78,9 @@ affiliation = None if not is_publisher: node = node or self.host.ns_map["merge_requests"] - affiliation = await self.host.getAffiliation(request, service, node) + affiliation = await self.host.get_affiliation(request, service, node) if is_publisher or affiliation == "owner": - template_data["url_list_item_edit"] = self.getURLByPath( + template_data["url_list_item_edit"] = self.get_url_by_path( SubPage("merge-requests"), service.full(), node or "@", @@ -90,9 +90,9 @@ async def on_data_post(self, request): - type_ = self.getPostedData(request, "type") + type_ = self.get_posted_data(request, "type") if type_ == "comment": - blog_page = self.getPageByName("blog_view") + blog_page = self.get_page_by_name("blog_view") await blog_page.on_data_post(self, request) else: log.warning(_("Unhandled data type: {}").format(type_)) diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/photos/_browser/__init__.py --- a/libervia/pages/photos/_browser/__init__.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/photos/_browser/__init__.py Sat Apr 08 13:44:11 2023 +0200 @@ -1,9 +1,9 @@ from browser import window, bind, DOMNode from javascript import JSON -from bridge import Bridge +from bridge import bridge import dialog -bridge = Bridge() +bridge = bridge() def album_delete_cb(item_elt, item): @@ -19,7 +19,7 @@ print(f"{item['name']} removed successfuly from list of interests") item_elt.classList.add("state_deleted") item_elt.bind("transitionend", lambda evt: item_elt.remove()) - bridge.fileSharingDelete( + bridge.file_sharing_delete( item['service'], item.get('path', ''), item.get('files_namespace', ''), @@ -34,7 +34,7 @@ def delete_ok(evt, notif_elt, item_elt, item): - bridge.interestRetract( + bridge.interest_retract( "", item['id'], callback=lambda: interest_retract_cb(item_elt, item), errback=lambda failure:interest_retract_eb(failure, item_elt, item)) diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/photos/album/_browser/__init__.py --- a/libervia/pages/photos/album/_browser/__init__.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/photos/album/_browser/__init__.py Sat Apr 08 13:44:11 2023 +0200 @@ -1,7 +1,7 @@ from browser import document, window, bind, html, DOMNode, aio from javascript import JSON -from bridge import Bridge -from aio_bridge import Bridge as AIOBridge +from bridge import bridge +from aio_bridge import bridge as AIOBridge from template import Template import dialog from slideshow import SlideShow @@ -19,7 +19,7 @@ affiliations = window.affiliations.to_dict() except AttributeError: pass -bridge = Bridge() +bridge = bridge() aio_bridge = AIOBridge() alt_media_player.install_if_needed() @@ -96,7 +96,7 @@ photo_elt.classList.add("progress_started") album_items <= photo_elt - bridge.fileHTTPUploadGetSlot( + bridge.file_http_upload_get_slot( file_.name, file_.size, file_.type or '', @@ -145,7 +145,7 @@ def delete_ok(evt, notif_elt, item_elt, item): file_path = f"{files_path.rstrip('/')}/{item['name']}" - bridge.fileSharingDelete( + bridge.file_sharing_delete( files_service, file_path, "", @@ -192,7 +192,7 @@ img_name = img_elt.src.rsplit('/', 1)[-1] img_size = img_blob.size - slot = await aio_bridge.fileHTTPUploadGetSlot( + slot = await aio_bridge.file_http_upload_get_slot( img_name, img_size, '', @@ -209,7 +209,7 @@ return extra = {"thumb_url": get_url} album_name = files_path.rsplit('/', 1)[-1] - await aio_bridge.interestsRegisterFileSharing( + await aio_bridge.interests_file_sharing_register( files_service, "photos", "", diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/photos/album/page_meta.py --- a/libervia/pages/photos/album/page_meta.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/photos/album/page_meta.py Sat Apr 08 13:44:11 2023 +0200 @@ -14,17 +14,17 @@ def parse_url(self, request): - self.getPathArgs(request, ["service", "*path"], min_args=1, service="jid", path="") + self.get_path_args(request, ["service", "*path"], min_args=1, service="jid", path="") def prepare_render(self, request): - data = self.getRData(request) + data = self.get_r_data(request) data["thumb_limit"] = 800 data["retrieve_comments"] = True - files_page = self.getPageByName("files_list") + files_page = self.get_page_by_name("files_list") return files_page.prepare_render(self, request) def on_data_post(self, request): - blog_page = self.getPageByName("blog_view") + blog_page = self.get_page_by_name("blog_view") return blog_page.on_data_post(self, request) diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/photos/new/page_meta.py --- a/libervia/pages/photos/new/page_meta.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/photos/new/page_meta.py Sat Apr 08 13:44:11 2023 +0200 @@ -16,17 +16,17 @@ async def on_data_post(self, request): - request_data = self.getRData(request) - profile = self.getProfile(request) - name = self.getPostedData(request, "name").replace('/', '_') + request_data = self.get_r_data(request) + profile = self.get_profile(request) + name = self.get_posted_data(request, "name").replace('/', '_') albums_path = "/albums" album_path = f"{albums_path}/{name}" if profile is None: - self.pageError(request, C.HTTP_BAD_REQUEST) + self.page_error(request, C.HTTP_BAD_REQUEST) fis_ns = self.host.ns_map["fis"] http_upload_ns = self.host.ns_map["http_upload"] - entities_services, __, __ = await self.host.bridgeCall( - "discoFindByFeatures", + entities_services, __, __ = await self.host.bridge_call( + "disco_find_by_features", [fis_ns, http_upload_ns], [], False, @@ -44,8 +44,8 @@ "administrator to add one")) try: - await self.host.bridgeCall( - "FISCreateDir", + await self.host.bridge_call( + "fis_create_dir", fis_service, "", albums_path, @@ -60,8 +60,8 @@ raise e try: - await self.host.bridgeCall( - "FISCreateDir", + await self.host.bridge_call( + "fis_create_dir", fis_service, "", album_path, @@ -75,8 +75,8 @@ log.error(f"Can't create {album_path} path: {e}") raise e - await self.host.bridgeCall( - "interestsRegisterFileSharing", + await self.host.bridge_call( + "interests_file_sharing_register", fis_service, "photos", "", @@ -86,5 +86,5 @@ profile ) log.info(f"album {name} created") - request_data["post_redirect_page"] = self.getPageByName("photos") + request_data["post_redirect_page"] = self.get_page_by_name("photos") defer.returnValue(C.POST_NO_CONFIRM) diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/photos/page_meta.py --- a/libervia/pages/photos/page_meta.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/photos/page_meta.py Sat Apr 08 13:44:11 2023 +0200 @@ -15,13 +15,13 @@ @defer.inlineCallbacks def prepare_render(self, request): - profile = self.getProfile(request) + profile = self.get_profile(request) template_data = request.template_data namespace = self.host.ns_map["fis"] if profile is not None: try: - interests = yield self.host.bridgeCall( - "interestsList", "", "", namespace, profile) + interests = yield self.host.bridge_call( + "interests_list", "", "", namespace, profile) except Exception: log.warning(_("Can't get interests list for {profile}").format( profile=profile)) @@ -33,7 +33,7 @@ continue path = interest.get('path', '') path_args = [p for p in path.split('/') if p] - interest["url"] = self.getSubPageURL( + interest["url"] = self.get_sub_page_url( request, "photos_album", interest['service'], @@ -43,11 +43,11 @@ template_data['interests'] = filtered_interests - template_data["url_photos_new"] = self.getSubPageURL(request, "photos_new") + template_data["url_photos_new"] = self.get_sub_page_url(request, "photos_new") @defer.inlineCallbacks def on_data_post(self, request): - jid_ = self.getPostedData(request, "jid") - url = self.getPageByName("photos_album").getURL(jid_) - self.HTTPRedirect(request, url) + jid_ = self.get_posted_data(request, "jid") + url = self.get_page_by_name("photos_album").get_url(jid_) + self.http_redirect(request, url) diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/register/page_meta.py --- a/libervia/pages/register/page_meta.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/register/page_meta.py Sat Apr 08 13:44:11 2023 +0200 @@ -17,47 +17,47 @@ def prepare_render(self, request): if not self.host.options["allow_registration"]: - self.pageError(request, C.HTTP_FORBIDDEN) - profile = self.getProfile(request) + self.page_error(request, C.HTTP_FORBIDDEN) + profile = self.get_profile(request) if profile is not None: - self.pageRedirect("/login/logged", request) + self.page_redirect("/login/logged", request) template_data = request.template_data - template_data["login_url"] = self.getPageByName("login").url + template_data["login_url"] = self.get_page_by_name("login").url template_data["S_C"] = C # we need server constants in template # login error message - session_data = self.host.getSessionData(request, session_iface.IWebSession) - login_error = session_data.popPageData(self, "login_error") + session_data = self.host.get_session_data(request, session_iface.IWebSession) + login_error = session_data.pop_page_data(self, "login_error") if login_error is not None: template_data["login_error"] = login_error #  if fields were already filled, we reuse them for k in ("login", "email", "password"): - template_data[k] = session_data.popPageData(self, k) + template_data[k] = session_data.pop_page_data(self, k) @defer.inlineCallbacks def on_data_post(self, request): - type_ = self.getPostedData(request, "type") + type_ = self.get_posted_data(request, "type") if type_ == "register": - login, email, password = self.getPostedData( + login, email, password = self.get_posted_data( request, ("login", "email", "password") ) - status = yield self.host.registerNewAccount(request, login, password, email) - session_data = self.host.getSessionData(request, session_iface.IWebSession) + status = yield self.host.register_new_account(request, login, password, email) + session_data = self.host.get_session_data(request, session_iface.IWebSession) if status == C.REGISTRATION_SUCCEED: # we prefill login field for login page - session_data.setPageData(self.getPageByName("login"), "login", login) + session_data.set_page_data(self.get_page_by_name("login"), "login", login) # if we have a redirect_url we follow it - self.redirectOrContinue(request) + self.redirect_or_continue(request) # else we redirect to login page - self.HTTPRedirect(request, self.getPageByName("login").url) + self.http_redirect(request, self.get_page_by_name("login").url) else: - session_data.setPageData(self, "login_error", status) + session_data.set_page_data(self, "login_error", status) l = locals() for k in ("login", "email", "password"): # we save fields so user doesn't have to enter them again - session_data.setPageData(self, k, l[k]) + session_data.set_page_data(self, k, l[k]) defer.returnValue(C.POST_NO_CONFIRM) else: - self.pageError(request, C.HTTP_BAD_REQUEST) + self.page_error(request, C.HTTP_BAD_REQUEST) diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/u/blog/page_meta.py --- a/libervia/pages/u/blog/page_meta.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/u/blog/page_meta.py Sat Apr 08 13:44:11 2023 +0200 @@ -8,8 +8,8 @@ # in this subpage, we want path args and query args # (i.e. what's remaining in URL: filters, id, etc.) # to be used by blog's url parser, so we don't skip parse_url - data = self.getRData(request) + data = self.get_r_data(request) service = data["service"] - self.pageRedirect( + self.page_redirect( "blog_view", request, skip_parse_url=False, path_args=[service.full(), "@"] ) diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/pages/u/page_meta.py --- a/libervia/pages/u/page_meta.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/pages/u/page_meta.py Sat Apr 08 13:44:11 2023 +0200 @@ -16,23 +16,23 @@ @defer.inlineCallbacks def parse_url(self, request): try: - prof_requested = self.nextPath(request) + prof_requested = self.next_path(request) except IndexError: - self.pageError(request) + self.page_error(request) - data = self.getRData(request) + data = self.get_r_data(request) - target_profile = yield self.host.bridgeCall("profileNameGet", prof_requested) + target_profile = yield self.host.bridge_call("profile_name_get", prof_requested) request.template_data["target_profile"] = target_profile - target_jid = yield self.host.bridgeCall( - "asyncGetParamA", "JabberID", "Connection", "value", profile_key=target_profile + target_jid = yield self.host.bridge_call( + "param_get_a_async", "JabberID", "Connection", "value", profile_key=target_profile ) target_jid = jid.JID(target_jid) data["service"] = target_jid # if URL is parsed here, we'll have atom.xml available and we need to # add the link to the page - atom_url = self.getSubPageURL(request, 'user_blog_feed_atom') + atom_url = self.get_sub_page_url(request, 'user_blog_feed_atom') request.template_data['atom_url'] = atom_url request.template_data.setdefault('links', []).append({ "href": atom_url, @@ -47,11 +47,11 @@ @defer.inlineCallbacks def prepare_render(self, request): - data = self.getRData(request) - self.checkCache( + data = self.get_r_data(request) + self.check_cache( request, C.CACHE_PUBSUB, service=data["service"], node=None, short="microblog" ) - self.pageRedirect("blog_view", request) + self.page_redirect("blog_view", request) def on_data_post(self, request): - return self.getPageByName("blog_view").on_data_post(self, request) + return self.get_page_by_name("blog_view").on_data_post(self, request) diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/server/html_tools.py --- a/libervia/server/html_tools.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/server/html_tools.py Sat Apr 08 13:44:11 2023 +0200 @@ -18,7 +18,7 @@ # along with this program. If not, see . -def sanitizeHtml(text): +def sanitize_html(text): """Sanitize HTML by escaping everything""" # this code comes from official python wiki: http://wiki.python.org/moin/EscapingHtml html_escape_table = { @@ -32,5 +32,5 @@ return "".join(html_escape_table.get(c, c) for c in text) -def convertNewLinesToXHTML(text): +def convert_new_lines_to_xhtml(text): return text.replace("\n", "
") diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/server/pages.py --- a/libervia/server/pages.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/server/pages.py Sat Apr 08 13:44:11 2023 +0200 @@ -39,7 +39,7 @@ from sat.core.i18n import _ from sat.core import exceptions -from sat.tools.utils import asDeferred +from sat.tools.utils import as_deferred from sat.tools.common import date_utils from sat.tools.common import utils from sat.tools.common import data_format @@ -137,10 +137,10 @@ can then be used for e.g. redirection "/" is not allowed in names (as it can be used to construct URL paths) @param redirect(unicode, None): if not None, this page will be redirected. - A redirected parameter is used as in self.pageRedirect. + A redirected parameter is used as in self.page_redirect. parse_url will not be skipped using this redirect parameter is called "full redirection" - using self.pageRedirect is called "partial redirection" (because some + using self.page_redirect is called "partial redirection" (because some rendering method can still be used, e.g. parse_url) @param access(unicode, None): permission needed to access the page None means public access. @@ -217,7 +217,7 @@ ): raise ValueError( _("you can't use full page redirection with other rendering" - "method, check self.pageRedirect if you need to use them")) + "method, check self.page_redirect if you need to use them")) self.redirect = redirect else: self.redirect = None @@ -274,7 +274,7 @@ return self.vhost_root.site_themes @staticmethod - def createPage(host, meta_path, vhost_root, url_elts, replace_on_conflict=False): + def create_page(host, meta_path, vhost_root, url_elts, replace_on_conflict=False): """Create a LiberviaPage instance @param meta_path(Path): path to the page_meta.py file @@ -314,7 +314,7 @@ ) @staticmethod - def createBrowserData( + def create_browser_data( vhost_root, resource: Optional[LiberviaPage], browser_path: Path, @@ -355,7 +355,7 @@ @classmethod - def importPages(cls, host, vhost_root, root_path=None, _parent=None, _path=None, + def import_pages(cls, host, vhost_root, root_path=None, _parent=None, _path=None, _extra_pages=False): """Recursively import Libervia pages @@ -381,7 +381,7 @@ _parent = vhost_root root_browser_path = root_dir / C.PAGES_BROWSER_DIR if root_browser_path.is_dir(): - cls.createBrowserData(vhost_root, None, root_browser_path, None) + cls.create_browser_data(vhost_root, None, root_browser_path, None) else: root_dir = _parent.root_dir @@ -397,7 +397,7 @@ if meta_path.is_file(): new_path = _path + [d] try: - page_data, resource = cls.createPage( + page_data, resource = cls.create_page( host, meta_path, vhost_root, new_path) except exceptions.ConflictError as e: if _extra_pages: @@ -431,18 +431,18 @@ .format(name=cb_name, *uri_tuple)) continue else: - resource.registerURI(uri_tuple, cb) + resource.register_uri(uri_tuple, cb) - LiberviaPage.importPages( + LiberviaPage.import_pages( host, vhost_root, _parent=resource, _path=new_path, _extra_pages=_extra_pages) # now we check if there is some code for browser browser_path = dir_path / C.PAGES_BROWSER_DIR if browser_path.is_dir(): - cls.createBrowserData(vhost_root, resource, browser_path, new_path) + cls.create_browser_data(vhost_root, resource, browser_path, new_path) @classmethod - def onFileChange(cls, host, file_path, flags, site_root, site_path): + def on_file_change(cls, host, file_path, flags, site_root, site_path): """Method triggered by file_watcher when something is changed in files This method is used in dev mode to reload pages when needed @@ -506,7 +506,7 @@ try: # we (re)create a page with the new/modified code - __, resource = cls.createPage(host, path, site_root, path_elts, + __, resource = cls.create_page(host, path, site_root, path_elts, replace_on_conflict=True) if not new_page: try: @@ -528,7 +528,7 @@ # is there any browser data to create? browser_path = resource.root_dir / C.PAGES_BROWSER_DIR if browser_path.is_dir(): - cls.createBrowserData( + cls.create_browser_data( resource.vhost_root, resource, browser_path, @@ -540,8 +540,8 @@ else: log.info(_("{page} reloaded").format(page=resource)) - def checkCSRF(self, request): - session = self.host.getSessionData( + def check_csrf(self, request): + session = self.host.get_session_data( request, session_iface.IWebSession ) if session.profile is None: @@ -552,7 +552,7 @@ given_csrf = request.getHeader("X-Csrf-Token") if given_csrf is None: try: - given_csrf = self.getPostedData(request, "csrf_token") + given_csrf = self.get_posted_data(request, "csrf_token") except KeyError: pass if given_csrf is None or given_csrf != csrf_token: @@ -561,9 +561,9 @@ url=request.uri, ip=request.getClientIP() ) ) - self.pageError(request, C.HTTP_FORBIDDEN) + self.page_error(request, C.HTTP_FORBIDDEN) - def exposeToScripts( + def expose_to_scripts( self, request: server.Request, **kwargs: str @@ -585,11 +585,11 @@ value = repr(value) scripts.add(Script(content=f"var {name}={value};")) - def registerURI(self, uri_tuple, get_uri_cb): + def register_uri(self, uri_tuple, get_uri_cb): """Register a URI handler @param uri_tuple(tuple[unicode, unicode]): type or URIs handler - type/subtype as returned by tools/common/parseXMPPUri + type/subtype as returned by tools/common/parse_xmpp_uri or type/None to handle all subtypes @param get_uri_cb(callable): method which take uri_data dict as only argument and return absolute path with correct arguments or None if the page @@ -600,20 +600,20 @@ .format( *uri_tuple)) self.uri_callbacks[uri_tuple] = (self, get_uri_cb) - def getConfig(self, key, default=None, value_type=None): - return self.host.getConfig(self.vhost_root, key=key, default=default, + def config_get(self, key, default=None, value_type=None): + return self.host.config_get(self.vhost_root, key=key, default=default, value_type=value_type) - def getBuildPath(self, session_data): + def get_build_path(self, session_data): return session_data.cache_dir + self.vhost.site_name - def getPageByName(self, name): - return self.vhost_root.getPageByName(name) + def get_page_by_name(self, name): + return self.vhost_root.get_page_by_name(name) - def getPagePathFromURI(self, uri): - return self.vhost_root.getPagePathFromURI(uri) + def get_page_path_from_uri(self, uri): + return self.vhost_root.get_page_path_from_uri(uri) - def getPageRedirectURL(self, request, page_name="login", url=None): + def get_page_redirect_url(self, request, page_name="login", url=None): """generate URL for a page with redirect_url parameter set mainly used for login page with redirection to current page @@ -624,13 +624,13 @@ @return (unicode): URL to use """ return "{root_url}?redirect_url={redirect_url}".format( - root_url=self.getPageByName(page_name).url, + root_url=self.get_page_by_name(page_name).url, redirect_url=urllib.parse.quote_plus(request.uri) if url is None else url.encode("utf-8"), ) - def getURL(self, *args: str, **kwargs: str) -> str: + def get_url(self, *args: str, **kwargs: str) -> str: """retrieve URL of the page set arguments @param *args: arguments to add to the URL as path elements empty or None @@ -662,12 +662,12 @@ ) url += f"?{encoded}" - return self.host.checkRedirection( + return self.host.check_redirection( self.vhost_root, url ) - def getCurrentURL(self, request): + def get_current_url(self, request): """retrieve URL used to access this page @return(unicode): current URL @@ -685,20 +685,20 @@ #  we remove trailing slash request.postpath = request.postpath[:-1] if request.postpath: - #  getSubPageURL must return subpage from the point where + #  get_sub_page_url must return subpage from the point where # the it is called, so we have to remove remanining # path elements path_elts = path_elts[: -len(request.postpath)] return "/" + "/".join(path_elts) - def getParamURL(self, request, **kwargs): + def get_param_url(self, request, **kwargs): """use URL of current request but modify the parameters in query part **kwargs(dict[str, unicode]): argument to use as query parameters @return (unicode): constructed URL """ - current_url = self.getCurrentURL(request) + current_url = self.get_current_url(request) if kwargs: encoded = urllib.parse.urlencode( {k: v for k, v in kwargs.items()} @@ -706,7 +706,7 @@ current_url = current_url + "?" + encoded return current_url - def getSubPageByName(self, subpage_name, parent=None): + def get_sub_page_by_name(self, subpage_name, parent=None): """retrieve a subpage and its path using its name @param subpage_name(unicode): name of the sub page @@ -730,7 +730,7 @@ _("requested sub page has not been found ({subpage_name})").format( subpage_name=subpage_name)) - def getSubPageURL(self, request, page_name, *args): + def get_sub_page_url(self, request, page_name, *args): """retrieve a page in direct children and build its URL according to request request's current path is used as base (at current parsing point, @@ -740,7 +740,7 @@ This method is useful to construct absolute URLs for children instead of using relative path, which may not work in subpages, and are linked to the names of directories (i.e. relative URL will break if subdirectory is renamed - while getSubPageURL won't as long as page_name is consistent). + while get_sub_page_url won't as long as page_name is consistent). Also, request.path is used, keeping real path used by user, and potential redirections. @param request(server.Request): current HTTP request @@ -750,13 +750,13 @@ if an arg is None, it will be ignored @return (unicode): absolute URL to the sub page """ - current_url = self.getCurrentURL(request) - path, child = self.getSubPageByName(page_name) + current_url = self.get_current_url(request) + path, child = self.get_sub_page_by_name(page_name) return os.path.join( "/", current_url, path, *[quote(a) for a in args if a is not None] ) - def getURLByNames(self, named_path): + def get_url_by_names(self, named_path): """Retrieve URL from pages names and arguments @param named_path(list[tuple[unicode, list[unicode]]]): path to the page as a list @@ -770,21 +770,21 @@ path = [] for page_name, page_args in named_path: if current_page is None: - current_page = self.getPageByName(page_name) - path.append(current_page.getURL(*page_args)) + current_page = self.get_page_by_name(page_name) + path.append(current_page.get_url(*page_args)) else: - sub_path, current_page = self.getSubPageByName( + sub_path, current_page = self.get_sub_page_by_name( page_name, parent=current_page ) path.append(sub_path) if page_args: path.extend([quote(a) for a in page_args]) - return self.host.checkRedirection(self.vhost_root, "/".join(path)) + return self.host.check_redirection(self.vhost_root, "/".join(path)) - def getURLByPath(self, *args): + def get_url_by_path(self, *args): """Generate URL by path - this method as a similar effect as getURLByNames, but it is more readable + this method as a similar effect as get_url_by_names, but it is more readable by using SubPage to get pages instead of using tuples @param *args: path element: - if unicode, will be used as argument @@ -799,7 +799,7 @@ if not isinstance(args[0], SubPage): root = self else: - root = self.getPageByName(args.pop(0)) + root = self.get_page_by_name(args.pop(0)) # we keep track of current page to check subpage current_page = root url_elts = [] @@ -808,15 +808,15 @@ while args and not isinstance(args[0], SubPage): arguments.append(quote(args.pop(0))) if not url_elts: - url_elts.append(root.getURL(*arguments)) + url_elts.append(root.get_url(*arguments)) else: url_elts.extend(arguments) if not args: break else: - path, current_page = current_page.getSubPageByName(args.pop(0)) + path, current_page = current_page.get_sub_page_by_name(args.pop(0)) arguments = [path] - return self.host.checkRedirection(self.vhost_root, "/".join(url_elts)) + return self.host.check_redirection(self.vhost_root, "/".join(url_elts)) def getChildWithDefault(self, path, request): # we handle children ourselves @@ -824,7 +824,7 @@ "this method should not be used with LiberviaPage" ) - def nextPath(self, request): + def next_path(self, request): """get next URL path segment, and update request accordingly will move first segment of postpath in prepath @@ -836,8 +836,8 @@ request.prepath.append(pathElement) return urllib.parse.unquote(pathElement.decode('utf-8')) - def _filterPathValue(self, value, handler, name, request): - """Modify a path value according to handler (see [getPathArgs])""" + def _filter_path_value(self, value, handler, name, request): + """Modify a path value according to handler (see [get_path_args])""" if handler in ("@", "@jid") and value == "@": value = None @@ -850,7 +850,7 @@ return jid.JID(value) except (RuntimeError, jid.InvalidFormat): log.warning(_("invalid jid argument: {value}").format(value=value)) - self.pageError(request, C.HTTP_BAD_REQUEST) + self.page_error(request, C.HTTP_BAD_REQUEST) else: return "" else: @@ -858,7 +858,7 @@ return value - def getPathArgs(self, request, names, min_args=0, **kwargs): + def get_path_args(self, request, names, min_args=0, **kwargs): """get several path arguments at once Arguments will be put in request data. @@ -877,14 +877,14 @@ - '@jid': if value of arguments is empty or '@', empty string will be used, else it will be converted to jid """ - data = self.getRData(request) + data = self.get_r_data(request) for idx, name in enumerate(names): if name[0] == "*": value = data[name[1:]] = [] while True: try: - value.append(self.nextPath(request)) + value.append(self.next_path(request)) except IndexError: idx -= 1 break @@ -892,7 +892,7 @@ idx += 1 else: try: - value = data[name] = self.nextPath(request) + value = data[name] = self.next_path(request) except IndexError: data[name] = None idx -= 1 @@ -902,7 +902,7 @@ if values_count < min_args: log.warning(_("Missing arguments in URL (got {count}, expected at least " "{min_args})").format(count=values_count, min_args=min_args)) - self.pageError(request, C.HTTP_BAD_REQUEST) + self.page_error(request, C.HTTP_BAD_REQUEST) for name in names[values_count:]: data[name] = None @@ -910,14 +910,14 @@ for name, handler in kwargs.items(): if name[0] == "*": data[name] = [ - self._filterPathValue(v, handler, name, request) for v in data[name] + self._filter_path_value(v, handler, name, request) for v in data[name] ] else: - data[name] = self._filterPathValue(data[name], handler, name, request) + data[name] = self._filter_path_value(data[name], handler, name, request) ## Pagination/Filtering ## - def getPubsubExtra(self, request, page_max=10, params=None, extra=None, + def get_pubsub_extra(self, request, page_max=10, params=None, extra=None, order_by=C.ORDER_BY_CREATION): """Set extra dict to retrieve PubSub items corresponding to URL parameters @@ -927,7 +927,7 @@ @param request(server.Request): current HTTP request @param page_max(int): required number of items per page @param params(None, dict[unicode, list[unicode]]): params as returned by - self.getAllPostedData. + self.get_all_posted_data. None to parse URL automatically @param extra(None, dict): extra dict to use, or None to use a new one @param order_by(unicode, None): key to order by @@ -935,7 +935,7 @@ @return (dict): fill extra data """ if params is None: - params = self.getAllPostedData(request, multiple=False) + params = self.get_all_posted_data(request, multiple=False) if extra is None: extra = {} else: @@ -954,7 +954,7 @@ extra['rsm_before'] = "" return extra - def setPagination(self, request: server.Request, pubsub_data: dict) -> None: + def set_pagination(self, request: server.Request, pubsub_data: dict) -> None: """Add to template_data if suitable "previous_page_url" and "next_page_url" will be added using respectively @@ -972,12 +972,12 @@ return # if we have a search query, we must keep it - search = self.getPostedData(request, 'search', raise_on_missing=False) + search = self.get_posted_data(request, 'search', raise_on_missing=False) if search is not None: extra['search'] = search.strip() # same for page_max - page_max = self.getPostedData(request, 'page_max', raise_on_missing=False) + page_max = self.get_posted_data(request, 'page_max', raise_on_missing=False) if page_max is not None: extra['page_max'] = page_max @@ -986,24 +986,24 @@ # If we have no index, we default to display the button anyway # as we can't know if we are on the first page or not. first_id = rsm["first"] - template_data['previous_page_url'] = self.getParamURL( + template_data['previous_page_url'] = self.get_param_url( request, before=first_id, **extra) if not pubsub_data["complete"]: # we also show the page next button if complete is None because we # can't know where we are in the feed in this case. - template_data['next_page_url'] = self.getParamURL( + template_data['next_page_url'] = self.get_param_url( request, after=last_id, **extra) ## Cache handling ## - def _setCacheHeaders(self, request, cache): + def _set_cache_headers(self, request, cache): """Set ETag and Last-Modified HTTP headers, used for caching""" request.setHeader("ETag", cache.hash) - last_modified = self.host.getHTTPDate(cache.created) + last_modified = self.host.get_http_date(cache.created) request.setHeader("Last-Modified", last_modified) - def _checkCacheHeaders(self, request, cache): + def _check_cache_headers(self, request, cache): """Check if a cache condition is set on the request if condition is valid, C.HTTP_NOT_MODIFIED is returned @@ -1011,25 +1011,25 @@ etag_match = request.getHeader("If-None-Match") if etag_match is not None: if cache.hash == etag_match: - self.pageError(request, C.HTTP_NOT_MODIFIED, no_body=True) + self.page_error(request, C.HTTP_NOT_MODIFIED, no_body=True) else: modified_match = request.getHeader("If-Modified-Since") if modified_match is not None: modified = date_utils.date_parse(modified_match) if modified >= int(cache.created): - self.pageError(request, C.HTTP_NOT_MODIFIED, no_body=True) + self.page_error(request, C.HTTP_NOT_MODIFIED, no_body=True) - def checkCacheSubscribeCb(self, sub_id, service, node): + def check_cache_subscribe_cb(self, sub_id, service, node): self.cache_pubsub_sub.add((service, node, sub_id)) - def checkCacheSubscribeEb(self, failure_, service, node): + def check_cache_subscribe_eb(self, failure_, service, node): log.warning(_("Can't subscribe to node: {msg}").format(msg=failure_)) # FIXME: cache must be marked as unusable here - def psNodeWatchAddEb(self, failure_, service, node): + def ps_node_watch_add_eb(self, failure_, service, node): log.warning(_("Can't add node watched: {msg}").format(msg=failure_)) - def useCache(self, request: server.Request) -> bool: + def use_cache(self, request: server.Request) -> bool: """Indicate if the cache should be used test request header to see if it is requested to skip the cache @@ -1037,7 +1037,7 @@ """ return request.getHeader('cache-control') != 'no-cache' - def checkCache(self, request, cache_type, **kwargs): + def check_cache(self, request, cache_type, **kwargs): """check if a page is in cache and return cached version if suitable this method may perform extra operation to handle cache (e.g. subscribing to a @@ -1060,9 +1060,9 @@ # influencing page results (e.g. search terms) log.debug("ignoring cache due to query arguments") - no_cache = not self.useCache(request) + no_cache = not self.use_cache(request) - profile = self.getProfile(request) or C.SERVICE_PROFILE + profile = self.get_profile(request) or C.SERVICE_PROFILE if cache_type == C.CACHE_PUBSUB: service, node = kwargs["service"], kwargs["node"] @@ -1078,7 +1078,7 @@ if profile != C.SERVICE_PROFILE: #  only service profile is cached for now return - session_data = self.host.getSessionData(request, session_iface.IWebSession) + session_data = self.host.get_session_data(request, session_iface.IWebSession) locale = session_data.locale if locale == C.DEFAULT_LOCALE: # no need to duplicate cache here @@ -1088,13 +1088,13 @@ [self.vhost_root][request.uri][locale][self]) except KeyError: # no cache yet, let's subscribe to the pubsub node - d1 = self.host.bridgeCall( - "psSubscribe", service.full(), node, "", profile + d1 = self.host.bridge_call( + "ps_subscribe", service.full(), node, "", profile ) - d1.addCallback(self.checkCacheSubscribeCb, service, node) - d1.addErrback(self.checkCacheSubscribeEb, service, node) - d2 = self.host.bridgeCall("psNodeWatchAdd", service.full(), node, profile) - d2.addErrback(self.psNodeWatchAddEb, service, node) + d1.addCallback(self.check_cache_subscribe_cb, service, node) + d1.addErrback(self.check_cache_subscribe_eb, service, node) + d2 = self.host.bridge_call("ps_node_watch_add", service.full(), node, profile) + d2.addErrback(self.ps_node_watch_add_eb, service, node) self._do_cache = [self, profile, cache_type, service, node, self.vhost_root, request.uri, locale] #  we don't return the Deferreds as it is not needed to wait for @@ -1111,17 +1111,17 @@ raise exceptions.InternalError("Unknown cache_type") log.debug("using cache for {page}".format(page=self)) cache.last_access = time.time() - self._setCacheHeaders(request, cache) - self._checkCacheHeaders(request, cache) + self._set_cache_headers(request, cache) + self._check_cache_headers(request, cache) request.write(cache.rendered) request.finish() raise failure.Failure(exceptions.CancelError("cache is used")) - def _cacheURL(self, request, profile): + def _cache_url(self, request, profile): self.cached_urls.setdefault(profile, {})[request.uri] = CacheURL(request) @classmethod - def onNodeEvent(cls, host, service, node, event_type, items, profile): + def on_node_event(cls, host, service, node, event_type, items, profile): """Invalidate cache for all pages linked to this node""" try: cache = cls.cache[profile][C.CACHE_PUBSUB][jid.JID(service)][node] @@ -1129,12 +1129,12 @@ log.info(_( "Removing subscription for {service}/{node}: " "the page is not cached").format(service=service, node=node)) - d1 = host.bridgeCall("psUnsubscribe", service, node, profile) + d1 = host.bridge_call("ps_unsubscribe", service, node, profile) d1.addErrback( lambda failure_: log.warning( _("Can't unsubscribe from {service}/{node}: {msg}").format( service=service, node=node, msg=failure_))) - d2 = host.bridgeCall("psNodeWatchAdd", service, node, profile) + d2 = host.bridge_call("ps_node_watch_add", service, node, profile) # TODO: check why the page is not in cache, remove subscription? d2.addErrback( lambda failure_: log.warning( @@ -1145,7 +1145,7 @@ # identities - async def fillMissingIdentities( + async def fill_missing_identities( self, request: server.Request, entities: List[Union[str, jid.JID, None]], @@ -1156,20 +1156,20 @@ @param entities: entities to check, None or empty strings will be filtered """ entities = {str(e) for e in entities if e} - profile = self.getProfile(request) or C.SERVICE_PROFILE - identities = self.host.getSessionData( + profile = self.get_profile(request) or C.SERVICE_PROFILE + identities = self.host.get_session_data( request, session_iface.IWebSession ).identities for e in entities: if e not in identities: - id_raw = await self.host.bridgeCall( - 'identityGet', e, [], True, profile) + id_raw = await self.host.bridge_call( + 'identity_get', e, [], True, profile) identities[e] = data_format.deserialise(id_raw) # signals, server => browser communication - def delegateToResource(self, request, resource): + def delegate_to_resource(self, request, resource): """continue workflow with Twisted Resource""" buf = resource.render(request) if buf == server.NOT_DONE_YET: @@ -1179,7 +1179,7 @@ request.finish() raise failure.Failure(exceptions.CancelError("resource delegation")) - def HTTPRedirect(self, request, url): + def http_redirect(self, request, url): """redirect to an URL using HTTP redirection @param request(server.Request): current HTTP request @@ -1189,14 +1189,14 @@ request.finish() raise failure.Failure(exceptions.CancelError("HTTP redirection is used")) - def redirectOrContinue(self, request, redirect_arg="redirect_url"): + def redirect_or_continue(self, request, redirect_arg="redirect_url"): """Helper method to redirect a page to an url given as arg if the arg is not present, the page will continue normal workflow @param request(server.Request): current HTTP request @param redirect_arg(unicode): argument to use to get redirection URL @interrupt: redirect the page to requested URL - @interrupt pageError(C.HTTP_BAD_REQUEST): empty or non local URL is used + @interrupt page_error(C.HTTP_BAD_REQUEST): empty or non local URL is used """ redirect_arg = redirect_arg.encode('utf-8') try: @@ -1207,16 +1207,16 @@ #  a redirection is requested if not url or url[0] != "/": # we only want local urls - self.pageError(request, C.HTTP_BAD_REQUEST) + self.page_error(request, C.HTTP_BAD_REQUEST) else: - self.HTTPRedirect(request, url) + self.http_redirect(request, url) - def pageRedirect(self, page_path, request, skip_parse_url=True, path_args=None): + def page_redirect(self, page_path, request, skip_parse_url=True, path_args=None): """redirect a page to a named page the workflow will continue with the workflow of the named page, skipping named page's parse_url method if it exist. - If you want to do a HTTP redirection, use HTTPRedirect + If you want to do a HTTP redirection, use http_redirect @param page_path(unicode): path to page (elements are separated by "/"): if path starts with a "/": path is a full path starting from root @@ -1256,11 +1256,11 @@ self._do_cache = None defer.ensureDeferred( - redirect_page.renderPage(request, skip_parse_url=skip_parse_url) + redirect_page.render_page(request, skip_parse_url=skip_parse_url) ) raise failure.Failure(exceptions.CancelError("page redirection is used")) - def pageError(self, request, code=C.HTTP_NOT_FOUND, no_body=False): + def page_error(self, request, code=C.HTTP_NOT_FOUND, no_body=False): """generate an error page and terminate the request @param request(server.Request): HTTP request @@ -1276,7 +1276,7 @@ else: template = "error/" + str(code) + ".html" template_data = request.template_data - session_data = self.host.getSessionData(request, session_iface.IWebSession) + session_data = self.host.get_session_data(request, session_iface.IWebSession) if session_data.locale is not None: template_data['locale'] = session_data.locale if self.vhost_root.site_name: @@ -1292,24 +1292,24 @@ **template_data ) - self.writeData(rendered, request) + self.write_data(rendered, request) raise failure.Failure(exceptions.CancelError("error page is used")) - def writeData(self, data, request): + def write_data(self, data, request): """write data to transport and finish the request""" if data is None: - self.pageError(request) + self.page_error(request) data_encoded = data.encode("utf-8") if self._do_cache is not None: redirected_page = self._do_cache.pop(0) cache = reduce(lambda d, k: d.setdefault(k, {}), self._do_cache, self.cache) page_cache = cache[redirected_page] = CachePage(data_encoded) - self._setCacheHeaders(request, page_cache) + self._set_cache_headers(request, page_cache) log.debug(_("{page} put in cache for [{profile}]") .format( page=self, profile=self._do_cache[0])) self._do_cache = None - self._checkCacheHeaders(request, page_cache) + self._check_cache_headers(request, page_cache) try: request.write(data_encoded) @@ -1319,7 +1319,7 @@ return request.finish() - def _subpagesHandler(self, request): + def _subpages_handler(self, request): """render subpage if suitable this method checks if there is still an unmanaged part of the path @@ -1328,17 +1328,17 @@ If there is no unmanaged part of the segment, current page workflow is pursued """ if request.postpath: - subpage = self.nextPath(request).encode('utf-8') + subpage = self.next_path(request).encode('utf-8') try: child = self.children[subpage] except KeyError: - self.pageError(request) + self.page_error(request) else: child.render(request) raise failure.Failure(exceptions.CancelError("subpage page is used")) def _prepare_dynamic(self, request): - session_data = self.host.getSessionData(request, session_iface.IWebSession) + session_data = self.host.get_session_data(request, session_iface.IWebSession) # we need to activate dynamic page # we set data for template, and create/register token # socket_token = str(uuid.uuid4()) @@ -1346,7 +1346,7 @@ # as for CSRF, it is important to not let the socket token if we use the service # profile, as those pages can be cached, and then the token leaked. socket_token = '' if session_data.profile is None else session_data.ws_token - socket_debug = C.boolConst(self.host.debug) + socket_debug = C.bool_const(self.host.debug) request.template_data["websocket"] = WebsocketMeta( socket_url, socket_token, socket_debug ) @@ -1359,11 +1359,11 @@ template_data = request.template_data # if confirm variable is set in case of successfuly data post - session_data = self.host.getSessionData(request, session_iface.IWebSession) + session_data = self.host.get_session_data(request, session_iface.IWebSession) template_data['identities'] = session_data.identities - if session_data.popPageFlag(self, C.FLAG_CONFIRM): + if session_data.pop_page_flag(self, C.FLAG_CONFIRM): template_data["confirm"] = True - notifs = session_data.popPageNotifications(self) + notifs = session_data.pop_page_notifications(self) if notifs: template_data["notifications"] = notifs if session_data.jid is not None: @@ -1393,10 +1393,10 @@ template_data[key] = value theme = session_data.theme or self.default_theme - self.exposeToScripts( + self.expose_to_scripts( request, cache_path=session_data.cache_dir, - templates_root_url=str(self.vhost_root.getFrontURL(theme)), + templates_root_url=str(self.vhost_root.get_front_url(theme)), profile=session_data.profile) uri = request.uri.decode() @@ -1411,7 +1411,7 @@ self.template, theme=theme, site_themes=self.site_themes, - page_url=self.getURL(), + page_url=self.get_url(), media_path=f"/{C.MEDIA_DIR}", build_path=f"/{C.BUILD_DIR}/", cache_path=session_data.cache_dir, @@ -1441,14 +1441,14 @@ raise NotImplementedError( _("iterable in on_data_post return value is not used yet") ) - session_data = self.host.getSessionData(request, session_iface.IWebSession) - request_data = self.getRData(request) + session_data = self.host.get_session_data(request, session_iface.IWebSession) + request_data = self.get_r_data(request) if "post_redirect_page" in request_data: redirect_page_data = request_data["post_redirect_page"] if isinstance(redirect_page_data, tuple): redirect_page = redirect_page_data[0] redirect_page_args = redirect_page_data[1:] - redirect_uri = redirect_page.getURL(*redirect_page_args) + redirect_uri = redirect_page.get_url(*redirect_page_args) else: redirect_page = redirect_page_data redirect_uri = redirect_page.url @@ -1457,21 +1457,21 @@ redirect_uri = request.uri if not C.POST_NO_CONFIRM in ret: - session_data.setPageFlag(redirect_page, C.FLAG_CONFIRM) + session_data.set_page_flag(redirect_page, C.FLAG_CONFIRM) request.setResponseCode(C.HTTP_SEE_OTHER) request.setHeader(b"location", redirect_uri) request.finish() raise failure.Failure(exceptions.CancelError("Post/Redirect/Get is used")) async def _on_data_post(self, request): - self.checkCSRF(request) + self.check_csrf(request) try: - ret = await asDeferred(self.on_data_post, self, request) + ret = await as_deferred(self.on_data_post, self, request) except exceptions.DataError as e: # something is wrong with the posted data, we re-display the page with a # warning notification - session_data = self.host.getSessionData(request, session_iface.IWebSession) - session_data.setPageNotification(self, str(e), C.LVL_WARNING) + session_data = self.host.get_session_data(request, session_iface.IWebSession) + session_data.set_page_notification(self, str(e), C.LVL_WARNING) request.setResponseCode(C.HTTP_SEE_OTHER) request.setHeader("location", request.uri) request.finish() @@ -1480,7 +1480,7 @@ if ret != "continue": self._on_data_post_redirect(ret, request) - def getPostedData( + def get_posted_data( self, request: server.Request, keys, @@ -1532,7 +1532,7 @@ else: return ret - def getAllPostedData(self, request, except_=(), multiple=True): + def get_all_posted_data(self, request, except_=(), multiple=True): """get all posted data @param request(server.Request): request linked to the session @@ -1555,25 +1555,25 @@ ret[key] = [urllib.parse.unquote(v) for v in values] return ret - def getProfile(self, request): + def get_profile(self, request): """Helper method to easily get current profile @return (unicode, None): current profile None if no profile session is started """ - web_session = self.host.getSessionData(request, session_iface.IWebSession) + web_session = self.host.get_session_data(request, session_iface.IWebSession) return web_session.profile - def getJid(self, request): + def get_jid(self, request): """Helper method to easily get current jid @return: current jid """ - web_session = self.host.getSessionData(request, session_iface.IWebSession) + web_session = self.host.get_session_data(request, session_iface.IWebSession) return web_session.jid - def getRData(self, request): + def get_r_data(self, request): """Helper method to get request data dict this dictionnary if for the request only, it is not saved in session @@ -1587,17 +1587,17 @@ request.data = {} return request.data - def getPageData(self, request, key): + def get_page_data(self, request, key): """Helper method to retrieve reload resistant data""" - web_session = self.host.getSessionData(request, session_iface.IWebSession) - return web_session.getPageData(self, key) + web_session = self.host.get_session_data(request, session_iface.IWebSession) + return web_session.get_page_data(self, key) - def setPageData(self, request, key, value): + def set_page_data(self, request, key, value): """Helper method to set reload resistant data""" - web_session = self.host.getSessionData(request, session_iface.IWebSession) - return web_session.setPageData(self, key, value) + web_session = self.host.get_session_data(request, session_iface.IWebSession) + return web_session.set_page_data(self, key, value) - def handleSearch(self, request, extra): + def handle_search(self, request, extra): """Manage Full-Text Search Check if "search" query argument is present, and add MAM filter for it if @@ -1605,7 +1605,7 @@ If used, the "search" variable will also be available in template data, thus frontend can display some information about it. """ - search = self.getPostedData(request, 'search', raise_on_missing=False) + search = self.get_posted_data(request, 'search', raise_on_missing=False) if search is not None: search = search.strip() if search: @@ -1616,22 +1616,22 @@ else: request.template_data['search'] = search - def _checkAccess(self, request): + def _check_access(self, request): """Check access according to self.access - if access is not granted, show a HTTP_FORBIDDEN pageError and stop request, + if access is not granted, show a HTTP_FORBIDDEN page_error and stop request, else return data (so it can be inserted in deferred chain """ if self.access == C.PAGES_ACCESS_PUBLIC: pass elif self.access == C.PAGES_ACCESS_PROFILE: - profile = self.getProfile(request) + profile = self.get_profile(request) if not profile: # registration allowed, we redirect to login page - login_url = self.getPageRedirectURL(request) - self.HTTPRedirect(request, login_url) + login_url = self.get_page_redirect_url(request) + self.http_redirect(request, login_url) - def setBestLocale(self, request): + def set_best_locale(self, request): """Guess the best locale when it is not specified explicitly by user This method will check "accept-language" header, and set locale to first @@ -1648,18 +1648,18 @@ continue for a in available: if a.lower().startswith(lang): - session_data = self.host.getSessionData(request, + session_data = self.host.get_session_data(request, session_iface.IWebSession) session_data.locale = a return - async def renderPage(self, request, skip_parse_url=False): + async def render_page(self, request, skip_parse_url=False): """Main method to handle the workflow of a LiberviaPage""" # template_data are the variables passed to template if not hasattr(request, "template_data"): # if template_data doesn't exist, it's the beginning of the request workflow # so we fill essential data - session_data = self.host.getSessionData(request, session_iface.IWebSession) + session_data = self.host.get_session_data(request, session_iface.IWebSession) profile = session_data.profile request.template_data = { "profile": profile, @@ -1694,7 +1694,7 @@ # if locale is not specified, we try to find one requested by browser if session_data.locale is None: - self.setBestLocale(request) + self.set_best_locale(request) # theme key_theme = C.KEY_THEME.encode() @@ -1710,26 +1710,26 @@ try: try: - self._checkAccess(request) + self._check_access(request) if self.redirect is not None: - self.pageRedirect(self.redirect, request, skip_parse_url=False) + self.page_redirect(self.redirect, request, skip_parse_url=False) if self.parse_url is not None and not skip_parse_url: if self.url_cache: - profile = self.getProfile(request) + profile = self.get_profile(request) try: cache_url = self.cached_urls[profile][request.uri] except KeyError: # no cache for this URI yet #  we do normal URL parsing, and then the cache - await asDeferred(self.parse_url, self, request) - self._cacheURL(request, profile) + await as_deferred(self.parse_url, self, request) + self._cache_url(request, profile) else: log.debug(f"using URI cache for {self}") cache_url.use(request) else: - await asDeferred(self.parse_url, self, request) + await as_deferred(self.parse_url, self, request) if self.add_breadcrumb is None: label = ( @@ -1743,18 +1743,18 @@ } request.template_data["breadcrumbs"].append(breadcrumb) else: - await asDeferred( + await as_deferred( self.add_breadcrumb, self, request, request.template_data["breadcrumbs"] ) - self._subpagesHandler(request) + self._subpages_handler(request) if request.method not in (C.HTTP_METHOD_GET, C.HTTP_METHOD_POST): # only HTTP GET and POST are handled so far - self.pageError(request, C.HTTP_BAD_REQUEST) + self.page_error(request, C.HTTP_BAD_REQUEST) if request.method == C.HTTP_METHOD_POST: if self.on_data_post == 'continue': @@ -1762,7 +1762,7 @@ elif self.on_data_post is None: # if we don't have on_data_post, the page was not expecting POST # so we return an error - self.pageError(request, C.HTTP_BAD_REQUEST) + self.page_error(request, C.HTTP_BAD_REQUEST) else: await self._on_data_post(request) # by default, POST follow normal behaviour after on_data_post is called @@ -1772,19 +1772,19 @@ self._prepare_dynamic(request) if self.prepare_render: - await asDeferred(self.prepare_render, self, request) + await as_deferred(self.prepare_render, self, request) if self.template: rendered = self._render_template(request) elif self.render_method: - rendered = await asDeferred(self.render_method, self, request) + rendered = await as_deferred(self.render_method, self, request) else: raise exceptions.InternalError( "No method set to render page, please set a template or use a " "render method" ) - self.writeData(rendered, request) + self.write_data(rendered, request) except failure.Failure as f: # we have to unpack the Failure to catch the right Exception @@ -1795,17 +1795,17 @@ except BridgeException as e: if e.condition == 'not-allowed': log.warning("not allowed exception catched") - self.pageError(request, C.HTTP_FORBIDDEN) + self.page_error(request, C.HTTP_FORBIDDEN) elif e.condition == 'item-not-found' or e.classname == 'NotFound': - self.pageError(request, C.HTTP_NOT_FOUND) + self.page_error(request, C.HTTP_NOT_FOUND) elif e.condition == 'remote-server-not-found': - self.pageError(request, C.HTTP_NOT_FOUND) + self.page_error(request, C.HTTP_NOT_FOUND) elif e.condition == 'forbidden': - if self.getProfile(request) is None: + if self.get_profile(request) is None: log.debug("access forbidden, we're redirecting to log-in page") - self.HTTPRedirect(request, self.getPageRedirectURL(request)) + self.http_redirect(request, self.get_page_redirect_url(request)) else: - self.pageError(request, C.HTTP_FORBIDDEN) + self.page_error(request, C.HTTP_FORBIDDEN) else: log.error( _("Uncatched bridge exception for HTTP request on {url}: {e}\n" @@ -1820,7 +1820,7 @@ ) ) try: - self.pageError(request, C.HTTP_INTERNAL_ERROR) + self.page_error(request, C.HTTP_INTERNAL_ERROR) except exceptions.CancelError: pass except Exception as e: @@ -1837,14 +1837,14 @@ ) ) try: - self.pageError(request, C.HTTP_INTERNAL_ERROR) + self.page_error(request, C.HTTP_INTERNAL_ERROR) except exceptions.CancelError: pass def render_GET(self, request): - defer.ensureDeferred(self.renderPage(request)) + defer.ensureDeferred(self.render_page(request)) return server.NOT_DONE_YET def render_POST(self, request): - defer.ensureDeferred(self.renderPage(request)) + defer.ensureDeferred(self.render_page(request)) return server.NOT_DONE_YET diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/server/pages_tools.py --- a/libervia/server/pages_tools.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/server/pages_tools.py Sat Apr 08 13:44:11 2023 +0200 @@ -32,7 +32,7 @@ return data_format.deserialise(comments_data_s) -def retrieveComments(self, service, node, profile, pass_exceptions=True): +def retrieve_comments(self, service, node, profile, pass_exceptions=True): """Retrieve comments from server and convert them to data objects @param service(unicode): service holding the comments @@ -42,8 +42,8 @@ else exception will be raised """ try: - d = self.host.bridgeCall( - "mbGet", service, node, C.NO_LIMIT, [], data_format.serialise({}), profile + d = self.host.bridge_call( + "mb_get", service, node, C.NO_LIMIT, [], data_format.serialise({}), profile ) except Exception as e: if not pass_exceptions: diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/server/restricted_bridge.py --- a/libervia/server/restricted_bridge.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/server/restricted_bridge.py Sat Apr 08 13:44:11 2023 +0200 @@ -22,7 +22,7 @@ class RestrictedBridge: - """Bridge with limited access, which can be used in browser + """bridge with limited access, which can be used in browser Only a few method are implemented, with potentially dangerous argument controlled. Security limit is used @@ -32,70 +32,70 @@ self.host = host self.security_limit = C.SECURITY_LIMIT - def noServiceProfile(self, profile): + def no_service_profile(self, profile): """Raise an error if service profile is used""" if profile == C.SERVICE_PROFILE: raise exceptions.PermissionError( "This action is not allowed for service profile" ) - async def getContacts(self, profile): - return await self.host.bridgeCall("getContacts", profile) + async def contacts_get(self, profile): + return await self.host.bridge_call("contacts_get", profile) - async def identityGet(self, entity, metadata_filter, use_cache, profile): - return await self.host.bridgeCall( - "identityGet", entity, metadata_filter, use_cache, profile) + async def identity_get(self, entity, metadata_filter, use_cache, profile): + return await self.host.bridge_call( + "identity_get", entity, metadata_filter, use_cache, profile) - async def identitiesGet(self, entities, metadata_filter, profile): - return await self.host.bridgeCall( - "identitiesGet", entities, metadata_filter, profile) + async def identities_get(self, entities, metadata_filter, profile): + return await self.host.bridge_call( + "identities_get", entities, metadata_filter, profile) - async def identitiesBaseGet(self, profile): - return await self.host.bridgeCall( - "identitiesBaseGet", profile) + async def identities_base_get(self, profile): + return await self.host.bridge_call( + "identities_base_get", profile) - async def psNodeDelete(self, service_s, node, profile): - self.noServiceProfile(profile) - return await self.host.bridgeCall( - "psNodeDelete", service_s, node, profile) + async def ps_node_delete(self, service_s, node, profile): + self.no_service_profile(profile) + return await self.host.bridge_call( + "ps_node_delete", service_s, node, profile) - async def psNodeAffiliationsSet(self, service_s, node, affiliations, profile): - self.noServiceProfile(profile) - return await self.host.bridgeCall( - "psNodeAffiliationsSet", service_s, node, affiliations, profile) + async def ps_node_affiliations_set(self, service_s, node, affiliations, profile): + self.no_service_profile(profile) + return await self.host.bridge_call( + "ps_node_affiliations_set", service_s, node, affiliations, profile) - async def psItemRetract(self, service_s, node, item_id, notify, profile): - self.noServiceProfile(profile) - return await self.host.bridgeCall( - "psItemRetract", service_s, node, item_id, notify, profile) + async def ps_item_retract(self, service_s, node, item_id, notify, profile): + self.no_service_profile(profile) + return await self.host.bridge_call( + "ps_item_retract", service_s, node, item_id, notify, profile) - async def mbPreview(self, service_s, node, data, profile): - return await self.host.bridgeCall( - "mbPreview", service_s, node, data, profile) + async def mb_preview(self, service_s, node, data, profile): + return await self.host.bridge_call( + "mb_preview", service_s, node, data, profile) - async def listSet(self, service_s, node, values, schema, item_id, extra, profile): - self.noServiceProfile(profile) - return await self.host.bridgeCall( - "listSet", service_s, node, values, "", item_id, "", profile) + async def list_set(self, service_s, node, values, schema, item_id, extra, profile): + self.no_service_profile(profile) + return await self.host.bridge_call( + "list_set", service_s, node, values, "", item_id, "", profile) - async def fileHTTPUploadGetSlot( + async def file_http_upload_get_slot( self, filename, size, content_type, upload_jid, profile): - self.noServiceProfile(profile) - return await self.host.bridgeCall( - "fileHTTPUploadGetSlot", filename, size, content_type, + self.no_service_profile(profile) + return await self.host.bridge_call( + "file_http_upload_get_slot", filename, size, content_type, upload_jid, profile) - async def fileSharingDelete( + async def file_sharing_delete( self, service_jid, path, namespace, profile): - self.noServiceProfile(profile) - return await self.host.bridgeCall( - "fileSharingDelete", service_jid, path, namespace, profile) + self.no_service_profile(profile) + return await self.host.bridge_call( + "file_sharing_delete", service_jid, path, namespace, profile) - async def interestsRegisterFileSharing( + async def interests_file_sharing_register( self, service, repos_type, namespace, path, name, extra_s, profile ): - self.noServiceProfile(profile) + self.no_service_profile(profile) if extra_s: # we only allow "thumb_url" here extra = data_format.deserialise(extra_s) @@ -104,31 +104,31 @@ else: extra_s = "" - return await self.host.bridgeCall( - "interestsRegisterFileSharing", service, repos_type, namespace, path, name, + return await self.host.bridge_call( + "interests_file_sharing_register", service, repos_type, namespace, path, name, extra_s, profile ) - async def interestRetract( + async def interest_retract( self, service_jid, item_id, profile ): - self.noServiceProfile(profile) - return await self.host.bridgeCall( - "interestRetract", service_jid, item_id, profile) + self.no_service_profile(profile) + return await self.host.bridge_call( + "interest_retract", service_jid, item_id, profile) - async def psInvite( + async def ps_invite( self, invitee_jid_s, service_s, node, item_id, name, extra_s, profile ): - self.noServiceProfile(profile) - return await self.host.bridgeCall( - "psInvite", invitee_jid_s, service_s, node, item_id, name, extra_s, profile + self.no_service_profile(profile) + return await self.host.bridge_call( + "ps_invite", invitee_jid_s, service_s, node, item_id, name, extra_s, profile ) - async def FISInvite( + async def fis_invite( self, invitee_jid_s, service_s, repos_type, namespace, path, name, extra_s, profile ): - self.noServiceProfile(profile) + self.no_service_profile(profile) if extra_s: # we only allow "thumb_url" here extra = data_format.deserialise(extra_s) @@ -137,24 +137,24 @@ else: extra_s = "" - return await self.host.bridgeCall( - "FISInvite", invitee_jid_s, service_s, repos_type, namespace, path, name, + return await self.host.bridge_call( + "fis_invite", invitee_jid_s, service_s, repos_type, namespace, path, name, extra_s, profile ) - async def FISAffiliationsSet( + async def fis_affiliations_set( self, service_s, namespace, path, affiliations, profile ): - self.noServiceProfile(profile) - return await self.host.bridgeCall( - "FISAffiliationsSet", service_s, namespace, path, affiliations, profile + self.no_service_profile(profile) + return await self.host.bridge_call( + "fis_affiliations_set", service_s, namespace, path, affiliations, profile ) - async def invitationSimpleCreate( + async def invitation_simple_create( self, invitee_email, invitee_name, url_template, extra_s, profile ): - self.noServiceProfile(profile) - return await self.host.bridgeCall( - "invitationSimpleCreate", invitee_email, invitee_name, url_template, extra_s, + self.no_service_profile(profile) + return await self.host.bridge_call( + "invitation_simple_create", invitee_email, invitee_name, url_template, extra_s, profile ) diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/server/server.py --- 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") diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/server/session_iface.py --- a/libervia/server/session_iface.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/server/session_iface.py Sat Apr 08 13:44:11 2023 +0200 @@ -139,7 +139,7 @@ def get_profile_sessions(cls, profile: str) -> List["WebSession"]: return cls.profiles_map.get(profile, []) - def getPageData(self, page, key): + def get_page_data(self, page, key): """get session data for a page @param page(LiberviaPage): instance of the page @@ -149,8 +149,8 @@ """ return self.pages_data.get(page, {}).get(key) - def popPageData(self, page, key, default=None): - """like getPageData, but remove key once value is gotten + def pop_page_data(self, page, key, default=None): + """like get_page_data, but remove key once value is gotten @param page(LiberviaPage): instance of the page @param key(object): data key @@ -166,7 +166,7 @@ del self.pages_data[page] return value - def setPageData(self, page, key, value): + def set_page_data(self, page, key, value): """set data to persist on reload @param page(LiberviaPage): instance of the page @@ -178,18 +178,18 @@ page_data[key] = value return value - def setPageFlag(self, page, flag): + def set_page_flag(self, page, flag): """set a flag for this page @param page(LiberviaPage): instance of the page @param flag(unicode): flag to set """ - flags = self.getPageData(page, FLAGS_KEY) + flags = self.get_page_data(page, FLAGS_KEY) if flags is None: - flags = self.setPageData(page, FLAGS_KEY, set()) + flags = self.set_page_data(page, FLAGS_KEY, set()) flags.add(flag) - def popPageFlag(self, page, flag): + def pop_page_flag(self, page, flag): """return True if flag is set flag is removed if it was set @@ -212,19 +212,19 @@ else: return False - def setPageNotification(self, page, message, level=C.LVL_INFO): + def set_page_notification(self, page, message, level=C.LVL_INFO): """set a flag for this page @param page(LiberviaPage): instance of the page @param flag(unicode): flag to set """ notif = Notification(message, level) - notifs = self.getPageData(page, NOTIFICATIONS_KEY) + notifs = self.get_page_data(page, NOTIFICATIONS_KEY) if notifs is None: - notifs = self.setPageData(page, NOTIFICATIONS_KEY, []) + notifs = self.set_page_data(page, NOTIFICATIONS_KEY, []) notifs.append(notif) - def popPageNotifications(self, page): + def pop_page_notifications(self, page): """Return and remove last page notification @param page(LiberviaPage): instance of the page @@ -238,7 +238,7 @@ del notifs[:] return ret - def getAffiliation(self, service, node): + def get_affiliation(self, service, node): """retrieve affiliation for a pubsub node @param service(jid.JID): pubsub service @@ -259,7 +259,7 @@ self.affiliations[(service, node)] = affiliation return affiliation - def setAffiliation(self, service, node, affiliation): + def set_affiliation(self, service, node, affiliation): """cache affiliation for a node will empty cache when it become too big diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/server/tasks/implicit/task_brython.py --- a/libervia/server/tasks/implicit/task_brython.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/server/tasks/implicit/task_brython.py Sat Apr 08 13:44:11 2023 +0200 @@ -98,9 +98,9 @@ else: shutil.copy(p, dest) - async def onDirEvent(self, host, filepath, flags): + async def on_dir_event(self, host, filepath, flags): self.set_common_scripts() - await self.manager.runTaskInstance(self) + await self.manager.run_task_instance(self) def start(self): dyn_path = self.build_path / C.BUILD_DIR_DYN diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/server/tasks/implicit/task_js_modules.py --- a/libervia/server/tasks/implicit/task_js_modules.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/server/tasks/implicit/task_js_modules.py Sat Apr 08 13:44:11 2023 +0200 @@ -25,7 +25,7 @@ with package_path.open('w') as f: json.dump(package, f) - cmd = self.findCommand('yarnpkg', 'yarn') + cmd = self.find_command('yarnpkg', 'yarn') await self.runCommand(cmd, 'install', path=str(self.build_path)) try: diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/server/tasks/implicit/task_sass.py --- a/libervia/server/tasks/implicit/task_sass.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/server/tasks/implicit/task_sass.py Sat Apr 08 13:44:11 2023 +0200 @@ -43,14 +43,14 @@ with package_path.open('w') as f: json.dump(package, f, indent=4) - cmd = self.findCommand('yarnpkg', 'yarn') + cmd = self.find_command('yarnpkg', 'yarn') await self.runCommand(cmd, 'install', path=str(d_path)) self.WATCH_DIRS = list(sass_dirs) - async def onDirEvent(self, host, filepath, flags): + async def on_dir_event(self, host, filepath, flags): if filepath.suffix in SASS_SUFFIXES: - await self.manager.runTaskInstance(self) + await self.manager.run_task_instance(self) async def start(self): d_path = self.resource.dev_build_path diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/server/tasks/manager.py --- a/libervia/server/tasks/manager.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/server/tasks/manager.py Sat Apr 08 13:44:11 2023 +0200 @@ -56,14 +56,14 @@ def build_path(self): """path where generated files will be build for this site""" if self._build_path is None: - self._build_path = self.host.getBuildPath(self.site_name) + self._build_path = self.host.get_build_path(self.site_name) return self._build_path @property def site_name(self): return self.resource.site_name - def validateData(self, task): + def validate_data(self, task): """Check workflow attributes in task""" for var, allowed in (("ON_ERROR", ("continue", "stop")), @@ -83,7 +83,7 @@ raise ValueError(_("Unexpected value for {var}: {value!r}").format( var=var, value=value)) - async def importTask( + async def import_task( self, task_name: str, task_path: Path, @@ -108,7 +108,7 @@ raise ValueError( f"task {task_name!r} must be run after {pre_task_name!r}, " f"however there is no task with such name") - await self.importTask(pre_task_name, pre_task_path, to_import) + await self.import_task(pre_task_name, pre_task_path, to_import) # we launch prepare, which is a method used to prepare # data at runtime (e.g. set WATCH_DIRS using config) @@ -120,21 +120,21 @@ log.info(_('== preparing task "{task_name}" for {site_name} =='.format( task_name=task_name, site_name=self.site_name or DEFAULT_SITE_LABEL))) try: - await utils.asDeferred(prepare) + await utils.as_deferred(prepare) except exceptions.CancelError as e: log.debug(f"Skipping {task_name} which cancelled itself: {e}") return self.tasks[task_name] = task - self.validateData(task) + self.validate_data(task) if self.host.options['dev-mode']: dirs = task.WATCH_DIRS or [] for dir_ in dirs: - self.host.files_watcher.watchDir( + self.host.files_watcher.watch_dir( dir_, auto_add=True, recursive=True, - callback=self._autorunTask, task_name=task_name) + callback=self._autorun_task, task_name=task_name) - async def parseTasksDir(self, dir_path: Path) -> None: + async def parse_tasks_dir(self, dir_path: Path) -> None: log.debug(f"parsing tasks in {dir_path}") tasks_paths = sorted(dir_path.glob('task_*.py')) to_import = {} @@ -152,40 +152,40 @@ to_import[task_name] = task_path for task_name, task_path in to_import.items(): - await self.importTask(task_name, task_path, to_import) + await self.import_task(task_name, task_path, to_import) - async def parseTasks(self): + async def parse_tasks(self): # implicit tasks are always run implicit_path = Path(implicit.__file__).parent - await self.parseTasksDir(implicit_path) + await self.parse_tasks_dir(implicit_path) # now we check if there are tasks specific to this site if not self.tasks_dir.is_dir(): log.debug(_("{name} has no task to launch.").format( name = self.resource.site_name or DEFAULT_SITE_LABEL)) return else: - await self.parseTasksDir(self.tasks_dir) + await self.parse_tasks_dir(self.tasks_dir) - def _autorunTask(self, host, filepath, flags, task_name): + def _autorun_task(self, host, filepath, flags, task_name): """Called when an event is received from a watched directory""" if flags == ['create']: return try: task = self.tasks[task_name] - on_dir_event_cb = task.onDirEvent + on_dir_event_cb = task.on_dir_event except AttributeError: - return defer.ensureDeferred(self.runTask(task_name)) + return defer.ensureDeferred(self.run_task(task_name)) else: - return utils.asDeferred( + return utils.as_deferred( on_dir_event_cb, host, Path(filepath.path.decode()), flags) - async def runTaskInstance(self, task: Task) -> None: + async def run_task_instance(self, task: Task) -> None: self._current_task = task.name log.info(_('== running task "{task_name}" for {site_name} =='.format( task_name=task.name, site_name=self.site_name or DEFAULT_SITE_LABEL))) os.chdir(self.site_path) try: - await utils.asDeferred(task.start) + await utils.as_deferred(task.start) except Exception as e: on_error = task.ON_ERROR if on_error == 'stop': @@ -197,17 +197,17 @@ raise exceptions.InternalError("we should never reach this point") self._current_task = None - async def runTask(self, task_name: str) -> None: + async def run_task(self, task_name: str) -> None: """Run a single task @param task_name(unicode): name of the task to run """ task = self.tasks[task_name] - await self.runTaskInstance(task) + await self.run_task_instance(task) - async def runTasks(self): + async def run_tasks(self): """Run all the tasks found""" old_path = os.getcwd() for task_name, task_value in self.tasks.items(): - await self.runTask(task_name) + await self.run_task(task_name) os.chdir(old_path) diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/server/tasks/task.py --- a/libervia/server/tasks/task.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/server/tasks/task.py Sat Apr 08 13:44:11 2023 +0200 @@ -31,7 +31,7 @@ ON_ERROR: str = "stop" LOG_OUTPUT: bool = True # list of directories to check for restarting this task - # Task.onDirEvent will be called if it exists, otherwise + # Task.on_dir_event will be called if it exists, otherwise # the task will be run and Task.start will be called WATCH_DIRS: Optional[list] = None # list of task names which must be prepared/started before this one @@ -58,15 +58,15 @@ """path where generated files will be build for this site""" return self.manager.build_path - def getConfig(self, key, default=None, value_type=None): - return self.host.getConfig(self.resource, key=key, default=default, + def config_get(self, key, default=None, value_type=None): + return self.host.config_get(self.resource, key=key, default=default, value_type=value_type) @property def site_name(self): return self.resource.site_name - def findCommand(self, name, *args): + def find_command(self, name, *args): """Find full path of a shell command @param name(unicode): name of the command to find diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/server/utils.py --- a/libervia/server/utils.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/server/utils.py Sat Apr 08 13:44:11 2023 +0200 @@ -87,9 +87,9 @@ def register(self, started_cb=None, finished_cb=None, error_cb=None, timeout=30): """register the signals to handle progression - @param started_cb(callable, None): method to call when progressStarted signal is received - @param finished_cb(callable, None): method to call when progressFinished signal is received - @param error_cb(callable, None): method to call when progressError signal is received + @param started_cb(callable, None): method to call when progress_started signal is received + @param finished_cb(callable, None): method to call when progress_finished signal is received + @param error_cb(callable, None): method to call when progress_error signal is received @param timeout(int): progress time out if nothing happen in this progression during this delay, an exception is raised diff -r ec3ad9abf9f9 -r 106bae41f5c8 libervia/server/websockets.py --- a/libervia/server/websockets.py Fri Apr 07 15:20:40 2023 +0200 +++ b/libervia/server/websockets.py Sat Apr 08 13:44:11 2023 +0200 @@ -114,7 +114,7 @@ log.debug(f"websocket connection connected for profile {self.__profile}") return "libervia-page" - def onOpen(self): + def on_open(self): log.debug("websocket connection opened") def onMessage(self, payload: bytes, isBinary: bool) -> None: @@ -190,7 +190,7 @@ self.sendClose(4401, "Unauthorized") return - def onClose(self, wasClean, code, reason): + def on_close(self, wasClean, code, reason): log.debug(f"closing websocket (profile: {self.__profile}, reason: {reason})") if self.__profile is None: log.error("self.__profile should not be None") @@ -208,14 +208,14 @@ self.__profile = None @classmethod - def getBaseURL(cls, secure): + def get_base_url(cls, secure): return "ws{sec}://localhost:{port}".format( sec="s" if secure else "", port=host.options["port_https" if secure else "port"], ) @classmethod - def getResource(cls, secure): - factory = websocket.WebSocketServerFactory(cls.getBaseURL(secure)) + def get_resource(cls, secure): + factory = websocket.WebSocketServerFactory(cls.get_base_url(secure)) factory.protocol = cls return resource.WebSocketResource(factory) diff -r ec3ad9abf9f9 -r 106bae41f5c8 twisted/plugins/libervia_server.py --- a/twisted/plugins/libervia_server.py Fri Apr 07 15:20:40 2023 +0200 +++ b/twisted/plugins/libervia_server.py Sat Apr 08 13:44:11 2023 +0200 @@ -160,7 +160,7 @@ # so here is the best place. from sat.core import log_config - log_config.satConfigure(C.LOG_BACKEND_TWISTED, C, backend_data=options) + log_config.sat_configure(C.LOG_BACKEND_TWISTED, C, backend_data=options) class Options(usage.Options): @@ -182,7 +182,7 @@ # on the command line. # FIXME: must be refactored + code can be factorised with backend - config_parser = config.parseMainConf() + config_parser = config.parse_main_conf() self.handleDeprecated(config_parser) for param in self.optParameters + OPT_PARAMETERS_CFG: name = param[0] @@ -190,7 +190,7 @@ try: value = os.getenv(env_name) if value is None: - value = config.getConfig( + value = config.config_get( config_parser, C.CONFIG_SECTION, name, Exception) try: param[2] = param[4](value) @@ -210,7 +210,7 @@ replacements = (("ssl_certificate", "tls_certificate"),) for old, new in replacements: try: - value = config.getConfig(config_parser, C.CONFIG_SECTION, old, Exception) + value = config.config_get(config_parser, C.CONFIG_SECTION, old, Exception) except (configparser.NoSectionError, configparser.NoOptionError): pass else: