Пример #1
0
def template(templatename, pattern=None):
    """
    Load XML template
    """
    return loaders.xmlfile(templatename, 
                           templateDir=config.TEMPLATE_PATH,
                           pattern=pattern)
Пример #2
0
    def getDocFactory(self, fragmentName, default=None):
        """
        For a given fragment, return a loaded Nevow template.

        @param fragmentName: the name of the template (can include relative
        paths).

        @param default: a default loader; only used if provided and the
        given fragment name cannot be resolved.

        @return: A loaded Nevow template.
        @type return: L{nevow.loaders.xmlfile}
        """
        if fragmentName in self.cachedLoaders:
            return self.cachedLoaders[fragmentName]
        segments = fragmentName.split('/')
        segments[-1] += '.html'
        file = self.directory
        for segment in segments:
            file = file.child(segment)
        if file.exists():
            loader = xmlfile(file.path)
            self.cachedLoaders[fragmentName] = loader
            return loader
        return default
Пример #3
0
class Events(rend.Page):
    docFactory = loaders.xmlfile("search.html")

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

    @print_timing
    def render_topics(self, ctx, data):
        graph = self.graph
        byClass = {}
        for row in self.graph.queryd("""
          SELECT DISTINCT ?topic ?cls WHERE {
            ?img a foaf:Image ;
              foaf:depicts ?topic .
            ?topic a ?cls .
          }"""):
            byClass.setdefault(row['cls'], set()).add(row['topic'])

        for cls, topics in byClass.items():
            yield T.h2[graph.label(cls, default=cls)]
            rows = []
            for topic in topics:
                try:
                    localUrl = localSite(topic)
                except ValueError, e:
                    log.warn("skipping topic %r: %s" % (topic, e))
                    continue
                lab = topicLabel(graph, topic)
                rows.append((lab.lower(), T.div[T.a(href=localUrl)[lab]]))
            rows.sort()
            yield [r[1] for r in rows]
Пример #4
0
class LightsElement(athena.LiveElement):
    """ a 'live' lights element.
    """
    docFactory = loaders.xmlfile(
        os.path.join(templatepath, 'lightsElement.html'))
    jsClass = u'lights.LightsWidget'

    def __init__(self, p_workspace_obj, _p_params):
        self.m_workspace_obj = p_workspace_obj
        self.m_pyhouse_obj = p_workspace_obj.m_pyhouse_obj

    @athena.expose
    def getHouseData(self):
        l_house = GetJSONHouseInfo(self.m_pyhouse_obj)
        return l_house

    @athena.expose
    def saveLightData(self, p_json):
        """A new/changed light is returned.  Process it and update the internal data via light_xxxx.py
        """
        l_json = JsonUnicode().decode_json(p_json)
        l_delete = l_json['Delete']
        l_light_ix = int(l_json['Key'])
        if l_delete:
            try:
                del self.m_pyhouse_obj.House.Lighting.Lights[l_light_ix]
            except AttributeError:
                LOG.error("web_lights - Failed to delete - JSON: {0:}".format(
                    l_json))
            return
        try:
            l_obj = self.m_pyhouse_obj.House.Lighting.Lights[l_light_ix]
        except KeyError:
            LOG.warning(
                'Creating a new light for light {0:}'.format(l_light_ix))
            l_obj = lighting_lights.LightData()
        #
        l_obj.Name = l_json['Name']
        l_obj.Active = l_json['Active']
        l_obj.Key = l_light_ix
        l_obj.Comment = l_json['Comment']
        l_coords = CoordinateData()
        l_coords.X_Easting = l_json['RoomCoords'][0]
        l_coords.Y_Northing = l_json['RoomCoords'][1]
        l_coords.Z_Height = l_json['RoomCoords'][2]
        l_obj.RoomCoords = l_coords
        l_obj.IsDimmable = l_json['IsDimmable']
        l_obj.DeviceFamily = l_json['DeviceFamily']
        l_obj.RoomName = l_json['RoomName']
        l_obj.LightingType = l_json['LightingType']
        l_obj.UUID = l_json['UUID']
        #  if len(l_obj.UUID) < 8:
        #    l_obj.UUID = str(uuid.uuid1())
        if l_obj.DeviceFamily == 'Insteon':
            Insteon_utils.Util().get_json_data(l_obj, l_json)
        elif l_obj.DeviceFamily == 'UPB':
            l_obj.UPBAddress = l_json['UPBAddress']
            l_obj.UPBPassword = l_json['UPBPassword']
            l_obj.UPBNetworkID = l_json['UPBNetworkID']
        self.m_pyhouse_obj.House.Lighting.Lights[l_light_ix] = l_obj
Пример #5
0
class MapWidget(athena.LiveElement):
    implements(iwebby.IMapWidget)
    jsClass = u'SVGMap.MapWidget'
    docFactory = loaders.xmlfile(RESOURCE('elements/MapWidget'))

    def __init__(self, channel, chatEntry, *a, **kw):
        super(MapWidget, self).__init__(*a, **kw)
        self.channel = channel
        self.chatEntry = chatEntry

    def setMapBackgroundFromChannel(self):
        """
        Create a new BackgroundImage widget and send it to the channel.
        """
        image = BackgroundImage(self.channel)
        image.setFragmentParent(self)
        return self.callRemote("setMapBackground", image)

    def updateObscurementFromChannel(self):
        """
        Just send a new md5key for the obscurement, which the client-side
        widget will use to reset the background.
        """
        return self.callRemote("updateObscurement",
                               self.channel.obscurement.md5)

    def sendCommand(self, command):
        return self.chatEntry.chatMessage(command)

    athena.expose(sendCommand)
