changeset 132:30d8e328559b

server & browser side: microblogging refactoring first draft - use of new getLastGroupBlogs and getMassiveLastGroupBlogs methods - microblgos browser's cache is temporarily deactivated - last 10 microblogs for everybody are requested on new meta microblog widget
author Goffi <goffi@goffi.org>
date Mon, 02 Apr 2012 00:25:38 +0200
parents ddfcc4cb6cee
children 4ad621df9e34
files browser_side/card_game.py browser_side/contact.py browser_side/panels.py libervia.py libervia.tac
diffstat 5 files changed, 80 insertions(+), 39 deletions(-) [+]
line wrap: on
line diff
--- a/browser_side/card_game.py	Tue Mar 06 09:09:15 2012 +0100
+++ b/browser_side/card_game.py	Mon Apr 02 00:25:38 2012 +0200
@@ -36,7 +36,6 @@
 from pyjamas import Window
 from pyjamas import DOM
 
-from pyjamas.dnd import makeDraggable
 from pyjamas.ui.DragWidget import DragWidget, DragContainer
 from jid import JID
 from dialog import ConfirmDialog, InfoDialog
--- a/browser_side/contact.py	Tue Mar 06 09:09:15 2012 +0100
+++ b/browser_side/contact.py	Mon Apr 02 00:25:38 2012 +0200
@@ -28,7 +28,6 @@
 from pyjamas import Window
 from pyjamas import DOM
 
-from pyjamas.dnd import makeDraggable
 from pyjamas.ui.DragWidget import DragWidget, DragContainer
 from browser_side.tools import html_sanitize
 from jid import JID
--- a/browser_side/panels.py	Tue Mar 06 09:09:15 2012 +0100
+++ b/browser_side/panels.py	Mon Apr 02 00:25:38 2012 +0200
@@ -97,17 +97,18 @@
             item_type = None
         DOM.eventPreventDefault(event)
         if item_type=="GROUP":
-            _new_panel = MicroblogPanel(self.host, item)
+            _new_panel = MicroblogPanel(self.host, [item])
             _new_panel.setAcceptedGroup(item)
-            self.host.FillMicroblogPanel(_new_panel)
+            self.host.FillMicroblogPanel(_new_panel) #XXX: cache is temporarly deactivated, need to be reworked
         elif item_type=="CONTACT":
             _contact = JID(item)
             self.host.contact_panel.setContactMessageWaiting(_contact.bare, False)
             _new_panel = ChatPanel(self.host, _contact)
             _new_panel.historyPrint()
         elif item_type=="CONTACT_TITLE":
-            _new_panel = MicroblogPanel(self.host, accept_all=True)
-            self.host.FillMicroblogPanel(_new_panel)
+            _new_panel = MicroblogPanel(self.host, [])
+            #self.host.FillMicroblogPanel(_new_panel) #XXX: cache is temporarly deactivated, need to be reworked
+            self.host.bridge.call('getMassiveLastMblogs', _new_panel.massiveInsert, 'ALL', [], 10)
         else:
             return False
         if isinstance(self, LiberviaWidget):
@@ -473,6 +474,15 @@
         #XXX: fixed directly on pyjamas, if the patch is accepted, no need to walk around this
         return AutoCompleteTextBox.complete(self)"""
 
+class MicroblogItem():
+    #XXX: should be moved in a separated module
+
+    def __init__(self, data):
+        self.id = data['id']
+        self.content = data['content']
+        self.author = data['author']
+        self.timestamp = float(data.get('timestamp',0)) #XXX: int doesn't work here
+        
 class MicroblogEntry(SimplePanel):
 
     def __init__(self, host, mblog_entry):
@@ -504,26 +514,44 @@
 
 class MicroblogPanel(LiberviaWidget):
 
-    def __init__(self, host, title='', accept_all=False):
+    def __init__(self, host, accepted_groups):
         """Panel used to show microblog
-        @param title: title of the panel
-        @param accept_all: if true, show every message, without filtering jids"""
-        LiberviaWidget.__init__(self, host, title)
+        @param accepted_groups: groups displayed in this panel, if empty, show all microblogs from all contacts
+        """
+        LiberviaWidget.__init__(self, host, ", ".join(accepted_groups))
         #ScrollPanelWrapper.__init__(self)
         #DropCell.__init__(self)
