changeset 470:34ce41e014c4

server side: options managing improvments: - cleaned a bit the code / comments - i18n - added Libervia.OPT_PARAMETERS_CFG and moved Libervia.OPT_PARAMETERS to Libervia.OPT_PARAMETERS_BOTH, to allow options to be only in sat.conf - use of new constant ASCII_APP_NAME for tap name
author Goffi <goffi@goffi.org>
date Tue, 10 Jun 2014 15:38:47 +0200
parents 305044acb6f0
children de039f008333
files src/server/constants.py src/server/server.py src/twisted/plugins/libervia_server.py
diffstat 3 files changed, 49 insertions(+), 40 deletions(-) [+]
line wrap: on
line diff
--- a/src/server/constants.py	Mon Jun 09 20:37:42 2014 +0200
+++ b/src/server/constants.py	Tue Jun 10 15:38:47 2014 +0200
@@ -23,6 +23,7 @@
 class Const(constants.Const):
 
     APP_NAME = 'Libervia'
+    ASCII_APP_NAME = "libervia"
     SERVICE_PROFILE = 'libervia'  # the SàT profile that is used for exporting the service
 
     TIMEOUT = 300  # Session's time out, after that the user will be disconnected
--- a/src/server/server.py	Mon Jun 09 20:37:42 2014 +0200
+++ b/src/server/server.py	Tue Jun 10 15:38:47 2014 +0200
@@ -111,11 +111,13 @@
 
     def waitForId(self, callback, action_id, profile, *args, **kwargs):
         """Wait for an action result
+
         @param callback: method to call when action gave a result back
         @param action_id: action_id to wait for
         @param profile: %(doc_profile)s
         @param *args: additional argument to pass to callback
-        @param **kwargs: idem"""
+        @param **kwargs: idem
+        """
         action_tuple = (action_id, profile)
         self.waiting_ids[action_tuple] = (callback, args, kwargs)
         reactor.callLater(self.ID_LIFETIME, self.purgeID, action_tuple)
@@ -1003,42 +1005,37 @@
 class Libervia(service.Service):
 
     DATA_DIR_DEFAULT = ''
-    OPT_PARAMETERS = [['connection_type', 't', 'https', "'http', 'https' or 'both' (to launch both servers).", coerceConnectionType],
-                      ['port', 'p', 8080, 'The port number to listen HTTP on.', int],
-                      ['port_https', 's', 8443, 'The port number to listen HTTPS on.', int],
-                      ['port_https_ext', 'e', 0, 'The external port number used for HTTPS (0 means port_https value).', int],
-                      ['ssl_certificate', 'c', 'libervia.pem', 'PEM certificate with both private and public parts.', str],
-                      ['redirect_to_https', 'r', 1, 'Automatically redirect from HTTP to HTTPS.', int],
-                      ['security_warning', 'w', 1, 'Warn user that he is about to connect on HTTP.', int],
-                      # FIXME: twistd bugs when printing 'à' on "Unknown command" error (works on normal command listing)
-                      ['passphrase', 'k', '', u"Passphrase for the SaT profile named '%s'" % C.SERVICE_PROFILE, str],
-                      ['data_dir', 'd', DATA_DIR_DEFAULT, u'Data directory for Libervia', coerceDataDir],
-                      ]
+    OPT_PARAMETERS_BOTH = [['connection_type', 't', 'https', _(u"'http', 'https' or 'both' (to launch both servers)."), coerceConnectionType],
+                           ['port', 'p', 8080, _(u'The port number to listen HTTP on.'), int],
+                           ['port_https', 's', 8443, _(u'The port number to listen HTTPS on.'), int],
+                           ['port_https_ext', 'e', 0, _(u'The external port number used for HTTPS (0 means port_https value).'), int],
+                           ['ssl_certificate', 'c', 'libervia.pem', _(u'PEM certificate with both private and public parts.'), str],
+                           ['redirect_to_https', 'r', 1, _(u'Automatically redirect from HTTP to HTTPS.'), int],
+                           ['security_warning', 'w', 1, _(u'Warn user that he is about to connect on HTTP.'), int],
+                           ['passphrase', 'k', '', _(u"Passphrase for the SàT profile named '%s'") % C.SERVICE_PROFILE, str],
+                           ['data_dir', 'd', DATA_DIR_DEFAULT, _(u'Data directory for Libervia'), coerceDataDir],
+                          ] # options which are in sat.conf and on command line, see https://twistedmatrix.com/documents/current/api/twisted.python.usage.Options.html
+    OPT_PARAMETERS_CFG = [] # Options which are in sat.conf only
 
     def __init__(self, *args, **kwargs):
-        if not kwargs:
-            # During the loading of the twisted plugins, we just need the default values.
-            # This part is not executed when the plugin is actually started.
-            for name, value in [(option[0], option[2]) for option in self.OPT_PARAMETERS]:
-                kwargs[name] = value
         self.initialised = defer.Deferred()
-        self.connection_type = kwargs['connection_type']
-        self.port = kwargs['port']
-        self.port_https = kwargs['port_https']
-        self.port_https_ext = kwargs['port_https_ext']
+
+        # options managing
+        for opt in self.OPT_PARAMETERS_BOTH + self.OPT_PARAMETERS_CFG:
+            opt_name = opt[0]
+            setattr(self, opt_name, kwargs.get(opt_name, opt[2]))
         if not self.port_https_ext:
             self.port_https_ext = self.port_https
-        self.ssl_certificate = kwargs['ssl_certificate']
-        self.redirect_to_https = kwargs['redirect_to_https']
-        self.security_warning = kwargs['security_warning']
-        self.passphrase = kwargs['passphrase']
-        self.data_dir = kwargs['data_dir']
         if self.data_dir == Libervia.DATA_DIR_DEFAULT:
             coerceDataDir(self.data_dir)  # this is not done when using the default value
+
         self.html_dir = os.path.join(self.data_dir, C.HTML_DIR)
         self.server_css_dir = os.path.join(self.data_dir, C.SERVER_CSS_DIR)
+
         self._cleanup = []
+
         root = ProtectedFile(self.html_dir)
+
         self.signal_handler = SignalHandler(self)
         _register = Register(self)
         _upload_radiocol = UploadManagerRadioCol(self)
@@ -1047,6 +1044,7 @@
         self.sessions = {}  # key = session value = user
         self.prof_connected = set()  # Profiles connected
         self.action_handler = SATActionIDHandler()
+
         ## bridge ##
         try:
             self.bridge = DBusBridgeFrontend()
--- a/src/twisted/plugins/libervia_server.py	Mon Jun 09 20:37:42 2014 +0200
+++ b/src/twisted/plugins/libervia_server.py	Tue Jun 10 15:38:47 2014 +0200
@@ -32,6 +32,10 @@
 from libervia.server.constants import Const as C
 from sat.core import log_config
 log_config.satConfigure(C.LOG_BACKEND_TWISTED, C)
+
+
+
+from sat.core.i18n import _
 from sat.tools.config import getConfig
 
 from zope.interface import implements
@@ -43,10 +47,12 @@
 from ConfigParser import SafeConfigParser, NoSectionError, NoOptionError
 try:
     from libervia.server.server import Libervia
-    opt_params = Libervia.OPT_PARAMETERS
+    opt_params = Libervia.OPT_PARAMETERS_BOTH
+    cfg_params = Libervia.OPT_PARAMETERS_CFG
 except (ImportError, SystemExit):
     # avoid raising an error when you call twisted and sat is not launched
     opt_params = []
+    cfg_params = []
 
 
 class Options(usage.Options):
@@ -55,22 +61,27 @@
     optParameters = opt_params
 
     def __init__(self):
-        """You want to read SàT configuration file now in order to overwrite the hard-coded default values.
-        This is because the priority for the usage of the values is (from lowest to highest):
-        - hard-coded default values
-        - values from SàT configuration files
-        - values passed on the command line
-        If you do it later: after the command line options have been parsed, there's no good way to know
-        if the  options values are the hard-coded ones or if they have been passed on the command line.
+        """Read SàT configuration file in order to overwrite the hard-coded default values.
+
+        Priority for the usage of the values is (from lowest to highest):
+            - hard-coded default values
+            - values from SàT configuration files
+            - values passed on the command line
         """
+        # If we do it the reading later: after the command line options have been parsed, there's no good way to know
+        # if the  options values are the hard-coded ones or if they have been passed on the command line.
+
+        # FIXME: must be refactored + code can be factorised with backend
         config = SafeConfigParser()
         config.read(C.CONFIG_FILES)
-        for index, param in list(enumerate(self.optParameters)):
-            # index is only used to not modify the loop variable "param"
+        for param in self.optParameters + cfg_params:
             name = param[0]
             try:
                 value = getConfig(config, 'libervia', name)
-                self.optParameters[index][2] = param[4](value)
+                try:
+                    param[2] = param[4](value)
+                except IndexError: # the coerce method is optional
+                    param[2] = value
             except (NoSectionError, NoOptionError):
                 pass
         usage.Options.__init__(self)
@@ -79,9 +90,8 @@
 class LiberviaMaker(object):
     implements(IServiceMaker, IPlugin)
 
-    tapname = 'libervia'
-    # FIXME: twistd bugs when printing 'à' on "Unknown command" error (works on normal command listing)
-    description = u'The web frontend of Salut a Toi'
+    tapname = C.ASCII_APP_NAME
+    description = _(u'The web frontend of Salut à Toi')
     options = Options
 
     def makeService(self, options):