Пример #6
0
class SecureButton(rend.Page):
    addSlash = True
    docFactory = loaders.xmlfile("securebutton.html")

    def __init__(self, graph, cmdlog, user):
        self.graph = graph
        self.cmdlog = cmdlog
        self.user = user
        self.ticketFile = "/tmp/garage-secret"
        self.lastCmd = ""
        rend.Page.__init__(self)

    @inlineCallbacks
    def renderHTTP(self, ctx):
        req = inevow.IRequest(ctx)
        if req.method == 'POST':
            try:
                if ctx.arg('ticket') != self.getTicket():
                    raise ValueError("incorrect access ticket")

                yield self.buttonPress()

                self.lastCmd = time.strftime("activated at %H:%M:%S")
            except ValueError, e:
                self.lastCmd = str(e)

        ret = yield rend.Page.renderHTTP(self, ctx)
        returnValue(ret)
Пример #7
0
class TypeAheadPage(athena.LivePage):
    _tmpl = util.sibpath(__file__, "typeahead.html")
    docFactory = loaders.xmlfile(_tmpl)
    def render_typehereField(self, ctx, data):
        frag = TypeAheadFieldFragment()
        frag.page = self
        return frag
Пример #8
0
class Page(PageHelpers.DefaultAthena):
    moduleName = 'calendar'
    moduleScript = 'calendar.js' 
    docFactory = loaders.xmlfile('calendar.xml', templateDir = Settings.BaseDir + '/templates')

    addSlash = True

    def render_thisFragment(self, ctx, data):
        """ Renders calendarFragment instance """
        f = calendarFragment(self.avatarId)
        f.setFragmentParent(self)
        return ctx.tag[f]

    def render_pageName(self, ctx, data):
        return ctx.tag[""]

    def render_sideMenu(self, ctx, data):
        return ctx.tag[""]

    def render_content(self, ctx, data):
        return ctx.tag[
            tags.div[
                tags.invisible(render=tags.directive('thisFragment'))
            ]
        ]
Пример #9
0
class TableWidget(athena.LiveFragment):
    jsClass = u"tableWidget"

    docFactory = loaders.xmlfile('tableWidget.xml', templateDir = '/usr/local/tcs/tums/templates')

    tableName = "dragTable"

    def __init__(self, *a, **kw):
        athena.LiveFragment.__init__(self, *a, **kw)
        self.sysconf = confparse.Config()

    def getData(self):
        # Returns 2D array of table data, and the headers
        return [[u"<a href='/'>Foo!</a>",2], [3,4]], [u"Number 1", u"Number 2"]
    athena.expose(getData)

    def tableChanged(self, rowOrder):
        print "New row order", rowOrder
        pass
    athena.expose(tableChanged)

    def getTableName(self):
        return unicode(self.tableName)

    athena.expose(getTableName)

    def render_tableSlot(self, ctx, tag):
        return ctx.tag[tags.div(id=self.tableName)[""]]
Пример #10
0
class ControllersElement(athena.LiveElement):
    """ a 'live' controllers element.
    """
    docFactory = loaders.xmlfile(
        os.path.join(templatepath, 'controllersElement.html'))
    jsClass = u'controllers.ControllersWidget'

    def __init__(self, p_workspace_obj, _p_params):
        self.m_workspace_obj = p_workspace_obj
        self.m_pyhouse_obj = p_workspace_obj.m_pyhouse_obj

    @athena.expose
    def getHouseData(self):
        l_house = GetJSONHouseInfo(self.m_pyhouse_obj)
        return l_house

    @athena.expose
    def getInterfaceData(self):
        """ A JS request for information has been received from the client.
        """
        l_interfaces = VALID_INTERFACES
        l_obj = {}
        for l_interface in l_interfaces:
            _l_name = l_interface + 'Data'
        l_json = json_tools.encode_json(l_obj)
        return unicode(l_json)

    @athena.expose
    def saveControllerInformation(self, p_json):
        """A new/changed controller is returned.  Process it and update the internal data via controller.py
        """
        l_json = json_tools.decode_json_unicode(p_json)
        l_ix = int(l_json['Key'])
        l_delete = l_json['Delete']
        if l_delete:
            try:
                del self.m_pyhouse_obj.House.Lighting.Controllers[l_ix]
            except AttributeError:
                LOG.error(
                    "web_controllers - Failed to delete - JSON: {}".FORMAT(
                        l_json))
            return
        l_obj = ControllerInformation()
        try:
            l_obj = self.m_pyhouse_obj.House.Lighting.Controllers[l_ix]
        except KeyError:
            LOG.warning('Creating a new controller {}'.format(l_ix))
        web_utils.get_base_info(l_obj, l_json)
        l_obj.Comment = l_json['Comment']
        l_obj.DeviceFamily = l_json['DeviceFamily']
        l_obj.DeviceType = 1
        l_obj.DeviceSubType = 2
        l_obj.InterfaceType = l_json['InterfaceType']
        l_obj.Port = l_json['Port']
        if l_obj.InterfaceType == 'Serial':
            l_obj.BaudRate = l_json['BaudRate']
        web_family.get_family_json_data(l_obj, l_json)
        web_utils.get_room_info(l_obj, l_json)
        self.m_pyhouse_obj.House.Lighting.Controllers[l_ix] = l_obj
        LOG.info('Controller Added - {}'.format(l_obj.Name))
Пример #11
0
class MainPage(rend.Page):

    docFactory = loaders.xmlfile(util.sibpath(__file__, "main.xhtml"))

    def __init__(self, config, dbpool, collector):
        self.config = config['web']
        self.dbpool = dbpool
        self.collector = collector
        rend.Page.__init__(self)

    def render_logo(self, ctx, data):
        if 'logo' in self.config and os.path.exists(self.config['logo']):
            return T.img(src="customlogo")
        return "To place your logo here, see the documentation"

    def child_customlogo(self, ctx):
        return static.File(self.config['logo'])

    def child_static(self, ctx):
        return static.File(util.sibpath(__file__, "static"))

    def child_api(self, ctx):
        return ApiResource(self.config, self.dbpool, self.collector)

    def childFactory(self, ctx, node):
        """Backward compatibility with previous API"""
        if node in ["equipment", "search", "complete", "past", "images"]:
            inevow.IRequest(ctx).rememberRootURL()
            return RedirectApi()
        return None
Пример #12
0
class ButtonsElement(athena.LiveElement):
    """ a 'live' login element containing a username and password.
    """
    docFactory = loaders.xmlfile(
        os.path.join(templatepath, 'buttonsElement.html'))
    jsClass = u'buttons.ButtonsWidget'

    def __init__(self, p_workspace_obj, _p_params):
        self.m_workspace_obj = p_workspace_obj
        self.m_pyhouse_obj = p_workspace_obj.m_pyhouse_obj

    @athena.expose
    def getHouseData(self):
        l_house = GetJSONHouseInfo(self.m_pyhouse_obj)
        return l_house

    @athena.expose
    def saveButtonData(self, p_json):
        """A new/changed button is returned.
        """
        l_json = JsonUnicode().decode_json(p_json)
        l_obj = lighting_buttons.ButtonData()
        l_obj.Name = l_json['Name']
        l_obj.Active = l_json['Active']
        l_obj.Key = l_json['Key']
        l_obj.Level = l_json['Level']
        if l_obj.DeviceFamily == 'Insteon':
            Insteon_utils.Util.get_json_data(l_obj, l_json)
Пример #13
0
class SignupPage(athena.LivePage):
    addSlash = 1
    docFactory = loaders.xmlfile(RESOURCE('templates/signup.xhtml'))

    def render_signup(self, ctx, data):
        pageURL = flat.flatten(url.URL.fromContext(ctx))
        signup = Signup(pageURL)
        signup.setFragmentParent(self)
        return signup

    def renderHTTP(self, ctx):
        """
        Check for a confirmation being used from the email link.

        If the user is confirming a login, move the password from
        unconfirmedPassword into password, thus enabling the account.
        """
        req = inevow.IRequest(ctx)
        confirm = req.args.get('confirm', None)
        if confirm is not None:
            confirm = unicode(confirm[0])
            store = theGlobal['database']
            u = store.findFirst(data.User,
                                data.User.confirmationKey == confirm)
            if u is not None:
                u.password = u.unconfirmedPassword
                u.unconfirmedPassword = None
                req.args.clear()
                self.docFactory = loaders.xmlfile(
                    RESOURCE('templates/confirmed.xhtml'))
            else:
                self.docFactory = loaders.stan(
                    ['Could not confirm that account.'])
        return super(SignupPage, self).renderHTTP(ctx)
Пример #14
0
    def render_content(self, ctx, data):
        role = self.getRole(ctx)

        if role == 0:
            return self.renderAlert('You are not authorized')

        return loaders.xmlfile(webappPath('agent/index.html'))
Пример #15
0
class Twister(livepage.LivePage):
    addSlash = True

    def render_form(self, context, data):
        return context.tag(onsubmit=ping)  # livepage.handler(ping))

    docFactory = loaders.xmlfile('twist.html')
Пример #16
0
class Atom(BaseUI):
    docFactory = loaders.xmlfile('atom.xml')
    
    def beforeRender(self, ctx):
        inevow.IRequest(ctx).setHeader("Content-Type", "application/application+xml; charset=UTF-8")
    
    def data_getFirstPost(self, ctx, data):
        for post in IBlog(IStore(ctx)).getPosts(1):
            return post

    def render_modified(self, ctx, data): 
        return ctx.tag.clear()[atompptime(data.modified)]
    
    def data_get_posts(self, ctx, data):
        return IBlog(IStore(ctx)).getPosts(15)
        
    def render_post(self, ctx, data):
        #id = data.poolToUID[IBlog(IStore(ctx)).postsPool]
        # mkp: ...I don't know what that means or what it's for.
        ctx.tag.fillSlots('title', data.title)
        ctx.tag.fillSlots('link', url.root.child(data.id))
        ctx.tag.fillSlots('id', data.id)
        ctx.tag.fillSlots('created', atompptime(data.created))
        ctx.tag.fillSlots('modified', atompptime(data.modified))        
        ctx.tag.fillSlots('author', data.author)
        ctx.tag.fillSlots('content', data.content)
        return ctx.tag
Пример #17
0
class MovePage(rend.Page):
    implements(iskin.ISkinnable)

    title = _('Ldaptor Move Page')

    addSlash = True
    docFactory = loaders.xmlfile('move.xhtml',
                                 templateDir=os.path.split(
                                     os.path.abspath(__file__))[0])

    def render_url(self, ctx, data):
        u = url.URL.fromContext(ctx)
        return ctx.tag(href=u.parentdir().child('search'))

    def childFactory(self, context, name):
        dn = uriUnquote(name)
        session = inevow.ISession(context)
        userEntry = session.getLoggedInRoot().loggedIn

        move = session.getComponent(IMove)
        if move is None:
            move = []
            session.setComponent(IMove, move)

        e = ldapsyntax.LDAPEntryWithClient(dn=dn, client=userEntry.client)
        move.append(e)
        u = url.URL.fromContext(context).sibling('search')
        return u

    render_i18n = i18n.render()
Пример #18
0
class LoginPage(rend.Page):
    """The resource that is returned when you are not logged in"""

    implements(iskin.ISkinnable)

    title = _('Login')

    docFactory = loaders.xmlfile(
        'login.xhtml',
        templateDir=os.path.split(os.path.abspath(__file__))[0])

    def __init__(self, history):
        self.history = history
        super(LoginPage, self).__init__()

    def locateChild(self, request, segments):
        return LoginPage(self.history + list(segments)), []

    def render_form(self, context, data):
        current = url.URL.fromContext(context)
        action = getActionURL(current, self.history)
        context.fillSlots('action-url', str(action))
        return context.tag

    render_i18n = i18n.render()
Пример #19
0
    def test_docFactoryInStanTree(self):

        class Page(rend.Page):

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

            def render_included(self, context, data):
                return self.included
            
            docFactory = loaders.stan(div[invisible(render=directive('included'))])

        doc = '<p>fum</p>'
        temp = self.mktemp()
        f = file(temp, 'w')
        f.write(doc)
        f.close()

        result = deferredRender(Page(loaders.stan(p['fee'])))
        self.assertEquals(result, '<div><p>fee</p></div>')
        result = deferredRender(Page(loaders.htmlstr('<p>fi</p>')))
        self.assertEquals(result, '<div><p>fi</p></div>')
        result = deferredRender(Page(loaders.xmlstr('<p>fo</p>')))
        self.assertEquals(result, '<div><p>fo</p></div>')
        result = deferredRender(Page(loaders.htmlfile(temp)))
        self.assertEquals(result, '<div><p>fum</p></div>')
        result = deferredRender(Page(loaders.xmlfile(temp)))
        self.assertEquals(result, '<div><p>fum</p></div>')
Пример #20
0
class Atom(Base):
    docFactory = loaders.xmlfile('atom.xml')
    
    def beforeRender(self, ctx):
        inevow.IRequest(ctx).setHeader(b"Content-Type", "application/application+xml; charset=UTF-8")
    
    def data_getFirstPost(self, ctx, data):
        for post in IPostit(self.store).getPosts(1):
            return post

    def render_modified(self, ctx, data): 
        return ctx.tag.clear()[atompptime(data.created)]
    
    def data_get_posts(self, ctx, data):
        return IPostit(self.store).getPosts(15)
        
    def render_post(self, ctx, data):
        ctx.tag.fillSlots('title', data.title)
        ctx.tag.fillSlots('link', data.url)
        ctx.tag.fillSlots('id', data.storeID)
        ctx.tag.fillSlots('created', atompptime(data.created))
        ctx.tag.fillSlots('modified', atompptime(data.created))
        ctx.tag.fillSlots('author', data.author)
        ctx.tag.fillSlots('content', data.content)
        return ctx.tag
Пример #21
0
class ClassIndexPage(page.Element):
    filename = 'classIndex.html'
    docFactory = loaders.xmlfile(templatefile('summary.html'))

    def __init__(self, system):
        self.system = system

    @page.renderer
    def title(self, request, tag):
        return tag.clear()["Class Hierarchy"]

    @page.renderer
    def stuff(self, request, tag):
        t = tag
        anchors = set()
        for b, o in findRootClasses(self.system):
            if isinstance(o, model.Class):
                t[subclassesFrom(self.system, o, anchors)]
            else:
                item = tags.li[b]
                if o:
                    ul = tags.ul()
                    for sc in sorted(o, key=_lckey):
                        ul[subclassesFrom(self.system, sc, anchors)]
                    item[ul]
                t[item]
        return t

    @page.renderer
    def heading(self, request, tag):
        return tag.clear()["Class Hierarchy"]
Пример #22
0
 def macro_content(self, ctx):
     return t.invisible[
                t.p["This macro has been called ",
                    next(counter2)+1,
                    " time(s)"],
                loaders.xmlfile(util.sibpath(__file__,'child_macro.html'), ignoreDocType=True).load()
         ]
Пример #23
0
class UndocumentedSummaryPage(page.Element):
    filename = 'undoccedSummary.html'
    docFactory = loaders.xmlfile(templatefile('summary.html'))

    def __init__(self, system):
        self.system = system

    @page.renderer
    def title(self, request, tag):
        return tag.clear()["Summary of Undocumented Objects"]

    @page.renderer
    def heading(self, request, tag):
        return tag.clear()["Summary of Undocumented Objects"]

    @page.renderer
    def stuff(self, request, tag):
        undoccedpublic = [
            o for o in self.system.orderedallobjects
            if o.isVisible and not hasdocstring(o)
        ]
        undoccedpublic.sort(key=lambda o: o.fullName())
        for o in undoccedpublic:
            tag[tags.li[o.kind, " - ", taglink(o)]]
        return tag
Пример #24
0
class ComposeMail(MailMixin, PageHelpers.DefaultAthena):
    docFactory = loaders.xmlfile('mail-compose.xml',
                                 templateDir=Settings.BaseDir + '/templates')

    moduleName = 'mailbox'
    moduleScript = 'mail-compose.js'

    def __init__(self, avatarId, db, *a, **kw):
        PageHelpers.DefaultAthena.__init__(self, avatarId, db, *a, **kw)
        self.imap = MailClient.IMAPClient(self.avatarId)

    def render_thisFragment(self, ctx, data):
        """ Renders MailFragment instance """
        f = ComposeFragment(self.avatarId, self.imap)
        f.setFragmentParent(self)
        return ctx.tag[f]

    def render_hashkey(self, ctx, data):
        return ctx.tag[tags.input(id="hashKey",
                                  name="hashKey",
                                  type="hidden",
                                  value="%s%s" %
                                  (int(time.time()), self.avatarId.username))]

    def render_content(self, ctx, data):
        toolbar = [("#", 'Send', "/images/inbox.png", "sendBtn")]

        return ctx.tag[tags.ul(id="mailTools")[[
            tags.li[tags.a(id=id, href=link)[tags.div[tags.img(src=image)],
                                             name]]
            for link, name, image, id in toolbar
        ]],
                       tags.invisible(render=tags.directive('thisFragment'))]
