comparison libervia_server/__init__.py @ 433:bbdbee25123a

import constants.Const as C (according to the coding rules)
author souliane <souliane@mailoo.org>
date Thu, 01 May 2014 11:29:09 +0200
parents b5b440e6ea16
children e63fc04efef7
comparison
equal deleted inserted replaced
432:8ecc5a7062e4 433:bbdbee25123a
42 import uuid 42 import uuid
43 from zope.interface import Interface, Attribute, implements 43 from zope.interface import Interface, Attribute, implements
44 from xml.dom import minidom 44 from xml.dom import minidom
45 from httplib import HTTPS_PORT 45 from httplib import HTTPS_PORT
46 46
47 from constants import Const 47 from constants import Const as C
48 from libervia_server.blog import MicroBlog 48 from libervia_server.blog import MicroBlog
49 from sat_frontends.bridge.DBus import DBusBridgeFrontend, BridgeExceptionNoService 49 from sat_frontends.bridge.DBus import DBusBridgeFrontend, BridgeExceptionNoService
50 from sat.core.i18n import _, D_ 50 from sat.core.i18n import _, D_
51 from sat.tools.xml_tools import paramsXML2XMLUI 51 from sat.tools.xml_tools import paramsXML2XMLUI
52 try: 52 try:
66 def __init__(self, session): 66 def __init__(self, session):
67 self.profile = None 67 self.profile = None
68 self.jid = None 68 self.jid = None
69 69
70 class LiberviaSession(server.Session): 70 class LiberviaSession(server.Session):
71 sessionTimeout = Const.TIMEOUT 71 sessionTimeout = C.TIMEOUT
72 72
73 def __init__(self, *args, **kwargs): 73 def __init__(self, *args, **kwargs):
74 self.__lock = False 74 self.__lock = False
75 server.Session.__init__(self, *args, **kwargs) 75 server.Session.__init__(self, *args, **kwargs)
76 76
147 if len(args) != 1: 147 if len(args) != 1:
148 Exception("Multiple return arguments not supported") 148 Exception("Multiple return arguments not supported")
149 d.callback(args[0]) 149 d.callback(args[0])
150 150
151 def _errback(result): 151 def _errback(result):
152 d.errback(Failure(jsonrpclib.Fault(Const.ERRNUM_BRIDGE_ERRBACK, unicode(result)))) 152 d.errback(Failure(jsonrpclib.Fault(C.ERRNUM_BRIDGE_ERRBACK, unicode(result))))
153 153
154 kwargs["callback"] = _callback 154 kwargs["callback"] = _callback
155 kwargs["errback"] = _errback 155 kwargs["errback"] = _errback
156 getattr(self.sat_host.bridge, method_name)(*args, **kwargs) 156 getattr(self.sat_host.bridge, method_name)(*args, **kwargs)
157 return d 157 return d
167 self.session = request.getSession() 167 self.session = request.getSession()
168 profile = ISATSession(self.session).profile 168 profile = ISATSession(self.session).profile
169 if not profile: 169 if not profile:
170 #user is not identified, we return a jsonrpc fault 170 #user is not identified, we return a jsonrpc fault
171 parsed = jsonrpclib.loads(request.content.read()) 171 parsed = jsonrpclib.loads(request.content.read())
172 fault = jsonrpclib.Fault(Const.ERRNUM_LIBERVIA, "Not allowed") #FIXME: define some standard error codes for libervia 172 fault = jsonrpclib.Fault(C.ERRNUM_LIBERVIA, "Not allowed") #FIXME: define some standard error codes for libervia
173 return jsonrpc.JSONRPC._cbRender(self, fault, request, parsed.get('id'), parsed.get('jsonrpc')) 173 return jsonrpc.JSONRPC._cbRender(self, fault, request, parsed.get('id'), parsed.get('jsonrpc'))
174 return jsonrpc.JSONRPC.render(self, request) 174 return jsonrpc.JSONRPC.render(self, request)
175 175
176 def jsonrpc_getProfileJid(self): 176 def jsonrpc_getProfileJid(self):
177 """Return the jid of the profile""" 177 """Return the jid of the profile"""
423 423
424 def jsonrpc_getTarotCardsPaths(self): 424 def jsonrpc_getTarotCardsPaths(self):
425 """Give the path of all the tarot cards""" 425 """Give the path of all the tarot cards"""
426 _join = os.path.join 426 _join = os.path.join
427 _media_dir = _join(self.sat_host.media_dir,'') 427 _media_dir = _join(self.sat_host.media_dir,'')
428 return map(lambda x: _join(Const.MEDIA_DIR, x[len(_media_dir):]), glob.glob(_join(_media_dir, Const.CARDS_DIR, '*_*.png'))); 428 return map(lambda x: _join(C.MEDIA_DIR, x[len(_media_dir):]), glob.glob(_join(_media_dir, C.CARDS_DIR, '*_*.png')));
429 429
430 def jsonrpc_tarotGameReady(self, player, referee): 430 def jsonrpc_tarotGameReady(self, player, referee):
431 """Tell to the server that we are ready to start the game""" 431 """Tell to the server that we are ready to start the game"""
432 profile = ISATSession(self.session).profile 432 profile = ISATSession(self.session).profile
433 self.sat_host.bridge.tarotGameReady(player, referee, profile) 433 self.sat_host.bridge.tarotGameReady(player, referee, profile)
472 return self.sat_host.bridge.getAccountDialogUI(profile) 472 return self.sat_host.bridge.getAccountDialogUI(profile)
473 473
474 def jsonrpc_getParamsUI(self): 474 def jsonrpc_getParamsUI(self):
475 """Return the parameters XML for profile""" 475 """Return the parameters XML for profile"""
476 profile = ISATSession(self.session).profile 476 profile = ISATSession(self.session).profile
477 d = self.asyncBridgeCall("getParams", Const.SECURITY_LIMIT, Const.APP_NAME, profile) 477 d = self.asyncBridgeCall("getParams", C.SECURITY_LIMIT, C.APP_NAME, profile)
478 478
479 def setAuthorizedParams(params_xml): 479 def setAuthorizedParams(params_xml):
480 if self.authorized_params is None: 480 if self.authorized_params is None:
481 self.authorized_params = {} 481 self.authorized_params = {}
482 for cat in minidom.parseString(params_xml.encode('utf-8')).getElementsByTagName("category"): 482 for cat in minidom.parseString(params_xml.encode('utf-8')).getElementsByTagName("category"):
495 return d 495 return d
496 496
497 def jsonrpc_asyncGetParamA(self, param, category, attribute="value"): 497 def jsonrpc_asyncGetParamA(self, param, category, attribute="value"):
498 """Return the parameter value for profile""" 498 """Return the parameter value for profile"""
499 profile = ISATSession(self.session).profile 499 profile = ISATSession(self.session).profile
500 d = self.asyncBridgeCall("asyncGetParamA", param, category, attribute, Const.SECURITY_LIMIT, profile_key=profile) 500 d = self.asyncBridgeCall("asyncGetParamA", param, category, attribute, C.SECURITY_LIMIT, profile_key=profile)
501 return d 501 return d
502 502
503 def jsonrpc_setParam(self, name, value, category): 503 def jsonrpc_setParam(self, name, value, category):
504 profile = ISATSession(self.session).profile 504 profile = ISATSession(self.session).profile
505 if category in self.authorized_params and name in self.authorized_params[category]: 505 if category in self.authorized_params and name in self.authorized_params[category]:
506 return self.sat_host.bridge.setParam(name, value, category, Const.SECURITY_LIMIT, profile) 506 return self.sat_host.bridge.setParam(name, value, category, C.SECURITY_LIMIT, profile)
507 else: 507 else:
508 warning("Trying to set parameter '%s' in category '%s' without authorization!!!" 508 warning("Trying to set parameter '%s' in category '%s' without authorization!!!"
509 % (name, category)) 509 % (name, category))
510 510
511 def jsonrpc_launchAction(self, callback_id, data): 511 def jsonrpc_launchAction(self, callback_id, data):
530 def jsonrpc_confirmationAnswer(self, confirmation_id, result, answer_data): 530 def jsonrpc_confirmationAnswer(self, confirmation_id, result, answer_data):
531 """Send the user's answer to any previous 'askConfirmation' signal""" 531 """Send the user's answer to any previous 'askConfirmation' signal"""
532 profile = ISATSession(self.session).profile 532 profile = ISATSession(self.session).profile
533 self.sat_host.bridge.confirmationAnswer(confirmation_id, result, answer_data, profile) 533 self.sat_host.bridge.confirmationAnswer(confirmation_id, result, answer_data, profile)
534 534
535 def jsonrpc_syntaxConvert(self, text, syntax_from=Const.SYNTAX_XHTML, syntax_to=Const.SYNTAX_CURRENT): 535 def jsonrpc_syntaxConvert(self, text, syntax_from=C.SYNTAX_XHTML, syntax_to=C.SYNTAX_CURRENT):
536 """ Convert a text between two syntaxes 536 """ Convert a text between two syntaxes
537 @param text: text to convert 537 @param text: text to convert
538 @param syntax_from: source syntax (e.g. "markdown") 538 @param syntax_from: source syntax (e.g. "markdown")
539 @param syntax_to: dest syntax (e.g.: "XHTML") 539 @param syntax_to: dest syntax (e.g.: "XHTML")
540 @param safe: clean resulting XHTML to avoid malicious code if True (forced here) 540 @param safe: clean resulting XHTML to avoid malicious code if True (forced here)
574 if method not in ['isRegistered', 'registerParams', 'getMenus']: 574 if method not in ['isRegistered', 'registerParams', 'getMenus']:
575 #if we don't call these methods, we need to be identified 575 #if we don't call these methods, we need to be identified
576 profile = ISATSession(_session).profile 576 profile = ISATSession(_session).profile
577 if not profile: 577 if not profile:
578 #user is not identified, we return a jsonrpc fault 578 #user is not identified, we return a jsonrpc fault
579 fault = jsonrpclib.Fault(Const.ERRNUM_LIBERVIA, "Not allowed") #FIXME: define some standard error codes for libervia 579 fault = jsonrpclib.Fault(C.ERRNUM_LIBERVIA, "Not allowed") #FIXME: define some standard error codes for libervia
580 return jsonrpc.JSONRPC._cbRender(self, fault, request, parsed.get('id'), parsed.get('jsonrpc')) 580 return jsonrpc.JSONRPC._cbRender(self, fault, request, parsed.get('id'), parsed.get('jsonrpc'))
581 self.request = request 581 self.request = request
582 return jsonrpc.JSONRPC.render(self, request) 582 return jsonrpc.JSONRPC.render(self, request)
583 583
584 def login(self, request): 584 def login(self, request):
768 <param name="%(param_name)s" label="%(param_label)s" value="false" type="bool" security="0"/> 768 <param name="%(param_name)s" label="%(param_label)s" value="false" type="bool" security="0"/>
769 </category> 769 </category>
770 </individual> 770 </individual>
771 </params> 771 </params>
772 """ % { 772 """ % {
773 'category_name': Const.ENABLE_UNIBOX_KEY, 773 'category_name': C.ENABLE_UNIBOX_KEY,
774 'category_label': _(Const.ENABLE_UNIBOX_KEY), 774 'category_label': _(C.ENABLE_UNIBOX_KEY),
775 'param_name': Const.ENABLE_UNIBOX_PARAM, 775 'param_name': C.ENABLE_UNIBOX_PARAM,
776 'param_label': _(Const.ENABLE_UNIBOX_PARAM) 776 'param_label': _(C.ENABLE_UNIBOX_PARAM)
777 } 777 }
778 778
779 self.sat_host.bridge.paramsRegisterApp(params, Const.SECURITY_LIMIT, Const.APP_NAME) 779 self.sat_host.bridge.paramsRegisterApp(params, C.SECURITY_LIMIT, C.APP_NAME)
780 780
781 def jsonrpc_getMenus(self): 781 def jsonrpc_getMenus(self):
782 """Return the parameters XML for profile""" 782 """Return the parameters XML for profile"""
783 # XXX: we put this method in Register because we get menus before being logged 783 # XXX: we put this method in Register because we get menus before being logged
784 return self.sat_host.bridge.getMenus('', Const.SECURITY_LIMIT) 784 return self.sat_host.bridge.getMenus('', C.SECURITY_LIMIT)
785 785
786 def __getSecurityWarning(self): 786 def __getSecurityWarning(self):
787 """@return: a security warning message, or None if the connection is secure""" 787 """@return: a security warning message, or None if the connection is secure"""
788 if self.request.URLPath().scheme == 'https' or not self.sat_host.security_warning: 788 if self.request.URLPath().scheme == 'https' or not self.sat_host.security_warning:
789 return None 789 return None
886 _session = request.getSession() 886 _session = request.getSession()
887 parsed = jsonrpclib.loads(request.content.read()) 887 parsed = jsonrpclib.loads(request.content.read())
888 profile = ISATSession(_session).profile 888 profile = ISATSession(_session).profile
889 if not profile: 889 if not profile:
890 #user is not identified, we return a jsonrpc fault 890 #user is not identified, we return a jsonrpc fault
891 fault = jsonrpclib.Fault(Const.ERRNUM_LIBERVIA, "Not allowed") #FIXME: define some standard error codes for libervia 891 fault = jsonrpclib.Fault(C.ERRNUM_LIBERVIA, "Not allowed") #FIXME: define some standard error codes for libervia
892 return jsonrpc.JSONRPC._cbRender(self, fault, request, parsed.get('id'), parsed.get('jsonrpc')) 892 return jsonrpc.JSONRPC._cbRender(self, fault, request, parsed.get('id'), parsed.get('jsonrpc'))
893 self.request = request 893 self.request = request
894 return jsonrpc.JSONRPC.render(self, request) 894 return jsonrpc.JSONRPC.render(self, request)
895 895
896 class UploadManager(Resource): 896 class UploadManager(Resource):
1018 self.port_https_ext = self.port_https 1018 self.port_https_ext = self.port_https
1019 self.ssl_certificate = kwargs['ssl_certificate'] 1019 self.ssl_certificate = kwargs['ssl_certificate']
1020 self.redirect_to_https = kwargs['redirect_to_https'] 1020 self.redirect_to_https = kwargs['redirect_to_https']
1021 self.security_warning = kwargs['security_warning'] 1021 self.security_warning = kwargs['security_warning']
1022 self._cleanup = [] 1022 self._cleanup = []
1023 root = ProtectedFile(Const.LIBERVIA_DIR) 1023 root = ProtectedFile(C.LIBERVIA_DIR)
1024 self.signal_handler = SignalHandler(self) 1024 self.signal_handler = SignalHandler(self)
1025 _register = Register(self) 1025 _register = Register(self)
1026 _upload_radiocol = UploadManagerRadioCol(self) 1026 _upload_radiocol = UploadManagerRadioCol(self)
1027 _upload_avatar = UploadManagerAvatar(self) 1027 _upload_avatar = UploadManagerAvatar(self)
1028 self.signal_handler.plugRegister(_register) 1028 self.signal_handler.plugRegister(_register)
1056 root.putChild('register_api', _register) 1056 root.putChild('register_api', _register)
1057 root.putChild('upload_radiocol', _upload_radiocol) 1057 root.putChild('upload_radiocol', _upload_radiocol)
1058 root.putChild('upload_avatar', _upload_avatar) 1058 root.putChild('upload_avatar', _upload_avatar)
1059 root.putChild('blog', MicroBlog(self)) 1059 root.putChild('blog', MicroBlog(self))
1060 root.putChild('css', ProtectedFile("server_css/")) 1060 root.putChild('css', ProtectedFile("server_css/"))
1061 root.putChild(os.path.dirname(Const.MEDIA_DIR), ProtectedFile(self.media_dir)) 1061 root.putChild(os.path.dirname(C.MEDIA_DIR), ProtectedFile(self.media_dir))
1062 root.putChild(os.path.dirname(Const.AVATARS_DIR), ProtectedFile(os.path.join(self.local_dir, Const.AVATARS_DIR))) 1062 root.putChild(os.path.dirname(C.AVATARS_DIR), ProtectedFile(os.path.join(self.local_dir, C.AVATARS_DIR)))
1063 root.putChild('radiocol', ProtectedFile(_upload_radiocol.getTmpDir(), defaultType="audio/ogg")) #We cheat for PoC because we know we are on the same host, so we use directly upload dir 1063 root.putChild('radiocol', ProtectedFile(_upload_radiocol.getTmpDir(), defaultType="audio/ogg")) #We cheat for PoC because we know we are on the same host, so we use directly upload dir
1064 self.site = server.Site(root) 1064 self.site = server.Site(root)
1065 self.site.sessionFactory = LiberviaSession 1065 self.site.sessionFactory = LiberviaSession
1066 1066
1067 def addCleanup(self, callback, *args, **kwargs): 1067 def addCleanup(self, callback, *args, **kwargs):
1118 url = "https://" + netloc + request.uri 1118 url = "https://" + netloc + request.uri
1119 return redirectTo(url, request) 1119 return redirectTo(url, request)
1120 1120
1121 1121
1122 registerAdapter(SATSession, server.Session, ISATSession) 1122 registerAdapter(SATSession, server.Session, ISATSession)
1123 application = service.Application(Const.APP_NAME) 1123 application = service.Application(C.APP_NAME)
1124 service = Libervia() 1124 service = Libervia()
1125 service.setServiceParent(application) 1125 service.setServiceParent(application)