-        self.accept_all = accept_all
-        self.accepted_groups = []
+        self.accepted_groups = accepted_groups
         self.entries = {}
         self.vpanel = VerticalPanel()
         self.vpanel.setStyleName('microblogPanel')
         self.setWidget(self.vpanel)
 
+    def accept_all(self):
+        return not self.accepted_groups #we accept every microblog only if we are not filtering by groups
+
+    def getEntries(self):
+        """Ask all the entries for the currenly accepted groups,
+        and fill the panel"""
+       
+    def massiveInsert(self, mblogs):
+        """Insert several microblogs at once
+        @param mblogs: dictionary of microblogs, as the result of getMassiveLastGroupBlogs
+        """
+        print "Massive insertion of microblogs"
+        for publisher in mblogs:
+            print "adding blogs for [%s]" % publisher
+            for mblog in mblogs[publisher]:
+                if not mblog.has_key('content'):
+                    print ("WARNING: No content found in microblog [%s]", mblog)
+                    continue
+                mblog_entry = MicroblogItem(mblog)
+                self.addEntry(mblog_entry)
+
     def addEntry(self, mblog_entry):
         """Add an entry to the panel
-        @param text: main text of the entry
-        @param id: unique id of the entry
-        @param author: who wrote the entry
-        @param date: when the entry was written"""
+        @param mblog_entry: MicroblogItem instance
+        """
         if mblog_entry.id in self.entries:
             return
         _entry = MicroblogEntry(self.host, mblog_entry)
@@ -553,7 +581,7 @@
         """Tell if a jid is actepted and show in this panel
         @param jid: jid
         @return: True if the jid is accepted"""
-        if self.accept_all:
+        if self.accept_all():
             return True
         for group in self.accepted_groups:
             if self.host.contact_panel.isContactInGroup(group, jid):
--- a/libervia.py	Tue Mar 06 09:09:15 2012 +0100
+++ b/libervia.py	Mon Apr 02 00:25:38 2012 +0200
@@ -28,7 +28,7 @@
 from pyjamas.JSONService import JSONProxy
 from browser_side.register import RegisterBox
 from browser_side.contact import ContactPanel
-from browser_side.panels import WidgetsPanel
+from browser_side.panels import WidgetsPanel, MicroblogItem
 from browser_side import panels, dialog
 from browser_side.jid import JID
 from browser_side.tools import html_sanitize
@@ -48,7 +48,15 @@
 
     def onRemoteResponse(self, response, request_info):
         if self.cb.has_key(request_info.id):
-            self.cb[request_info.id](response)
+            _cb = self.cb[request_info.id]
+            if isinstance(_cb, tuple):
+                #we have arguments attached to the callback
+                #we send them after the answer
+                callback, args = _cb
+                callback(response, *args)
+            else:
+                #No additional argument, we call directly the callback
+                _cb(response)
             del self.cb[request_info.id]
         
     def onRemoteError(self, code, errobj, request_info):
@@ -70,13 +78,11 @@
     def __init__(self):
         LiberviaJsonProxy.__init__(self, "/register_api",
                         ["isRegistered","isConnected","connect"])
-        self.handler=self
-        self.cb={}
 
 class BridgeCall(LiberviaJsonProxy):
     def __init__(self):
         LiberviaJsonProxy.__init__(self, "/json_api",
-                        ["getContacts", "addContact", "sendMessage", "sendMblog", "getMblogNodes", "getProfileJid", "getHistory", "getPresenceStatus",
+                        ["getContacts", "addContact", "sendMessage", "sendMblog", "getLastMblogs", "getMassiveLastMblogs", "getProfileJid", "getHistory", "getPresenceStatus",
                          "joinMUC", "getRoomsJoined", "launchTarotGame", "getTarotCardsPaths", "tarotGameReady", "tarotGameContratChoosed",
                          "tarotGamePlayCards", "launchRadioCollective", "getWaitingSub", "subscription", "delContact", "updateContact", "getCardCache"])
 
@@ -96,14 +102,6 @@
                 self.host.bridge_signals.call('getSignals', self.host._getSignalsCB)
             Timer(notify=_timerCb).schedule(5000) #we wait 5 s and try again
 
-class MicroblogEntry():
-    def __init__(self, data):
-        self.id = data['id']
-        self.content = data['content']
-        self.author = data['author']
-        self.timestamp = float(data.get('timestamp',0)) #XXX: int doesn't work here
-        
-
 class SatWebFrontend:
     def onModuleLoad(self):
         self.whoami = None
@@ -121,7 +119,9 @@
         self.mblog_cache = [] #used to keep blog entries in memory, to show them in new mblog panel
         self.avatars_cache = {} #keep track of jid's avatar hash (key=jid, value=file)
         #self.discuss_panel.addWidget(panels.EmptyPanel(self))
-        self.discuss_panel.addWidget(panels.MicroblogPanel(self, accept_all=True))
+        mblog_panel = panels.MicroblogPanel(self, [])
+        self.bridge.call('getMassiveLastMblogs', mblog_panel.massiveInsert, 'ALL', [], 10)
+        self.discuss_panel.addWidget(mblog_panel)
         #self.discuss_panel.addWidget(panels.EmptyPanel(self))
         self._register_box = None
         RootPanel().add(self.panel)
@@ -282,7 +282,7 @@
                 _groups = set(data['groups'].split() if data['groups'] else [])
             else:
                 _groups=None
-            mblog_entry = MicroblogEntry(data)
+            mblog_entry = MicroblogItem(data)
             
             for lib_wid in self.libervia_widgets:
                 if isinstance(lib_wid, panels.MicroblogPanel):
@@ -297,7 +297,7 @@
         @param mblog_panel: MicroblogPanel instance
         @param sender: jid of the entry sender
         @param _groups: groups which can receive this entry
-        @param mblog_entry: MicroblogEntry instance"""
+        @param mblog_entry: MicroblogItem instance"""
         if mblog_panel.isJidAccepted(sender) or (_groups == None and self.whoami and sender == self.whoami.bare) \
            or (_groups and _groups.intersection(mblog_panel.accepted_groups)):
             mblog_panel.addEntry(mblog_entry)
--- a/libervia.tac	Tue Mar 06 09:09:15 2012 +0100
+++ b/libervia.tac	Mon Apr 02 00:25:38 2012 +0200
@@ -201,6 +201,27 @@
                 return self.sat_host.bridge.sendPersonalEvent("MICROBLOG", {'content':text}, profile)
             else:
                 return self.sat_host.bridge.sendGroupBlog([recip], text, profile)
+    
+    def jsonrpc_getLastMblogs(self, publisher_jid, max_item):
+        """Get last microblogs posted by a contact
+        @param publisher_jid: jid of the publisher
+        @param max_item: number of items to ask
+        @return list of microblog data (dict)"""
+        profile = ISATSession(self.session).profile
+        d = defer.Deferred()
+        self.sat_host.bridge.getLastGroupBlogs(publisher_jid, max_item, profile, callback=d.callback, errback=d.errback)
+        return d
+
+    def jsonrpc_getMassiveLastMblogs(self, publishers_type, publishers_list, max_item):
+        """Get lasts microblogs posted by several contacts at once
+        @param publishers_type: one of "ALL", "GROUP", "JID"
+        @param publishers_list: list of publishers type (empty list of all, list of groups or list of jids)
+        @param max_item: number of items to ask
+        @return: dictionary key=publisher's jid, value=list of microblog data (dict)"""
+        profile = ISATSession(self.session).profile
+        d = defer.Deferred()
+        self.sat_host.bridge.getMassiveLastGroupBlogs(publishers_type, publishers_list, max_item, profile, callback=d.callback, errback=d.errback)
+        return d
 
     def jsonrpc_getPresenceStatus(self):
         """Get Presence information for connected contacts"""
@@ -301,10 +322,6 @@
         else:
             return None
 
-    def _fillMblogNodes(self, result, session):
-        """Fill the microblog nodes association for this session"""
-        session.sat_mblog_nodes = dict(result)
-
     def render(self, request):
         """
         Render method with some hacks:
@@ -514,8 +531,6 @@
         _session.notifyOnExpire(onExpire)
         
         d = defer.Deferred()
-        self.sat_host.bridge.getMblogNodes(profile, d.callback, d.errback)
-        d.addCallback(self._fillMblogNodes, _session)
         return result('LOGGED')
 
     def _logginError(self, login, request, error_type):