Пример #25
0
    def test_docFactoryInStanTree(self):
        class Page(rend.Page):
            def __init__(self, included):
                self.included = included
                rend.Page.__init__(self)

            def render_included(self, context, data):
                return self.included

            docFactory = loaders.stan(
                div[invisible(render=directive('included'))])

        doc = '<p>fum</p>'
        temp = self.mktemp()
        f = file(temp, 'w')
        f.write(doc)
        f.close()

        result = deferredRender(Page(loaders.stan(p['fee'])))
        self.assertEquals(result, '<div><p>fee</p></div>')
        result = deferredRender(Page(loaders.htmlstr('<p>fi</p>')))
        self.assertEquals(result, '<div><p>fi</p></div>')
        result = deferredRender(Page(loaders.xmlstr('<p>fo</p>')))
        self.assertEquals(result, '<div><p>fo</p></div>')
        result = deferredRender(Page(loaders.htmlfile(temp)))
        self.assertEquals(result, '<div><p>fum</p></div>')
        result = deferredRender(Page(loaders.xmlfile(temp)))
        self.assertEquals(result, '<div><p>fum</p></div>')
Пример #26
0
 def render_content(self, ctx, data):
     role = self.getRole(ctx)
     
     if role == 0:
         return self.renderAlert('You are not authorized')
     
     return loaders.xmlfile(webappPath('agent/index.html'))
Пример #27
0
class DefaultPage(formal.ResourceMixin, rend.Page, VulaniMixin):
    isTool = False
    addSlash = True
    childPages = {}
    docFactory  = loaders.xmlfile('default.xml', templateDir=Settings.BaseDir+'/templates')

    pageMenu = []

    def __init__(self, avatarId = None, db = None, *a, **k):
        formal.ResourceMixin.__init__(self, *a, **k)
        rend.Page.__init__(self, *a, **k)
        self.avatarId = avatarId
        self.db = db
        self.sysconf = confparse.Config()
        self.render_userBar = render_userBar

        self.lockStatus, self.lockTime, self.lockUser = isLocked()
        try:
            self.text = db[2]
            self.handler = db[3]
        except:
            print "Failed to get i18l module"

    def childFactory(self, ctx, seg):
        if seg in self.childPages:
            return self.childPages[seg](self.avatarId, self.db)
        print "Passing childFactory"
        return rend.Page.childFactory(self, ctx, seg)

    def logout(self):
        print "Logged out"
Пример #28
0
class ChatterElement(LiveElement):

    docFactory = xmlfile(sibpath(__file__, 'template.html'))
    jsClass = u'ChatThing.ChatterWidget'

    def __init__(self, room):
        self.room = room

    def setUsername(self, username):
        self.username = username
        message = ' * user ' + username + ' has joined the room'
        self.room.wall(message)

    setUsername = expose(setUsername)

    def say(self, message):
        self.room.tellEverybody(self, message)

    say = expose(say)

    def wall(self, message):
        self.callRemote('displayMessage', message)

    def hear(self, username, what):
        self.callRemote('displayUserMessage', username, what)
Пример #29
0
class MailPage(MailMixin, PageHelpers.DefaultAthena):

    docFactory = loaders.xmlfile('mail.xml',
                                 templateDir=Settings.BaseDir + '/templates')

    moduleName = 'mailbox'
    moduleScript = 'mailbox.js'

    def __init__(self, *a, **kw):
        PageHelpers.DefaultAthena.__init__(self, *a, **kw)
        self.imap = MailClient.IMAPClient(self.avatarId)

    def render_thisFragment(self, ctx, data):
        """ Renders MailFragment instance """
        f = MailFragment(self.avatarId, self.imap)
        f.setFragmentParent(self)
        return ctx.tag[f]

    def render_content(self, ctx, data):
        toolbar = [
            ("/mail/New/", 'New', "/images/inbox.png", "newmail"),
            ("#", 'Delete', "/images/inbox.png", "deletesel"),
        ]

        return ctx.tag[tags.ul(id="mailTools")[[
            tags.li(id=id)[tags.a(href=link)[tags.div[tags.img(src=image)],
                                             name]]
            for link, name, image, id in toolbar
        ]],
                       tags.invisible(render=tags.directive('thisFragment'))]
Пример #30
0
class MassPasswordChangePage(rend.Page):
    implements(iskin.ISkinnable)

    title = _('Ldaptor Mass Password Change Page')

    addSlash = True
    docFactory = loaders.xmlfile('mass_change_password.xhtml',
                                 templateDir=os.path.split(
                                     os.path.abspath(__file__))[0])

    def __init__(self, baseObject):
        super(MassPasswordChangePage, self).__init__()
        self.baseObject = baseObject

    def render_url(self, context, data):
        u = url.URL.fromContext(context)
        return context.tag(href=u.parentdir().child('search'))

    def childFactory(self, context, name):
        entry = inevow.ISession(context).getLoggedInRoot().loggedIn

        filt = uriUnquote(name)

        e = ldapsyntax.LDAPEntry(client=entry.client, dn=self.baseObject)
        d = e.search(filterText=filt, sizeLimit=20)
        d.addCallback(ReallyMassPasswordChangePage)
        return d

    render_i18n = i18n.render()
Пример #31
0
class Page(PageHelpers.DefaultAthena):
    moduleName = 'diagnostics'
    moduleScript = 'mail-diagnostics.js' 
    docFactory = loaders.xmlfile('livepage.xml', templateDir = Settings.BaseDir + '/templates')

    addSlash = True

    def render_thisFragment(self, ctx, data):
        """ Renders liveGraphFragment instance """
        f = liveGraphFragment()
        f.setFragmentParent(self)
        return ctx.tag[f]

    def render_pageName(self, ctx, data):
        return ctx.tag[tags.h2[tags.img(src='/images/tools-lg.png'), " Tools"]]

    def render_sideMenu(self, ctx, data):
        return ctx.tag[Tools.Page.sideMenu(Tools.Page(None, self.db), ctx, data)]

    def render_content(self, ctx, data):
        return ctx.tag[
            tags.h3[tags.img(src="/images/networking_section.png"), " Mail Diagnostics"],
            tags.div[
                tags.invisible(render=tags.directive('thisFragment'))
            ]
        ]
Пример #32
0
class WebsElement(athena.LiveElement):
    """ a 'live' webs element.
    """
    docFactory = loaders.xmlfile(os.path.join(templatepath,
                                              'websElement.html'))
    jsClass = u'webs.WebsWidget'

    def __init__(self, p_workspace_obj, _p_params):
        self.m_workspace_obj = p_workspace_obj
        self.m_pyhouse_obj = p_workspace_obj.m_pyhouse_obj

    @athena.expose
    def getWebsData(self):
        """ A JS client has requested all the webs information.
        """
        l_obj = self.m_pyhouse_obj.Computer.Web
        l_json = unicode(json_tools.encode_json(l_obj))
        return l_json

    @athena.expose
    def saveWebData(self, p_json):
        """A new/changed web is returned.  Process it and update the internal data via ???.py
        """
        l_json = json_tools.decode_json_unicode(p_json)
        l_obj = WebInformation()
        l_obj.Port = l_json['Port']
        self.m_pyhouse_obj._APIs.Computer.WebAPI.SaveXml(l_obj)
Пример #33
0
 def __init__(self, original, ctx, factory):
     self.factory = factory  
     self.user = self.factory.getUser(original)
     rend.Page.__init__(self, original)
     
     r = manager.ResourceManager()
     UserAdmin.docFactory = loaders.xmlfile( r["resources"]["web"]["user_admin.html"] )
Пример #34
0
class SVGUI_HMI(website.PLCHMI):
    jsClass = u"LiveSVGPage.LiveSVGWidget"

    docFactory = loaders.stan(
        tags.div(render=tags.directive('liveElement'))[
            tags.xml(loaders.xmlfile(os.path.join(NS.WorkingDir, svgfile))), ])

    def HMIinitialisation(self):
        gadgets = []
        for gadget in svguiWidgets.values():
            gadgets.append(
                text(
                    json.dumps(gadget, default=get_object_init_state,
                               indent=2), 'ascii'))
        d = self.callRemote('init', gadgets)
        d.addCallback(self.HMIinitialised)

    def sendData(self, data):
        if self.initialised:
            return self.callRemote(
                'receiveData',
                text(
                    json.dumps(data,
                               default=get_object_current_state,
                               indent=2), 'ascii'))
        return None

    def setattr(self, id, attrname, value):
        svguiWidgets[id].setinput(attrname, value)
Пример #35
0
class Main(Base):
    docFactory = loaders.xmlfile('postit.html')
    child_styles = static.File('styles/')
    child_images = static.File('images/')

    def childFactory(self, ctx, segment):
        if segment == 'atom.xml':
            return Atom(self.store)
        elif segment == 'rpc2.py':
            return PostItRPC(self.store)

    def render_title(self, ctx, data): 
        return ctx.tag.clear()[IPostit(self.store).name]
    
    def data_get_posts(self, ctx, data):
        return IPostit(self.store).getPosts(15)
        
    def render_post(self, ctx, data):
        ctx.tag.fillSlots('tit_tit_attr', data.title)
        ctx.tag.fillSlots('tit_url_attr', data.url)
        ctx.tag.fillSlots('title', data.title)
        ctx.tag.fillSlots('perma_tit_attr', 'PermaLink')
        ctx.tag.fillSlots('perma_url_attr', url.here.add('view', data.storeID))
        ctx.tag.fillSlots('id', data.storeID)
        ctx.tag.fillSlots('author', data.author)
        ctx.tag.fillSlots('data', pptime(data.created))
        ctx.tag.fillSlots('content', data.content)
        return ctx.tag
Пример #36
0
    def __init__(self, parent, package=None, webServer=None, name=None):
        """
        Pass me a 'parent' rendering component,
        a 'package' that I'm rendering for
        and a 'webServer' instance reference (from webServer.py)
        If you don't pass 'webServer' and 'package' I'll
        get them from 'parent'
        'name' is a identifier to distuniguish us from the other children of our
        parent
        """
        self.parent = parent # This is the same for both blocks and pages
        if name:
            self.name = name
        elif not self.name:
            raise AssertionError('Element of class "%s" created with no name.' %
                                 self.__class__.__name__)
            
        # Make pylint happy. These attributes will be gotten from
        # self.application
        self.config = Unset
        self.ideviceStore = Unset
        self.packageStore = Unset

        # Overwrite old instances with same name
        if parent:
            parent.renderChildren[self.name] = self
        self.renderChildren = {}
        if package:
            self.package = package
        elif parent:
            self.package = parent.package
        else:
            self.package = None
        if webServer:
            self.webServer = webServer
        elif parent:
            self.webServer = parent.webServer
        else:
            self.webServer = None
        if self._templateFileName:
            if hasattr(self, 'config') and self.config:
                pth = self.config.webDir/'templates'/self._templateFileName
                self.docFactory = loaders.xmlfile(pth)
            else:
                # Assume directory is included in the filename
                self.docFactory = loaders.xmlfile(self._templateFileName)
Пример #37
0
 def test_xmlfile(self):
     doc = '<ul id="nav"><li>a</li><li>b</li><li>c</li></ul>'
     temp = self.mktemp()
     f = file(temp, 'w')
     f.write(doc)
     f.close()
     df = loaders.xmlfile(temp)
     self.assertEquals(df.load()[0], doc)
Пример #38
0
 def __init__(self, original, options=None, otherOption=None):
     self.original = original
     if options is not None:
         self.options = options
     if otherOption is not None:
         self.otherOption = otherOption
     if self.template is None:
         self.template = loaders.xmlfile(util.resource_filename('formal',
             'html/SelectOtherChoice.html'))
Пример #39
0
	def __init__(self, *args, **kwargs):
		zoto_base_page.__init__(self, *args, **kwargs)
		self.album_id = -1
		self.offset = 0
		self.username = args[0]
		self.album_id = args[1]
		self.can_view = False
		self.docFactory = loaders.xmlfile(os.path.join(self.tpl_path, "album_template.xml"))
		self.template_path = "%s/album_templates" % aztk_config.setup.get("paths", "web")
Пример #40
0
 def render_content(self, ctx, data):
     # FIXME: should check roles
     
     yield self.getBasicAgentInfo(ctx)
     
     if self.agentInfo is None:
         returnValue(self.renderAlert("Couldn't retrieve information for agent %s" % self.agentUuid))
     else:            
         returnValue(loaders.xmlfile(webappPath('agent/loadinfo.html')))
Пример #41
0
 def __init__(self, parent):
     """
     Initialize
     """
     RenderableLivePage.__init__(self, parent)
     mainxul = Path(self.config.xulDir).joinpath('templates', 'properties.xul')
     self.docFactory  = loaders.xmlfile(mainxul)
     self.client = None
     self.fieldsReceived = set()
     log.info("creating the properties page")
Пример #42
0
 def test_xmlfileReload(self):
     temp = self.mktemp()
     f = file(temp, 'w')
     f.write(self.nsdoc)
     f.close()
     loader = loaders.xmlfile(temp)
     r = loader.load()
     self.assertEquals(id(r), id(loader.load()))
     os.utime(temp, (os.path.getatime(temp), os.path.getmtime(temp)+5))
     self.assertNotEqual(id(r), id(loader.load()))
Пример #43
0
    def run(self):
        kwargs = {}
        template = self.get('template', None)
        if template is not None:
            kwargs['docFactory'] = loaders.xmlfile(template)

        feed = readFeed(self.path)
        a = Atom(feed, **kwargs)
        d = a.renderString()
        d.addCallback(self._print)
        return d
Пример #44
0
 def test_xmlfilePreprocessors(self):
     """
     Test that the xmlstr loader properly passes uncompiled documents to
     preprocessors it is given.
     """
     xmlFile = self.mktemp()
     f = file(xmlFile, 'w')
     f.write('<div><span>Hello</span><span>world</span></div>')
     f.close()
     factory = loaders.xmlfile(xmlFile)
     return self._preprocessorTest(factory)
Пример #45
0
    def getfiles(self,nodes):
        for node in nodes:
            if len(node) == 4:
                self.getfiles(node[3])

            try:
                newpage = rend.Page()
                newpage.docFactory = loaders.xmlfile(node[2],templateDir='apidoc')
            except Exception,e:
                pass
            else:
                self.children[node[1]] = newpage
Пример #46
0
def getHtml(yamlfile, countItems, template):
    ydata = list(yaml.loadFile(yamlfile))[0]
    Page.docFactory = loaders.xmlfile(template)

    d = Page(ydata, countItems).renderString()

    output = []
    d.addCallback(cb, output)
    d.addErrback(eb)
    reactor.run()

    return output[0]
Пример #47
0
 def __init__(self, factory):
     '''
     Constructor
     
     @param factory: ScrabbleServerFactory
     '''
     rend.Page.__init__(self)
     self.factory = factory
     flat.registerFlattener(self.flattenTime, util.Time)
     
     r = manager.ResourceManager()
     ScrabbleSite.child_styles = static.File( r["resources"]["web"].path )
     ScrabbleSite.docFactory = loaders.xmlfile( r["resources"]["web"]["index.html"] )
    def test_xmlFileInStanTree(self):
        """
        Like L{test_htmlStringInStanTree}, but for an xmlfile loader.
        """
        doc = '<p>I</p>'
        temp = self.mktemp()
        f = file(temp, 'w')
        f.write(doc)
        f.close()

        return self._testDocFactoryInStanTree(
            loaders.xmlfile(temp),
            '<p>I</p>')
Пример #49
0
 def workloadType(self, ctx, wltypeName):
     session = inevow.ISession(ctx) 
     if self.workloadTypes is None:
         self.workloadTypes = yield session.agent.expsvcAgent.getWorkloadTypes(agentId = self.agentId)
     
     wltype = self.workloadTypes[wltypeName]
     
     wlcDescriptions = [T.li[wlclasses[wlc][1]]
                        for wlc 
                        in wltype.wlclass]
     
     ctx.fillSlots('name', wltypeName)
     ctx.fillSlots('module', wltype.module)
     ctx.fillSlots('path', wltype.path)
     ctx.fillSlots('classes', T.ul()[wlcDescriptions])
     
     self.data_workloadParams = []
     
     for paramName, param in wltype.params.iteritems():
                 if param.flags & TSWLParamCommon.WLPF_OPTIONAL:
                     paramName = T.span[paramName,
                                        T.sup['OPT']]
                 
                 wlpType = WLParamHelper.getTypeName(param)
                 
                 minVal, maxVal = WLParamHelper.getIntegerRange(param)
                 lenVal = WLParamHelper.getStringLength(param)
                 range = 'None'
                 
                 if minVal is not None and maxVal is not None:
                     range = '[%s...%s]' % (_wlparamToStr(minVal, param), 
                                            _wlparamToStr(maxVal, param))
                 elif lenVal is not None:
                     range = 'len: %s' % lenVal
                 
                 default = WLParamHelper.getDefaultValue(param)
                 if default is not None:
                     default = _wlparamToStr(default, param)
                 else:
                     default = 'None'
                 
                 self.data_workloadParams.append({'param': paramName, 
                                                  'type': wlpType, 
                                                  'range': range, 
                                                  'default': default, 
                                                  'description': param.description})
     
     wltparams = loaders.xmlfile(webappPath('agent/wltypeparam.html'))
     
     returnValue(wltparams)
