Set newurl on admin actions to stay on the page
[cascardo/ipsilon.git] / ipsilon / admin / common.py
index 827038e..530cb22 100755 (executable)
@@ -21,6 +21,7 @@ import cherrypy
 from ipsilon.util.page import Page
 from ipsilon.util.page import admin_protect
 from ipsilon.util.plugin import PluginObject
+from ipsilon.util import config as pconfig
 
 
 class AdminPage(Page):
@@ -46,73 +47,67 @@ class AdminPluginConfig(AdminPage):
         self.menu = [parent]
         self.back = parent.url
 
-        # Get the defaults
-        options = po.get_config_desc()
-        if options is None:
-            options = dict()
-
-        self.options_order = []
-        if hasattr(po, 'conf_opt_order'):
-            self.options_order = po.conf_opt_order
-
-        # append any undefined options
-        add = []
-        for k in options.keys():
-            if k not in self.options_order:
-                add.append(k)
-        if len(add):
-            add.sort()
-            for k in add:
-                self.options_order.append(k)
-
-    @admin_protect
-    def GET(self, *args, **kwargs):
+    def root_with_msg(self, message=None, message_type=None):
         return self._template('admin/plugin_config.html', title=self.title,
+                              menu=self.menu, action=self.url, back=self.back,
+                              message=message, message_type=message_type,
                               name='admin_%s_%s_form' % (self.facility,
                                                          self._po.name),
-                              menu=self.menu, action=self.url, back=self.back,
-                              options_order=self.options_order,
-                              plugin=self._po)
+                              config=self._po.get_config_obj())
+
+    @admin_protect
+    def GET(self, *args, **kwargs):
+        return self.root_with_msg()
 
     @admin_protect
     def POST(self, *args, **kwargs):
 
         message = "Nothing was modified."
         message_type = "info"
-        new_values = dict()
-
-        # Get the defaults
-        options = self._po.get_config_desc()
-        if options is None:
-            options = dict()
-
-        for key, value in kwargs.iteritems():
-            if key in options:
-                if value != self._po.get_config_value(key):
-                    cherrypy.log.error("Storing [%s]: %s = %s" %
-                                       (self._po.name, key, value))
-                    new_values[key] = value
-
-        if len(new_values) != 0:
+        new_db_values = dict()
+
+        conf = self._po.get_config_obj()
+
+        for name, option in conf.iteritems():
+            if name in kwargs:
+                value = kwargs[name]
+                if isinstance(option, pconfig.List):
+                    value = [x.strip() for x in value.split('\n')]
+                elif isinstance(option, pconfig.Condition):
+                    value = True
+            else:
+                if isinstance(option, pconfig.Condition):
+                    value = False
+                elif isinstance(option, pconfig.Choice):
+                    value = list()
+                    for a in option.get_allowed():
+                        aname = '%s_%s' % (name, a)
+                        if aname in kwargs:
+                            value.append(a)
+                else:
+                    continue
+
+            if value != option.get_value():
+                cherrypy.log.error("Storing [%s]: %s = %s" %
+                                   (self._po.name, name, value))
+            option.set_value(value)
+            new_db_values[name] = option.export_value()
+
+        if len(new_db_values) != 0:
             # First we try to save in the database
             try:
-                self._po.save_plugin_config(self.facility, new_values)
+                self._po.save_plugin_config(self.facility, new_db_values)
                 message = "New configuration saved."
                 message_type = "success"
             except Exception:  # pylint: disable=broad-except
                 message = "Failed to save data!"
                 message_type = "error"
 
-            # And only if it succeeds we change the live object
+            # Then refresh the actual objects
             self._po.refresh_plugin_config(self.facility)
 
-        return self._template('admin/plugin_config.html', title=self.title,
-                              message=message,
-                              message_type=message_type,
-                              name='admin_%s_%s_form' % (self.facility,
-                                                         self._po.name),
-                              menu=self.menu, action=self.url,
-                              plugin=self._po)
+        return self.root_with_msg(message=message,
+                                  message_type=message_type)
 
 
 class AdminPluginsOrder(AdminPage):
