changeset 1322:a0954b6610aa

pages: identities are not using `data_objects` anymore: - identities are now handler directly with the dict received from backend, without using a specific data object. - a new `fillMissingIdentities` method in `LiberivaPage` will help to get all needed identities before rendering the template, and to avoid missing avatar or nickname. - (blog/view): fill missing identities for main blog items, not only for comments
author Goffi <goffi@goffi.org>
date Sun, 02 Aug 2020 17:45:15 +0200
parents eb85ef26cb4a
children a20fe9eb307b
files libervia/pages/blog/view/page_meta.py libervia/server/pages.py libervia/server/session_iface.py
diffstat 3 files changed, 44 insertions(+), 33 deletions(-) [+]
line wrap: on
line diff
--- a/libervia/pages/blog/view/page_meta.py	Sat Aug 01 16:56:04 2020 +0200
+++ b/libervia/pages/blog/view/page_meta.py	Sun Aug 02 17:45:15 2020 +0200
@@ -5,9 +5,6 @@
 import html
 from libervia.server.constants import Const as C
 from twisted.words.protocols.jabber import jid
-from twisted.internet import defer
-from sat.tools.common import data_objects
-from libervia.server import session_iface
 from sat.core.i18n import _
 from sat.tools.common.template import safe
 from sat.tools.common import uri
@@ -109,24 +106,15 @@
         "title": "{service}'s blog".format(service=service)})
 
 
-@defer.inlineCallbacks
-def appendComments(self, blog_items, identities, profile):
+async def appendComments(self, request, blog_items, profile):
+    await self.fillMissingIdentities(
+        request, [i['author_jid'] for i in blog_items['items']])
     for blog_item in blog_items['items']:
-        if identities is not None:
-            author = blog_item['author_jid']
-            if not author:
-                log.warning(_("no author found for item {item_id}").format(
-                    item_id=blog_item['id']))
-            else:
-                if author not in identities:
-                    id_raw = yield self.host.bridgeCall(
-                        'identityGet', author, [], True, profile)
-                    identities[author] = data_format.deserialise(id_raw)
         for comment_data in blog_item['comments']:
             service = comment_data['service']
             node = comment_data['node']
             try:
-                comments_data = yield self.host.bridgeCall('mbGet',
+                comments_data = await self.host.bridgeCall('mbGet',
                                       service,
                                       node,
                                       C.NO_LIMIT,
@@ -143,16 +131,15 @@
 
             comments = data_format.deserialise(comments_data)
             comment_data['items'] = comments['items']
-            yield appendComments(self, comments, identities, profile)
+            await appendComments(self, request, comments, profile)
 
-@defer.inlineCallbacks
-def getBlogItems(self, request, service, node, item_id, extra, profile):
+async def getBlogItems(self, request, service, node, item_id, extra, profile):
     try:
         if item_id:
             items_id = [item_id]
         else:
             items_id = []
-        blog_data = yield self.host.bridgeCall('mbGet',
+        blog_data = await self.host.bridgeCall('mbGet',
                               service.userhost(),
                               node,
                               C.NO_LIMIT,
@@ -170,10 +157,9 @@
     else:
         blog_data = data_format.deserialise(blog_data)
 
-    defer.returnValue(blog_data)
+    return blog_data
 
-@defer.inlineCallbacks
-def prepare_render(self, request):
+async def prepare_render(self, request):
     data = self.getRData(request)
     page_max = data.get("page_max", 10)
     # if the comments are not explicitly hidden, we show them
@@ -196,7 +182,7 @@
 
     ## main data ##
     # we get data from backend/XMPP here
-    blog_items = yield getBlogItems(self, request, service, node, item_id, extra, profile)
+    blog_items = await getBlogItems(self, request, service, node, item_id, extra, profile)
 
     ## navigation ##
     # no let's fill service, node and pagination URLs
@@ -218,12 +204,12 @@
 
     ## identities ##
     # identities are used to show nice nickname or avatars
-    identities = self.host.getSessionData(request, session_iface.ISATSession).identities
+    await self.fillMissingIdentities(request, [i['author_jid'] for i in blog_items['items']])
 
     ## Comments ##
     # if comments are requested, we need to take them
     if show_comments:
-        yield appendComments(self, blog_items, identities, profile)
+        await appendComments(self, request, blog_items, profile)
 
     ## URLs ##
     # We will fill items_http_uri and tags_http_uri in template_data with suitable urls
@@ -235,7 +221,7 @@
         blog_base_url_item = self.getURLByNames([('user', [target_profile]), ('user_blog', ['id'])])
         blog_base_url_tag = self.getURLByNames([('user', [target_profile]), ('user_blog', ['tag'])])
         # we also set the background image if specified by user
-        bg_img = yield self.host.bridgeCall('asyncGetParamA', 'Background', 'Blog page', 'value', -1, template_data['target_profile'])
+        bg_img = await self.host.bridgeCall('asyncGetParamA', 'Background', 'Blog page', 'value', -1, template_data['target_profile'])
         if bg_img:
             template_data['dynamic_style'] = safe("""
                 :root {
@@ -290,8 +276,7 @@
     template_data['xmpp_uri'] = uri.buildXMPPUri('pubsub', subtype='microblog', **uri_args)
 
 
-@defer.inlineCallbacks
-def on_data_post(self, request):
+async def on_data_post(self, request):
     profile = self.getProfile(request)
     if profile is None:
         self.pageError(request, C.HTTP_FORBIDDEN)
@@ -303,7 +288,7 @@
             self.pageError(request, C.HTTP_BAD_REQUEST)
         comment_data = {"content": body}
         try:
-            yield self.host.bridgeCall('mbSend',
+            await self.host.bridgeCall('mbSend',
                                        service,
                                        node,
                                        data_format.serialise(comment_data),
--- a/libervia/server/pages.py	Sat Aug 01 16:56:04 2020 +0200
+++ b/libervia/server/pages.py	Sun Aug 02 17:45:15 2020 +0200
@@ -28,7 +28,7 @@
 import traceback
 from pathlib import Path
 from functools import reduce
-from typing import Optional, List
+from typing import Optional, Union, List
 
 from twisted.web import server
 from twisted.web import resource as web_resource
@@ -42,6 +42,7 @@
 from sat.tools.utils import asDeferred
 from sat.tools.common import date_utils
 from sat.tools.common import utils
+from sat.tools.common import data_format
 from sat.core.log import getLogger
 from sat_frontends.bridge.bridge_frontend import BridgeException
 
@@ -1111,6 +1112,32 @@
         else:
             cache.clear()
 
+    # identities
+
+    async def fillMissingIdentities(
+        self,
+        request: server.Request,
+        entities: List[Union[str, jid.JID, None]],
+    ) -> None:
+        """Check if all entities have an identity cache, get missing ones from backend
+
+        @param request: request with a plugged profile
+        @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(
+            request,
+            session_iface.ISATSession
+        ).identities
+        for e in entities:
+            if e not in identities:
+                id_raw = await self.host.bridgeCall(
+                    'identityGet', e, [], True, profile)
+                identities[e] = data_format.deserialise(id_raw)
+
+    # signals, server => browser communication
+
     @classmethod
     def onSignal(cls, host, signal, *args):
         """Generic method which receive registered signals
--- a/libervia/server/session_iface.py	Sat Aug 01 16:56:04 2020 +0200
+++ b/libervia/server/session_iface.py	Sun Aug 02 17:45:15 2020 +0200
@@ -17,7 +17,6 @@
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 from zope.interface import Interface, Attribute
 from zope.interface import implementer
-from sat.tools.common import data_objects
 from libervia.server.constants import Const as C
 from libervia.server.classes import Notification
 from collections import OrderedDict
@@ -47,7 +46,7 @@
         # time when the backend session was started
         self.backend_started = None
         self.uuid = str(shortuuid.uuid())
-        self.identities = data_objects.Identities()
+        self.identities = {}
         self.csrf_token = str(shortuuid.uuid())
         self.locale = None  # i18n of the pages
         self.theme = None