comparison libervia.py @ 226:744426c2b699

browser_side, misc: better PEP8 compliance
author souliane <souliane@mailoo.org>
date Thu, 26 Sep 2013 14:32:24 +0200
parents 624a87377412
children 67e24c342e7f
comparison
equal deleted inserted replaced
225:9b93a21dc5e2 226:744426c2b699
17 17
18 You should have received a copy of the GNU Affero General Public License 18 You should have received a copy of the GNU Affero General Public License
19 along with this program. If not, see <http://www.gnu.org/licenses/>. 19 along with this program. If not, see <http://www.gnu.org/licenses/>.
20 """ 20 """
21 21
22 import pyjd # this is dummy in pyjs 22 import pyjd # this is dummy in pyjs
23 from pyjamas.ui.RootPanel import RootPanel 23 from pyjamas.ui.RootPanel import RootPanel
24 from pyjamas.ui.HTML import HTML 24 from pyjamas.ui.HTML import HTML
25 from pyjamas.ui.KeyboardListener import KEY_ESCAPE 25 from pyjamas.ui.KeyboardListener import KEY_ESCAPE
26 from pyjamas.Timer import Timer 26 from pyjamas.Timer import Timer
27 from pyjamas import Window, DOM 27 from pyjamas import Window, DOM
37 MAX_MBLOG_CACHE = 500 #Max microblog entries kept in memories 37 MAX_MBLOG_CACHE = 500 #Max microblog entries kept in memories
38 38
39 class LiberviaJsonProxy(JSONProxy): 39 class LiberviaJsonProxy(JSONProxy):
40 def __init__(self, *args, **kwargs): 40 def __init__(self, *args, **kwargs):
41 JSONProxy.__init__(self, *args, **kwargs) 41 JSONProxy.__init__(self, *args, **kwargs)
42 self.handler=self 42 self.handler = self
43 self.cb={} 43 self.cb = {}
44 self.eb={} 44 self.eb = {}
45 45
46 def call(self, method, cb, *args): 46 def call(self, method, cb, *args):
47 _id = self.callMethod(method,args) 47 _id = self.callMethod(method, args)
48 if cb: 48 if cb:
49 if isinstance(cb, tuple): 49 if isinstance(cb, tuple):
50 if len(cb) != 2: 50 if len(cb) != 2:
51 print ("ERROR: tuple syntax for bridge.call is (callback, errback), aborting") 51 print ("ERROR: tuple syntax for bridge.call is (callback, errback), aborting")
52 return 52 return
67 # #No additional argument, we call directly the callback 67 # #No additional argument, we call directly the callback
68 _cb(response) 68 _cb(response)
69 del self.cb[request_info.id] 69 del self.cb[request_info.id]
70 if request_info.id in self.eb: 70 if request_info.id in self.eb:
71 del self.eb[request_info.id] 71 del self.eb[request_info.id]
72 72
73 def onRemoteError(self, code, errobj, request_info): 73 def onRemoteError(self, code, errobj, request_info):
74 """def dump(obj): 74 """def dump(obj):
75 print "\n\nDUMPING %s\n\n" % obj 75 print "\n\nDUMPING %s\n\n" % obj
76 for i in dir(obj): 76 for i in dir(obj):
77 print "%s: %s" % (i, getattr(obj,i))""" 77 print "%s: %s" % (i, getattr(obj,i))"""
84 if code != 0: 84 if code != 0:
85 print ("Internal server error") 85 print ("Internal server error")
86 """for o in code, error, request_info: 86 """for o in code, error, request_info:
87 dump(o)""" 87 dump(o)"""
88 else: 88 else:
89 if isinstance(errobj['message'],dict): 89 if isinstance(errobj['message'], dict):
90 print("Error %s: %s" % (errobj['message']['faultCode'], errobj['message']['faultString'])) 90 print("Error %s: %s" % (errobj['message']['faultCode'], errobj['message']['faultString']))
91 else: 91 else:
92 print("Error: %s" % errobj['message']) 92 print("Error: %s" % errobj['message'])
93 93
94 class RegisterCall(LiberviaJsonProxy): 94 class RegisterCall(LiberviaJsonProxy):
95 def __init__(self): 95 def __init__(self):
96 LiberviaJsonProxy.__init__(self, "/register_api", 96 LiberviaJsonProxy.__init__(self, "/register_api",
97 ["isRegistered","isConnected","connect"]) 97 ["isRegistered", "isConnected", "connect"])
98 98
99 class BridgeCall(LiberviaJsonProxy): 99 class BridgeCall(LiberviaJsonProxy):
100 def __init__(self): 100 def __init__(self):
101 LiberviaJsonProxy.__init__(self, "/json_api", 101 LiberviaJsonProxy.__init__(self, "/json_api",
102 ["getContacts", "addContact", "sendMessage", "sendMblog", "sendMblogComment", 102 ["getContacts", "addContact", "sendMessage", "sendMblog", "sendMblogComment",
112 class BridgeSignals(LiberviaJsonProxy): 112 class BridgeSignals(LiberviaJsonProxy):
113 RETRY_BASE_DELAY = 1000 113 RETRY_BASE_DELAY = 1000
114 114
115 def __init__(self, host): 115 def __init__(self, host):
116 self.host = host 116 self.host = host
117 self.retry_delay = self.RETRY_BASE_DELAY 117 self.retry_delay = self.RETRY_BASE_DELAY
118 LiberviaJsonProxy.__init__(self, "/json_signal_api", 118 LiberviaJsonProxy.__init__(self, "/json_signal_api",
119 ["getSignals"]) 119 ["getSignals"])
120 120
121 def onRemoteResponse(self, response, request_info): 121 def onRemoteResponse(self, response, request_info):
122 self.retry_delay = self.RETRY_BASE_DELAY 122 self.retry_delay = self.RETRY_BASE_DELAY
123 LiberviaJsonProxy.onRemoteResponse(self, response, request_info) 123 LiberviaJsonProxy.onRemoteResponse(self, response, request_info)
124 124
125 125
126 def onRemoteError(self, code, errobj, request_info): 126 def onRemoteError(self, code, errobj, request_info):
127 if errobj['message'] == 'Empty Response': 127 if errobj['message'] == 'Empty Response':
164 self._register_box = None 164 self._register_box = None
165 RootPanel().add(self.panel) 165 RootPanel().add(self.panel)
166 DOM.addEventPreview(self) 166 DOM.addEventPreview(self)
167 self.resize() 167 self.resize()
168 self._register = RegisterCall() 168 self._register = RegisterCall()
169 self._register.call('isRegistered',self._isRegisteredCB) 169 self._register.call('isRegistered', self._isRegisteredCB)
170 self.initialised = False 170 self.initialised = False
171 self.init_cache = [] # used to cache events until initialisation is done 171 self.init_cache = [] # used to cache events until initialisation is done
172 172
173 def addSelectedListener(self, callback): 173 def addSelectedListener(self, callback):
174 self._selected_listeners.add(callback) 174 self._selected_listeners.add(callback)
175 175
176 def getSelected(self): 176 def getSelected(self):
191 if selected == widget: 191 if selected == widget:
192 return 192 return
193 193
194 if selected: 194 if selected:
195 selected.removeStyleName('selected_widget') 195 selected.removeStyleName('selected_widget')
196 196
197 widgets_panel.selected = widget 197 widgets_panel.selected = widget
198 198
199 if widget: 199 if widget:
200 widgets_panel.selected.addStyleName('selected_widget') 200 widgets_panel.selected.addStyleName('selected_widget')
201 201
202 for callback in self._selected_listeners: 202 for callback in self._selected_listeners:
203 callback(widget) 203 callback(widget)
228 else: 228 else:
229 self.bridge.call("getCard", None, jid_str) 229 self.bridge.call("getCard", None, jid_str)
230 def avatarError(error_data): 230 def avatarError(error_data):
231 # The jid is maybe not in our roster, we ask for the VCard 231 # The jid is maybe not in our roster, we ask for the VCard
232 self.bridge.call("getCard", None, jid_str) 232 self.bridge.call("getCard", None, jid_str)
233 233
234 if jid_str not in self.avatars_cache: 234 if jid_str not in self.avatars_cache:
235 self.bridge.call('getEntityData', (dataReceived, avatarError), jid_str, ['avatar']) 235 self.bridge.call('getEntityData', (dataReceived, avatarError), jid_str, ['avatar'])
236 self.avatars_cache[jid_str] = "/media/misc/empty_avatar" 236 self.avatars_cache[jid_str] = "/media/misc/empty_avatar"
237 return self.avatars_cache[jid_str] 237 return self.avatars_cache[jid_str]
238 238
274 else: 274 else:
275 self._register.call('isConnected', self._isConnectedCB) 275 self._register.call('isConnected', self._isConnectedCB)
276 276
277 def _isConnectedCB(self, connected): 277 def _isConnectedCB(self, connected):
278 if not connected: 278 if not connected:
279 self._register.call('connect',lambda x:self.logged()) 279 self._register.call('connect', lambda x:self.logged())
280 else: 280 else:
281 self.logged() 281 self.logged()
282 282
283 def logged(self): 283 def logged(self):
284 if self._register_box: 284 if self._register_box:
285 self._register_box.hide() 285 self._register_box.hide()
286 del self._register_box # don't work if self._register_box is None 286 del self._register_box # don't work if self._register_box is None
287 287
288 #it's time to fill the page 288 #it's time to fill the page
289 self.bridge.call('getContacts', self._getContactsCB) 289 self.bridge.call('getContacts', self._getContactsCB)
290 self.bridge.call('getParamsUI', self._getParamsUICB) 290 self.bridge.call('getParamsUI', self._getParamsUICB)
291 self.bridge_signals.call('getSignals', self._getSignalsCB) 291 self.bridge_signals.call('getSignals', self._getSignalsCB)
297 jid, attributes, groups = contact 297 jid, attributes, groups = contact
298 self._newContactCb(jid, attributes, groups) 298 self._newContactCb(jid, attributes, groups)
299 299
300 def _getSignalsCB(self, signal_data): 300 def _getSignalsCB(self, signal_data):
301 self.bridge_signals.call('getSignals', self._getSignalsCB) 301 self.bridge_signals.call('getSignals', self._getSignalsCB)
302 print('Got signal ==> name: %s, params: %s' % (signal_data[0],signal_data[1])) 302 print('Got signal ==> name: %s, params: %s' % (signal_data[0], signal_data[1]))
303 name,args = signal_data 303 name, args = signal_data
304 if name == 'personalEvent': 304 if name == 'personalEvent':
305 self._personalEventCb(*args) 305 self._personalEventCb(*args)
306 elif name == 'newMessage': 306 elif name == 'newMessage':
307 self._newMessageCb(*args) 307 self._newMessageCb(*args)
308 elif name == 'presenceUpdate': 308 elif name == 'presenceUpdate':
359 print ("WARNING: No content found in microblog [%s]", mblog) 359 print ("WARNING: No content found in microblog [%s]", mblog)
360 continue 360 continue
361 if mblog.has_key('groups'): 361 if mblog.has_key('groups'):
362 _groups = set(mblog['groups'].split() if mblog['groups'] else []) 362 _groups = set(mblog['groups'].split() if mblog['groups'] else [])
363 else: 363 else:
364 _groups=None 364 _groups = None
365 mblog_entry = MicroblogItem(mblog) 365 mblog_entry = MicroblogItem(mblog)
366 self.mblog_cache.append((_groups, mblog_entry)) 366 self.mblog_cache.append((_groups, mblog_entry))
367 367
368 if len(self.mblog_cache) > MAX_MBLOG_CACHE: 368 if len(self.mblog_cache) > MAX_MBLOG_CACHE:
369 del self.mblog_cache[0:len(self.mblog_cache-MAX_MBLOG_CACHE)] 369 del self.mblog_cache[0:len(self.mblog_cache - MAX_MBLOG_CACHE)]
370 for lib_wid in self.libervia_widgets: 370 for lib_wid in self.libervia_widgets:
371 if isinstance(lib_wid, panels.MicroblogPanel): 371 if isinstance(lib_wid, panels.MicroblogPanel):
372 self.FillMicroblogPanel(lib_wid) 372 self.FillMicroblogPanel(lib_wid)
373 self.initialised = True # initialisation phase is finished here 373 self.initialised = True # initialisation phase is finished here
374 for event_data in self.init_cache: # so we have to send all the cached events 374 for event_data in self.init_cache: # so we have to send all the cached events
405 print ("WARNING: No content found in microblog data") 405 print ("WARNING: No content found in microblog data")
406 return 406 return
407 if 'groups' in data: 407 if 'groups' in data:
408 _groups = set(data['groups'].split() if data['groups'] else []) 408 _groups = set(data['groups'].split() if data['groups'] else [])
409 else: 409 else:
410 _groups=None 410 _groups = None
411 mblog_entry = MicroblogItem(data) 411 mblog_entry = MicroblogItem(data)
412 412
413 for lib_wid in self.libervia_widgets: 413 for lib_wid in self.libervia_widgets:
414 if isinstance(lib_wid, panels.MicroblogPanel): 414 if isinstance(lib_wid, panels.MicroblogPanel):
415 self.addBlogEntry(lib_wid, sender, _groups, mblog_entry) 415 self.addBlogEntry(lib_wid, sender, _groups, mblog_entry)
416 416
417 if sender == self.whoami.bare: 417 if sender == self.whoami.bare:
418 self.mblog_cache.append((_groups, mblog_entry)) 418 self.mblog_cache.append((_groups, mblog_entry))
419 if len(self.mblog_cache) > MAX_MBLOG_CACHE: 419 if len(self.mblog_cache) > MAX_MBLOG_CACHE:
420 del self.mblog_cache[0:len(self.mblog_cache-MAX_MBLOG_CACHE)] 420 del self.mblog_cache[0:len(self.mblog_cache - MAX_MBLOG_CACHE)]
421 421
422 def addBlogEntry(self, mblog_panel, sender, _groups, mblog_entry): 422 def addBlogEntry(self, mblog_panel, sender, _groups, mblog_entry):
423 """Check if an entry can go in MicroblogPanel and add to it 423 """Check if an entry can go in MicroblogPanel and add to it
424 @param mblog_panel: MicroblogPanel instance 424 @param mblog_panel: MicroblogPanel instance
425 @param sender: jid of the entry sender 425 @param sender: jid of the entry sender
433 """Fill a microblog panel with entries in cache 433 """Fill a microblog panel with entries in cache
434 @param mblog_panel: MicroblogPanel instance 434 @param mblog_panel: MicroblogPanel instance
435 """ 435 """
436 #XXX: only our own entries are cached 436 #XXX: only our own entries are cached
437 for cache_entry in self.mblog_cache: 437 for cache_entry in self.mblog_cache:
438 _groups, mblog_entry = cache_entry 438 _groups, mblog_entry = cache_entry
439 self.addBlogEntry(mblog_panel, self.whoami.bare, *cache_entry) 439 self.addBlogEntry(mblog_panel, self.whoami.bare, *cache_entry)
440 440
441 def getEntityMBlog(self, entity): 441 def getEntityMBlog(self, entity):
442 print "geting mblog for entity [%s]" % (entity,) 442 print "geting mblog for entity [%s]" % (entity,)
443 for lib_wid in self.libervia_widgets: 443 for lib_wid in self.libervia_widgets:
456 showed = True 456 showed = True
457 if not showed: 457 if not showed:
458 #The message has not been showed, we must indicate it 458 #The message has not been showed, we must indicate it
459 other = _to if _from.bare == self.whoami.bare else _from 459 other = _to if _from.bare == self.whoami.bare else _from
460 self.contact_panel.setContactMessageWaiting(other.bare, True) 460 self.contact_panel.setContactMessageWaiting(other.bare, True)
461 461
462 def _presenceUpdateCb(self, entity, show, priority, statuses): 462 def _presenceUpdateCb(self, entity, show, priority, statuses):
463 _entity = JID(entity) 463 _entity = JID(entity)
464 #XXX: QnD way to get our status 464 #XXX: QnD way to get our status
465 if self.whoami and self.whoami.bare == _entity.bare and statuses: 465 if self.whoami and self.whoami.bare == _entity.bare and statuses:
466 self.status_panel.changeStatus(statuses.values()[0]) 466 self.status_panel.changeStatus(statuses.values()[0])
481 chat_panel.setPresents(room_nicks) 481 chat_panel.setPresents(room_nicks)
482 chat_panel.historyPrint() 482 chat_panel.historyPrint()
483 483
484 def _roomUserJoinedCb(self, room_jid_s, user_nick, user_data): 484 def _roomUserJoinedCb(self, room_jid_s, user_nick, user_data):
485 for lib_wid in self.libervia_widgets: 485 for lib_wid in self.libervia_widgets:
486 if isinstance(lib_wid,panels.ChatPanel) and lib_wid.type == 'group' and lib_wid.target.bare == room_jid_s: 486 if isinstance(lib_wid, panels.ChatPanel) and lib_wid.type == 'group' and lib_wid.target.bare == room_jid_s:
487 lib_wid.userJoined(user_nick, user_data) 487 lib_wid.userJoined(user_nick, user_data)
488 488
489 def _roomUserLeftCb(self, room_jid_s, user_nick, user_data): 489 def _roomUserLeftCb(self, room_jid_s, user_nick, user_data):
490 for lib_wid in self.libervia_widgets: 490 for lib_wid in self.libervia_widgets:
491 if isinstance(lib_wid,panels.ChatPanel) and lib_wid.type == 'group' and lib_wid.target.bare == room_jid_s: 491 if isinstance(lib_wid, panels.ChatPanel) and lib_wid.type == 'group' and lib_wid.target.bare == room_jid_s:
492 lib_wid.userLeft(user_nick, user_data) 492 lib_wid.userLeft(user_nick, user_data)
493 493
494 def _tarotGameStartedCb(self, room_jid_s, referee, players): 494 def _tarotGameStartedCb(self, room_jid_s, referee, players):
495 print ("Tarot Game Started \o/") 495 print ("Tarot Game Started \o/")
496 for lib_wid in self.libervia_widgets: 496 for lib_wid in self.libervia_widgets:
497 if isinstance(lib_wid,panels.ChatPanel) and lib_wid.type == 'group' and lib_wid.target.bare == room_jid_s: 497 if isinstance(lib_wid, panels.ChatPanel) and lib_wid.type == 'group' and lib_wid.target.bare == room_jid_s:
498 lib_wid.startGame("Tarot", referee, players) 498 lib_wid.startGame("Tarot", referee, players)
499 499
500 def _tarotGameGenericCb(self, event_name, room_jid_s, args): 500 def _tarotGameGenericCb(self, event_name, room_jid_s, args):
501 for lib_wid in self.libervia_widgets: 501 for lib_wid in self.libervia_widgets:
502 if isinstance(lib_wid,panels.ChatPanel) and lib_wid.type == 'group' and lib_wid.target.bare == room_jid_s: 502 if isinstance(lib_wid, panels.ChatPanel) and lib_wid.type == 'group' and lib_wid.target.bare == room_jid_s:
503 getattr(lib_wid.getGame("Tarot"), event_name)(*args) 503 getattr(lib_wid.getGame("Tarot"), event_name)(*args)
504 504
505 def _radioColStartedCb(self, room_jid_s, referee): 505 def _radioColStartedCb(self, room_jid_s, referee):
506 for lib_wid in self.libervia_widgets: 506 for lib_wid in self.libervia_widgets:
507 if isinstance(lib_wid,panels.ChatPanel) and lib_wid.type == 'group' and lib_wid.target.bare == room_jid_s: 507 if isinstance(lib_wid, panels.ChatPanel) and lib_wid.type == 'group' and lib_wid.target.bare == room_jid_s:
508 lib_wid.startGame("RadioCol", referee) 508 lib_wid.startGame("RadioCol", referee)
509 509
510 def _radioColGenericCb(self, event_name, room_jid_s, args): 510 def _radioColGenericCb(self, event_name, room_jid_s, args):
511 for lib_wid in self.libervia_widgets: 511 for lib_wid in self.libervia_widgets:
512 if isinstance(lib_wid,panels.ChatPanel) and lib_wid.type == 'group' and lib_wid.target.bare == room_jid_s: 512 if isinstance(lib_wid, panels.ChatPanel) and lib_wid.type == 'group' and lib_wid.target.bare == room_jid_s:
513 getattr(lib_wid.getGame("RadioCol"), event_name)(*args) 513 getattr(lib_wid.getGame("RadioCol"), event_name)(*args)
514 514
515 515
516 def _getPresenceStatusCb(self, presence_data): 516 def _getPresenceStatusCb(self, presence_data):
517 for entity in presence_data: 517 for entity in presence_data:
518 for resource in presence_data[entity]: 518 for resource in presence_data[entity]:
538 538
539 elif sub_type == 'subscribe': 539 elif sub_type == 'subscribe':
540 #The user want to subscribe to our presence 540 #The user want to subscribe to our presence
541 _dialog = None 541 _dialog = None
542 msg = HTML('The contact <b>%s</b> want to add you in his/her contact list, do you accept ?' % html_sanitize(entity)) 542 msg = HTML('The contact <b>%s</b> want to add you in his/her contact list, do you accept ?' % html_sanitize(entity))
543 543
544 def ok_cb(ignore): 544 def ok_cb(ignore):
545 self.bridge.call('subscription', None, "subscribed", entity, '', _dialog.getSelectedGroups()) 545 self.bridge.call('subscription', None, "subscribed", entity, '', _dialog.getSelectedGroups())
546 def cancel_cb(ignore): 546 def cancel_cb(ignore):
547 self.bridge.call('subscription', None, "unsubscribed", entity, '', '') 547 self.bridge.call('subscription', None, "unsubscribed", entity, '', '')
548 548
549 _dialog = dialog.GroupSelector([msg], self.contact_panel.getGroups(), [], ok_cb, cancel_cb) 549 _dialog = dialog.GroupSelector([msg], self.contact_panel.getGroups(), [], ok_cb, cancel_cb)
550 _dialog.setHTML('<b>Add contact request</b>') 550 _dialog.setHTML('<b>Add contact request</b>')
551 _dialog.show() 551 _dialog.show()
552 552
553 def _contactDeletedCb(self, entity): 553 def _contactDeletedCb(self, entity):