Remove unnecessary layer of abstraction over template rendering

This commit is contained in:
Sunil Mohan Adapa 2014-05-05 00:08:58 +05:30
parent 851536ffbe
commit 4b44741c68
23 changed files with 136 additions and 105 deletions

View File

@ -4,6 +4,8 @@ from modules.auth import require
from plugin_mount import PagePlugin from plugin_mount import PagePlugin
from forms import Form from forms import Form
import cfg import cfg
import util
class Apps(PagePlugin): class Apps(PagePlugin):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
@ -24,12 +26,14 @@ class Apps(PagePlugin):
Many of the services you use on the web could soon be on site Many of the services you use on the web could soon be on site
and under your control!</p> and under your control!</p>
""" % (cfg.product_name) """ % (cfg.product_name)
return self.fill_template(title="User Applications", main=main, sidebar_right='') return util.render_template(title="User Applications", main=main,
sidebar_right='')
@cherrypy.expose @cherrypy.expose
@require() @require()
def photos(self): def photos(self):
return self.fill_template(title="Photo Gallery", main='', sidebar_right=""" return util.render_template(title="Photo Gallery", main='',
sidebar_right="""
<strong>Photo Gallery</strong><p>Your photos might well be the most valuable <strong>Photo Gallery</strong><p>Your photos might well be the most valuable
digital property you have, so why trust it to companies that have no digital property you have, so why trust it to companies that have no
investment in the sentimental value of your family snaps? Keep those investment in the sentimental value of your family snaps? Keep those

View File

@ -6,7 +6,8 @@ from forms import Form
import actions import actions
import cfg import cfg
import service import service
from util import Message import util
class Owncloud(PagePlugin, FormPlugin): class Owncloud(PagePlugin, FormPlugin):
order = 90 order = 90
@ -42,7 +43,8 @@ class Owncloud(PagePlugin, FormPlugin):
<p>ownCloud gives you universal access to your files through a web interface or WebDAV. It also provides a platform to easily view & sync your contacts, calendars and bookmarks across all your devices and enables basic editing right on the web. Installation has minimal server requirements, doesn't need special permissions and is quick. ownCloud is extendable via a simple but powerful API for applications and plugins. <p>ownCloud gives you universal access to your files through a web interface or WebDAV. It also provides a platform to easily view & sync your contacts, calendars and bookmarks across all your devices and enables basic editing right on the web. Installation has minimal server requirements, doesn't need special permissions and is quick. ownCloud is extendable via a simple but powerful API for applications and plugins.
</p> </p>
""" """
return self.fill_template(title="Owncloud", main=main, sidebar_right=sidebar_right) return util.render_template(title="Owncloud", main=main,
sidebar_right=sidebar_right)
def form(self, owncloud_enable, message=None): def form(self, owncloud_enable, message=None):
form = Form(title="Configuration", form = Form(title="Configuration",

View File

@ -4,11 +4,11 @@ from gettext import gettext as _
from plugin_mount import PagePlugin, PluginMount, FormPlugin from plugin_mount import PagePlugin, PluginMount, FormPlugin
from modules.auth import require, add_user from modules.auth import require, add_user
from forms import Form from forms import Form
import util as u
from withsqlite.withsqlite import sqlite_db from withsqlite.withsqlite import sqlite_db
import cfg import cfg
import config import config
from model import User from model import User
import util
"""First Boot: Initial Plinth Configuration. """First Boot: Initial Plinth Configuration.
@ -118,7 +118,7 @@ class FirstBoot(PagePlugin):
form.submit("Box it up!") form.submit("Box it up!")
main += form.render() main += form.render()
return self.fill_template( return util.render_template(
template="base", template="base",
title=_("First Boot!"), title=_("First Boot!"),
main=main, main=main,
@ -155,7 +155,7 @@ href="../router">continue</a> to see the rest of the web interface.</p>
# # TODO: switch to HTTPS # # TODO: switch to HTTPS
# raise cherrypy.InternalRedirect('state1') # raise cherrypy.InternalRedirect('state1')
return self.fill_template( return util.render_template(
template="base", template="base",
title=_("Installing the Certificate"), title=_("Installing the Certificate"),
main=main, main=main,

View File

@ -3,6 +3,9 @@ import cherrypy
from gettext import gettext as _ from gettext import gettext as _
from plugin_mount import PagePlugin from plugin_mount import PagePlugin
import cfg import cfg
import util
class Help(PagePlugin): class Help(PagePlugin):
order = 20 # order of running init in PagePlugins order = 20 # order of running init in PagePlugins
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
@ -43,11 +46,12 @@ class Help(PagePlugin):
the question frequency is currently zero for all the question frequency is currently zero for all
questions.</p> questions.</p>
""" % {'box':cfg.box_name} """ % {'box':cfg.box_name}
return self.fill_template(title="Documentation and FAQ", main=main) return util.render_template(title="Documentation and FAQ", main=main)
@cherrypy.expose @cherrypy.expose
def about(self): def about(self):
return self.fill_template(title=_("About the %s" % cfg.box_name), main=""" return util.render_template(title=_("About the %s" % cfg.box_name),
main="""
<img src="/static/theme/img/freedombox-logo-250px.png" class="main-graphic" /> <img src="/static/theme/img/freedombox-logo-250px.png" class="main-graphic" />
<p>We live in a world where our use of the network is <p>We live in a world where our use of the network is
mediated by those who often do not have our best mediated by those who often do not have our best
@ -82,7 +86,8 @@ class View(PagePlugin):
def default(self, page=''): def default(self, page=''):
if page not in ['design', 'plinth', 'hacking', 'faq']: if page not in ['design', 'plinth', 'hacking', 'faq']:
raise cherrypy.HTTPError(404, "The path '/help/view/%s' was not found." % page) raise cherrypy.HTTPError(404, "The path '/help/view/%s' was not found." % page)
return self.fill_template(template="err", main="<p>Sorry, as much as I would like to show you that page, I don't seem to have a page named %s!</p>" % page)
with open(os.path.join("doc", "%s.part.html" % page), 'r') as IF: with open(os.path.join("doc", "%s.part.html" % page), 'r') as IF:
main = IF.read() main = IF.read()
return self.fill_template(title=_("%s Documentation" % cfg.product_name), main=main) return util.render_template(title=_("%s Documentation" %
cfg.product_name), main=main)

View File

@ -1,9 +1,14 @@
"""
Controller to provide login and logout actions
"""
import cherrypy import cherrypy
import cfg import cfg
from plugin_mount import PagePlugin from plugin_mount import PagePlugin
from modules.forms import Form from modules.forms import Form
from auth import * from auth import *
# Controller to provide login and logout actions import util
class AuthController(PagePlugin): class AuthController(PagePlugin):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
@ -23,7 +28,7 @@ class AuthController(PagePlugin):
form.text_input("Passphrase", name="passphrase", type="password") form.text_input("Passphrase", name="passphrase", type="password")
form.submit(label="Login") form.submit(label="Login")
return self.fill_template(main=form.render(), sidebar_right=" ") return util.render_template(main=form.render(), sidebar_right=" ")
@cherrypy.expose @cherrypy.expose
def login(self, username=None, passphrase=None, from_page=cfg.server_dir+"/", **kwargs): def login(self, username=None, passphrase=None, from_page=cfg.server_dir+"/", **kwargs):

View File

@ -3,6 +3,8 @@ from gettext import gettext as _
from plugin_mount import PagePlugin from plugin_mount import PagePlugin
from modules.auth import require from modules.auth import require
import cfg import cfg
import util
class Privacy(PagePlugin): class Privacy(PagePlugin):
order = 20 # order of running init in PagePlugins order = 20 # order of running init in PagePlugins
@ -27,7 +29,8 @@ class Privacy(PagePlugin):
placeholder and a promise: privacy is important enough that it placeholder and a promise: privacy is important enough that it
is a founding consideration, not an afterthought.</p> is a founding consideration, not an afterthought.</p>
""" """
return self.fill_template(title=_("Privacy Control Panel"), main=main, return util.render_template(title=_("Privacy Control Panel"),
main=main,
sidebar_right=_("""<strong>Statement of Principles</strong><p>When we say your sidebar_right=_("""<strong>Statement of Principles</strong><p>When we say your
privacy is important, it's not just an empty pleasantry. We really privacy is important, it's not just an empty pleasantry. We really
mean it. Your privacy control panel should give you fine-grained mean it. Your privacy control panel should give you fine-grained

View File

@ -25,6 +25,8 @@ from plugin_mount import PagePlugin
from modules.auth import require from modules.auth import require
import actions import actions
import cfg import cfg
import util
class tor(PagePlugin): class tor(PagePlugin):
order = 30 # order of running init in PagePlugins order = 30 # order of running init in PagePlugins
@ -58,4 +60,4 @@ class tor(PagePlugin):
main += "<td>" + str(ports[key]) + "</td></tr>" main += "<td>" + str(ports[key]) + "</td></tr>"
main += "</table>" main += "</table>"
return self.fill_template(title=_("Tor Control Panel"), main=main) return util.render_template(title=_("Tor Control Panel"), main=main)

View File

@ -1,6 +1,8 @@
import cherrypy import cherrypy
from plugin_mount import PagePlugin from plugin_mount import PagePlugin
from modules.auth import require from modules.auth import require
import util
class Info(PagePlugin): class Info(PagePlugin):
title = 'Info' title = 'Info'
@ -13,6 +15,7 @@ class Info(PagePlugin):
@cherrypy.expose @cherrypy.expose
@require() @require()
def index(self): def index(self):
return self.fill_template(title="Router Information", main=""" return util.render_template(title="Router Information", main="""
<p>Eventually we will display a bunch of info, graphs and logs about the routing functions here.</p> <p>Eventually we will display a bunch of info, graphs and logs about
the routing functions here.</p>
""") """)

View File

@ -89,8 +89,8 @@ PageKite</a></p>
<p><a href="{server_dir}/router/setup/pagekite/configure">Configure <p><a href="{server_dir}/router/setup/pagekite/configure">Configure
PageKite</a> </p>''').format(server_dir=cfg.server_dir) PageKite</a> </p>''').format(server_dir=cfg.server_dir)
return self.fill_template(title=_("Public Visibility (PageKite)"), return util.render_template(title=_("Public Visibility (PageKite)"),
main=main, sidebar_right=sidebar_right) main=main, sidebar_right=sidebar_right)
class configure(FormPlugin, PagePlugin): # pylint: disable-msg=C0103 class configure(FormPlugin, PagePlugin): # pylint: disable-msg=C0103

View File

@ -1,11 +1,9 @@
from urlparse import urlparse import cherrypy
import os, cherrypy from plugin_mount import PagePlugin, FormPlugin
from gettext import gettext as _
from plugin_mount import PagePlugin, PluginMount, FormPlugin
from modules.auth import require from modules.auth import require
from forms import Form from forms import Form
from util import *
import cfg import cfg
import util
class router(PagePlugin): class router(PagePlugin):
order = 9 # order of running init in PagePlugins order = 9 # order of running init in PagePlugins
@ -28,18 +26,20 @@ class router(PagePlugin):
@cherrypy.expose @cherrypy.expose
@require() @require()
def wireless(self): def wireless(self):
return self.fill_template(title="Wireless", main="<p>wireless setup: essid, etc.</p>") return util.render_template(title="Wireless",
main="<p>wireless setup: essid, etc.</p>")
@cherrypy.expose @cherrypy.expose
@require() @require()
def firewall(self): def firewall(self):
return self.fill_template(title="Firewall", main="<p>Iptables twiddling.</p>") return util.render_template(title="Firewall",
main="<p>Iptables twiddling.</p>")
@cherrypy.expose @cherrypy.expose
@require() @require()
def hotspot(self): def hotspot(self):
return self.fill_template(title="Hotspot and Mesh", main="<p>connection sharing setup.</p>") return util.render_template(title="Hotspot and Mesh",
main="<p>connection sharing setup.</p>")
class setup(PagePlugin): class setup(PagePlugin):
@ -70,18 +70,18 @@ can rival those of high-end routers costing hundreds of dollars.</p>
Configure" menu.</p>""" % {'product':cfg.box_name} Configure" menu.</p>""" % {'product':cfg.box_name}
else: else:
parts['main'] += "<p>router name, domain name, router IP, dhcp</p>" parts['main'] += "<p>router name, domain name, router IP, dhcp</p>"
return self.fill_template(**parts) return util.render_template(**parts)
@cherrypy.expose @cherrypy.expose
@require() @require()
def ddns(self): def ddns(self):
return self.fill_template(title="Dynamic DNS", main="<p>Masquerade setup</p>") return util.render_template(title="Dynamic DNS", main="<p>Masquerade setup</p>")
@cherrypy.expose @cherrypy.expose
@require() @require()
def mac_address(self): def mac_address(self):
return self.fill_template(title="MAC Address Cloning", return util.render_template(title="MAC Address Cloning",
main="<p>Your router can pretend to have a different MAC address on any interface.</p>") main="<p>Your router can pretend to have a different MAC address on any interface.</p>")
class wan(FormPlugin, PagePlugin): class wan(FormPlugin, PagePlugin):
@ -127,7 +127,7 @@ class wan(FormPlugin, PagePlugin):
if not cfg.users.expert(): if not cfg.users.expert():
return '' return ''
store = filedict_con(cfg.store_file, 'router') store = util.filedict_con(cfg.store_file, 'router')
defaults = {'connect_type': 'DHCP'} defaults = {'connect_type': 'DHCP'}
for key, value in defaults.items(): for key, value in defaults.items():
if not key in kwargs: if not key in kwargs:
@ -136,10 +136,10 @@ class wan(FormPlugin, PagePlugin):
except KeyError: except KeyError:
store[key] = kwargs[key] = value store[key] = kwargs[key] = value
form = Form(title="WAN Connection", form = Form(title="WAN Connection",
action=cfg.server_dir + "/router/setup/wan/index", action=cfg.server_dir + "/router/setup/wan/index",
name="wan_connection_form", name="wan_connection_form",
message=message) message=message)
form.dropdown('Connection Type', vals=["DHCP", "Static IP"], id="connect_type") form.dropdown('Connection Type', vals=["DHCP", "Static IP"], id="connect_type")
form.html('<div id="static_ip_form">') form.html('<div id="static_ip_form">')
form.dotted_quad("WAN IP Address", name="wan_ip", quad=[wan_ip0, wan_ip1, wan_ip2, wan_ip3]) form.dotted_quad("WAN IP Address", name="wan_ip", quad=[wan_ip0, wan_ip1, wan_ip2, wan_ip3])
@ -151,4 +151,3 @@ class wan(FormPlugin, PagePlugin):
form.html('</div>') form.html('</div>')
form.submit("Set Wan") form.submit("Set Wan")
return form.render() return form.render()

View File

@ -2,6 +2,8 @@ import cherrypy
from modules.auth import require from modules.auth import require
from plugin_mount import PagePlugin from plugin_mount import PagePlugin
import cfg import cfg
import util
class Services(PagePlugin): class Services(PagePlugin):
order = 9 # order of running init in PagePlugins order = 9 # order of running init in PagePlugins
@ -18,7 +20,8 @@ class Services(PagePlugin):
@cherrypy.expose @cherrypy.expose
@require() @require()
def openid(self): def openid(self):
return self.fill_template(title="Open ID", main='', sidebar_right=""" return util.render_template(title="Open ID", main='',
sidebar_right="""
<strong>One Login for Every Site</strong><p>Your %s is also an OpenID <strong>One Login for Every Site</strong><p>Your %s is also an OpenID
machine. It can generate credentials that allow you to log in to many machine. It can generate credentials that allow you to log in to many
websites without the need to remember or enter a separate username and websites without the need to remember or enter a separate username and

View File

@ -6,7 +6,8 @@ import cfg
from forms import Form from forms import Form
import actions import actions
import service import service
from util import Message import util
class xmpp(PagePlugin): class xmpp(PagePlugin):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
@ -32,7 +33,7 @@ class xmpp(PagePlugin):
main = "<p>XMPP Server Accounts and Configuration</p>" main = "<p>XMPP Server Accounts and Configuration</p>"
sidebar_right = '<strong><a href="'+cfg.server_dir+'/services/xmpp/configure">Configure XMPP Server</a></strong><br />' sidebar_right = '<strong><a href="'+cfg.server_dir+'/services/xmpp/configure">Configure XMPP Server</a></strong><br />'
sidebar_right = sidebar_right + '<strong><a href="'+cfg.server_dir+'/services/xmpp/register">Register XMPP Account</a></strong>' sidebar_right = sidebar_right + '<strong><a href="'+cfg.server_dir+'/services/xmpp/register">Register XMPP Account</a></strong>'
return self.fill_template(title="XMPP Server", main=main, sidebar_right=sidebar_right) return util.render_template(title="XMPP Server", main=main, sidebar_right=sidebar_right)
class configure(FormPlugin, PagePlugin): class configure(FormPlugin, PagePlugin):
url = ["/services/xmpp/configure"] url = ["/services/xmpp/configure"]
@ -78,7 +79,7 @@ class configure(FormPlugin, PagePlugin):
actions.run("xmpp-setup", opts) actions.run("xmpp-setup", opts)
main = self.main(checkedinfo['inband_enable']) main = self.main(checkedinfo['inband_enable'])
return self.fill_template(title="XMPP Server Configuration", main=main, sidebar_left=self.sidebar_left, sidebar_right=self.sidebar_right) return util.render_template(title="XMPP Server Configuration", main=main, sidebar_left=self.sidebar_left, sidebar_right=self.sidebar_right)
class register(FormPlugin, PagePlugin): class register(FormPlugin, PagePlugin):
url = ["/services/xmpp/register"] url = ["/services/xmpp/register"]
@ -97,7 +98,7 @@ class register(FormPlugin, PagePlugin):
return form.render() return form.render()
def process_form(self, username=None, password=None, **kwargs): def process_form(self, username=None, password=None, **kwargs):
msg = Message() msg = util.Message()
if not username: msg.add = _("Must specify a username!") if not username: msg.add = _("Must specify a username!")
if not password: msg.add = _("Must specify a password!") if not password: msg.add = _("Must specify a password!")
@ -115,7 +116,7 @@ class register(FormPlugin, PagePlugin):
cfg.log(msg.text) cfg.log(msg.text)
main = self.main(username, msg=msg.text) main = self.main(username, msg=msg.text)
return self.fill_template( return util.render_template(
title="XMPP Server Configuration", title="XMPP Server Configuration",
main=main, main=main,
sidebar_left=self.sidebar_left, sidebar_left=self.sidebar_left,

View File

@ -2,6 +2,8 @@ import cherrypy
from modules.auth import require from modules.auth import require
from plugin_mount import PagePlugin from plugin_mount import PagePlugin
import cfg import cfg
import util
class FileExplorer(PagePlugin): class FileExplorer(PagePlugin):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
@ -32,4 +34,5 @@ href="http://blogfreakz.com/jquery/web-based-filemanager/">FileManager</a>.
It appears to be mostly javascript with some bindings to make it It appears to be mostly javascript with some bindings to make it
python-friendly.</p> python-friendly.</p>
""" """
return self.fill_template(title="File Explorer", main=main, sidebar_right='') return util.render_template(title="File Explorer", main=main,
sidebar_right='')

View File

@ -3,6 +3,8 @@ from gettext import gettext as _
from modules.auth import require from modules.auth import require
from plugin_mount import PagePlugin from plugin_mount import PagePlugin
import cfg import cfg
import util
class Sharing(PagePlugin): class Sharing(PagePlugin):
order = 9 # order of running init in PagePlugins order = 9 # order of running init in PagePlugins
@ -24,7 +26,8 @@ class Sharing(PagePlugin):
@cherrypy.expose @cherrypy.expose
@require() @require()
def files(self): def files(self):
return self.fill_template(title="File Server", main='', sidebar_right=_(""" return util.render_template(title="File Server", main='',
sidebar_right=_("""
<strong>Freedom NAS</strong><p> The %s can make your spare hard drives accessible to your <strong>Freedom NAS</strong><p> The %s can make your spare hard drives accessible to your
local network, thus acting as a NAS server. We currently support local network, thus acting as a NAS server. We currently support
sharing files via NFS and SMB. sharing files via NFS and SMB.
@ -46,7 +49,8 @@ class PrinterSharing(PagePlugin):
<p>TODO: Setup and install SAMBA</p> <p>TODO: Setup and install SAMBA</p>
<p>TODO: Setup and install CUPS</p> <p>TODO: Setup and install CUPS</p>
""" """
return self.fill_template(title="Printer Sharing", main=main, sidebar_right=""" return util.render_template(title="Printer Sharing", main=main,
sidebar_right="""
<strong>Share Your Printer</strong><p> The %s can share your printer via Samba and CUPS.</p> <strong>Share Your Printer</strong><p> The %s can share your printer via Samba and CUPS.</p>
""" % cfg.box_name) """ % cfg.box_name)

View File

@ -52,7 +52,7 @@ class Config(PagePlugin):
parts['title'] = _("Configure this {box_name}") \ parts['title'] = _("Configure this {box_name}") \
.format(box_name=cfg.box_name) .format(box_name=cfg.box_name)
return self.fill_template(**parts) # pylint: disable-msg=W0142 return util.render_template(**parts) # pylint: disable-msg=W0142
def valid_hostname(name): def valid_hostname(name):

View File

@ -25,6 +25,8 @@ from auth import require
from plugin_mount import PagePlugin from plugin_mount import PagePlugin
import actions import actions
import cfg import cfg
import util
class diagnostics(PagePlugin): class diagnostics(PagePlugin):
order = 30 order = 30
@ -42,7 +44,7 @@ class diagnostics(PagePlugin):
properly. It may take a minute to complete.</p> properly. It may take a minute to complete.</p>
""") """)
main += '<p><a class="btn btn-primary btn-large" href="'+cfg.server_dir+'/sys/diagnostics/test">Run diagnostic test &raquo;</a></p>' main += '<p><a class="btn btn-primary btn-large" href="'+cfg.server_dir+'/sys/diagnostics/test">Run diagnostic test &raquo;</a></p>'
return self.fill_template(title=_("System Diagnostics"), main=main) return util.render_template(title=_("System Diagnostics"), main=main)
class test(PagePlugin): class test(PagePlugin):
order = 31 order = 31
@ -66,4 +68,4 @@ class test(PagePlugin):
for line in output.split('\n'): for line in output.split('\n'):
main += line + "</br>" main += line + "</br>"
return self.fill_template(title=_("Diagnostic Test"), main=main) return util.render_template(title=_("Diagnostic Test"), main=main)

View File

@ -27,6 +27,7 @@ import cfg
from modules.auth import require from modules.auth import require
from plugin_mount import PagePlugin from plugin_mount import PagePlugin
import service as service_module import service as service_module
import util
class Firewall(PagePlugin): class Firewall(PagePlugin):
@ -65,7 +66,8 @@ pre-installed with {box_name}. On any Debian based system (such as
{box_name}) you may install it using the command 'aptitude install {box_name}) you may install it using the command 'aptitude install
firewalld'</p>''').format(box_name=cfg.box_name) firewalld'</p>''').format(box_name=cfg.box_name)
return self.fill_template(title=_("Firewall"), main=main + status) return util.render_template(title=_("Firewall"),
main=main + status)
if not self.get_enabled_status(): if not self.get_enabled_status():
status = _(''' status = _('''
@ -75,7 +77,8 @@ enabled by default on {box_name}. On any Debian based system (such as
or in case of system with systemd 'systemctl start firewalld'</p> or in case of system with systemd 'systemctl start firewalld'</p>
''').format(box_name=cfg.box_name) ''').format(box_name=cfg.box_name)
return self.fill_template(title=_("Firewall"), main=main + status) return util.render_template(title=_("Firewall"),
main=main + status)
internal_enabled_sevices = self.get_enabled_services(zone='internal') internal_enabled_sevices = self.get_enabled_services(zone='internal')
external_enabled_sevices = self.get_enabled_services(zone='external') external_enabled_sevices = self.get_enabled_services(zone='external')
@ -129,8 +132,8 @@ or in case of system with systemd 'systemctl start firewalld'</p>
service it is automatically permitted in the firewall and you disable service it is automatically permitted in the firewall and you disable
a service is automatically disabled in the firewall.</em></p>''' a service is automatically disabled in the firewall.</em></p>'''
return self.fill_template(title=_("Firewall"), main=main + return util.render_template(title=_("Firewall"), main=main +
services_info + footnote) services_info + footnote)
def get_installed_status(self): def get_installed_status(self):
"""Return whether firewall is installed""" """Return whether firewall is installed"""

View File

@ -5,7 +5,7 @@ from plugin_mount import PagePlugin, FormPlugin
from forms import Form from forms import Form
import actions import actions
import cfg import cfg
from util import Message import util
class Packages(PagePlugin, FormPlugin): class Packages(PagePlugin, FormPlugin):
order = 20 order = 20
@ -52,12 +52,12 @@ class Packages(PagePlugin, FormPlugin):
<p>aptitude purge modules</p> <p>aptitude purge modules</p>
<p>aptitude install modules</p> <p>aptitude install modules</p>
<p>The modules should depend on the appropriate Debian packages.</p>""") <p>The modules should depend on the appropriate Debian packages.</p>""")
main += self.form(self, Message(output), args, kwargs) main += self.form(self, util.Message(output), args, kwargs)
sidebar_right = _(""" sidebar_right = _("""
<strong>Help</strong> <strong>Help</strong>
<p>On this page, you can add or remove %s plugins to your %s.</p> <p>On this page, you can add or remove %s plugins to your %s.</p>
<p>Plugins are just Debian packages, so Debian's usual package management features should make this job fairly easy.</p>""" % (cfg.product_name, cfg.box_name)) <p>Plugins are just Debian packages, so Debian's usual package management features should make this job fairly easy.</p>""" % (cfg.product_name, cfg.box_name))
return self.fill_template(title=_("Add/Remove Plugins"), main=main, sidebar_right=sidebar_right) return util.render_template(title=_("Add/Remove Plugins"), main=main, sidebar_right=sidebar_right)
def form(self, message=None, *args, **kwargs): def form(self, message=None, *args, **kwargs):
output, error = actions.run("module-manager", ["list-available"]) output, error = actions.run("module-manager", ["list-available"])

View File

@ -1,17 +1,8 @@
import os
import cherrypy import cherrypy
try:
import simplejson as json
except ImportError:
import json
from gettext import gettext as _ from gettext import gettext as _
from filedict import FileDict from plugin_mount import PagePlugin
from auth import require
from plugin_mount import PagePlugin, FormPlugin
import cfg import cfg
from forms import Form import util
from model import User
from util import *
sys_dir = "modules/installed/sys" sys_dir = "modules/installed/sys"
@ -27,7 +18,7 @@ class Sys(PagePlugin):
@cherrypy.expose @cherrypy.expose
def index(self): def index(self):
return self.fill_template(title=_("System Configuration"), main=_(""" return util.render_template(title=_("System Configuration"), main=_("""
<p>In this section, you can control the %(product)s's <p>In this section, you can control the %(product)s's
underlying system, as opposed to its various applications and underlying system, as opposed to its various applications and
services. These options affect the %(product)s at its most services. These options affect the %(product)s at its most

View File

@ -1,11 +1,12 @@
import os, cherrypy import cherrypy
from gettext import gettext as _ from gettext import gettext as _
from auth import require, add_user from auth import require, add_user
from plugin_mount import PagePlugin, FormPlugin from plugin_mount import PagePlugin, FormPlugin
import cfg import cfg
from forms import Form from forms import Form
from util import *
from model import User from model import User
import util
class users(PagePlugin): class users(PagePlugin):
order = 20 # order of running init in PagePlugins order = 20 # order of running init in PagePlugins
@ -19,7 +20,9 @@ class users(PagePlugin):
@require() @require()
def index(self): def index(self):
sidebar_right = '<strong><a href="'+cfg.server_dir+'/sys/users/add">Add User</a></strong><br/><strong><a href="'+cfg.server_dir+'/sys/users/edit">Edit Users</a></strong>' sidebar_right = '<strong><a href="'+cfg.server_dir+'/sys/users/add">Add User</a></strong><br/><strong><a href="'+cfg.server_dir+'/sys/users/edit">Edit Users</a></strong>'
return self.fill_template(title="Manage Users and Groups", sidebar_right=sidebar_right) return util.render_template(title="Manage Users and Groups",
sidebar_right=sidebar_right)
class add(FormPlugin, PagePlugin): class add(FormPlugin, PagePlugin):
url = ["/sys/users/add"] url = ["/sys/users/add"]
@ -34,9 +37,9 @@ class add(FormPlugin, PagePlugin):
def main(self, username='', name='', email='', message=None, *args, **kwargs): def main(self, username='', name='', email='', message=None, *args, **kwargs):
form = Form(title="Add User", form = Form(title="Add User",
action=cfg.server_dir + "/sys/users/add/index", action=cfg.server_dir + "/sys/users/add/index",
name="add_user_form", name="add_user_form",
message=message) message=message)
form.text_input(_("Username"), name="username", value=username) form.text_input(_("Username"), name="username", value=username)
form.text_input(_("Full name"), name="name", value=name) form.text_input(_("Full name"), name="name", value=name)
form.text_input(_("Email"), name="email", value=email) form.text_input(_("Email"), name="email", value=email)
@ -45,7 +48,7 @@ class add(FormPlugin, PagePlugin):
return form.render() return form.render()
def process_form(self, username=None, name=None, email=None, password=None, **kwargs): def process_form(self, username=None, name=None, email=None, password=None, **kwargs):
msg = Message() msg = util.Message()
error = add_user(username, password, name, email, False) error = add_user(username, password, name, email, False)
if error: if error:
@ -55,7 +58,10 @@ class add(FormPlugin, PagePlugin):
cfg.log(msg.text) cfg.log(msg.text)
main = self.main(username, name, email, msg=msg.text) main = self.main(username, name, email, msg=msg.text)
return self.fill_template(title="Manage Users and Groups", main=main, sidebar_left=self.sidebar_left, sidebar_right=self.sidebar_right) return util.render_template(title="Manage Users and Groups", main=main,
sidebar_left=self.sidebar_left,
sidebar_right=self.sidebar_right)
class edit(FormPlugin, PagePlugin): class edit(FormPlugin, PagePlugin):
url = ["/sys/users/edit"] url = ["/sys/users/edit"]
@ -68,7 +74,7 @@ class edit(FormPlugin, PagePlugin):
"Delete User" to remove users from %s and the %s "Delete User" to remove users from %s and the %s
system.</p><p>Deleting users is permanent!</p>""" % (cfg.product_name, cfg.box_name)) system.</p><p>Deleting users is permanent!</p>""" % (cfg.product_name, cfg.box_name))
def main(self, msg=''): def main(self, msg='', **kwargs):
users = cfg.users.get_all() users = cfg.users.get_all()
add_form = Form(title=_("Edit or Delete User"), action=cfg.server_dir + "/sys/users/edit", message=msg) add_form = Form(title=_("Edit or Delete User"), action=cfg.server_dir + "/sys/users/edit", message=msg)
add_form.html('<span class="indent"><strong>Delete</strong><br /></span>') add_form.html('<span class="indent"><strong>Delete</strong><br /></span>')
@ -83,8 +89,8 @@ class edit(FormPlugin, PagePlugin):
def process_form(self, **kwargs): def process_form(self, **kwargs):
if 'delete' in kwargs: if 'delete' in kwargs:
msg = Message() msg = util.Message()
usernames = find_keys(kwargs, 'on') usernames = util.find_keys(kwargs, 'on')
cfg.log.info("%s asked to delete %s" % (cherrypy.session.get(cfg.session_key), usernames)) cfg.log.info("%s asked to delete %s" % (cherrypy.session.get(cfg.session_key), usernames))
if usernames: if usernames:
for username in usernames: for username in usernames:
@ -107,15 +113,22 @@ class edit(FormPlugin, PagePlugin):
else: else:
msg.add = _("Must specify at least one valid, existing user.") msg.add = _("Must specify at least one valid, existing user.")
main = self.main(msg=msg.text) main = self.main(msg=msg.text)
return self.fill_template(title="Manage Users and Groups", main=main, sidebar_left=self.sidebar_left, sidebar_right=self.sidebar_right) return util.render_template(title="Manage Users and Groups",
main=main,
sidebar_left=self.sidebar_left,
sidebar_right=self.sidebar_right)
sidebar_right = '' sidebar_right = ''
u = cfg.users[kwargs['username']] u = cfg.users[kwargs['username']]
if not u: if not u:
main = _("<p>Could not find a user with username of %s!</p>" % kwargs['username']) main = _("<p>Could not find a user with username of %s!</p>" % kwargs['username'])
return self.fill_template(template="err", title=_("Unknown User"), main=main, return util.render_template(template="err",
sidebar_left=self.sidebar_left, sidebar_right=sidebar_right) title=_("Unknown User"), main=main,
sidebar_left=self.sidebar_left,
sidebar_right=sidebar_right)
main = _("""<strong>Edit User '%s'</strong>""" % u['username']) main = _("""<strong>Edit User '%s'</strong>""" % u['username'])
sidebar_right = '' sidebar_right = ''
return self.fill_template(title="Manage Users and Groups", main=main, sidebar_left=self.sidebar_left, sidebar_right=sidebar_right) return util.render_template(title="Manage Users and Groups", main=main,
sidebar_left=self.sidebar_left,
sidebar_right=sidebar_right)

View File

@ -33,7 +33,7 @@ __status__ = "Development"
import urlparse import urlparse
def error_page(status, dynamic_msg, stock_msg): def error_page(status, dynamic_msg, stock_msg):
return u.page_template(template="err", title=status, main="<p>%s</p>%s" % (dynamic_msg, stock_msg)) return u.render_template(template="err", title=status, main="<p>%s</p>%s" % (dynamic_msg, stock_msg))
def error_page_404(status, message, traceback, version): def error_page_404(status, message, traceback, version):
return error_page(status, message, """<p>If you believe this return error_page(status, message, """<p>If you believe this

View File

@ -1,8 +1,8 @@
import cherrypy import cherrypy
from modules.auth import require from modules.auth import require
import cfg import cfg
from util import * import util
import util as u
class PluginMount(type): class PluginMount(type):
"""See http://martyalchin.com/2008/jan/10/simple-plugin-framework/ for documentation""" """See http://martyalchin.com/2008/jan/10/simple-plugin-framework/ for documentation"""
@ -87,9 +87,6 @@ class PagePlugin:
cfg.log.info("Registering page: %s" % url) cfg.log.info("Registering page: %s" % url)
_setattr_deep(cfg.html_root, url, self) _setattr_deep(cfg.html_root, url, self)
def fill_template(self, *args, **kwargs):
return u.page_template(*args, **kwargs)
def forms(self, url, *args, **kwargs): def forms(self, url, *args, **kwargs):
for form in cfg.forms: for form in cfg.forms:
if url in form.url: if url in form.url:
@ -98,7 +95,7 @@ class PagePlugin:
parts = get_parts(form, None, *args, **kwargs) parts = get_parts(form, None, *args, **kwargs)
return parts return parts
return {'sidebar_left':left, 'sidebar_right':right, 'main':main}
class FormPlugin(): class FormPlugin():
""" """
@ -138,11 +135,10 @@ class FormPlugin():
order = 50 order = 50
url = [] url = []
js = ''
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
for u in self.url: for unit in self.url:
path = u.split("/")[1:] + [self.__class__.__name__] path = unit.split("/")[1:] + [self.__class__.__name__]
_setattr_deep(cfg.html_root, path, self) _setattr_deep(cfg.html_root, path, self)
cfg.log("Registered page: %s" % '.'.join(path)) cfg.log("Registered page: %s" % '.'.join(path))
@ -156,20 +152,12 @@ class FormPlugin():
if kwargs: if kwargs:
kwargs['message'] = self.process_form(**kwargs) kwargs['message'] = self.process_form(**kwargs)
parts = get_parts(self, **kwargs) parts = get_parts(self, **kwargs)
return self.fill_template(**parts) return util.render_template(**parts)
def process_form(self, **kwargs): def process_form(self, **kwargs):
"""Process the form. Return any message as a result of processing.""" """Process the form. Return any message as a result of processing."""
pass pass
def fill_template(self, *args, **kwargs):
if not 'js' in kwargs:
try:
kwargs['js'] = self.js
except AttributeError:
pass
cfg.log("%%%%%%%%%%% %s" % kwargs)
return u.page_template(*args, **kwargs)
class UserStoreModule: class UserStoreModule:
""" """

View File

@ -62,7 +62,7 @@ class Message():
self.text += "<br />%s" % text self.text += "<br />%s" % text
def page_template(template='login_nav', **kwargs): def render_template(template='login_nav', **kwargs):
for key in ['sidebar_left', 'sidebar_right', 'main', 'js', 'onload', 'nav', for key in ['sidebar_left', 'sidebar_right', 'main', 'js', 'onload', 'nav',
'css', 'title', 'basehref']: 'css', 'title', 'basehref']:
if not key in kwargs: if not key in kwargs: