Ejemplo n.º 1
0
 def render_content(self, ctx, data):
     rules = self.rules.read()
     classes = self.classes.read()
     print rules
     return ctx.tag[
         Tools.Page.sideMenu(Tools.Page(None, self.db), ctx, data),
         tags.div(id="rightBlockIFrame")[tags.h2[tags.img(
             src="/images/firewall.png"), " Bandwidth Management"], [[
                 tags.fieldset[
                     tags.legend[r[6]], tags.h3["Class Details"],
                     tags.table(cellspacing=0, _class='listing')[tags.thead(
                         background="/images/gradMB.png")[tags.tr[
                             tags.th["Interface"], tags.th["Base Rate"],
                             tags.th["Maximum Rate"],
                             tags.th["Priority"]], ], tags.tbody[
                                 tags.tr[tags.td[r[0]], tags.td[r[2]],
                                         tags.td[r[3]], tags.td[r[4]]], ]],
                     tags.h3["Rules"],
                     tags.table(cellspacing=0, _class='listing')[tags.thead(
                         background="/images/gradMB.png")[tags.tr[
                             tags.th["Source IP"],
                             tags.th["Destination IP"], tags.th["Protocol"],
                             tags.th["Source Port"],
                             tags.th["Destination Port"]], ], tags.tbody[[
                                 tags.tr[tags.td[t[0] or "??"],
                                         tags.td[t[1] or "??"],
                                         tags.td[t[2] or "Any"],
                                         tags.td[t[3] or "Any"],
                                         tags.td[t[4] or "Any"], ]
                                 for t in rules.get(r[1], [])
                             ]]]], tags.br
             ] for r in classes], ]]
Ejemplo n.º 2
0
    def processTable(t):
        if len(t) < 1:
            return

        # If list of lists
        if type(t[0]) == type([]):
            return T.table(cellspacing="3", cellpadding="4") [ map(lambda x: processTR(x), t) ]
        else:
            return T.table(cellspacing="3", cellpadding="4") [ processTR(t) ]
Ejemplo n.º 3
0
    def processTable(t):
        if len(t) < 1:
            return

        # If list of lists
        if type(t[0]) == type([]):
            return T.table(cellspacing="3", cellpadding="4") [ map(lambda x: processTR(x), t) ]
        else:
            return T.table(cellspacing="3", cellpadding="4") [ processTR(t) ]
Ejemplo n.º 4
0
 def __init__(self, other=None):
     super().__init__()
     self.other = other
     self.header = tags.thead()
     self.body = tags.tbody(border='1px solid black')
     self.tag = tags.table(border='1 px solid black')[self.header, self.body]
     self.functions = [self.setStyle]
Ejemplo n.º 5
0
    def render_content(self, ctx, data):
        """ Function is deffered to make less blocking on system calls"""

        if not self.avatarId.isAdmin:
            return ctx.tag[""]

        # Fetch running profile
        thisProfile = Utils.currentProfile()

        runningProfile = Utils.runningProfile()[0]

        if thisProfile[0] != runningProfile:
            thisProfile = [
                thisProfile[0], " [",
                tags.a(href=url.root.child("Profiles").child("switch").child(
                    thisProfile[1]))["Activate"]
            ], "]"
        else:
            thisProfile = thisProfile[0]

        return ctx.tag[tags.table(
            width="100%",
            cellspacing="10")[tags.tr[tags.td(colspan=2)[tags.div(
                id="ProfileBlock")[tags.div(_class="roundedBlock")[
                    tags.h1["Profile"],
                    tags.div(id="123")["Current profile: ", thisProfile,
                                       tags.br, "Running profile: ",
                                       runningProfile, tags.br,
                                       tags.directive('form selectProfile'),
                                       tags.a(href=url.root.child("Profiles")
                                              )["Manage Profiles"]]], ], ]],
                              tags.tr[tags.invisible(
                                  render=tags.directive('thisFragment'))]]]
Ejemplo n.º 6
0
    def render_menu(self, ctx, data):
        request = inevow.IRequest(ctx)
        username = request.getUser()

        ret = tags.table(border=0, cellspacing=3, cellpadding=3)
        row = tags.tr(valign="middle")
        row[tags.td(_class="menuentry", width="150", align="center",
                    onclick="self.location='/account/'",
                    onmouseover="this.className='menuentrypressed';",
                    onmouseout="this.className='menuentry';")
            [tags.a(_class="menuentry", href="/account/")["Account"]]]

        if config.admins.count(username) > 0:
            row[tags.td(_class="menuentry", width="150", align="center",
                        onclick="self.location='/status/'",
                        onmouseover="this.className='menuentrypressed';",
                        onmouseout="this.className='menuentry';")
                [tags.a(_class="menuentry", href="/status/")["Status"]]]
            row[tags.td(_class="menuentry", width="150", align="center",
                        onclick="self.location='/config/'",
                        onmouseover="this.className='menuentrypressed';",
                        onmouseout="this.className='menuentry';")
                [tags.a(_class="menuentry", href="/config/")["Configuration"]]]
            row[tags.td(_class="menuentry", width="150", align="center",
                        onclick="self.location='/controls/'",
                        onmouseover="this.className='menuentrypressed';",
                        onmouseout="this.className='menuentry';")
                [tags.a(_class="menuentry", href="/controls/")["Controls"]]]

        return ret
Ejemplo n.º 7
0
 def renderTable(result):
     resCopy = [i for i in result]
     return ctx.tag[
         tags.h2["Shorewall Rules"],
         tags.table(cellspacing=0)[tags.thead[tags.tr[
             tags.th["Priority"], tags.th["Action"], tags.th["Source"],
             tags.th["Destination"], tags.th["Protocol"],
             tags.th["Port"], tags.th["Comment"],
             tags.th[""]]], tags.tbody[[
                 tags.tr[tags.td[tags.a(
                     href=url.root.child("swapShorerule").
                     child(self.machineID).child(i[0]).
                     child(resCopy[1 + loc -
                                   len(resCopy)][0]))["Down"], "|",
                                 tags.
                                 a(href=url.root.child("swapShorerule").
                                   child(self.machineID).child(i[0]).
                                   child(resCopy[loc - 1][0]))["Up"]],
                         tags.td[i[2]], tags.td[i[3]], tags.td[i[4]],
                         tags.td[i[5]], tags.td[i[6]], tags.td[i[10]],
                         tags.td[tags.a(
                             href=url.root.child("deleteShorerule").
                             child(self.machineID).child(i[0])
                         )[tags.img(src="/images/delete.png")]]]
                 for loc, i in enumerate(resCopy)
             ]]],
         tags.a(href=url.root.child("updateShorewall").
                child(self.machineID))["Send to client"]]
Ejemplo n.º 8
0
def dataTable(headings, content, sortable = False, tabid=None):
    """ Produces a tabular listing which is either sortable or not. Sortable expects headings to be a 
        list of tuples, but if it is not a list of tuples the 'string' type will be assumed for every cell """
    if sortable:
        if isinstance(headings[0], tuple):
            header = [ tags.th(colformat=j)[i] for j,i in headings ]
        else:
            header = [ tags.th(colformat='istr')[i] for i in headings ]
        tclass = 'sortable'
    else:
        header = [ tags.th[i] for i in headings ]
        tclass = 'listing'

    if not content: 
        rows = tags.tr[ tags.td(colspan=len(headings))[tags.em["No entries."]]]
    else:
        rows = [tags.tr[ [tags.td[col] for col in row] ]
        for row in content]

    return tags.table(id = tabid, cellspacing=0,  _class=tclass)[
        tags.thead(background="/images/gradMB.png")[
            tags.tr[
                header
            ]
        ],
        tags.tbody[
            rows
        ]
    ]
Ejemplo n.º 9
0
    def render_exits(self, ctx, data):
        if self.bse != 'Room':
            return ''

        xs = self.obj.exits()
        xs.sort(key=attrgetter('name'))
        if xs:
            lines = [T.h2(_class="section")['Exits:']]

            rows = []
            for x in xs:
                tzid = x.tzid
                destf = 'dest_%s' % tzid
                namef = 'name_%s' % tzid
                dest = x.destination
                rows.append(T.tr[
                                T.td[self.deletelink_widget(x)],
                                T.td[self.editlink_widget(x)],
                                T.td[self.str_widget(namef, x.name, 20)],
                                T.td['-->'],
                                T.td[self.rooms_widget(destf, dest)],
                                T.td[self.editlink_widget(dest)],
                                T.td[T.input(_type="submit", value="update")]])
            tbl = T.table(_class="center")[rows]
            lines.append(tbl)
            return T.form(action="/exits/update/", method="POST")[lines]

        else:
            return T.h2(_class="warn")['No exits']
Ejemplo n.º 10
0
    def render_content(self, ctx, data):
        shares = self.sysconf.SambaShares

        return ctx.tag[
            tags.h2[tags.img(src="/images/sharefold.png"), " Shared folders"],
            tags.table(cellspacing="0", _class="listing")[
                tags.thead(background="/images/gradMB.png")[tags.tr[
                    tags.th['Shared Folder'], tags.th['Shared Path'],
                    tags.th['Comment'], tags.th['Writable'], tags.th['Public'],
                    tags.th['Permission'], tags.th[''], ]],
                tags.tbody[[
                    tags.tr[tags.td[share], [
                        tags.td[shares[share].get(i, None) or ""] for i in [
                            'path', 'comment', 'writable', 'public',
                            'valid users'
                        ]
                    ], tags.td[
                        tags.
                        a(href='Delete/%s/' % (share, ),
                          onclick
                          ="return confirm('Are you sure you want to delete this share?');"
                          )[tags.img(src="/images/ex.png")]]]
                    for share in shares.keys() if not share == "global"
                ]]], tags.h3["Add new share"],
            tags.directive('form addShare'), ]
Ejemplo n.º 11
0
 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))]
Ejemplo n.º 12
0
 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))]
Ejemplo n.º 13
0
 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))]
Ejemplo n.º 14
0
        def gotMail(mail):
            print mail
            attachments, hdrs, data = mail
            uFrom, uDate, uSubject = hdrs

            toolbar = [("/mail/Mail/##%s" % self.params[0], 'Inbox',
                        "/images/inbox.png"),
                       ("/mail/New/##%s.%s" % self.params, 'Reply',
                        "/images/inbox.png")]

            return ctx.tag[tags.div(
                id="mailViewHolder")[
                    tags.ul(
                        id="mailTools")[[
                            tags.li[tags.a(href=link)[tags.div[tags.img(
                                src=image)], name]]
                            for link, name, image in toolbar
                        ]],
                    tags.table(
                        id="mailViewHeaders"
                    )[tags.tr[tags.td["From:"],
                              tags.td[uFrom]], tags.tr[tags.td["Date:"],
                                                       tags.td[uDate]],
                      tags.tr[tags.td["Subject:"], tags.td[uSubject]],
                      tags.tr[tags.td["Attachments:"], tags.td[[[
                          tags.a(href="/mail/mdata/%s/%s" %
                                 (self.avatarId.username, v[0]))[tags.img(
                                     src="/images/attachment.png"), " ", k],
                          " (%0.2f KB)" % (v[1] / 1024.0), tags.br
                      ] for k, v in attachments.items()]]], ],
                    tags.div(id="mailViewContentBox")[tags.xml(data)], ]]
Ejemplo n.º 15
0
Archivo: edit.py Proyecto: drewp/photo
    def render_pics(self, ctx, data):
        rows = []
        d = URIRef(ctx.arg('dir'))
        for i, (pic, filename) in enumerate(sorted(picsInDirectory(self.graph, d))[:]):
            img = T.img(src=[localSite(pic), '?size=thumb'],
                        # look these up in the graph
                        width=75, height=56,
                        onclick='javascript:photo.showLarge("%s")' %
                        (localSite(pic) + "?size=large"))


            tableRow = T.table(class_="picRow")[T.tr[
                T.td[T.a(href=localSite(pic))[filename]],
                T.td[img],
                T.td[
                T.div["Depicts: ", T.input(type="text", class_="tags")],
                T.div["Comment: ", T.input(type="text")],
                ],
                ]]

            toCopy = "protoSectionSplitter"
            if i ==0:
                toCopy = "protoSectionBreak"
                

            rows.append([T.raw('<script type="text/javascript">document.write(document.getElementById("%s").innerHTML);</script>' % toCopy),
                         tableRow])
            
        return rows
Ejemplo n.º 16
0
 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))]
Ejemplo n.º 17
0
 def returnMailLog(mail):
     if self.offset > 0:
         previousTag = tags.a(
             href=url.root.child("Mail").child(self.offset -
                                               20))["Previous 20"]
     else:
         previousTag = "Previous 20"
     return ctx.tag[
         #tags.div(id="rightBlockIFrame")[
         tags.h3[tags.img(src="/images/maillog.png"),
                 " Mail Logs"], previousTag,
         tags.a(href=url.root.child("Mail").child(self.offset +
                                                  20))["Next 20"],
         tags.br,
         tags.table(cellspacing=0, _class='listing')[tags.thead(
             background="/images/gradMB.png")[tags.tr[
                 tags.th["Date"], tags.th["From"], tags.th["To"],
                 tags.th["Size"], tags.th["Message ID"]]], tags.tbody[[
                     tags.tr[tags.td[time.ctime(m[2])], tags.td[m[5]],
                             tags.td[m[18]],
                             tags.td["%0.3f KB" %
                                     (float(m[11]) / 1024.0)],
                             tags.td[m[1]]] for m in mail
                 ]]], tags.br, previousTag,
         tags.a(href=url.root.child("Mail").child(self.offset +
                                                  20))["Next 20"],
         tags.br, tags.h3["Search Logs"],
         tags.invisible(render=tags.directive('form searchForm'))]
Ejemplo n.º 18
0
    def render_settings(self, ctx, data):
        settings = self.obj.settings[:]
        if self.bse != 'Room':
            settings.append('room')
        if self.bse == 'Exit':
            settings.append('destination')

        lines = []
        for setting in settings:
            error = self.args.get('_%s__error' % setting, False)
            if error:
                cls = 'textlabel_error'
            else:
                cls = 'textlabel'
            label = T.td(_class=cls)[setting]
            val = self.obj.setting(setting)
            if val is None:
                val = getattr(self.obj, setting, None)
            inpt = T.td[self.get_setting_widget(setting, val)]
            lines.append(T.tr[label, inpt])

        if self.bse != 'Room' and self.obj.container != self.obj.room:
            label = T.td(_class="textlabel")['container']
            inpt = T.td[self.container_widget(self.obj)]
            lines.append(T.tr[label, inpt])

        empty = T.td(_class='empty')['']
        lines.append(T.tr[empty, empty])
        submit = T.input(_type="submit", value=" Change ")
        lines.append(T.tr[empty, T.td[submit]])

        tbl = T.table(_class="center")[lines]

        return T.form(action=".", method="POST")[tbl]
Ejemplo n.º 19
0
    def render_sessions(self, ctx, data):
        if len(self.pytrans.sessions) <= 0:
            return "No active sessions."

        ret = tags.table(border=0, width="100%", cellspacing=5, cellpadding=2)
        row = tags.tr[
            tags.th["User"],
            tags.th["Incoming Messages"],
            tags.th["Outgoing Messages"],
            tags.th["Connections"]
        ]
        ret[row]
        for key in self.pytrans.sessions:
            jid = self.pytrans.sessions[key].jabberID
            row = tags.tr[
                tags.td[jid],
                tags.td(align="center")[self.pytrans.serviceplugins[
                    'Statistics'].sessionstats[jid]['IncomingMessages']],
                tags.td(align="center")[self.pytrans.serviceplugins[
                    'Statistics'].sessionstats[jid]['OutgoingMessages']],
                tags.td(align="center")[
                    self.pytrans.serviceplugins['Statistics'].sessionstats[jid]['Connections']]
            ]
            ret[row]
        return ret
Ejemplo n.º 20
0
    def rend(self, data):
        def row(k,v):
            query, n, elapsed, rowCount = v

#            if k[0].startswith("(count)"):
#                rowCount = "(count) %s" % rowCount
            return (elapsed, T.tr[T.td["%.2f (%.4f)" % (elapsed, elapsed / n)],
                                  T.td[n],
                                  T.td[T.pre[reindent(stripPrefixes(query))]],
                                  T.td[repr(k[1]) or ''],
                                  T.td["%.1f" % (rowCount / n)],
                                  T.td[[T.div[self.shortFilename(s)] for s in
                                        self.original.sources.get(k,'')]],
                                  ])

        rows = [row(k,v) for k,v in self.original.counts.items()]
        rows.sort(reverse=True)
        return T.table(class_="queryProfile")[
            T.tr[T.th["total secs (per)"],
                 T.th["count"],
                 T.th["query (with sample initBindings; prefixes hidden)"],
                 T.th["bound"],
                 T.th["avg rows"],
                 T.th["sources"]],
            [r[1] for r in rows]]
Ejemplo n.º 21
0
 def render_content(self, ctx, data):
     if self.db[0] == "FIRSTRUN":
         return ctx.tag[tags.table(
             height="100%", width="100%"
         )[tags.tr(height="100%")[tags.td[tags.div(
             id="centerBox", valign="middle"
         )[tags.div(id="blockTop")
           [""],
           tags
           .div(id="centerBlock")[tags.h1(
               style="color:#fff;font-family:arial;"
           )["TUMS Installation Wizard"]],
           tags
           .div(id="menuBlock")[tags.div(
               style=
               "margin-top:-5em; text-align:left; font-family:arial; color:#786D38;"
           )[tags.h3["Welcome to the TUMS installation wizard."],
             """This wizard will guide you through an initial configuration of the host system.
                                     This should be carried out by a Thusa employee. If your server has arrived unconfigured it
                                     is recommended that you contact Thusa support for this to be carried out. 
                                     """, tags.br,
             """Click the NEXT button bellow to continue with the installation""",
             tags.br, tags.br,
             tags.a(href="Wizard/1/")[tags.img(
                 src='/images/next.png')]]]]]]]]
     return ctx.tag[tags.a(href="/auth/")["Login"]]
Ejemplo n.º 22
0
 def returnMailLog(mail):
     return ctx.tag[
             tags.h3[tags.img(src="/images/maillog.png"), " Mail Queue"],
             tags.br,
             tags.table(cellspacing=0, _class='listing')[
                 tags.thead(background="/images/gradMB.png")[
                     tags.tr[
                         tags.th["Date"],
                         tags.th["From"],
                         tags.th["To"],
                         tags.th["Subject"],
                         tags.th["Message ID"]
                     ]
                 ],
                 tags.tbody[
                     [tags.tr[
                             tags.td[time.ctime(m[3])],
                             tags.td[m[2] or ""],
                             tags.td[m[5] or ""],
                             tags.td[m[9] or ""],
                             tags.td[m[1] or ""]
                         ]
                     for m in mail]
                 ]
             ],
     ]
Ejemplo n.º 23
0
def varTable(usedVars):
    return t.table(_class="variables")[[
        t.tr(_class="varRow")[
            t.td(_class="varName")[ key ],
            t.td(_class="varValue")[ htmlrepr(value) ]
        ]
        for (key, value) in usedVars
    ]]
Ejemplo n.º 24
0
def varTable(usedVars):
    return t.table(_class="variables")[[
        t.tr(_class="varRow")[
            t.td(_class="varName")[ key ],
            t.td(_class="varValue")[ htmlrepr(value) ]
        ]
        for (key, value) in usedVars
    ]]
Ejemplo n.º 25
0
def htmlDict(d):
    return t.div(_class="dict")[
        t.span(_class="heading")["Dictionary instance @ 0x%x" % id(d)],
        t.table(_class="dict")[[
            t.tr[t.td(
                _class="dictKey")[k == '__builtins__' and 'builtin dictionary'
                                  or htmlrepr(k)],
                 t.td(_class="dictValue")[htmlrepr(v)]] for k, v in d.items()
        ]]]
Ejemplo n.º 26
0
    def render_roster(self, ctx, data):
        request = inevow.IRequest(ctx)
        username = request.getUser()

        ret = tags.table(border=0, cellspacing=5, cellpadding=2)
        row = tags.tr(height=25)[
            tags.th["UIN/Screen Name"],
            tags.th["Nickname"],
            tags.th["Network"],
            tags.th["Avatar"],
            tags.th["Status"]
        ]
        ret[row]
        roster = self.pytrans.xdb.getList("roster", username)
        if not roster:
            return ret
        for item in roster:
            if item[0][0].isdigit():
                network = "ICQ"
            else:
                network = "AIM"
            avatar = "-"
            if not config.disableAvatars and item[1].has_key("shahash"):
                avatar = tags.a(href=("/avatars/%s" % item[1]["shahash"]))[
                    tags.img(
                        border=0, height=25, src=("/avatars/%s" % item[1]["shahash"]))
                ]
            nickname = "-"
            if "nickname" in item[1]:
                nickname = item[1]["nickname"]
            else:
                if username in self.pytrans.sessions and \
                        self.pytrans.sessions[username].ready:
                    c = self.pytrans.sessions[username].contactList.getContact(
                        "%s@%s" % (item[0], config.jid))
                    if c.nickname and c.nickname != "":
                        nickname = c.nickname
            status = "-"
            if username in self.pytrans.sessions and \
                    self.pytrans.sessions[username].ready:
                c = self.pytrans.sessions[username].contactList.getContact(
                    "%s@%s" % (item[0], config.jid))
                status = c.ptype
                if not status:
                    status = c.show
                    if not status:
                        status = "available"
            row = tags.tr(height=25)[
                tags.td(height=25, align="middle")[item[0]],
                tags.td(height=25, align="middle")[nickname],
                tags.td(height=25, align="middle")[network],
                tags.td(height=25, align="middle")[avatar],
                tags.td(height=25, align="middle")[status]
            ]
            ret[row]
        return ret
Ejemplo n.º 27
0
    def render_webconsole_environments(self):
        return [
            tags.h3()['Web console Environments'],
            tags.table()[
                tags.tr()[
                    tags.th()['Port'],
                    tags.td()[lumen.config['webport']],
                ],

            ],
        ]
Ejemplo n.º 28
0
 def render_config(self, ctx, data):
     table = T.table(border=0)
     for key in config.__dict__.keys():
         if key[0] == "_":
             continue
         if key.find("secret") >= 0:
             setting = "**hidden**"
         else:
             setting = config.__dict__[key]
         row = T.tr[T.td[key], T.td["="], T.td[setting]]
         table[row]
     return table
Ejemplo n.º 29
0
    def render_statistics(self, ctx, data):
        ret = T.table(border=0, width="100%", cellspacing=5, cellpadding=2)
        for key in self.pytrans.serviceplugins['Statistics'].stats:
            label = lang.get("statistics_%s" % key, config.lang)
            description = lang.get("statistics_%s_Desc" % key, config.lang)

            row = T.tr[
                T.th(align="right")[label + ":"],
                T.td[self.pytrans.serviceplugins['Statistics'].stats[key]],
                T.td[description]]
            ret[row]
        return ret
Ejemplo n.º 30
0
 def makeComplex(self):
     return tags.html[
         tags.body[
             tags.table(data=5)[
                 tags.tr[
                     tags.td[
                         tags.span(render=str)
                     ],
                 ]
             ]
         ]
     ]
Ejemplo n.º 31
0
    def render_content(self, ctx, data):
        try:
            l = open(Settings.BaseDir+'/backup.dat')
        except:
            WebUtils.system('echo > %s/backup.dat' % Settings.BaseDir)
            l = []

        sets = []
        for i in l:
            if i.strip('\n'):
                dta = i.strip('\n').split('|')
                delmsg = "return confirm('%s');" % self.text.backupConfirmDelete
                if dta[6] =="True":
                    dta[6] = dta[7]
                    dta[7] = [
                        tags.img(src="/images/blankblock.png"), "  ",
                        tags.a(href="Delete/%s/" % (dta[0],), onclick = delmsg)[tags.img(src="/images/ex.png")]
                    ]

                else:
                    dta[6] = "No"
                    dta[7] = [
                        tags.a(href="Execute/%s/" % (dta[0],))[tags.img(src="/images/start.png")], "  ", 
                        tags.a(href="Delete/%s/" % (dta[0],), onclick = delmsg)[tags.img(src="/images/ex.png")]
                    ]

                dta[4] = [ [i, tags.br] for i in dta[4].split(';')]
                dta[2] = [ [i, tags.br] for i in dta[2].split(';')]

                del dta[0]
    
                sets.append(dta)
                
        return ctx.tag[
            tags.h2[tags.img(src="/images/netdrive.png"), self.text.backupSet],
            tags.table(cellspacing=0,  _class='listing')[
                tags.thead(background="/images/gradMB.png")[
                    tags.tr[
                        [ tags.th[i] for i in [
                            self.text.backupHeaderDescription, self.text.backupHeaderNotify, 
                            self.text.backupHeaderDevice, self.text.backupHeaderSource, 
                            self.text.backupHeaderDestination, self.text.backupHeaderAutomated, '']]
                    ]
                ],
                tags.tbody[
                [
                    tags.tr[ [tags.td[col] for col in row] ]
                for row in sets],
                ]
            ],
            tags.h3[self.text.backupCreateSet], 
            tags.directive('form addBackup')
        ]
Ejemplo n.º 32
0
 def makeComplex(self):
     return tags.html[
         tags.body[
             tags.table(data=5)[
                 tags.tr[
                     tags.td[
                         tags.span(render=str)
                     ],
                 ]
             ]
         ]
     ]
Ejemplo n.º 33
0
 def render_config(self, ctx, data):
     table = tags.table(border=0)
     for key in config.__dict__.keys():
         if key[0] == "_":
             continue
         if key.find("secret") >= 0:
             setting = "**hidden**"
         else:
             setting = config.__dict__[key]
         row = tags.tr[tags.td[key], tags.td["="], tags.td[setting]]
         table[row]
     return table
Ejemplo n.º 34
0
class Tester(livepage.LivePage):
    addSlash = True
    child_css = static.File(util.resource_filename('nevow', 'livetest.css'))
    child_scripts = static.File(util.resource_filename('nevow', 'livetest.js'))
    child_postscripts = static.File(util.resource_filename('nevow', 'livetest-postscripts.js'))
    docFactory = loaders.stan(tags.html[
        tags.head[
            tags.script(src="scripts"),
            tags.link(rel="stylesheet", type="text/css", href="css")],
        tags.body[
            tags.table(id="testprogress")[
                tags.tr[
                    tags.th["Tests"], tags.th["Pass"], tags.th["Fail"]],
                tags.tr[
                    tags.td(id="test-status")["Running"],
                    tags.td(id="test-passes", _class="test-passes")[entities.nbsp],
                    tags.td(id="test-failures", _class="test-failures")[entities.nbsp]]],
            tags.table(id="testresults", render=tags.directive('sequence'))[
                tags.tr(pattern="item", render=tags.directive('test'))[
                    tags.td(title=tags.slot('action'))[tags.slot('action')],
                    tags.td(title=tags.slot('target'))[tags.slot('target')],
                    tags.td(title=tags.slot('parameter'))[tags.slot('parameter')]]],
            tags.iframe(id="testframe", src="asdf"),
            tags.script(src="postscripts"),
            livepage.glue]])

    def beforeRender(self, ctx):
        self.testId = 0

    def render_test(self, ctx, test):
        ctx.tag(id=("test-", self.testId))
        action, target, parameter = test
        ctx.fillSlots('action', action)
        ctx.fillSlots('target', str(target))
        ctx.fillSlots('parameter', str(parameter))
        self.testId += 1
        return ctx.tag

    def goingLive(self, ctx, handle):
        Driver(handle, self.original)
Ejemplo n.º 35
0
def dataTable(headings, content):
    return tags.table(cellspacing=0,  _class='listing')[
        tags.thead(background="/images/gradMB.png")[
            tags.tr[
                [ tags.th[i] for i in headings ]
            ]
        ],
        tags.tbody[
        [   
            tags.tr[ [tags.td[col] for col in row] ]
        for row in content],
        ]
    ]
Ejemplo n.º 36
0
    def render_statistics(self, ctx, data):
        ret = tags.table(border=0, width="100%", cellspacing=5, cellpadding=2)
        for key in self.pytrans.serviceplugins['Statistics'].stats:
            label = lang.get("statistics_%s" % key, config.lang)
            description = lang.get("statistics_%s_Desc" % key, config.lang)

            row = tags.tr[
                tags.th(align="right")[label + ":"],
                tags.td[self.pytrans.serviceplugins['Statistics'].stats[key]],
                tags.td[description]
            ]
            ret[row]
        return ret
Ejemplo n.º 37
0
 def test_slots(self):
     tag = tags.html[
         tags.body[
             tags.table(data={'one': 1, 'two': 2}, render=rend.mapping)[
                 tags.tr[tags.td["Header one."], tags.td["Header two."]],
                 tags.tr[
                     tags.td["One: ", tags.slot("one")],
                     tags.td["Two: ", tags.slot("two")]
                 ]
             ]
         ]
     ]
     self.assertEquals(self.render(tag), "<html><body><table><tr><td>Header one.</td><td>Header two.</td></tr><tr><td>One: 1</td><td>Two: 2</td></tr></table></body></html>")
Ejemplo n.º 38
0
 def test_slots(self):
     tag = tags.html[
         tags.body[
             tags.table(data={'one': 1, 'two': 2}, render=rend.mapping)[
                 tags.tr[tags.td["Header one."], tags.td["Header two."]],
                 tags.tr[
                     tags.td["One: ", tags.slot("one")],
                     tags.td["Two: ", tags.slot("two")]
                 ]
             ]
         ]
     ]
     self.assertEqual(self.render(tag), "<html><body><table><tr><td>Header one.</td><td>Header two.</td></tr><tr><td>One: 1</td><td>Two: 2</td></tr></table></body></html>")
Ejemplo n.º 39
0
def htmlDict(d):
    return t.div(_class="dict")[
        t.span(_class="heading")[
            "Dictionary instance @ 0x%x" % id(d)
        ],
        t.table(_class="dict")[[
            t.tr[
                t.td(_class="dictKey")[ k == '__builtins__' and 'builtin dictionary' or htmlrepr(k) ],
                t.td(_class="dictValue")[ htmlrepr(v) ]
            ]
            for k, v in d.items()
        ]]
    ]
Ejemplo n.º 40
0
    def render_content(self, ctx, data):
        keys = [i for i in os.listdir('/etc/openvpn/keys/') if 'key' in i]

        keys.sort()
        for key in ['vpn.key', 'ca.key']:
            try:
                keys.remove(key)
            except:
                pass

        return ctx.tag[
                tags.h2[tags.img(src="/images/vpn.png"), self.text.vpnConfig],
                PageHelpers.TabSwitcher((
                    (self.text.vpnTabWindows, 'panelWindows'),
                    (self.text.vpnTabTCS, 'panelOpenVPN'),
                    (self.text.vpnTabUsers, 'panelVPNUsers')
                )),
                tags.div(id="panelWindows", _class="tabPane")[
                    tags.h3[self.text.vpnHeadingWindows],
                    tags.directive('form winForm'),
                ],
                tags.div(id="panelOpenVPN", _class="tabPane")[
                    tags.h3[self.text.vpnHeadingTCS],
                    tags.directive('form vpnForm'), tags.br,
                ],
                tags.div(id="panelVPNUsers", _class="tabPane")[
                    tags.h3[self.text.vpnHeadingTCSUsers],
                    tags.table(cellspacing=0,  _class='listing')[
                        tags.thead(background="/images/gradMB.png")[
                            tags.tr[
                                tags.th[self.text.vpnCertificateName],
                                tags.th[""],
                            ]
                        ],
                        tags.tbody[
                        [
                            tags.tr[
                                tags.td['.'.join(i.split('.')[:-1])],
                                tags.td[tags.a(href="Revoke/%s/" % '.'.join(i.split('.')[:-1]), onclick="return confirm('%s');" % self.text.vpnConfirmRevoke)[ 
                                    tags.img(src="/images/ex.png")]
                                ]
                            ]
                        for i in keys],
                        ]
                    ], tags.br,
                    tags.h3[self.text.vpnHeadingAddUser],
                    tags.directive('form addUser')
                ],
                PageHelpers.LoadTabSwitcher()
            ]
Ejemplo n.º 41
0
class LoginForm(MaayPage):
    """a basic login form. This page is rendered until the user
    is logged.
    """
    addSlash = True
    docFactory = loaders.stan(tags.html[
        tags.head[tags.title["Maay Login Page"]],
        tags.body[tags.form(action=guard.LOGIN_AVATAR, method='post')[
            tags.table(_class="loginTable")[tags.tr[
                tags.td["Username:"******"Password:"],
                    tags.td[tags.input(type='password', name='password')], ]],
            tags.input(type='submit'), tags.p, ]]])
Ejemplo n.º 42
0
 def returnMailLog(mail):
     return ctx.tag[
         tags.h3[tags.img(src="/images/maillog.png"),
                 " Mail Logs"], tags.br,
         tags.table(cellspacing=0, _class='listing')[tags.thead(
             background="/images/gradMB.png")[tags.tr[
                 tags.th["Date"], tags.th["From"], tags.th["To"],
                 tags.th["Size"], tags.th["Message ID"]]], tags.tbody[[
                     tags.tr[tags.td[time.ctime(m[2])], tags.td[m[5]],
                             tags.td[m[18]],
                             tags.td["%0.3f KB" %
                                     (float(m[11]) / 1024.0)],
                             tags.td[m[1]]] for m in mail
                 ]]], tags.br, ]
Ejemplo n.º 43
0
 def render_bayeux_environments(self):
     return [
         tags.h3()['Bayeux Environmerts'],
         tags.table()[
             tags.tr()[
                 tags.th()['Port'],
                 tags.td()[lumen.config['port']],
             ],
             tags.tr()[
                 tags.th()['Engine'],
                 tags.td()[lumen.config['engine']],
             ]
         ],
     ]
Ejemplo n.º 44
0
    def format(self):
        r = []

        ivs = []
        for iv in self.ivar_descs:
            attr = zopeinterface.Attribute(self.obj.system, iv.name, iv.body,
                                           self.obj)
            if iv.name is None or attr.isVisible:
                ivs.append(iv)
        self.ivar_descs = ivs

        cvs = []
        for cv in self.cvar_descs:
            attr = zopeinterface.Attribute(self.obj.system, cv.name, cv.body,
                                           self.obj)
            if attr.isVisible:
                cvs.append(cv)
        self.cvar_descs = cvs

        for d, l in (('Parameters', self.parameter_descs),
                     ('Instance Variables', self.ivar_descs),
                     ('Class Variables', self.cvar_descs), ('Variables',
                                                            self.var_descs)):
            r.append(format_desc_list(d, l, d))
        if self.return_desc:
            r.append(
                tags.tr(class_="fieldStart")[
                    tags.td(class_="fieldName")['Returns'],
                    tags.td(colspan="2")[self.return_desc.format()]])
        r.append(format_desc_list("Raises", self.raise_descs, "Raises"))
        for s, p, l in (('Author', 'Authors', self.authors),
                        ('See Also', 'See Also', self.seealsos),
                        ('Present Since', 'Present Since',
                         self.sinces), ('Note', 'Notes', self.notes)):
            r.append(format_field_list(self.obj, s, l, p))
        unknowns = {}
        unknownsinorder = []
        for fieldinfo in self.unknowns:
            tag = fieldinfo.kind
            if tag in unknowns:
                unknowns[tag].append(fieldinfo)
            else:
                unknowns[tag] = [fieldinfo]
                unknownsinorder.append(unknowns[tag])
        for fieldlist in unknownsinorder:
            label = "Unknown Field: " + fieldlist[0].kind
            r.append(format_desc_list(label, fieldlist, label))

        return tags.table(class_='fieldTable')[r]
Ejemplo n.º 45
0
    def render_roster(self, ctx, data):
        request = inevow.IRequest(ctx)
        username = request.getUser()

        ret = T.table(border=0, cellspacing=5, cellpadding=2)
        row = T.tr(height=25)[T.th["UIN/Screen Name"], T.th["Nickname"],
                              T.th["Network"], T.th["Avatar"], T.th["Status"]]
        ret[row]
        roster = self.pytrans.xdb.getList("roster", username)
        if not roster:
            return ret
        for item in roster:
            if item[0][0].isdigit():
                network = "ICQ"
            else:
                network = "AIM"
            avatar = "-"
            if not config.disableAvatars and item[1].has_key("shahash"):
                avatar = T.a(href=("/avatars/%s" % item[1]["shahash"]))[T.img(
                    border=0,
                    height=25,
                    src=("/avatars/%s" % item[1]["shahash"]))]
            nickname = "-"
            if item[1].has_key("nickname"):
                nickname = item[1]["nickname"]
            else:
                if self.pytrans.sessions.has_key(
                        username) and self.pytrans.sessions[username].ready:
                    c = self.pytrans.sessions[username].contactList.getContact(
                        "%s@%s" % (item[0], config.jid))
                    if c.nickname and c.nickname != "":
                        nickname = c.nickname
            status = "-"
            if self.pytrans.sessions.has_key(
                    username) and self.pytrans.sessions[username].ready:
                c = self.pytrans.sessions[username].contactList.getContact(
                    "%s@%s" % (item[0], config.jid))
                status = c.ptype
                if not status:
                    status = c.show
                    if not status:
                        status = "available"
            row = T.tr(height=25)[T.td(height=25, align="middle")[item[0]],
                                  T.td(height=25, align="middle")[nickname],
                                  T.td(height=25, align="middle")[network],
                                  T.td(height=25, align="middle")[avatar],
                                  T.td(height=25, align="middle")[status]]
            ret[row]
        return ret
Ejemplo n.º 46
0
	def makeDocFactory(self):
		return loaders.stan([
			T.div(render=T.directive("meta"), class_="warning")["_warning"],
			T.table(class_="keyvalue", render=rend.mapping,
					data=T.directive("firstrow")) [
				[[T.tr[
						T.th(data=colDef, render=T.directive("headCell"),
							class_="thHorizontal"),
						td],
					T.tr(class_="keyvaluedesc")[T.td(colspan=2)[
						colDef.description]]]
					for colDef, td in zip(self.serManager.table.tableDef.columns, 
						self.defaultTds)]],
			T.invisible(render=T.directive("footnotes")),
			])
Ejemplo n.º 47
0
 def test_nestedpatterns(self):
     def data_table(context, data):  return [[1,2,3],[4,5,6]]
     def data_header(context, data):  return ['col1', 'col2', 'col3']
     tag = tags.html[
         tags.body[
             tags.table(data=data_table, render=rend.sequence)[
                 tags.tr(pattern='header', data=data_header, render=rend.sequence)[
                     tags.td(pattern='item')[str]
                 ],
                 tags.tr(pattern='item', render=rend.sequence)[
                     tags.td(pattern='item')[str]
                 ]
             ]
         ]
     ]
     self.assertEqual(self.render(tag), "<html><body><table><tr><td>col1</td><td>col2</td><td>col3</td></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table></body></html>")
Ejemplo n.º 48
0
 def render_channels_list(self):
     result = tags.table()
     result.children.append(
         tags.tr()[
             tags.th()['id'],
             tags.th()['subscribers'],
         ]
     )
     for clientId, c in channel.channels.items():
         result.children.append(
             tags.tr()[
                 tags.td()[c.id],
                 tags.td()[len(c.subscribers)],
             ]
         )
     return result
Ejemplo n.º 49
0
 def test_nestedpatterns(self):
     def data_table(context, data):  return [[1,2,3],[4,5,6]]
     def data_header(context, data):  return ['col1', 'col2', 'col3']
     tag = tags.html[
         tags.body[
             tags.table(data=data_table, render=rend.sequence)[
                 tags.tr(pattern='header', data=data_header, render=rend.sequence)[
                     tags.td(pattern='item')[str]
                 ],
                 tags.tr(pattern='item', render=rend.sequence)[
                     tags.td(pattern='item')[str]
                 ]
             ]
         ]
     ]
     self.assertEquals(self.render(tag), "<html><body><table><tr><td>col1</td><td>col2</td><td>col3</td></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table></body></html>")
Ejemplo n.º 50
0
    def format(self):
        r = []

        ivs = []
        for iv in self.ivar_descs:
            attr = zopeinterface.Attribute(
                self.obj.system, iv.name, iv.body, self.obj)
            if iv.name is None or attr.isVisible:
                ivs.append(iv)
        self.ivar_descs = ivs

        cvs = []
        for cv in self.cvar_descs:
            attr = zopeinterface.Attribute(
                self.obj.system, cv.name, cv.body, self.obj)
            if attr.isVisible:
                cvs.append(cv)
        self.cvar_descs = cvs

        for d, l in (('Parameters', self.parameter_descs),
                     ('Instance Variables', self.ivar_descs),
                     ('Class Variables', self.cvar_descs),
                     ('Variables', self.var_descs)):
            r.append(format_desc_list(d, l, d))
        if self.return_desc:
            r.append(tags.tr(class_="fieldStart")[tags.td(class_="fieldName")['Returns'],
                               tags.td(colspan="2")[self.return_desc.format()]])
        r.append(format_desc_list("Raises", self.raise_descs, "Raises"))
        for s, p, l in (('Author', 'Authors', self.authors),
                        ('See Also', 'See Also', self.seealsos),
                        ('Present Since', 'Present Since', self.sinces),
                        ('Note', 'Notes', self.notes)):
            r.append(format_field_list(self.obj, s, l, p))
        unknowns = {}
        unknownsinorder = []
        for fieldinfo in self.unknowns:
            tag = fieldinfo.kind
            if tag in unknowns:
                unknowns[tag].append(fieldinfo)
            else:
                unknowns[tag] = [fieldinfo]
                unknownsinorder.append(unknowns[tag])
        for fieldlist in unknownsinorder:
            label = "Unknown Field: " + fieldlist[0].kind
            r.append(format_desc_list(label, fieldlist, label))

        return tags.table(class_='fieldTable')[r]
Ejemplo n.º 51
0
    def render_transactions(self, ctx):
        coll = mongo['heist']['transactions']
        rows = reversed(list(coll.find(sort=[("readAt", -1)], limit=6)))
        now = datetime.datetime.now(tzlocal())

        def recentClass(d):
            if (now - d).total_seconds() < 86400 * 2:
                return {"class": "recent"}
            return {}

        return T.table(class_="transactions")[[
            T.tr(**recentClass(row['date']))[T.td(
                class_="date")[row['date'].date().isoformat()],
                                             T.td(class_="to")[row['payee']],
                                             T.td(class_="amt")[row['amount']]]
            for row in rows
        ]]
