comparison libervia.py @ 439:d52f529a6d42

browser side: use of new log system (first draft): - configuration is hardcoded in libervia.py, it will change in the (hopefuly) near future - log level is DEBUG for the moment, will be changed to INFO when configuration will not be hardcoded anymore - the basic log backend is used, in the future, a console.debug/info/etc should be used instead. A log widget which HTML colors is also an option
author Goffi <goffi@goffi.org>
date Thu, 08 May 2014 17:21:34 +0200
parents bbdbee25123a
children 88461e9c3e47
comparison
equal deleted inserted replaced
438:582c435dab6b 439:d52f529a6d42
16 16
17 # You should have received a copy of the GNU Affero General Public License 17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>. 18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
19 19
20 import pyjd # this is dummy in pyjs 20 import pyjd # this is dummy in pyjs
21
22 from constants import Const as C
23 ### logging configuration ###
24 from sat.core.log import configure, getLogger
25 configure(C.LOG_BACKEND_BASIC,
26 level = C.LOG_LVL_DEBUG,
27 fmt = '[%(name)s / %(levelname)s] %(message)s',
28 output = None,
29 logger = None,
30 colors = False,
31 force_colors = False)
32 log = getLogger(__name__)
33 ###
34
21 from pyjamas.ui.RootPanel import RootPanel 35 from pyjamas.ui.RootPanel import RootPanel
22 from pyjamas.ui.HTML import HTML 36 from pyjamas.ui.HTML import HTML
23 from pyjamas.ui.KeyboardListener import KEY_ESCAPE 37 from pyjamas.ui.KeyboardListener import KEY_ESCAPE
24 from pyjamas.Timer import Timer 38 from pyjamas.Timer import Timer
25 from pyjamas import Window, DOM 39 from pyjamas import Window, DOM
35 from browser_side.html_tools import html_sanitize 49 from browser_side.html_tools import html_sanitize
36 from browser_side.notification import Notification 50 from browser_side.notification import Notification
37 51
38 from sat_frontends.tools.misc import InputHistory 52 from sat_frontends.tools.misc import InputHistory
39 from sat_frontends.tools.strings import getURLParams 53 from sat_frontends.tools.strings import getURLParams
40 from constants import Const as C
41 from sat.core.i18n import _ 54 from sat.core.i18n import _
42 55
43 56
44 MAX_MBLOG_CACHE = 500 # Max microblog entries kept in memories 57 MAX_MBLOG_CACHE = 500 # Max microblog entries kept in memories
45 58
61 def call(self, method, cb, *args): 74 def call(self, method, cb, *args):
62 _id = self.callMethod(method, args) 75 _id = self.callMethod(method, args)
63 if cb: 76 if cb:
64 if isinstance(cb, tuple): 77 if isinstance(cb, tuple):
65 if len(cb) != 2: 78 if len(cb) != 2:
66 print ("ERROR: tuple syntax for bridge.call is (callback, errback), aborting") 79 log.error("tuple syntax for bridge.call is (callback, errback), aborting")
67 return 80 return
68 if cb[0] is not None: 81 if cb[0] is not None:
69 self.cb[_id] = cb[0] 82 self.cb[_id] = cb[0]
70 self.eb[_id] = cb[1] 83 self.eb[_id] = cb[1]
71 else: 84 else:
96 _eb((code, errobj)) 109 _eb((code, errobj))
97 del self.cb[request_info.id] 110 del self.cb[request_info.id]
98 del self.eb[request_info.id] 111 del self.eb[request_info.id]
99 else: 112 else:
100 if code != 0: 113 if code != 0:
101 print ("Internal server error") 114 log.error("Internal server error")
102 """for o in code, error, request_info: 115 """for o in code, error, request_info:
103 dump(o)""" 116 dump(o)"""
104 else: 117 else:
105 if isinstance(errobj['message'], dict): 118 if isinstance(errobj['message'], dict):
106 print("Error %s: %s" % (errobj['message']['faultCode'], errobj['message']['faultString'])) 119 log.error("Error %s: %s" % (errobj['message']['faultCode'], errobj['message']['faultString']))
107 else: 120 else:
108 print("Error: %s" % errobj['message']) 121 log.error("%s" % errobj['message'])
109 122
110 123
111 class RegisterCall(LiberviaJsonProxy): 124 class RegisterCall(LiberviaJsonProxy):
112 def __init__(self): 125 def __init__(self):
113 LiberviaJsonProxy.__init__(self, "/register_api", 126 LiberviaJsonProxy.__init__(self, "/register_api",
157 self.retry_delay *= 2 170 self.retry_delay *= 2
158 171
159 172
160 class SatWebFrontend(InputHistory): 173 class SatWebFrontend(InputHistory):
161 def onModuleLoad(self): 174 def onModuleLoad(self):
162 print "============ onModuleLoad ==============" 175 log.info("============ onModuleLoad ==============")
163 panels.ChatPanel.registerClass() 176 panels.ChatPanel.registerClass()
164 panels.MicroblogPanel.registerClass() 177 panels.MicroblogPanel.registerClass()
165 self.whoami = None 178 self.whoami = None
166 self._selected_listeners = set() 179 self._selected_listeners = set()
167 self.bridge = BridgeCall() 180 self.bridge = BridgeCall()
199 self._selected_listeners.add(callback) 212 self._selected_listeners.add(callback)
200 213
201 def getSelected(self): 214 def getSelected(self):
202 wid = self.tab_panel.getCurrentPanel() 215 wid = self.tab_panel.getCurrentPanel()
203 if not isinstance(wid, WidgetsPanel): 216 if not isinstance(wid, WidgetsPanel):
204 print "ERROR: Tab widget is not a WidgetsPanel, can't get selected widget" 217 log.error("Tab widget is not a WidgetsPanel, can't get selected widget")
205 return None 218 return None
206 return wid.selected 219 return wid.selected
207 220
208 def setSelected(self, widget): 221 def setSelected(self, widget):
209 """Define the selected widget""" 222 """Define the selected widget"""
261 self.bridge.call('getEntityData', (dataReceived, avatarError), jid_str, ['avatar']) 274 self.bridge.call('getEntityData', (dataReceived, avatarError), jid_str, ['avatar'])
262 self.avatars_cache[jid_str] = "/media/misc/empty_avatar" 275 self.avatars_cache[jid_str] = "/media/misc/empty_avatar"
263 return self.avatars_cache[jid_str] 276 return self.avatars_cache[jid_str]
264 277
265 def registerWidget(self, wid): 278 def registerWidget(self, wid):
266 print "Registering", wid.getDebugName() 279 log.debug("Registering %s" % wid.getDebugName())
267 self.libervia_widgets.add(wid) 280 self.libervia_widgets.add(wid)
268 281
269 def unregisterWidget(self, wid): 282 def unregisterWidget(self, wid):
270 try: 283 try:
271 self.libervia_widgets.remove(wid) 284 self.libervia_widgets.remove(wid)
272 except KeyError: 285 except KeyError:
273 print ('WARNING: trying to remove a non registered Widget:', wid.getDebugName()) 286 log.warning('trying to remove a non registered Widget: %s' % wid.getDebugName())
274 287
275 def refresh(self): 288 def refresh(self):
276 """Refresh the general display.""" 289 """Refresh the general display."""
277 self.panel.refresh() 290 self.panel.refresh()
278 if self.params_ui['unibox']['value']: 291 if self.params_ui['unibox']['value']:
344 #We want to know our own jid 357 #We want to know our own jid
345 self.bridge.call('getProfileJid', self._getProfileJidCB) 358 self.bridge.call('getProfileJid', self._getProfileJidCB)
346 359
347 def domain_cb(value): 360 def domain_cb(value):
348 self._defaultDomain = value 361 self._defaultDomain = value
349 print("new account domain: %s" % value) 362 log.info("new account domain: %s" % value)
350 363
351 def domain_eb(value): 364 def domain_eb(value):
352 self._defaultDomain = "libervia.org" 365 self._defaultDomain = "libervia.org"
353 366
354 self.bridge.call("getNewAccountDomain", (domain_cb, domain_eb)) 367 self.bridge.call("getNewAccountDomain", (domain_cb, domain_eb))
417 jid, attributes, groups = contact 430 jid, attributes, groups = contact
418 self._newContactCb(jid, attributes, groups) 431 self._newContactCb(jid, attributes, groups)
419 432
420 def _getSignalsCB(self, signal_data): 433 def _getSignalsCB(self, signal_data):
421 self.bridge_signals.call('getSignals', self._getSignalsCB) 434 self.bridge_signals.call('getSignals', self._getSignalsCB)
422 print('Got signal ==> name: %s, params: %s' % (signal_data[0], signal_data[1])) 435 log.debug("Got signal ==> name: %s, params: %s" % (signal_data[0], signal_data[1]))
423 name, args = signal_data 436 name, args = signal_data
424 if name == 'personalEvent': 437 if name == 'personalEvent':
425 self._personalEventCb(*args) 438 self._personalEventCb(*args)
426 elif name == 'newMessage': 439 elif name == 'newMessage':
427 self._newMessageCb(*args) 440 self._newMessageCb(*args)
488 def _ownBlogsFills(self, mblogs): 501 def _ownBlogsFills(self, mblogs):
489 #put our own microblogs in cache, then fill all panels with them 502 #put our own microblogs in cache, then fill all panels with them
490 for publisher in mblogs: 503 for publisher in mblogs:
491 for mblog in mblogs[publisher]: 504 for mblog in mblogs[publisher]:
492 if not mblog.has_key('content'): 505 if not mblog.has_key('content'):
493 print ("WARNING: No content found in microblog [%s]", mblog) 506 log.warning("No content found in microblog [%s]" % mblog)
494 continue 507 continue
495 if mblog.has_key('groups'): 508 if mblog.has_key('groups'):
496 _groups = set(mblog['groups'].split() if mblog['groups'] else []) 509 _groups = set(mblog['groups'].split() if mblog['groups'] else [])
497 else: 510 else:
498 _groups = None 511 _groups = None
535 self.init_cache.append((sender, event_type, data)) 548 self.init_cache.append((sender, event_type, data))
536 return 549 return
537 sender = JID(sender).bare 550 sender = JID(sender).bare
538 if event_type == "MICROBLOG": 551 if event_type == "MICROBLOG":
539 if not 'content' in data: 552 if not 'content' in data:
540 print ("WARNING: No content found in microblog data") 553 log.warning("No content found in microblog data")
541 return 554 return
542 if 'groups' in data: 555 if 'groups' in data:
543 _groups = set(data['groups'].split() if data['groups'] else []) 556 _groups = set(data['groups'].split() if data['groups'] else [])
544 else: 557 else:
545 _groups = None 558 _groups = None
565 del self.mblog_cache[0:len(self.mblog_cache - MAX_MBLOG_CACHE)] 578 del self.mblog_cache[0:len(self.mblog_cache - MAX_MBLOG_CACHE)]
566 elif event_type == 'MICROBLOG_DELETE': 579 elif event_type == 'MICROBLOG_DELETE':
567 for lib_wid in self.libervia_widgets: 580 for lib_wid in self.libervia_widgets:
568 if isinstance(lib_wid, panels.MicroblogPanel): 581 if isinstance(lib_wid, panels.MicroblogPanel):
569 lib_wid.removeEntry(data['type'], data['id']) 582 lib_wid.removeEntry(data['type'], data['id'])
570 print self.whoami.bare, sender, data['type'] 583 log.debug("%s %s %s" % (self.whoami.bare, sender, data['type']))
584
571 if sender == self.whoami.bare and data['type'] == 'main_item': 585 if sender == self.whoami.bare and data['type'] == 'main_item':
572 for index in xrange(0, len(self.mblog_cache)): 586 for index in xrange(0, len(self.mblog_cache)):
573 entry = self.mblog_cache[index] 587 entry = self.mblog_cache[index]
574 if entry[1].id == data['id']: 588 if entry[1].id == data['id']:
575 self.mblog_cache.remove(entry) 589 self.mblog_cache.remove(entry)
593 for cache_entry in self.mblog_cache: 607 for cache_entry in self.mblog_cache:
594 _groups, mblog_entry = cache_entry 608 _groups, mblog_entry = cache_entry
595 self.addBlogEntry(mblog_panel, self.whoami.bare, *cache_entry) 609 self.addBlogEntry(mblog_panel, self.whoami.bare, *cache_entry)
596 610
597 def getEntityMBlog(self, entity): 611 def getEntityMBlog(self, entity):
598 print "geting mblog for entity [%s]" % (entity,) 612 log.info("geting mblog for entity [%s]" % (entity,))
599 for lib_wid in self.libervia_widgets: 613 for lib_wid in self.libervia_widgets:
600 if isinstance(lib_wid, panels.MicroblogPanel): 614 if isinstance(lib_wid, panels.MicroblogPanel):
601 if lib_wid.isJidAccepted(entity): 615 if lib_wid.isJidAccepted(entity):
602 self.bridge.call('getMassiveLastMblogs', lib_wid.massiveInsert, 'JID', [entity], 10) 616 self.bridge.call('getMassiveLastMblogs', lib_wid.massiveInsert, 'JID', [entity], 10)
603 617
615 # do not return a widget that is not in the currently selected tab 629 # do not return a widget that is not in the currently selected tab
616 continue 630 continue
617 if isinstance(lib_wid, class_): 631 if isinstance(lib_wid, class_):
618 try: 632 try:
619 if lib_wid.matchEntity(entity): 633 if lib_wid.matchEntity(entity):
620 print "existing widget found: %s" % lib_wid.getDebugName() 634 log.debug("existing widget found: %s" % lib_wid.getDebugName())
621 return lib_wid 635 return lib_wid
622 except AttributeError as e: 636 except AttributeError as e:
623 e.stack_list() 637 e.stack_list()
624 return None 638 return None
625 return None 639 return None
842 break 856 break
843 857
844 def sendError(self, errorData): 858 def sendError(self, errorData):
845 dialog.InfoDialog("Error while sending message", 859 dialog.InfoDialog("Error while sending message",
846 "Your message can't be sent", Width="400px").center() 860 "Your message can't be sent", Width="400px").center()
847 print "sendError: %s" % str(errorData) 861 log.error("sendError: %s" % str(errorData))
848 862
849 def send(self, targets, text, extra={}): 863 def send(self, targets, text, extra={}):
850 """Send a message to any target type. 864 """Send a message to any target type.
851 @param targets: list of tuples (type, entities, addr) with: 865 @param targets: list of tuples (type, entities, addr) with:
852 - type in ("PUBLIC", "GROUP", "COMMENT", "STATUS" , "groupchat" , "chat") 866 - type in ("PUBLIC", "GROUP", "COMMENT", "STATUS" , "groupchat" , "chat")
866 elif type_ == "STATUS": 880 elif type_ == "STATUS":
867 self.bridge.call('setStatus', None, self.status_panel.presence, text) 881 self.bridge.call('setStatus', None, self.status_panel.presence, text)
868 elif type_ in ("groupchat", "chat"): 882 elif type_ in ("groupchat", "chat"):
869 addresses.append((addr, entities)) 883 addresses.append((addr, entities))
870 else: 884 else:
871 print "ERROR: Unknown target type" 885 log.error("Unknown target type")
872 if addresses: 886 if addresses:
873 if len(addresses) == 1 and addresses[0][0] == 'to': 887 if len(addresses) == 1 and addresses[0][0] == 'to':
874 self.bridge.call('sendMessage', (None, self.sendError), addresses[0][1], text, '', type_, extra) 888 self.bridge.call('sendMessage', (None, self.sendError), addresses[0][1], text, '', type_, extra)
875 else: 889 else:
876 extra.update({'address': '\n'.join([('%s:%s' % entry) for entry in addresses])}) 890 extra.update({'address': '\n'.join([('%s:%s' % entry) for entry in addresses])})