diff twisted/plugins/libervia_server.py @ 1216:b2d067339de3

python 3 port: /!\ Python 3.6+ is now needed to use libervia /!\ instability may occur and features may not be working anymore, this will improve with time /!\ TxJSONRPC dependency has been removed The same procedure as in backend has been applied (check backend commit ab2696e34d29 logs for details). Removed now deprecated code (Pyjamas compiled browser part, legacy blog, JSON RPC related code). Adapted code to work without `html` and `themes` dirs.
author Goffi <goffi@goffi.org>
date Tue, 13 Aug 2019 19:12:31 +0200
parents b300eaec53b6
children 331ada56cdca
line wrap: on
line diff
--- a/twisted/plugins/libervia_server.py	Tue Aug 13 09:39:33 2019 +0200
+++ b/twisted/plugins/libervia_server.py	Tue Aug 13 19:12:31 2019 +0200
@@ -41,12 +41,12 @@
 from sat.core.i18n import _
 from sat.tools import config
 
-from zope.interface import implements
+from zope.interface import implementer
 
 from twisted.python import usage
 from twisted.plugin import IPlugin
 from twisted.application.service import IServiceMaker
-import ConfigParser
+import configparser
 
 
 CONFIG_SECTION = C.APP_NAME.lower()
@@ -54,7 +54,7 @@
     import sys
 
     sys.stderr.write(
-        u"""sat module version ({sat_version}) and {current_app} version ({current_version}) mismatch
+        """sat module version ({sat_version}) and {current_app} version ({current_version}) mismatch
 
 sat module is located at {sat_path}
 libervia module is located at {libervia_path}
@@ -78,6 +78,7 @@
 
 
 def coerceConnectionType(value):  # called from Libervia.OPT_PARAMETERS
+    assert isinstance(value, str)
     allowed_values = ("http", "https", "both")
     if value not in allowed_values:
         raise ValueError(
@@ -87,35 +88,12 @@
     return value
 
 
-def coerceDataDir(value):  # called from Libervia.OPT_PARAMETERS
-    if not value:
-        # we ignore missing values
-        return u''
-    if isinstance(value, unicode):
-        # XXX: if value comes from sat.conf, it's unicode,
-        # and we need byte str here (for twisted)
-        value = value.encode("utf-8")
-    value = value.encode("utf-8")
-    html = os.path.join(value, C.HTML_DIR)
-    if not os.path.isfile(os.path.join(html, C.LIBERVIA_MAIN_PAGE)):
-        raise ValueError(
-            "%s is not a Libervia's browser HTML directory" % os.path.realpath(html)
-        )
-    themes_dir = os.path.join(value, C.THEMES_DIR)
-    if not os.path.isfile(os.path.join(themes_dir, "default/styles/blog.css")):
-        # XXX: we just display a message, as themes_dir is only used by legacy blog
-        #      which will be removed entirely in 0.8
-        # TODO: remove entirely legacy blog and linked options
-        print "%s is not a Libervia's server data directory" % os.path.realpath(
-            themes_dir)
-    return value
-
-
 def coerceBool(value):
     return C.bool(value)
 
 
 def coerceUnicode(value):
+    assert isinstance(value, str)
     # XXX: we use this method to check which value to convert to Unicode
     #      but we don't do the conversion here as Twisted expect str
     return value
@@ -124,45 +102,43 @@
 DATA_DIR_DEFAULT = ''
 # options which are in sat.conf and on command line,
 # see https://twistedmatrix.com/documents/current/api/twisted.python.usage.Options.html
-OPT_PARAMETERS_BOTH = [['connection_type', 't', 'https', _(u"'http', 'https' or 'both' "
+OPT_PARAMETERS_BOTH = [['connection_type', 't', 'https', _("'http', 'https' or 'both' "
                         "(to launch both servers).").encode('utf-8'),
                         coerceConnectionType],
                        ['port', 'p', 8080,
-                        _(u'The port number to listen HTTP on.').encode('utf-8'), int],
+                        _('The port number to listen HTTP on.').encode('utf-8'), int],
                        ['port_https', 's', 8443,
-                        _(u'The port number to listen HTTPS on.').encode('utf-8'), int],
-                       ['port_https_ext', 'e', 0, _(u'The external port number used for '
-                        u'HTTPS (0 means port_https value).').encode('utf-8'), int],
-                       ['tls_private_key', '', '', _(u'TLS certificate private key (PEM '
-                        u'format)').encode('utf-8'), coerceUnicode],
-                       ['tls_certificate', 'c', 'libervia.pem', _(u'TLS public '
-                        u'certificate or private key and public certificate combined '
-                        u'(PEM format)').encode('utf-8'), coerceUnicode],
-                       ['tls_chain', '', '', _(u'TLS certificate intermediate chain (PEM '
-                        u'format)').encode('utf-8'), coerceUnicode],
-                       ['redirect_to_https', 'r', True, _(u'Automatically redirect from '
-                        u'HTTP to HTTPS.').encode('utf-8'), coerceBool],
-                       ['security_warning', 'w', True, _(u'Warn user that he is about to '
-                        u'connect on HTTP.').encode('utf-8'), coerceBool],
-                       ['passphrase', 'k', '', (_(u"Passphrase for the SàT profile "
-                        u"named '%s'") % C.SERVICE_PROFILE).encode('utf-8'),
+                        _('The port number to listen HTTPS on.').encode('utf-8'), int],
+                       ['port_https_ext', 'e', 0, _('The external port number used for '
+                        'HTTPS (0 means port_https value).').encode('utf-8'), int],
+                       ['tls_private_key', '', '', _('TLS certificate private key (PEM '
+                        'format)').encode('utf-8'), coerceUnicode],
+                       ['tls_certificate', 'c', 'libervia.pem', _('TLS public '
+                        'certificate or private key and public certificate combined '
+                        '(PEM format)').encode('utf-8'), coerceUnicode],
+                       ['tls_chain', '', '', _('TLS certificate intermediate chain (PEM '
+                        'format)').encode('utf-8'), coerceUnicode],
+                       ['redirect_to_https', 'r', True, _('Automatically redirect from '
+                        'HTTP to HTTPS.').encode('utf-8'), coerceBool],
+                       ['security_warning', 'w', True, _('Warn user that he is about to '
+                        'connect on HTTP.').encode('utf-8'), coerceBool],
+                       ['passphrase', 'k', '', (_("Passphrase for the SàT profile "
+                        "named '%s'") % C.SERVICE_PROFILE).encode('utf-8'),
                         coerceUnicode],
-                       ['data_dir', 'd', DATA_DIR_DEFAULT, _(u'Data directory for '
-                        u'Libervia legacy').encode('utf-8'), coerceDataDir],
-                       ['allow_registration', '', True, _(u'Allow user to register new '
-                        u'account').encode('utf-8'), coerceBool],
+                       ['allow_registration', '', True, _('Allow user to register new '
+                        'account').encode('utf-8'), coerceBool],
                        ['base_url_ext', '', '',
-                        _(u'The external URL to use as base URL').encode('utf-8'),
+                        _('The external URL to use as base URL').encode('utf-8'),
                         coerceUnicode],
-                       ['dev_mode', 'D', False, _(u'Developer mode, automatically reload'
-                        u'modified pages').encode('utf-8'), coerceBool],
+                       ['dev_mode', 'D', False, _('Developer mode, automatically reload'
+                        'modified pages').encode('utf-8'), coerceBool],
                       ]
 # Options which are in sat.conf only
 OPT_PARAMETERS_CFG = [
     ["empty_password_allowed_warning_dangerous_list", None, "", None],
     ["vhosts_dict", None, {}, None],
     ["url_redirections_dict", None, {}, None],
-    ["menu_json", None, {u'': C.DEFAULT_MENU}, None],
+    ["menu_json", None, {'': C.DEFAULT_MENU}, None],
     ["tickets_trackers_json", None, None, None],
     ["mr_handlers_json", None, None, None],
 ]
@@ -183,7 +159,6 @@
     server.DATA_DIR_DEFAULT = DATA_DIR_DEFAULT
     server.OPT_PARAMETERS_BOTH = OPT_PARAMETERS_BOTH
     server.OPT_PARAMETERS_CFG = OPT_PARAMETERS_CFG
-    server.coerceDataDir = coerceDataDir
 
 
 class Options(usage.Options):
@@ -204,20 +179,20 @@
         # on the command line.
 
         # FIXME: must be refactored + code can be factorised with backend
-        config_parser = ConfigParser.SafeConfigParser()
+        config_parser = configparser.SafeConfigParser()
         config_parser.read(C.CONFIG_FILES)
         self.handleDeprecated(config_parser)
         for param in self.optParameters + OPT_PARAMETERS_CFG:
             name = param[0]
             try:
                 value = config.getConfig(config_parser, CONFIG_SECTION, name, Exception)
-                if isinstance(value, unicode):
-                    value = value.encode("utf-8")
+                # if isinstance(value, str):
+                #     value = value.encode("utf-8")
                 try:
                     param[2] = param[4](value)
                 except IndexError:  # the coerce method is optional
                     param[2] = value
-            except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
+            except (configparser.NoSectionError, configparser.NoOptionError):
                 pass
         usage.Options.__init__(self)
         for opt_data in OPT_PARAMETERS_CFG:
@@ -232,19 +207,19 @@
         for old, new in replacements:
             try:
                 value = config.getConfig(config_parser, CONFIG_SECTION, old, Exception)
-            except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
+            except (configparser.NoSectionError, configparser.NoOptionError):
                 pass
             else:
-                print(u"\n/!\\ Use of {old} is deprecated, please use {new} instead\n"
-                      .format(old=old, new=new))
+                print(("\n/!\\ Use of {old} is deprecated, please use {new} instead\n"
+                      .format(old=old, new=new)))
                 config_parser.set(CONFIG_SECTION, new, value)
 
 
+@implementer(IServiceMaker, IPlugin)
 class LiberviaMaker(object):
-    implements(IServiceMaker, IPlugin)
 
     tapname = C.APP_NAME_FILE
-    description = _(u"The web frontend of Salut à Toi")
+    description = _("The web frontend of Salut à Toi")
     options = Options
 
     def makeService(self, options):
@@ -259,7 +234,9 @@
             except IndexError:
                 continue
             if coerce_cb == coerceUnicode:
-                options[opt[0]] = options[opt[0]].decode("utf-8")
+                if not isinstance(options[opt[0]], str):
+                    print(f"FIXME: {opt[0]} is not unicode")
+                    options[opt[0]] = options[opt[0]].decode("utf-8")
         initialise(options.parent)
         from libervia.server import server