Пример #50
0
 def __init__(self, parent, package):
     """
     Initialize a new XUL page
     'package' is the package that we look after
     """
     self.name = package.name
     RenderableLivePage.__init__(self, parent, package)
     self.putChild("resources", static.File(package.resourceDir))
     mainxul = Path(self.config.xulDir).joinpath('templates', 'mainpage.xul')
     self.docFactory  = loaders.xmlfile(mainxul)
     self.outlinePane = OutlinePane(self)
     self.idevicePane = IdevicePane(self)
     self.styleMenu   = StyleMenu(self)
     self.authoringPage  = AuthoringPage(self)
     self.propertiesPage = PropertiesPage(self)
Пример #51
0
 def test_xmlfile(self):
     temp = self.mktemp()
     f = file(temp, 'w')
     f.write(self.nsdoc)
     f.close()
     loader = loaders.xmlfile(temp)
     self.assertEquals( id(loader.load()), id(loader.load()) )
     loader = loaders.xmlfile(temp, pattern='1')
     self.assertEquals( id(loader.load()), id(loader.load()) )
     l1 = loaders.xmlfile(temp, pattern='1')
     l2 = loaders.xmlfile(temp, pattern='1')
     self.assertNotEqual( id(l1.load()), id(l2.load()) )
     l1 = loaders.xmlfile(temp, pattern='1')
     l2 = loaders.xmlfile(temp, pattern='2')
     self.assertNotEqual( id(l1.load()), id(l2.load()) )
Пример #52
0
    def renderHTTP(self, ctx):
        """
        Check for a confirmation being used from the email link.

        If the user is confirming a login, move the password from
        unconfirmedPassword into password, thus enabling the account.
        """
        req = inevow.IRequest(ctx)
        confirm = req.args.get('confirm', None) 
        if confirm is not None:
            confirm = unicode(confirm[0])
            store = theGlobal['database']
            u = store.findFirst(data.User, data.User.confirmationKey==confirm)
            if u is not None:
                u.password = u.unconfirmedPassword
                u.unconfirmedPassword = None
                req.args.clear()
                self.docFactory = loaders.xmlfile(
                        RESOURCE('templates/confirmed.xhtml'))
            else:
                self.docFactory = loaders.stan(['Could not confirm that account.'])
        return super(SignupPage, self).renderHTTP(ctx)
Пример #53
0
    def __init__(self, parent, package):
        """
        Initialize a new XUL page
        'package' is the package that we look after
        """
        self.name = package.name
        RenderableLivePage.__init__(self, parent, package)
        self.putChild("resources", static.File(package.resourceDir))

        mainxul = Path(self.config.xulDir).joinpath('templates', 'mainpage.xul')
        self.docFactory  = loaders.xmlfile(mainxul)

        # Create all the children on the left
        self.outlinePane = OutlinePane(self)
        self.idevicePane = IdevicePane(self)
        self.styleMenu   = StyleMenu(self)

        # And in the main section
        self.authoringPage  = AuthoringPage(self)
        self.propertiesPage = PropertiesPage(self)

        # translate the "don't close the window" message
        red_x = _("Please use eXe's\n   File... Quit\nmenu to close eXe.")
Пример #54
0
 def agentCommonInfo(self, ctx):
     agentInfo = self.agentInfo
     clientInfo = self.clientInfo
     
     if clientInfo is None:
         clientStateImg = T.img(src = '/images/cl-status/dead.png')
         clientState = 'disconnected'
         
         clientId = 'N/A'
         clientUuid = 'N/A'
         clientEndpoint = 'N/A'
     else:
         clientStateImg = T.img(src = '/images/cl-status/established.png')
         clientState = 'established'
         
         clientId = clientInfo.id
         clientUuid = clientInfo.uuid
         clientEndpoint = clientInfo.endpoint
     
     for slot, data in [('hostname', agentInfo.hostname),
                         ('domainname', agentInfo.domainname),
                         ('osname', agentInfo.osname),
                         ('release', agentInfo.release),
                         ('arch', agentInfo.machineArch),
                         ('numCPUs', agentInfo.numCPUs),
                         ('numCores', agentInfo.numCores),
                         ('memTotal', agentInfo.memTotal),
                         ('agentId', agentInfo.agentId),
                         ('lastOnline', agentInfo.lastOnline),
                         ('clientStateImg', clientStateImg),
                         ('clientState', clientState),
                         ('clientId', clientId),
                         ('clientUuid', clientUuid),
                         ('clientEndpoint', clientEndpoint)]:
             ctx.fillSlots(slot, data)
         
     return loaders.xmlfile(webappPath('agent/loadinfoagent.html'))
Пример #55
0
 def test_xmlfile(self):
     temp = self.mktemp()
     f = file(temp, 'w')
     f.write('<p>hello</p>')
     f.close()
     self._withAndWithout(loaders.xmlfile(temp))
Пример #56
0
 def docFactory(self):
     return loaders.xmlfile(_tpl.path)
Пример #57
0
 def render_servicePasswords(self, ctx, data):
     docFactory = loaders.xmlfile(
         'change_service_passwords.xhtml',
         templateDir=os.path.split(os.path.abspath(__file__))[0])
     r = inevow.IQ(docFactory).onePattern('main')
     return r
Пример #58
0
def getxmlfile(name):
    return loaders.xmlfile(resource_filename('allmydata.web', '%s' % name))
Пример #59
0
def loader(filename):
    return loaders.xmlfile(util.resource_filename('ecommerce.product.templates',
        filename), ignoreDocType=True)