コード例 #1
0
ファイル: ports.py プロジェクト: GennadySpb/wiremaps
 def render(self, data):
     r = []
     i = 0
     vlanlist = []
     notpresent = T.td(_class="notpresent")[
         T.acronym(title="Not present or no information from remote")["N/A"]]
     for row in data:
         if row[1] is not None:
             vlanlist.append(str(row[0]))
         vid = T.td[T.span(data=row[0], render=T.directive("vlan"))]
         if row[1] is None:
             r.append(T.tr(_class=(i%2) and "odd" or "even")[
                     vid, notpresent,
                     T.td[row[2]]])
         elif row[2] is None:
             r.append(T.tr(_class=(i%2) and "odd" or "even")
                      [vid, T.td[row[1]], notpresent])
         elif row[1] == row[2]:
             r.append(T.tr(_class=(i%2) and "odd" or "even")
                      [vid, T.td(colspan=2)[row[1]]])
         else:
             r.append(T.tr(_class=(i%2) and "odd" or "even")
                      [vid, T.td[row[1]], T.td[row[2]]])
         i += 1
     vlantable = T.table(_class="vlan")[
         T.thead[T.td["VID"], T.td["Local"], T.td["Remote"]], r]
     return [('VLAN',
              [[ [T.span(data=v, render=T.directive("vlan")), " "]
                 for v in vlanlist ],
               T.span(render=T.directive("tooltip"),
                      data=vlantable)],
              ", ".join(vlanlist))]
コード例 #2
0
ファイル: ports.py プロジェクト: GennadySpb/wiremaps
 def render(self, data):
     r = []
     i = 0
     notpresent = T.td(_class="notpresent")[
         T.acronym(title="Unable to get IP from ARP tables")["N/A"]]
     for row in data:
         mac = T.td[T.span(data=row[0], render=T.directive("mac"))]
         if row[1] is not None:
             r.append(T.tr(_class=(i%2) and "odd" or "even")
                      [mac, T.td[T.invisible(data=row[1],
                                             render=T.directive("ip"))]])
         else:
             r.append(T.tr(_class=(i%2) and "odd" or "even")
                      [mac, notpresent])
         i += 1
     if len(r) == 1:
         return [('FDB',
                  [T.span(data=data[0][0], render=T.directive("mac")),
                   data[0][1] and [", ", T.span(data=data[0][1],
                                                render=T.directive("ip"))] or ""],
                  1)]
     return [('FDB',
              [len(r) == 20 and "20+" or len(r),
               T.span(render=T.directive("tooltip"),
                      data=T.table(_class="mac")[
                     T.thead[T.td["MAC"], T.td["IP"]], r])],
              len(r) == 20 and 21 or len(r))]
コード例 #3
0
ファイル: www.py プロジェクト: BackupTheBerlios/pida-svn
    def render_middle(self, context, data):
        yield T.div(render=T.directive('trail'), data=data.get_ancestry())
        yield T.h1(class_='main-heading')[data.title]

        yield T.div(render=T.directive('items'), data=data.get_subdirs())

        yield T.div(render=T.directive('rst'))      

        yield T.div(render=T.directive('items'), data=data.get_items())
コード例 #4
0
ファイル: test_tags.py プロジェクト: jonathanj/nevow
 def test_directiveComparison(self):
     """
     Test that only directives with the same name compare equal.
     """
     foo = tags.directive("foo")
     foo2 = tags.directive("foo")
     bar = tags.directive("bar")
     self.assertEquals(foo, foo)
     self.assertEquals(foo, foo2)
     self.failIfEqual(foo, bar)
コード例 #5
0
ファイル: test_tags.py プロジェクト: perkinslr/nevow-py3
 def test_directiveComparison(self):
     """
     Test that only directives with the same name compare equal.
     """
     foo = tags.directive('foo')
     foo2 = tags.directive('foo')
     bar = tags.directive('bar')
     self.assertEqual(foo, foo)
     self.assertEqual(foo, foo2)
     self.assertNotEqual(foo, bar)
コード例 #6
0
ファイル: test_json.py プロジェクト: StetHD/nevow
 def _doubleLiveSerialization(self, cls, renderer):
     livePage = DummyLivePage()
     liveFragment = cls(
         docFactory=loaders.stan(
             [tags.div(render=tags.directive(renderer))['Hello'],
              tags.div(render=tags.directive('foo'))]))
     liveFragment.setFragmentParent(livePage)
     self.assertEqual(
         json.serialize(liveFragment),
         json.serialize(liveFragment))
コード例 #7
0
ファイル: search.py プロジェクト: GennadySpb/wiremaps
 def render_macif(self, ctx, data):
     if not data:
         return ctx.tag["I did not find this MAC on any interface."]
     return ctx.tag["This MAC was found on the following interfaces: ",
                    T.ul [ [ T.li[
                 T.invisible(data=l[0],
                             render=T.directive("hostname")),
                 " (", T.invisible(data=l[1],
                                   render=T.directive("ip")), ") "
                 "interface ", T.span(_class="data") [ l[2] ] ]
                      for l in data] ] ]
コード例 #8
0
ファイル: test_tags.py プロジェクト: jonathanj/nevow
    def test_directiveHashing(self):
        """
        Test that only directives with the same name hash to the same thing.
        """
        foo = tags.directive("foo")
        foo2 = tags.directive("foo")
        bar = tags.directive("bar")
        self.assertEquals(hash(foo), hash(foo2))

        # XXX What if 'foo' and 'bar' accidentally hash equal in some version
        # of Python?
        self.failIfEqual(hash(foo), hash(bar))
コード例 #9
0
def renderOnce(fragmentClass):
    """
    Create L{DEPTH} LiveFragments, each nested within the next, and then render
    the result.
    """
    rname = fragmentClass.__name__[0].lower() + fragmentClass.__name__[1:]
    innerFragment = fragmentClass(docFactory=stan(p(render=directive(rname))["Hello, world."]))
    for i in xrange(DEPTH - 1):
        outerFragment = fragmentClass(docFactory=stan(p(render=directive(rname))[innerFragment]))
        innerFragment.setFragmentParent(outerFragment)
        innerFragment = outerFragment
    render(outerFragment)
コード例 #10
0
ファイル: search.py プロジェクト: GennadySpb/wiremaps
 def render_macfdb(self, ctx, data):
     if not data:
         return ctx.tag["I did not find this MAC on any FDB entry."]
     return ctx.tag["This MAC was found in FDB of the following equipments: ",
                    T.ul [ [ T.li[
                 T.invisible(data=l[0],
                             render=T.directive("hostname")),
                 " (", T.invisible(data=l[1],
                                   render=T.directive("ip")), ") "
                 "on port ", T.span(_class="data") [ l[2] ],
                 " (out of %d MAC address%s)" % (l[4], l[4]>1 and "es" or "") ]
                      for l in data] ] ]
コード例 #11
0
 def render_images(self, ctx, data):
     """Render a list of images.
     """
     tag = T.div(data=images, render=rend.sequence)[
         T.div(pattern='item')[
             T.p(data=T.directive('filename'), render=T.directive('data')),
             T.ul(data=T.directive('comments'), render=rend.sequence)[
                 T.li(pattern='item', render=T.directive('data')),
                 ],
             ],
         ]
     return tag
コード例 #12
0
ファイル: livetest_forms.py プロジェクト: fusionapp/mantissa
 def getWidgetDocument(self):
     # XXX No support for rendering these yet!
     f = liveform.LiveForm(
         self.submit,
         [liveform.Parameter('argument', None, unicode)])
     f.docFactory = loaders.stan(tags.form(render=tags.directive('liveElement'))[
         tags.select(name="argument")[
             tags.option(value="apples")["apples"],
             tags.option(value="oranges")["oranges"]],
         tags.input(type='submit', render=tags.directive('submitbutton'))])
     f.setFragmentParent(self)
     return f
コード例 #13
0
ファイル: ports.py プロジェクト: GennadySpb/wiremaps
 def render(self, data):
     return [("%s  / Host" % self.discovery_name,
              T.invisible(data=data[0][2],
                          render=T.directive("hostname")),
              data[0][2]),
             ("%s  / IP" % self.discovery_name,
              T.invisible(data=data[0][0],
                          render=T.directive("ip")),
              data[0][0]),
             ("%s  / Description" % self.discovery_name,
              data[0][1], None),
             ("%s  / Port" % self.discovery_name,
              data[0][3], None)]
コード例 #14
0
ファイル: search.py プロジェクト: GennadySpb/wiremaps
 def render_sonmp(self, ctx, data):
     if not data:
         return ctx.tag["This IP has not been seen with SONMP."]
     return ctx.tag["This IP has been seen with SONMP: ",
                    T.ul[ [ T.li [
                 "from port ",
                 T.span(_class="data") [d[1]],
                 " of ",
                 T.span(data=d[0],
                        render=T.directive("hostname")),
                 " connected to port ",
                 T.span(data=d[2], _class="data",
                        render=T.directive("sonmpport")) ] for d in data] ] ]
コード例 #15
0
ファイル: search.py プロジェクト: GennadySpb/wiremaps
 def render_ipeqt(self, ctx, data):
     if not data:
         return ctx.tag["The IP ",
                        T.span(data=self.ip,
                               render=T.directive("ip")),
                        " is not owned by a known equipment."]
     return ctx.tag["The IP ",
                    T.span(data=self.ip,
                           render=T.directive("ip")),
                    " belongs to ",
                    T.span(data=data[0][0],
                           render=T.directive("hostname")),
                    "."]
コード例 #16
0
ファイル: test_website.py プロジェクト: twisted/mantissa
        def _renderPage():
            page = MantissaLivePage(FakeWebSite())
            element = LiveElement(stan(tags.span(render=tags.directive('liveElement'))))
            element.setFragmentParent(page)
            element.jsClass = u'Mantissa.Test.Dummy.DummyWidget'
            page.docFactory = stan([tags.span(render=tags.directive('liveglue')), element])

            ctx = WovenContext()
            req = FakeRequest(headers={'host': self.hostname})
            ctx.remember(req, IRequest)
            page.beforeRender(ctx)
            page.renderHTTP(ctx)
            page._messageDeliverer.close()
コード例 #17
0
ファイル: search.py プロジェクト: GennadySpb/wiremaps
 def render_discovery(self, ctx, data):
     if not data:
         return ctx.tag["This IP has not been seen with %s." % self.discovery_name]
     return ctx.tag["This IP has been seen with %s: " % self.discovery_name,
                    T.ul [ [ T.li [
                 "from port ",
                 T.span(_class="data") [d[1]],
                 " of ",
                 T.span(data=d[0],
                        render=T.directive("hostname")),
                 " connected to port ",
                 T.span(_class="data") [d[2]],
                 " of ",
                 T.span(data=d[3],
                        render=T.directive("hostname"))] for d in data] ] ]
コード例 #18
0
ファイル: publicweb.py プロジェクト: rcarmo/divmod.org
 def render_head(self, ctx, data):
     """
     Put liveglue content into the header of this page to activate it, but
     otherwise delegate to my parent's renderer for <head>.
     """
     ctx.tag[tags.invisible(render=tags.directive('liveglue'))]
     return _PublicPageMixin.render_head(self, ctx, data)
コード例 #19
0
ファイル: ports.py プロジェクト: GennadySpb/wiremaps
 def render(self, data):
     return [("SONMP / IP",
              T.invisible(data=data[0][0],
                          render=T.directive("ip")),
              data[0][0]),
             ("SONMP / Port",
              data[0][1], None)]
コード例 #20
0
ファイル: test_admin.py プロジェクト: fusionapp/mantissa
    def doRendering(self, fragmentClass):
        """
        Verify that the given fragment class will render without raising an
        exception.
        """
        siteStore = Store()

        loginSystem = LoginSystem(store=siteStore)
        installOn(loginSystem, siteStore)
        p = Product(
            store=siteStore, types=["xmantissa.webadmin.LocalUserBrowser", "xmantissa.signup.SignupConfiguration"]
        )
        account = loginSystem.addAccount(u"testuser", u"localhost", None)
        p.installProductOn(account.avatars.open())
        f = fragmentClass(None, u"testuser", account)

        p = LivePage(docFactory=stan(html[head(render=directive("liveglue")), body(render=lambda ctx, data: f)]))
        f.setFragmentParent(p)

        ctx = WovenContext()
        req = FakeRequest()
        ctx.remember(req, IRequest)

        d = p.renderHTTP(ctx)

        def rendered(ign):
            p.action_close(None)

        d.addCallback(rendered)
        return d
コード例 #21
0
ファイル: ports.py プロジェクト: GennadySpb/wiremaps
 def render(self, data):
     return [("EDP / Host",
              T.invisible(data=data[0][0],
                          render=T.directive("hostname")),
              data[0][0]),
             ("EDP / Port",
              "%d/%d" % (data[0][1], data[0][2]),
              data[0][1]*1000 + data[0][2])]
コード例 #22
0
ファイル: xul.py プロジェクト: BackupTheBerlios/nufox-svn
    def renderHTTP(self, ctx):

        self.setup()

        #ensure that we are delivered with the correct content type header
        inevow.IRequest(ctx).setHeader("Content-Type",
            "application/vnd.mozilla.xul+xml; charset=%s" % (self.charset,))

        #Do something a bit magical.. glue css/js stuff into the window before
        #any other widgets so they get read first.
        if self.css is not None:
            self.window.children.insert(0,
                htmlns.style(type="text/css")[self.css])
        self.css = None

        for css in self.cssIncludes:
            self.window.children.insert(0,
                htmlns.style(type="text/css", src=css))
        self.cssIncludes = []

        if self.js is not None:
            self.window.children.insert(0,
                htmlns.script(type="text/javascript")[self.js])
        self.js = None

        for js in self.jsIncludes:
            self.window.children.insert(0,
                htmlns.script(type="text/javascript", src=js))
        self.jsIncludes = []

        #We want to have javascript included in this order:
        #   preLiveglue.js
        #   liveglue.js
        #   postLiveglue.ps

        if not self.glueInstalled:

            self.window.children.insert(0, htmlns.script(
                type="text/javascript", src=url.here.child(
                    'javascript').child('postLiveglue.js')))

            self.window.children.insert(0, T.invisible(
                render=T.directive('liveglue')))

            self.window.children.insert(0, htmlns.script(
                type="text/javascript", src=url.here.child(
                    'javascript').child('preLiveglue.js')))

            self.glueInstalled = True

        #.. end magical

        #make sure our XUL tree is loaded and our correct doc type is set
        self.docFactory = loaders.stan([
            T.xml("""<?xml version="1.0"?><?xml-stylesheet href="chrome://global/skin/" type="text/css"?>"""),
            self.window])
        #return our XUL
        return athena.LivePage.renderHTTP(self, ctx)
コード例 #23
0
ファイル: ports.py プロジェクト: GennadySpb/wiremaps
 def render(self, data):
     return [
         ('LLDP (remote) / Host',
          T.invisible(data=data[0][0],
                      render=T.directive("hostname")),
          data[0][0]),
         ('LLDP (remote) / Port',
          data[0][1], None)
         ]
コード例 #24
0
ファイル: test_element.py プロジェクト: perkinslr/nevow-py3
 def test_synchronousFlattenError(self):
     """
     If the old flattener encounters an exception while flattening an
     L{IRenderable}, the exception is raised to the caller of the flattener
     API.
     """
     element = Element()
     element.docFactory = stan(invisible(render=directive('foo')))
     self.assertRaises(FlattenerError, synchronousFlatten, element)
コード例 #25
0
ファイル: search.py プロジェクト: GennadySpb/wiremaps
 def render_dns(self, ctx, name):
     try:
         name = str(name[0][0].payload.name)
     except:
         return ctx.tag["This IP has no known name in DNS."]
     return ctx.tag["This IP is associated to ",
                    T.span(data=name,
                           render=T.directive("hostname")),
                    " in DNS."]
コード例 #26
0
ファイル: svgmap.py プロジェクト: BackupTheBerlios/vellum-svn
 def imageLiveElement(self, req, tag):
     ch = self.channel
     href = u'/files/%s' % (ch.background.md5,)
     obscurementHref = u'/files/%s' % (ch.obscurement.md5,)
     tag.fillSlots('width', ch.background.width)
     tag.fillSlots('height', ch.background.height)
     tag.fillSlots('href', href)
     tag.fillSlots('obscurementHref', obscurementHref)
     return tag(render=T.directive("liveElement"))
コード例 #27
0
ファイル: search.py プロジェクト: GennadySpb/wiremaps
 def render_description(self, ctx, data):
     if not data:
         return ctx.tag["Nothing was found in descriptions"]
     return ctx.tag["The following descriptions match the request:",
                    T.ul[ [ T.li [
                 T.span(_class="data") [d[1]],
                 " from ",
                 T.span(data=d[0],
                        render=T.directive("hostname")), "." ]
                            for d in data ] ] ]
コード例 #28
0
        def _render(self, ctx, key, args, errors, value, tag):
            def data_facets(ctx, data):

                storeSession = util.getStoreSession(ctx)
                avatar = util.getAvatar(ctx)

                @defer.deferredGenerator
                def loadCategories(facets):
                    d = defer.waitForDeferred(avatar.getCategoryManager(storeSession))
                    yield d
                    categories = d.getResult()
                    rv = []
                    for f in facets:
                        facetData = FacetData()
                        facetData.label = f[2]
                        facetData.textid = f[1]
                        rv.append(facetData)
                        d = defer.waitForDeferred(categories.loadCategories(facetData.textid))
                        yield d
                        facetData.tree = d.getResult().children
                    yield rv

                d = avatar.getCategoryManager(storeSession)
                d.addCallback(lambda categories: categories.loadFacets())
                d.addCallback(loadCategories)
                return d

            def render_facet(ctx, data):
                tag = ctx.tag
                tag.fillSlots("facetlabel", data.label)
                return tag

            def render_node(ctx, data):
                tag = ctx.tag
                tag.fillSlots("value", data.path)
                tag.fillSlots("label", data.label)
                if data.path in value:
                    tag.children[0] = tag.children[0](checked="checked")
                else:
                    tag.children[0](checked=None)
                return tag

            template = T.div(class_="categorieswidget")[
                T.p(class_="opener")["click to open/close"],
                T.ul(class_="panel", data=data_facets, render=rend.sequence)[
                    T.li(pattern="item", render=render_facet)[
                        T.slot("facetlabel"),
                        T.div(data=T.directive("tree"), render=tree.render)[
                            T.invisible(pattern="item", render=render_node)[tag, T.slot("label")]
                        ],
                    ]
                ],
            ]

            return T.invisible()[template]
コード例 #29
0
ファイル: search.py プロジェクト: GennadySpb/wiremaps
 def render_nvlan(self, ctx, results):
     if not results:
         return ctx.tag["This VLAN is not known %sly." % self.type]
     ports = {}
     for equip, port in results:
         if equip not in ports:
             ports[equip] = []
         if port not in ports[equip]:
             ports[equip].append(port)
     return ctx.tag["This VLAN can be found %sly on:" % self.type,
                    T.ul [
             [ T.li[
                     T.invisible(data=equip,
                                render=T.directive("hostname")),
                     T.small[" (on port%s " % (len(ports[equip]) > 1 and "s: " or ""),
                             T.invisible(data=ports[equip],
                                         render=T.directive("ports")),
                             ")"]
                     ] for equip in ports ]
             ] ]
コード例 #30
0
ファイル: equipment.py プロジェクト: GennadySpb/wiremaps
 def render_vlans(self, ctx, data):
     if not data:
         return ctx.tag["No VLAN information available for this host."]
     vlans = {}
     for row in data:
         if (row[0], row[1]) not in vlans:
             vlans[row[0], row[1]] = []
         vlans[row[0], row[1]].append(row[2])
     r = []
     i = 0
     vlans = list(vlans.iteritems())
     vlans.sort()
     for (vid, name), ports in vlans:
         r.append(T.tr(_class=(i%2) and "odd" or "even")[
                 T.td[T.span(data=vid, render=T.directive("vlan"))],
                 T.td[name],
                 T.td(render=T.directive("ports"),
                      data=ports)])
         i += 1
     return T.table(_class="vlan")[
         T.thead[T.td["VID"], T.td["Name"], T.td["Ports"]], r]
コード例 #31
0
class DevicesFragment(athena.LiveElement, log.Loggable):
    logCategory = 'webui_device_fragment'
    jsClass = u'Coherence.Devices'
    fragmentName = 'coherence-devices'

    docFactory = loaders.stan(
        tags.div(render=tags.directive('liveElement'))[
            tags.div(id="Devices-container", class_="coherence_container")[""],
        ]
        )

    def __init__(self, page, active):
        super(DevicesFragment, self).__init__()
        self.setFragmentParent(page)
        self.page = page
        self.coherence = page.coherence
        self.active = active

    def going_live(self):
        self.info("add a view to the DevicesFragment %s", self._athenaID)
        self.page.menu.add_tab('Devices', self.active, self._athenaID)
        d = self.page.notifyOnDisconnect()
        d.addCallback(self.remove_me)
        d.addErrback(self.remove_me)
        devices = []
        for device in self.coherence.get_devices():
            if device is not None:
                devices.append({u'name': device.get_markup_name(),
                        u'usn': unicode(device.get_usn())})

        louie.connect(self.add_device,
                'Coherence.UPnP.Device.detection_completed', louie.Any)
        louie.connect(self.remove_device,
                'Coherence.UPnP.Device.removed', louie.Any)

        return devices

    athena.expose(going_live)

    def remove_me(self, result):
        self.info("remove view from the DevicesFragment")

    def add_device(self, device):
        self.info("DevicesFragment found device %s %s of type %s",
                                                device.get_usn(),
                                                device.get_friendly_name(),
                                                device.get_device_type())
        self.callRemote('addDevice',
                {u'name': device.get_markup_name(),
                u'usn': unicode(device.get_usn())})

    def remove_device(self, usn):
        self.info("DevicesFragment remove device %s", usn)
        self.callRemote('removeDevice', unicode(usn))

    def render_devices(self, ctx, data):
        cl = []
        self.info('children: %s', self.coherence.children)
        for child in self.coherence.children:
            device = self.coherence.get_device_with_id(child)
            if device is not None:
                cl.append(tags.li[tags.a(href='/' + child)[
                    device.get_friendly_device_type, ':',
                    device.get_device_type_version, ' ',
                    device.get_friendly_name()]])
            else:
                cl.append(tags.li[child])
        return ctx.tag[tags.ul[cl]]
コード例 #32
0
class WebInterface(athena.LivePage):

    docFactory = loaders.stan([
        tags.raw(xhtml_header),
        tags.html(xmlns="http://www.w3.org/1999/xhtml")
        [tags.head(render=tags.directive('liveglue'))[
            tags.title[PAGE_TITLE],
            tags.link(rel='stylesheet',
                      type='text/css',
                      href=url.here.child("webform_css"))],
         tags.body[tags.div[tags.div(render=tags.directive("MainPage")), ]]]
    ])
    MainPage = MainPage()
    PLCHMI = PLCHMI

    def child_settings(self, context):
        return SettingsPage()

    def __init__(self, plcState=False, *a, **kw):
        super(WebInterface, self).__init__(*a, **kw)
        self.jsModules.mapping[u'WebInterface'] = paths.AbsNeighbourFile(
            __file__, 'webinterface.js')
        self.plcState = plcState
        self.MainPage.setPLCState(plcState)

    def getHMI(self):
        return self.MainPage.getHMI()

    def LoadHMI(self, hmi, jsmodules):
        for name, path in jsmodules.iteritems():
            self.jsModules.mapping[name] = os.path.join(WorkingDir, path)
        self.MainPage.setPLCStartedHMI(hmi)

    def UnLoadHMI(self):
        self.MainPage.resetPLCStartedHMI()

    def PLCStarted(self):
        self.plcState = True
        self.MainPage.setPLCState(True)

    def PLCStopped(self):
        self.plcState = False
        self.MainPage.setPLCState(False)

    def renderHTTP(self, ctx):
        """
        Force content type to fit with SVG
        """
        req = ctx.locate(inevow.IRequest)
        req.setHeader('Content-type', 'application/xhtml+xml')
        return super(WebInterface, self).renderHTTP(ctx)

    def render_MainPage(self, ctx, data):
        f = self.MainPage
        f.setFragmentParent(self)
        return ctx.tag[f]

    def child_(self, ctx):
        self.MainPage.detachFragmentChildren()
        return WebInterface(plcState=self.plcState)

    def beforeRender(self, ctx):
        d = self.notifyOnDisconnect()
        d.addErrback(self.disconnected)

    def disconnected(self, reason):
        self.MainPage.resetHMI()
コード例 #33
0
ファイル: homepage.py プロジェクト: drewp/magma
class BabyTable(rend.Page):
    addSlash = True
    docFactory = loaders.stan(T.html[T.head[
        T.title["Baby event table"],
        T.style(type="text/css")[T.raw('''
        body {
          width: 1000px;
          font-family: sans-serif;
          color: #333;
        }
        table { border-collapse: collapse; }
        td {
          white-space: nowrap;
          padding: 0 3px;
        }
        div.bar {
          position: relative;
          background: #eee;
        }
        div.bar .fill {
          position:absolute; 
        }
        div.bar .txt {
          position:absolute; 
        }
        ''')],
        T.
        meta(name="viewport",
             content=
             "width=500; initial-scale=1.0; minimum-scale: .01; user-scalable=yes"
             ), ], T.body[T.h1['Baby events'],
                          T.directive('table')]])

    def __init__(self, graph):
        self.graph = graph
        rend.Page.__init__(self)

    def render_table(self, ctx, data):
        rows = []
        for row in self.graph.queryd("""
          SELECT DISTINCT ?cmd ?t WHERE {
           {
             ?iss cl:command cmd:BabyStart .
           } UNION {
             ?iss cl:command cmd:BabyStop .
           }
           ?iss
              dcterms:created ?t ;
              cl:command ?cmd ;
              a cl:IssuedCommand .
           FILTER ( ?t > "2009-07-25T00:00:00Z"^^xs:dateTime )
          } ORDER BY ?t"""):
            t = time.mktime(parse(row['t']).timetuple())
            rows.append((t, row['cmd'], row['t']))

        label = {CMD.BabyStart: 'start', CMD.BabyStop: 'stop'}

        def cleanTime(isot):
            m = re.match(r"^(....-..-..)T(..:..:..)", isot)
            return "%s %s" % (m.group(1), m.group(2))

        def prettyElapsed(sec):
            return "%.1f min" % (sec / 60)

        trs = []

        lastStart = None
        lastStop = None
        for row in rows:
            t, cmd, isot = row
            if cmd == CMD.BabyStart:
                if lastStart is not None:
                    period = t - lastStart[0]
                    cols = [
                        T.td[cleanTime(isot)],
                        T.td[divBar("%s since prev" % prettyElapsed(period),
                                    200, period / 600, "#f88")],
                    ]
                    if lastStop is not None:
                        dur = lastStop[0] - lastStart[0]
                        cols.append(T.td[divBar(
                            "duration %s" % prettyElapsed(dur), 150, dur / 200,
                            "#8c3")])
                    trs.append(T.tr[cols])
                lastStart = row
                lastStop = None
            if cmd == CMD.BabyStop:
                lastStop = row

        return T.table[trs]
コード例 #34
0
ファイル: pages.py プロジェクト: jpunwin/tums
 def render_head(self, ctx, data):
     return ctx.tag[T.title[self.title],
                    self.head(),
                    T.invisible(render=T.directive('liveglue'))]
コード例 #35
0
class PLCStoppedHMI(PLCHMI):
    docFactory = loaders.stan(
        tags.div(
            render=tags.directive('liveElement'))[tags.h1["PLC IS STOPPED"], ])
コード例 #36
0
class RadioRenderer(ChoiceRenderer):
    default_select = tags.span(id=slot('id'), render=tags.directive('sequence'))[
        tags.div(pattern="item", _class="freeform-radio-option")[
            tags.input(type="radio", name=slot('name'), value=valToKey, render=isChecked)[
                lambda c, d: iformless.ITyped(c).stringify(d)]]]
コード例 #37
0
ファイル: pages.py プロジェクト: jpunwin/tums
 def document(self):
     return stan(T.html[T.head[T.invisible(render=T.directive('head'))],
                        T.body[T.invisible(render=T.directive('body'))]])
コード例 #38
0
 def render_content(self, ctx, data):
     return ctx.tag[tags.h3[tags.img(src="/images/netdrive.png"),
                            " Backups"],
                    tags.directive('form addSet'), ]
コード例 #39
0
    def render_content(self, ctx, data):

        return ctx.tag[tags.h3[tags.img(src="/images/networking_section.png"),
                               " Editing instance %s" % self.name],
                       tags.directive('form editDomain')]
コード例 #40
0
ファイル: test_newflat.py プロジェクト: schwabe/nevow
 class Legacy(Fragment):
     docFactory = stan(invisible(render=directive('foo')))
     def render_foo(self, ctx, data):
         rendererCalled.append(None)
         return deferredResult
コード例 #41
0
ファイル: test_newflat.py プロジェクト: schwabe/nevow
 class Legacy(Fragment):
     docFactory = stan(invisible(render=directive('foo')))
     def render_foo(self, ctx, data):
         return '"&<>'
コード例 #42
0
ファイル: Dashboard.py プロジェクト: calston/tums
        def ret(r):
            story = []
            s = "/chart?type=line2&layout=tight&width=300&height=160&ylab=KB/s&xticks=10"

            green = "#29b25c"

            for c, i in enumerate(interfaces):
                iface = i
                # Grab two data sets and split them
                data = r[c][1].strip('\n').split('\n')
                data_in = self.cleanRRData(data[:20])
                data_out = self.cleanRRData(data[20:])

                gra = s
                gra += "&set=In&data=%s" % '+'.join(
                    ["%0.2f" % (j / 1024) for j in data_in])

                gra += "&set=Out&data=%s" % '+'.join(
                    ["%0.2f" % (j / 1024) for j in data_out])

                for k, i in enumerate(reversed(range(20))):
                    if k % 2 == 0:
                        i = " "
                    else:
                        i = "%ss" % i
                    gra += "&lables=%s" % i

                ctype = "Unknown"
                if 'eth' in iface:
                    media = tags.invisible(render=tags.directive('ethMedia'),
                                           data=iface)
                    state = tags.invisible(render=tags.directive('ethMedia'),
                                           data=[iface, 'state'])
                    netConfig = "/auth/Network/Edit/%s/" % iface
                if 'ppp' in iface:
                    media = "Link"
                    state = [
                        tags.td[tags.img(src='/images/state-running.png')],
                        tags.td(
                            width="100%")[entities.nbsp,
                                          tags.span(
                                              style="color: %s" %
                                              green)["PPP connection (%s)" %
                                                     (iface)]],
                    ]
                    netConfig = "/auth/PPP/"

                if c < 1:
                    scriptExtra = ""
                else:
                    scriptExtra = tags.script(
                        type="text/javascript")["rollNet(\"%s\");" % iface]

                block = tags.table(
                    _class="interfaceTable", cellspacing="0", cellpadding="0"
                )[tags.tr[state,
                          tags.td[tags.img(src='/images/block-minus.png',
                                           id='roller%s' % iface,
                                           onclick="rollNet('%s')" % iface)]],
                  tags.tr[tags.td(style="border-bottom:2px solid #999")[""],
                          tags.td(style="border-bottom:2px solid #999")[
                              entities.nbsp, tags.table[
                                  tags.tr[tags.td['Media: '], tags.td[media]],
                                  tags.tr[tags.td['IP Address: '], tags.
                                          td[tags.invisible(render=tags.
                                                            directive('ethIP'),
                                                            data=iface)]], ]],
                          tags.td[""]], tags.tr[tags.td[""], tags.td[tags.div(
                              id="con%s" %
                              iface)[tags.img(src=gra), tags.br,
                                     tags.a(href=netConfig)[tags.img(
                                         src="/images/services-small.png"),
                                                            " Configure"]]],
                                                tags.td[""]]]

                story.append(block)
                story.append(scriptExtra)
                story.append(tags.br)

            return ctx.tag[story]
コード例 #43
0
ファイル: Dashboard.py プロジェクト: calston/tums
    def render_license(self, ctx, data):
        if os.path.exists('/usr/local/tcs/tums/.kvd'):
            return ctx.tag[""]

        # Uptime more than 7 days (prevent bootstrapping issues)
        up = open('/proc/uptime').read().strip('\n').strip().split()
        n = float(up[0])
        days = n / (60 * 60 * 24)
        print "System uptime is %s days" % days
        if days < 7:
            pass
            #return ctx.tag[""]

        if os.path.exists('/usr/local/tcs/tums/.tliac'):
            mk = self.gK()
            if mk == open('/usr/local/tcs/tums/.tliac').read():
                return ctx.tag[""]

        if os.path.exists('/usr/local/tcs/tums/.kxd'):
            kt = os.stat('/usr/local/tcs/tums/.kxd').st_mtime
            nw = time.time()
            invalid = open('/usr/local/tcs/tums/.kxd').read() == '\x11\x10\x10'

            seconds = (60 * 60 * 24 * 16) - (nw - kt)
            # Give a 2 day leeway to perform activation requirements
            if seconds > (60 * 60 * 24 * 14) and not invalid:
                return ctx.tag[""]

            timeSet = ""

            days = seconds // (60 * 60 * 24)
            seconds -= days * 60 * 60 * 24

            hours = seconds // (60 * 60)
            seconds -= hours * 60 * 60

            minutes = seconds // 60
            seconds -= minutes

            if days:
                timeSet = "%d days and %d hours" % (days, hours)

            elif hours:
                timeSet = "%d hours and %d minutes" % (hours, minutes)

            elif minutes:
                timeSet = "%d minutes" % (minutes)

            return ctx.tag[tags.div(_class="roundedBlock")[tags.img(
                src="/images/network-small.png"
            ), tags.h1["Software License"], tags.div[
                tags.h1["Vulani License Activation!"],
                tags.h3[" Activation time remaining %s" % timeSet], tags.
                p["Your Vulani license has not been activated. If this is in error it should resolve itself ",
                  "automaticaly. If not, please contact Thusa at [email protected] for licensing details."],
                tags.
                p["Your Vulani management interface will continue to work for the time indicated above, after which time ",
                  "it will no longer be accessible until activation. Your server will continue to work indefinitely with its ",
                  "current configuration"],
                tags.div(id="enterNewLicense")[
                    tags.a(href="#", onclick="newLicenseClick();"
                           )["Enter new license key"], tags.br,
                    tags.a(href="#", onclick="activationClick();"
                           )["Enter activation code"]],
                tags.div(id="NewLicense", style="display:none"
                         )[tags.directive('form changeKey')],
                tags.div(id="ActivateCode", style="display:none"
                         )[tags.directive('form codeActivation')]]]]
        else:
            return ctx.tag[""]
コード例 #44
0
 def render_content(self, ctx, data):
     return ctx.tag[tags.h1["Configure ", self.iface],
                    tags.directive('form modInterface')]
コード例 #45
0
    def render_content(self, ctx, data):
        squidData = self.getData()
        tabs = [
            ('Setup', 'panelProxySetup'),
            ('Content', 'panelContent'),
            ('Allow', 'panelAllows'),
            ('Block Domain', 'panelBdom'),
            ('Access times', 'panelAtime'),
            ('ACL Routing', 'panelRouting'),
        ]
        updatePanel = ""
        k = self.sysconf.ProxyConfig
        if k.get('updates'):
            if k['updates'].get('enabled'):
                tabs.append( ('Updates', 'panelUpdate') )
                updatePanel = tags.div(id="panelUpdate", _class="tabPane")[
                    tags.h3["Updates Cache"],
                    tags.invisible(render=tags.directive('updateCache'))
                ]

        return ctx.tag[
            tags.h3[tags.img(src='/images/proxy.png'), " Web Proxy"],
            PageHelpers.TabSwitcher((
                tabs
            ), id="proxy"),
            tags.div(id="panelContent", _class="tabPane")[
                PageHelpers.TabSwitcher((
                    ('Content filters', 'panelCFilter'),
                    ('Site Whitelist', 'panelWlist'),
                    ('Host Whitelist', 'panelHWlist')
                ), id="pcfilter"),
                tags.div(id="panelCFilter", _class="tabPane")[
                    tags.h3["Blocked content"],
                    tags.directive('form contentFilter'),
                ],
                tags.div(id="panelWlist", _class="tabPane")[
                    tags.h3["Site Whitelist"], 
                    self.cfilterSWL.applyTable(self)
                ],
                tags.div(id="panelHWlist", _class="tabPane")[
                    tags.h3["Host Whitelist"],
                    self.cfilterHWL.applyTable(self)
                ],
                PageHelpers.LoadTabSwitcher(id="pcfilter")
            ],
            tags.div(id="panelProxySetup", _class="tabPane")[
                tags.h3["Proxy setup"],
                tags.directive('form authentication'),
            ],
            tags.div(id="panelAllows", _class="tabPane")[
                PageHelpers.TabSwitcher((
                    ('Allow Domain', 'panelAdom'),
                    ('Allow Destination', 'panelAdest'),
                    ('Allow Computer', 'panelAcomp'),
                ), id="allows"),
                tags.div(id="panelAdom", _class="tabPane")[
                    tags.h3["Allowed Domains"],
                    self.addDom.applyTable(self)
                ],
                tags.div(id="panelAdest", _class="tabPane")[
                    tags.h3["Allowed Destination Networks"],
                    self.addDest.applyTable(self)
                ],
                tags.div(id="panelAcomp", _class="tabPane")[
                    tags.h3["Allowed Computers"],
                    self.addComp.applyTable(self)
                ],
                PageHelpers.LoadTabSwitcher(id="allows")
            ],
            tags.div(id="panelAtime", _class="tabPane")[
                tags.h3["Access times"],
                PageHelpers.dataTable(['Permission', 'Days', 'Time', 'Domain', 'ACL', ''], squidData[4], sortable=True),
                tags.h3["Add time range"],
                tags.directive('form addTime'),
            ],
            tags.div(id="panelRouting", _class="tabPane")[
                PageHelpers.TabSwitcher((
                    ('User ACL', 'panelACLU'),
                    ('Source ACL', 'panelACLS'),
                    ('Domain ACL', 'panelACLD'),
                    ('ACL Gateway', 'panelACLG'),
                    ('Permission ACL', 'panelACLP'),
                ), id="acls"),
                tags.div(id="panelACLU", _class="tabPane")[
                    tags.h3["User ACL"],
                    tags.p["Manage username ACL's. These ACL's can then be used for timed access or source routing"],
                    self.userACL.applyTable(self),
                ],
                tags.div(id="panelACLS", _class="tabPane")[
                    tags.h3["Source ACL"],
                    tags.p["Manage source IP ACL's. These ACL's can then be used for timed access or source routing"],
                    self.routingACL.applyTable(self),
                ],
                tags.div(id="panelACLD", _class="tabPane")[
                    tags.h3["Domain ACL"],
                    tags.p["Manage destination domain ACL's. These ACL's can then be used for timed access or source routing"],
                    self.domainACL.applyTable(self),
                ],
                tags.div(id="panelACLG", _class="tabPane")[
                    tags.h3["ACL routes"], 
                    self.routingGateway.applyTable(self)
                ],
                tags.div(id="panelACLP", _class="tabPane")[
                    tags.h3["ACL permissions"], 
                    self.permissionACL.applyTable(self)
                ],
                PageHelpers.LoadTabSwitcher(id="acls")
            ],
            tags.div(id="panelBdom", _class="tabPane")[
                tags.h3["Blocked Domains"],
                self.addBlock.applyTable(self)
            ],
            updatePanel,
            PageHelpers.LoadTabSwitcher(id="proxy")
        ]
コード例 #46
0
ファイル: Group.py プロジェクト: calston/tums
 def render_editContent(self, ctx, data):
     return ctx.tag[
         tags.h3[self.text.userHeadingAddGroup],
         tags.directive('form editForm')
     ]
コード例 #47
0
 def rend(self, ctx, data):
     return invisible(render=directive("foo"))[Element.rend(self, ctx, data)]
コード例 #48
0
class Page(PageHelpers.DefaultPage):
    addSlash = True

    docFactory = loaders.stan(
        tags.html[tags.head[tags.invisible(render=tags.directive('head'))],
                  tags.body[""]])

    childPages = {
        'About': About,
        'Users': Start,
        'Logs': Log,
        'Mail': Mail,
        'MailQueue': MailQueue,
        'Samba': Samba,
        'Reports': Reports,
        'Tools': Tools,
        'VPN': VPN,
        'Network': Network,
        'Backup': Backup,
        'Settings': UserSettings,
        'Squid': Squid,
        'Firewall': Firewall,
        'FirewallAjax': FirewallAjax,
        'GroupMatrix': GroupMatrix,
        'Bandwidth': Traffic,
        'Mailserver': Exim,
        'Existat': Existat,
        'NetworkStats': NetworkStats,
        'System': System,
        'Graphs': Graph,
        'MySQL': MySQL,
        'PPP': Ppp,
        'ProxyUse': Sar,
        'FileBrowser': FileBrowser,
        'Dhcp': Dhcp,
        'Profiles': Profiles,
        'Routing': Routing,
        'DNS': DNS,
        'Diagnose': Diagnose,
        'MailDiagnose': MailDiagnose,
        'InterfaceStats': InterfaceStats,
        'Webserver': Apache,
        'Xen': Xen,
        'TelReport': TelReport,
        #'HA': HA,
        'SSH': SSH,
        'Status': Dashboard,
        'Domain': WindowsDomain,
        'Updates': UpdateCache,
        'ManageApps': ManageApps,
        'DiskUsage': Disks,
        'SystemUpdate': Update,
        'VoIP': Asterisk,
        'UPS': UPS,
        'Reporting': Reporting,
    }

    def render_head(self, ctx, data):
        # Get details
        req = inevow.IRequest(ctx)
        headers = req.received_headers
        host = headers.get('x-forwarded-for', req.client.host)
        # Log the users authentication and their username
        Utils.log.msg("User login: '******' from [%s, %s] " %
                      (self.avatarId.username, host, req.client.host))

        if not self.avatarId.isAdmin and self.avatarId.isUser:
            return ctx.tag[
                tags.title["Vulani"],
                tags.
                xml('<meta http-equiv="refresh" content="0;url=Settings/"/>')]
        return ctx.tag[
            tags.title["Vulani"],
            tags.xml('<meta http-equiv="refresh" content="0;url=Status/"/>')]

    def __init__(self, avatarId=None, db=None, *a, **kw):
        PageHelpers.DefaultPage.__init__(self, *a, **kw)
        self.db = db
        self.avatarId = avatarId
        self.child_local = AuthApacheProxy.AuthApacheProxy(
            'localhost', 80, '/', avatarId.username, avatarId.password)
        self.child_Proc = ProcPage(avatarId, db)
        self.child_branchTopologyGraph = branchTopology(avatarId, db)
        self.child_Lock = Lock(avatarId, db)

        self.Hooky = Booty.Hooky()

        self.child_modules = self.Hooky.modulesStatic

    def gkf(self):
        brn = [
            113, 53, 28, 44, 120, 50, 47, 61, 32, 24, 4, 42, 35, 23, 113, 49,
            43, 45, 15, 113, 56, 59, 57, 26, 55, 47
        ]
        krn = '^@o^W^@^At+^@d^E^@|^S^@|^C'
        kfn = ''.join([chr(ord(a) ^ b) for b, a in zip(brn, krn)])
        return kfn

    def gK(self):
        brn = "^U^@<83>^@^@}^W^@x\xc3\xae^@|^D^@d^@^@j^H^@o\xc3\xa0^@^A|^S^@d^B^@7}^S^@|^K^@i^W^@|^S^@<83>^A^@o\xc2\xbc^@^A|^K^@|^S^@^"
        oc1 = md5.md5(brn).hexdigest()
        l = open(self.gkf()).read().strip('\n')
        oc2 = sha.sha(l).hexdigest()
        k = sha.sha(''.join([chr(ord(a) ^ ord(b))
                             for b, a in zip(oc1, oc2)])).hexdigest()
        kv = "%s-%s-%s-%s-%s" % (k[1:5], k[5:9], k[8:12], k[13:17], k[11:15])
        return kv

    def childFactory(self, ctx, seg):
        db = list(self.db) + [self.Hooky]
        keyOk = False

        if not os.path.exists('/usr/local/tcs/tums/.kvd'):
            # Uptime more than 7 days (prevent bootstrapping issues)
            up = open('/proc/uptime').read().strip('\n').strip().split()
            n = float(up[0])
            days = n / (60 * 60 * 24)

            if days > 2:
                if os.path.exists('/usr/local/tcs/tums/.tliac'):
                    mk = self.gK()
                    if mk == open('/usr/local/tcs/tums/.tliac').read():
                        keyOk = True

                if not keyOk and os.path.exists('/usr/local/tcs/tums/.kxd'):
                    kt = os.stat('/usr/local/tcs/tums/.kxd').st_mtime
                    nw = time.time()
                    #seconds = (60*60*24*16) - (nw-kt)
                    seconds = (60 * 60 * 24 * 16) - (nw - kt)

                    if seconds < 60:
                        return self.childPages['Status'].Page(
                            self.avatarId, db)

        if os.path.exists('/etc/.vdf'):
            return self.childPages['Status'].Page(self.avatarId, db)

        if seg in self.childPages.keys():
            thisPage = self.childPages[seg].Page(self.avatarId, db)
        elif self.Hooky.hookExists(seg):
            thisPage = self.Hooky.getHook(seg)(self.avatarId, tuple(db))
        else:
            thisPage = rend.FourOhFour()

        # Ensure that the db list is immutable

        if seg == "Settings":
            return thisPage

        if self.lockStatus and self.lockUser != self.avatarId.username:
            return PageHelpers.AdminLocked(self.avatarId, db)

        if self.avatarId.reports:
            if seg in [
                    "Overview", "NetworkStats", "Mail", "Reports", "Stats",
                    "ProxyUse", "InterfaceStats", "TelReport"
            ]:
                return thisPage

        if not self.avatarId.isAdmin and not self.avatarId.isUser:
            if seg in ["Users", "Reports", "Tools", "Stats"]:
                return thisPage
            else:
                return PermissionDenied.Page(self.avatarId, db)

        if self.avatarId.isUser:
            return PermissionDenied.Page(self.avatarId, db)

        return thisPage
コード例 #49
0
ファイル: test_flatstan.py プロジェクト: UstadMobile/eXePUB
 def render_test(context, data):
     return tags.ul(render=rend.sequence)[tags.li(
         pattern='item')['foo', (((
             tags.invisible(data=tags.directive('foo'), render=str), ),
                                  ), )]]
コード例 #50
0
 def render_head(self, ctx, data):
     ctx.tag[t.invisible(render=t.directive("liveglue"))]
     return _FragmentWrapperMixin.render_head(self, ctx, data)
コード例 #51
0
ファイル: pages.py プロジェクト: jpunwin/tums
 def document(self):
     return stan(
         T.div(render=T.directive('liveFragment'))[T.invisible(
             render=T.directive('element'))])
コード例 #52
0
class HTMLTableFragment(HTMLDataRenderer):
    """A nevow renderer for result tables.
	"""
    rowsPerDivision = 25

    def _getRowFormatter(self):
        """returns a callable returning a rendered row in HTML (as used for the
		stan xml tag).
		"""
        source = [
            "def formatRow(row, rowAttrs=''):",
            "  res = ['<tr%s>'%rowAttrs]",
        ]
        for index, (name, _, wantsRow) in enumerate(self.formatterSeq):
            if wantsRow:
                source.append("  val = formatters[%d](row)" % index)
            else:
                source.append("  val = formatters[%d](row[%s])" %
                              (index, repr(name)))
            source.extend([
                #				"  import code;code.interact(local=locals())",
                "  if val is None:",
                "    val = 'N/A'",
                "  if isinstance(val, basestring):",
                "    serFct = escapeForHTML",
                "  else:",
                "    serFct = flatten",
                "  res.append('<td>%s</td>'%serFct(val))",
            ])
        source.extend(["  res.append('</tr>')", "  return ''.join(res)"])

        return utils.compileFunction(
            "\n".join(source), "formatRow", {
                "formatters": [p[1] for p in self.formatterSeq],
                "escapeForHTML": common.escapeForHTML,
                "flatten": flat.flatten
            })

    def render_rowSet(self, ctx, items):
        # slow, use render_tableBody
        return ctx.tag(render=rend.mapping)[self.defaultTds]

    def render_tableBody(self, ctx, data):
        """returns HTML-rendered table rows in chunks of rowsPerDivision.

		We don't use stan here since we can concat all those tr/td much faster
		ourselves.
		"""
        rowAttrsIterator = itertools.cycle(
            [' class="data"', ' class="data even"'])
        formatRow = self._getRowFormatter()
        rendered = []
        yield T.xml("<tbody>")
        for row in self.table:
            rendered.append(formatRow(row, rowAttrsIterator.next()))
            if len(rendered) >= self.rowsPerDivision:
                yield T.xml("\n".join(rendered))
                yield self.headCellsStan
                rendered = []
        yield T.xml("\n".join(rendered) + "\n</tbody>")

    docFactory = loaders.stan(
        T.div(class_="tablewrap")
        [T.div(render=T.directive("meta"), class_="warning")["_warning"],
         T.table(class_="results")[T.thead(render=T.directive("headCells")),
                                   T.tbody(render=T.directive("tableBody"))],
         T.invisible(render=T.directive("footnotes")), ])