Ejemplo n.º 52
0
    def render_addroomform(self, ctx, data):
        action = '/rooms/add/'
        lines = [T.h2['Add Room']]
        roomclasses = rooms.classes()
        roomclasses.sort()
        choices = [(cls, cls) for cls in roomclasses]
        roomsinfo = dict(name='roomclass',
                            choices=choices,
                            selected='Room')
        row = T.tr[T.td[self.render_form_select(roomsinfo)],
                    T.td[T.input(name='roomname')],
                    T.td[T.input(type='submit', value=' Add ')]]
        tbl = T.table(_class="center")[row]
        lines.append(tbl)
        form = T.form(action=action, method='POST')[lines]

        return T.div(_class='addroom')[form]
Ejemplo n.º 53
0
 def render_widgets(self, ctx, data):
     f = aw.CommandWidget(self.controller)
     f.setFragmentParent(self)
     g = aw.StatusWidget(self.controller)
     g.setFragmentParent(self)
     h = aw.ResultWidget()
     h.setFragmentParent(self)
     n1 = results.notifierFromFunction(h.handleResult)
     self.controller.addNotifier(n1)
     n2 = results.notifierFromFunction(g.refreshStatus)
     f.addNotifier(n2)
     reactor.callLater(1, g.refreshStatus)
     build = tags.table(id="monitor")[tags.tr[tags.td(valign="top")[g],
                                              tags.td(valign="top")[h,
                                                                    tags.br,
                                                                    f]]]
     return ctx.tag[build]
Ejemplo n.º 54
0
    def render_transactions(self, ctx):
        coll = mongo["heist"]["transactions"]
        rows = reversed(list(coll.find(sort=[("readAt", -1)], limit=6)))
        now = datetime.datetime.now(tzlocal())

        def recentClass(d):
            if (now - d).total_seconds() < 86400 * 2:
                return {"class": "recent"}
            return {}

        return T.table(class_="transactions")[
            [
                T.tr(**recentClass(row["date"]))[
                    T.td(class_="date")[row["date"].date().isoformat()],
                    T.td(class_="to")[row["payee"]],
                    T.td(class_="amt")[row["amount"]],
                ]
                for row in rows
            ]
        ]
Ejemplo n.º 55
0
    def render_clients_list(self):
        result = tags.table()
        result.children.append(
            tags.tr()[
                tags.th()['id'],
                tags.th()['type'],
                tags.th()['created at'],


            ]
        )
        for clientId, c in client.clients.items():
            result.children.append(
                tags.tr()[
                    tags.td()[clientId],
                    tags.td()[c.typename],
                    tags.td()[c.createdAt.strftime("%A, %d. %B %Y %I:%M%p")],
                ]
            )
        return result
Ejemplo n.º 56
0
 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]
Ejemplo n.º 57
0
    def render_addexitform(self, ctx, data):
        if self.bse != 'Room':
            return ''

        tzid = self.tzid # to know which room to add the exit to
        action = '/exits/add/'
        lines = [T.h2['Add Exit to Room']]
        exitclasses = exits.classes()
        exitclasses.sort()
        choices = [(cls, cls) for cls in exitclasses]
        xinfo = dict(name='xclass',
                            choices=choices,
                            selected='Exit')
        bxinfo = dict(name='bxclass',
                            choices=choices,
                            selected='Exit')
        row = T.tr[T.td['Exit type...', T.br,
                            self.render_form_select(xinfo), T.br,
                            'named...', T.br,
                            T.input(name='xname')],
                    T.td['to...', T.br, '-->'],
                    T.td(align="center")[self.rooms_widget('dest', None),
                            T.br, 'or', T.br,
                            self.new_room_widget('newroom'), T.br,
                            'named...', T.br,
                            T.input(name='newroomname'), T.br,
                            T.input(type='submit', value=' Add ')],
                    T.td[T.br, '<--'],
                    T.td['return by...', T.br,
                            'Exit type...', T.br,
                            self.render_form_select(bxinfo), T.br,
                            'named...', T.br,
                            T.input(name='bxname')]]
        tbl = T.table(_class="center")[row]
        lines.append(tbl)
        lines.append(T.input(_type="hidden", name="roomid", value=tzid))
        form = T.form(action=action, method='POST')[lines]

        return T.div(_class='addexit')[form]
Ejemplo n.º 58
0
def recentReviews():
    result = fetch("""
PREFIX rev: <http://purl.org/stuff/rev#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?thing ?name ?review ?createdOn ?rating
WHERE
{
  ?thing rdfs:label ?name ;
         rev:hasReview ?review .
  ?review rev:reviewer <people/drewp> ;
          rev:createdOn ?createdOn ;
          rev:rating ?rating .
} 
ORDER BY DESC(?createdOn)
LIMIT 10
""")

    et = fromstring(result)
    headers = [e.get('name') for e in et.find(SPARQL_RESULTS + 'head')]
    rows = []
    for result in et.find(SPARQL_RESULTS + 'results').getchildren():
        bindings = dict([(b.get('name').replace('?',''),
                          nodeElement(b.getchildren()))
                         for b in result.findall(SPARQL_RESULTS + 'binding')])
        rows.append(bindings)
        
    rows.sort(key=lambda row: row['createdOn'], reverse=True)
    return flat.ten.flatten(T.table(class_="recentReviews")[
        T.tr[T.th(class_="recentReviews title", colspan=3)[
             "Recent reviews on ", T.a(class_="recentReviews",
                                       href="http://revyu.com")["revyu.com"],
             #" (-tmp)"
               ]],
        T.tr[T.th["Date"], T.th["Review"], T.th["Rating"]],
        [T.tr[T.td(class_="date")[row['createdOn'].split('T')[0]],
              T.td(class_="subj")[T.a(href=row['review'])[row['name']]],
              T.td(class_="rate")[row['rating']]]
         for row in rows]
        ])