@@ -128,11 +123,18 @@ class AdminPluginsOrder(AdminPage):
     def GET(self, *args, **kwargs):
         return self.parent.root_with_msg()
 
+    def _get_enabled_by_name(self):
+        by_name = dict()
+        for p in self._site[self.facility]['available'].values():
+            if p.is_enabled:
+                by_name[p.name] = p
+        return by_name
+
     @admin_protect
     def POST(self, *args, **kwargs):
         message = "Nothing was modified."
         message_type = "info"
-        by_name = {p.name: p for p in self._site[self.facility]['enabled']}
+        by_name = self._get_enabled_by_name()
 
         if 'order' in kwargs:
             order = kwargs['order'].split(',')
@@ -204,7 +206,7 @@ class AdminPlugins(AdminPage):
         po.name = "global"
         globalconf = dict()
         globalconf['order'] = ','.join(names)
-        po.set_config(globalconf)
+        po.import_config(globalconf)
         po.save_plugin_config(self.facility)
 
     def reorder_plugins(self, names):
@@ -213,15 +215,23 @@ class AdminPlugins(AdminPage):
     def root_with_msg(self, message=None, message_type=None):
         plugins = self._site[self.facility]
         enabled = []
-        for p in plugins['enabled']:
-            enabled.append(p.name)
+        if self.order:
+            for plugin in plugins['enabled']:
+                if plugin.is_enabled:
+                    enabled.append(plugin.name)
+        else:
+            for _, plugin in plugins['available'].iteritems():
+                if plugin.is_enabled:
+                    enabled.append(plugin.name)
+
         targs = {'title': self.title,
                  'menu': self._master.menu,
                  'message': message,
                  'message_type': message_type,
                  'available': plugins['available'],
                  'enabled': enabled,
-                 'baseurl': self.url}
+                 'baseurl': self.url,
+                 'newurl': self.url}
         if self.order:
             targs['order_name'] = '%s_order_form' % self.name
             targs['order_action'] = self.order.url
@@ -240,7 +250,7 @@ class AdminPlugins(AdminPage):
             msg = "Unknown plugin %s" % plugin
             return self.root_with_msg(msg, "error")
         obj = plugins['available'][plugin]
-        if obj not in plugins['enabled']:
+        if not obj.is_enabled:
             obj.enable(self._site)
             if self.order:
                 enabled = list(x.name for x in plugins['enabled'])
@@ -257,7 +267,7 @@ class AdminPlugins(AdminPage):
             msg = "Unknown plugin %s" % plugin
             return self.root_with_msg(msg, "error")
         obj = plugins['available'][plugin]
-        if obj in plugins['enabled']:
+        if obj.is_enabled:
             obj.disable(self._site)
             if self.order:
                 enabled = list(x.name for x in plugins['enabled'])
@@ -271,12 +281,15 @@ class Admin(AdminPage):
 
     def __init__(self, site, mount):
         super(Admin, self).__init__(site)
+        self.title = 'Home'
+        self.mount = mount
         self.url = '%s/%s' % (self.basepath, mount)
-        self.menu = []
+        self.menu = [self]
 
     def root(self, *args, **kwargs):
         return self._template('admin/index.html',
                               title='Configuration',
+                              baseurl=self.url,
                               menu=self.menu)
 
     def add_subtree(self, name, page):
@@ -286,3 +299,20 @@ class Admin(AdminPage):
     def del_subtree(self, name):
         self.menu.remove(self.__dict__[name])
         del self.__dict__[name]
+
+    def get_menu_urls(self):
+        urls = dict()
+        for item in self.menu:
+            name = getattr(item, 'name', None)
+            if name:
+                urls['%s_url' % name] = cherrypy.url('/%s/%s' % (self.mount,
+                                                                 name))
+        return urls
+
+    @admin_protect
+    def scheme(self):
+        cherrypy.response.headers.update({'Content-Type': 'image/svg+xml'})
+        urls = self.get_menu_urls()
+        # pylint: disable=star-args
+        return self._template('admin/ipsilon-scheme.svg', **urls)
+    scheme.public_function = True