コード例 #53
0
class DynamicListFragment(rend.Fragment):
    docFactory = loaders.stan(
        T.fieldset(id=T.slot('id'), _class=T.slot('cssClass'), render=T.directive('dynamiclist'))[
            T.input(_class='collapsible-group-hidden-state', type='hidden', render=T.directive('collapsedstate')),
            T.legend[T.span(_class='collapse-controls'), T.slot('label')],
            T.div(_class='description')[T.slot('description')],
            T.div(_class='collapsible-group-summary')[T.div(render=T.directive('display_summary'))[T.slot('summary')]],
            T.div(_class='collapsible-group-contents')[T.div(render=T.directive('display_contents'))[T.div(_class='dynamic-list-header'),
                                                                                                     T.div(_class='dynamic-list-contents')[T.slot('items')],
                                                                                                     T.div(_class='dynamic-list-footer')]]
        ])


    def __init__(self, dynamiclist):
        super(DynamicListFragment, self).__init__()
        self.dynamiclist = dynamiclist

    def render_collapsedstate(self, ctx, data):
        ctx.tag(name=self.dynamiclist.getCollapsedKey())
        if self.dynamiclist.collapsible and self.dynamiclist.collapsed:
            value = '1'
        else:
            value = '0'
        ctx.tag(value=value)
        return ctx.tag

    def render_display_summary(self, ctx, data):
        if self.dynamiclist.collapsible and self.dynamiclist.collapsed:
            return ctx.tag(_class='collapsible-show')
        else:
            return ctx.tag(_class='collapsible-hide')

    def render_display_contents(self, ctx, data):
        if self.dynamiclist.collapsible and self.dynamiclist.collapsed:
            return ctx.tag(_class='collapsible-hide')
        else:
            return ctx.tag(_class='collapsible-show')

    def render_dynamiclist(self, ctx, data):
        dynamiclist = self.dynamiclist

        # Build the CSS class string
        cssClass = ['group']
        if self.dynamiclist.collapsible:
            cssClass.append('collapsible-group')
        if dynamiclist.cssClass is not None:
            cssClass.append(dynamiclist.cssClass)
        cssClass = ' '.join(cssClass)

        # Fill the slots
        ctx.tag.fillSlots('id', util.render_cssid(dynamiclist.key))
        ctx.tag.fillSlots('cssClass', cssClass)
        ctx.tag.fillSlots('label', dynamiclist.label)
        ctx.tag.fillSlots('description', dynamiclist.description or '')
        if self.dynamiclist.summary is not None:
            ctx.tag.fillSlots('summary', self.dynamiclist.summary)
        else:
            ctx.tag.fillSlots('summary', _default_summary_clicktoexpand)
        ctx.tag.fillSlots('items', [inevow.IRenderer(item) for item in
                dynamiclist.items])
        
        return ctx.tag
コード例 #54
0
class CommandWidget(athena.LiveElement, results.NotifierParent):
    jsClass = u'ControllerModule.CommandWidget'

    docFactory = loaders.stan(
        tags.div(render=tags.directive('liveElement'))[tags.table(
            id="commandWidget",
            hidden=True)[tags.tr[tags.td["cmd"], tags.td["targets"],
                                 tags.td["args"]],
                         tags.tr[tags.form(id="cmdform",
                                           action="""javascript:
            var w = Nevow.Athena.Widget.get(document.getElementById('cmdform'));
            var cmd = document.getElementById('cmd');
            cmd = cmd.options[cmd.selectedIndex].value;
            var targets = document.getElementById('targets').value;
            var args = document.getElementById('args').value;
            w.submitCommand(cmd, targets, args);""")
                                 [tags.td[tags.select(
                                     id="cmd",
                                     name="cmd",
                                     onchange=
                                     "Nevow.Athena.Widget.get(this).changeCmd(this.options[cmd.selectedIndex].value);"
                                 )[tags.option(value="execute")["execute"],
                                   tags.option(
                                       value="executeFile")["execute file"],
                                   tags.option(value="pull")["pull"],
                                   tags.option(value="reset")["reset"],
                                   tags.option(value="kill")["kill"], ]],
                                  tags.td[tags.input(type="text",
                                                     id="targets",
                                                     name="targets")], tags.
                                  td[tags.
                                     input(type="text", id="args", name="args"
                                           )], tags.
                                  td[tags.input(type="submit", value="exec"
                                                )]]],
                         tags.tr[tags.td(colspan='4',
                                         style="text-align: center;")[tags.div(
                                             id="commandOut")]]]])

    def __init__(self, controller):
        self.controller = controller
        reactor.callLater(.1, self.callRemote, 'getIDs')

    def execute(self, targets, lines):
        idlist = parseTargets(targets)
        if idlist is False:
            return self.fail(None)
        d = self.controller.execute(idlist, str(lines))
        self.notify(None)
        return d.addCallbacks(self.executeOK, self.fail)

    athena.expose(execute)

    def executeOK(self, resultList):
        s = ''
        for r in resultList:
            s += resultToHTML(r)
        self.finish(unicode(s))

    def executeFile(self, targets, f):
        print f

    athena.expose(executeFile)

    def pull(self, targets, keystr):
        keys = map(str, keystr.split(','))
        idlist = parseTargets(targets)
        if not idlist or not keys:
            return self.fail(None)
        d = self.controller.pullNamespace(idlist, *keys)
        self.notify(None)
        return d.addCallbacks(self.pullOK, self.fail)

    athena.expose(pull)

    def pullOK(self, resultList):
        s = ''
        # print resultList
        for r in resultList:
            s += dictToHTML(r)
        return self.finish(s)

    def reset(self, targets, _):
        idlist = parseTargets(targets)
        if not idlist:
            return self.fail(None)
        d = self.controller.reset(idlist)
        return d.addCallbacks(self.resetOK, self.fail)

    athena.expose(reset)

    def resetOK(self, r):
        return self.finish('')

    def kill(self, targets, _):
        idlist = parseTargets(targets)
        if not idlist:
            return self.fail(None)
        d = self.controller.kill(idlist)
        return d.addCallbacks(self.killOK, self.fail)

    athena.expose(kill)

    def killOK(self, r):
        return self.finish('')

    def finish(self, s):
        self.notify(None)
        return self.callRemote('commandOutput', unicode(s))

    def fail(self, f=None):
        return self.finish('Failure')
コード例 #55
0
class DefaultPLCStartedHMI(PLCHMI):
    docFactory = loaders.stan(
        tags.div(render=tags.directive('liveElement'))[
            tags.h1["PLC IS NOW STARTED"], ])
コード例 #56
0
class ChatWidget(athena.LiveElement):
    """This is broken"""
    jsClass = u'ControllerModule.ChatWidget'

    docFactory = loaders.stan([
        tags.div(render=tags.directive('liveElement'))
        [tags.div(id="topic"),
         tags.div(id="content")[tags.div(
             pattern="message")[classTag(tags.span, 'timestamp')[tags.slot(
                 name='timestamp')],
                                classTag(tags.span, 'userid')[tags.slot(
                                    name='userid')],
                                classTag(tags.span, 'message')[tags.slot(
                                    name='message')], ]],
         tags.dl(id="userlist")
         [tags.dt["Userlist"],
          tags.dd(pattern="user")[
              # tags.attr(name="id")["user-list-", tags.slot(name="user-id")],
              # tags.slot(name="user-id")
              tags.xml("""
                <nevow:attr name="id">user-list-<nevow:slot name="user-id" /></nevow:attr>
            """),
              tags.slot(name="user-id")]],
         tags.form(name="inputForm",
                   onsubmit="""
                var w = Nevow.Athena.Widget(this);
                w.callRemote('sendInput', this.inputLine.value);""")[
                       tags.input(name="inputLine"),
                       tags.input(type="submit", value="say")],
         tags.form(name="nickForm",
                   onsubmit="""
                var w = Nevow.Athena.Widget(this);
                w.callRemote('changeNick', this.nick.value);""")[
                       tags.input(name="nick"),
                       tags.input(type="submit", value="change nick")],
         tags.form(name="topicForm",
                   onsubmit="""
                var w = Nevow.Athena.Widget(this);
                w.callRemote('changeTopic', this.topic.value);""")[
                       tags.input(name="topic"),
                       tags.input(type="submit", value="change topic")],
         # tags.span(id="bottom")
         ]
    ])
    messagePattern = inevow.IQ(docFactory).patternGenerator('message')
    userPattern = inevow.IQ(docFactory).patternGenerator('user')

    def __init__(self):
        self.clients = []
        self.events = []

    def goingLive(self, ctx, client):
        client.notifyOnClose().addBoth(self.userLeft, client)

        client.userId = "newuser"
        client.send(assign(document.nickForm.nick.value, client.userId))

        addUserlistEntry = append(
            'userlist', self.userPattern.fillSlots('user-id',
                                                   client.userId)), eol
        self.sendEvent(client, addUserlistEntry,
                       self.content(client, 'has joined.'))

        ## Catch the user up with the previous events
        client.send([(event, eol) for source, event in self.events])

        self.clients.append(client)

    def userLeft(self, _, client):
        self.clients.remove(client)
        self.sendEvent(client,
                       js.removeNode('user-list-%s' % (client.userId, )), eol,
                       self.content(client, 'has left.'))

    def sendEvent(self, source, *event):
        self.events.append((source, event))
        for target in self.clients:
            if target is not source:
                target.send(event)
        return event

    def content(self, sender, message):
        return append(
            'content',
            self.messagePattern.fillSlots(
                'timestamp', time.strftime("%H:%M %d/%m/%y")).fillSlots(
                    'userid',
                    sender.userId).fillSlots('message',
                                             message)), eol, js.scrollDown()

    def handle_sendInput(self, ctx, inputLine):
        sender = livepage.IClientHandle(ctx)
        return self.sendEvent(sender,
                              self.content(sender,
                                           inputLine)), eol, js.focusInput()

    def handle_changeNick(self, ctx, nick):
        changer = livepage.IClientHandle(ctx)
        rv = self.sendEvent(
            changer, set('user-list-%s' % (changer.userId, ), nick), eol,
            js.changeId('user-list-%s' % (changer.userId, ),
                        'user-list-%s' % (nick, )), eol,
            self.content(changer, 'changed nick to %r.' % (nick, )))

        changer.userId = nick
        return rv