Ejemplo n.º 59
0
    def render_events(self, ctx, data):
        if not self.download_status.storage_index:
            return
        srt = self.short_relative_time
        l = T.div()

        t = T.table(align="left", class_="status-download-events")
        t[T.tr[T.th["serverid"], T.th["sent"], T.th["received"],
               T.th["shnums"], T.th["RTT"]]]
        for d_ev in self.download_status.dyhb_requests:
            server = d_ev["server"]
            sent = d_ev["start_time"]
            shnums = d_ev["response_shnums"]
            received = d_ev["finish_time"]
            rtt = None
            if received is not None:
                rtt = received - sent
            if not shnums:
                shnums = ["-"]
            t[T.tr(style="background: %s" % self.color(server))[
                [T.td[server.get_name()], T.td[srt(sent)], T.td[srt(received)],
                 T.td[",".join([str(shnum) for shnum in shnums])],
                 T.td[self.render_time(None, rtt)],
                 ]]]

        l[T.h2["DYHB Requests:"], t]
        l[T.br(clear="all")]

        t = T.table(align="left",class_="status-download-events")
        t[T.tr[T.th["range"], T.th["start"], T.th["finish"], T.th["got"],
               T.th["time"], T.th["decrypttime"], T.th["pausedtime"],
               T.th["speed"]]]
        for r_ev in self.download_status.read_events:
            start = r_ev["start"]
            length = r_ev["length"]
            bytes = r_ev["bytes_returned"]
            decrypt_time = ""
            if bytes:
                decrypt_time = self._rate_and_time(bytes, r_ev["decrypt_time"])
            speed, rtt = "",""
            if r_ev["finish_time"] is not None:
                rtt = r_ev["finish_time"] - r_ev["start_time"] - r_ev["paused_time"]
                speed = self.render_rate(None, compute_rate(bytes, rtt))
                rtt = self.render_time(None, rtt)
            paused = self.render_time(None, r_ev["paused_time"])

            t[T.tr[T.td["[%d:+%d]" % (start, length)],
                   T.td[srt(r_ev["start_time"])], T.td[srt(r_ev["finish_time"])],
                   T.td[bytes], T.td[rtt],
                   T.td[decrypt_time], T.td[paused],
                   T.td[speed],
                   ]]

        l[T.h2["Read Events:"], t]
        l[T.br(clear="all")]

        t = T.table(align="left",class_="status-download-events")
        t[T.tr[T.th["segnum"], T.th["start"], T.th["active"], T.th["finish"],
               T.th["range"],
               T.th["decodetime"], T.th["segtime"], T.th["speed"]]]
        for s_ev in self.download_status.segment_events:
            range_s = "-"
            segtime_s = "-"
            speed = "-"
            decode_time = "-"
            if s_ev["finish_time"] is not None:
                if s_ev["success"]:
                    segtime = s_ev["finish_time"] - s_ev["active_time"]
                    segtime_s = self.render_time(None, segtime)
                    seglen = s_ev["segment_length"]
                    range_s = "[%d:+%d]" % (s_ev["segment_start"], seglen)
                    speed = self.render_rate(None, compute_rate(seglen, segtime))
                    decode_time = self._rate_and_time(seglen, s_ev["decode_time"])
                else:
                    # error
                    range_s = "error"
            else:
                # not finished yet
                pass

            t[T.tr[T.td["seg%d" % s_ev["segment_number"]],
                   T.td[srt(s_ev["start_time"])],
                   T.td[srt(s_ev["active_time"])],
                   T.td[srt(s_ev["finish_time"])],
                   T.td[range_s],
                   T.td[decode_time],
                   T.td[segtime_s], T.td[speed]]]

        l[T.h2["Segment Events:"], t]
        l[T.br(clear="all")]
        t = T.table(align="left",class_="status-download-events")
        t[T.tr[T.th["serverid"], T.th["shnum"], T.th["range"],
               T.th["txtime"], T.th["rxtime"],
               T.th["received"], T.th["RTT"]]]
        for r_ev in self.download_status.block_requests:
            server = r_ev["server"]
            rtt = None
            if r_ev["finish_time"] is not None:
                rtt = r_ev["finish_time"] - r_ev["start_time"]
            color = self.color(server)
            t[T.tr(style="background: %s" % color)[
                T.td[server.get_name()], T.td[r_ev["shnum"]],
                T.td["[%d:+%d]" % (r_ev["start"], r_ev["length"])],
                T.td[srt(r_ev["start_time"])], T.td[srt(r_ev["finish_time"])],
                T.td[r_ev["response_length"] or ""],
                T.td[self.render_time(None, rtt)],
                ]]

        l[T.h2["Requests:"], t]
        l[T.br(clear="all")]

        return l
Ejemplo n.º 60
0
    def _render_results(self, ctx, cr):
        assert ICheckResults(cr)
        c = self.client
        sb = c.get_storage_broker()
        r = []
        def add(name, value):
            r.append(T.li[name + ": ", value])

        add("Report", T.pre["\n".join(self._html(cr.get_report()))])
        add("Share Counts",
            "need %d-of-%d, have %d" % (cr.get_encoding_needed(),
                                        cr.get_encoding_expected(),
                                        cr.get_share_counter_good()))
        add("Happiness Level", cr.get_happiness())
        add("Hosts with good shares", cr.get_host_counter_good_shares())

        if cr.get_corrupt_shares():
            badsharemap = []
            for (s, si, shnum) in cr.get_corrupt_shares():
                d = T.tr[T.td["sh#%d" % shnum],
                         T.td[T.div(class_="nickname")[s.get_nickname()],
                              T.div(class_="nodeid")[T.tt[s.get_name()]]],
                         ]
                badsharemap.append(d)
            add("Corrupt shares", T.table()[
                T.tr[T.th["Share ID"],
                     T.th(class_="nickname-and-peerid")[T.div["Nickname"], T.div(class_="nodeid")["Node ID"]]],
                badsharemap])
        else:
            add("Corrupt shares", "none")

        add("Wrong Shares", cr.get_share_counter_wrong())

        sharemap_data = []
        shares_on_server = dictutil.DictOfSets()

        # FIXME: The two tables below contain nickname-and-nodeid table column markup which is duplicated with each other, introducer.xhtml, and deep-check-results.xhtml. All of these (and any other presentations of nickname-and-nodeid) should be combined.

        for shareid in sorted(cr.get_sharemap().keys()):
            servers = sorted(cr.get_sharemap()[shareid],
                             key=lambda s: s.get_longname())
            for i,s in enumerate(servers):
                shares_on_server.add(s, shareid)
                shareid_s = ""
                if i == 0:
                    shareid_s = shareid
                d = T.tr[T.td[shareid_s],
                         T.td[T.div(class_="nickname")[s.get_nickname()],
                              T.div(class_="nodeid")[T.tt[s.get_name()]]]
                         ]
                sharemap_data.append(d)
        add("Good Shares (sorted in share order)",
            T.table()[T.tr[T.th["Share ID"], T.th(class_="nickname-and-peerid")[T.div["Nickname"], T.div(class_="nodeid")["Node ID"]]],
                      sharemap_data])


        add("Recoverable Versions", cr.get_version_counter_recoverable())
        add("Unrecoverable Versions", cr.get_version_counter_unrecoverable())

        # this table is sorted by permuted order
        permuted_servers = [s
                            for s
                            in sb.get_servers_for_psi(cr.get_storage_index())]

        num_shares_left = sum([len(shareids)
                               for shareids in shares_on_server.values()])
        servermap = []
        for s in permuted_servers:
            shareids = list(shares_on_server.get(s, []))
            shareids.reverse()
            shareids_s = [ T.tt[shareid, " "] for shareid in sorted(shareids) ]
            d = T.tr[T.td[T.div(class_="nickname")[s.get_nickname()],
                          T.div(class_="nodeid")[T.tt[s.get_name()]]],
                     T.td[shareids_s],
                     ]
            servermap.append(d)
            num_shares_left -= len(shareids)
            if not num_shares_left:
                break
        add("Share Balancing (servers in permuted order)",
            T.table()[T.tr[T.th(class_="nickname-and-peerid")[T.div["Nickname"], T.div(class_="nodeid")["Node ID"]], T.th["Share IDs"]],
                      servermap])

        return T.ul[r]