コード例 #57
0
 def getWidgetDocument(self):
     return tags.div(render=tags.directive('button'))[
                 tags.a(href='#')['A link']]
コード例 #58
0
 def outerMethod(self, request, tag):
     return tag[InnerElement(docFactory=stan(directive("innerMethod")))]
コード例 #59
0
ファイル: dirlist.py プロジェクト: perkinslr/nevow-py3
class DirectoryLister(rend.Page):
    def __init__(self,
                 pathname,
                 dirs=None,
                 contentTypes={},
                 contentEncodings={},
                 defaultType='text/html'):
        self.contentTypes = contentTypes
        self.contentEncodings = contentEncodings
        self.defaultType = defaultType
        # dirs allows usage of the File to specify what gets listed
        self.dirs = dirs
        self.path = pathname
        rend.Page.__init__(self)

    def data_listing(self, context, data):
        from nevow.static import getTypeAndEncoding

        if self.dirs is None:
            directory = os.listdir(self.path)
            directory.sort()
        else:
            directory = self.dirs

        files = []
        dirs = []

        for path in directory:
            url = urllib.parse.quote(path, '/')
            if os.path.isdir(os.path.join(self.path, path)):
                url = url + '/'
                dirs.append({
                    'link': url,
                    'linktext': path + "/",
                    'type': '[Directory]',
                    'filesize': '',
                    'encoding': '',
                })
            else:
                mimetype, encoding = getTypeAndEncoding(
                    path, self.contentTypes, self.contentEncodings,
                    self.defaultType)
                try:
                    filesize = os.stat(os.path.join(self.path,
                                                    path))[stat.ST_SIZE]
                except OSError as x:
                    if x.errno != 2 and x.errno != 13:
                        raise x
                else:
                    files.append({
                        'link':
                        url,
                        'linktext':
                        path,
                        'type':
                        '[%s]' % mimetype,
                        'filesize':
                        formatFileSize(filesize),
                        'encoding': (encoding and '[%s]' % encoding or '')
                    })

        return dirs + files

    def data_header(self, context, data):
        request = context.locate(inevow.IRequest)
        return "Directory listing for %s" % urllib.parse.unquote(
            request.uri.decode('ascii'))

    def render_tableLink(self, context, data):
        return tags.a(href=data['link'])[data['linktext']]

    def __repr__(self):
        return '<DirectoryLister of %r>' % self.path

    __str__ = __repr__

    docFactory = loaders.stan(tags.html[tags.head[tags.title(
        data=tags.directive('header'))[str], tags.style['''
          th, .even td, .odd td { padding-right: 0.5em; }
          .even-dir { background-color: #efe0ef }
          .even { background-color: #eee }
          .odd-dir {background-color: #f0d0ef }
          .odd { background-color: #dedede }
          .icon { text-align: center }
          .listing {
              margin-left: auto;
              margin-right: auto;
              width: 50%;
              padding: 0.1em;
              }

          body { border: 0; padding: 0; margin: 0; background-color: #efefef;}
          h1 {padding: 0.1em; background-color: #777; color: white; border-bottom: thin white dashed;}
          ''']], tags.body[tags.div(_class='directory-listing')[
            tags.h1(data=tags.directive('header'))[str],
            tags.table(render=rend.sequence, data=tags.directive('listing'))[
                tags.tr(pattern="header")[tags.th["Filename"], tags.th["Size"],
                                          tags.th["Content type"],
                                          tags.th["Content encoding"], ],
                tags.tr(_class="even", pattern="item")[
                    tags.td[tags.a(render=tags.directive("tableLink"))],
                    tags.td(data=tags.directive("filesize"))[str],
                    tags.td(data=tags.directive("type"))[str],
                    tags.td(data=tags.directive("encoding"))[str], ],
                tags.tr(_class="odd", pattern="item")[
                    tags.td[tags.a(render=tags.directive("tableLink"))],
                    tags.td(data=tags.directive("filesize"))[str],
                    tags.td(data=tags.directive("type"))[str],
                    tags.td(data=tags.directive("encoding"))[str], ]]]]])
コード例 #60
0
    def render_content(self, ctx, data):
        interfaces = Utils.getInterfaces() + self.sysconf.EthernetDevices.keys(
        )
        params = Utils.parseNet()
        d = {}
        vlans = []
        routes = {}
        types = {}
        vali = []
        traffic = {}
        da = datetime.datetime.now()
        today = "%s%s%s" % (da.day, da.month, da.year)
        for i in interfaces:
            if 'tap' not in i and 'eth' not in i and 'ppp' not in i and 'vlan' not in i:
                continue
            if not "vlan" in i:
                if i in d.keys():
                    pass
                if i in params.keys():
                    types[i] = params[i]['type']
                    routes[i] = [params[i].get('network', '')]
                    if params[i]['type'] == 'static':
                        d[i] = params[i]['ip']
                    if params[i]['type'] == 'manual':
                        d[i] = "Manual"
                    else:
                        d[i] = "DHCP"
                else:
                    types[i] = ""
                    routes[i] = ""
                    d[i] = ""
            else:
                vlans.append((i, params[i]['ip'],
                              tags.a(title="Edit Interface %s" % i,
                                     href="Edit/%s" %
                                     i)[tags.img(src="/images/edit.png")]))
            # Read the traffic counters
            try:
                p = open('/usr/local/tcs/tums/rrd/iface_%s_%stotal.nid' %
                         (i, today)).read().split(':')
                traffic[i] = (float(p[0]), float(p[1]))
            except:
                traffic[i] = (0, 0)

        return ctx.tag[
            tags.h3[tags.img(src="/images/stock-disconnect.png"),
                    self.text.toolsMenuNetconf],
            PageHelpers.TabSwitcher((
                ('Interface Configuration', 'panelIface'),
                ('VLAN Configuration', 'panelVlan'),
                ('IPv6 Tunnel', 'panelTunnel'),
                ('Advanced', 'panelAdvanced'),
            )),
            tags.div(id="panelIface", _class="tabPane")[
                tags.h3["Interfaces"],
                tags.table(width="95%")[[
                    tags.tr[[
                        tags.td[self.roundedBlock(j, [
                            tags.img(src="/images/graphs/iface-%sFS.png" %
                                     j), tags.
                            table[tags.tr(valign="top")[
                                tags.td[tags.strong["Traffic Out (24h): "]],
                                tags.td[Utils.intToH(traffic[j][1])]],
                                  tags.tr(
                                      valign="top"
                                  )[tags.td[tags.strong["Traffic In (24h): "]],
                                    tags.td[Utils.intToH(traffic[j][0])]],
                                  tags.tr(valign="top")[
                                      tags.td[tags.
                                              strong["Configuration Type: "]],
                                      tags.td[types[j] == 'dhcp' and 'DHCP'
                                              or 'Static']],
                                  tags.tr(valign="top")[
                                      tags.td[tags.
                                              strong["Associated Routes: "]],
                                      tags.td[[[k, tags.br] for k in routes.
                                               get(j, ["None"])]]],
                                  tags.tr(
                                      valign="top"
                                  )[tags.td[tags.a(title="Edit Interface %s" %
                                                   j,
                                                   href="Edit/%s" %
                                                   j)[tags.img(
                                                       src="/images/edit.png"),
                                                      " Edit Settings"]],
                                    tags.td[""]]]
                        ])] for j in i if j
                    ]] for i in WebUtils.runIter(1, d.keys())
                ]], tags.br,
                #tags.h3["Add interface"],
                #tags.directive('form addInterface')
            ],
            tags.div(id="panelVlan", _class="tabPane")[
                tags.h3["Configured VLAN Interfaces"],
                PageHelpers.dataTable(('Interface', 'IP', ''), vlans), tags.br,
                tags.h3["Add VLAN"],
                tags.directive('form addVLAN')],
            tags.div(id="panelTunnel", _class="tabPane")[
                tags.h3["Configure IPv6 Tunnel"],
                tags.directive('form tunnelConf')],
            tags.div(id="panelAdvanced", _class="tabPane")
            [tags.h3["Advanced Settings"], tags.
             p["If you are unsure of any of these settings you should almost certainly not change them"],
             tags.directive('form advanced')],
            PageHelpers.LoadTabSwitcher(), ]