def resourceFactory(self, fileName): """ Retrieve an L{inevow.IResource} which will render the contents of C{fileName}. """ return static.File(fileName)
liveInput = Input() def _locateGlueJS(): """Calculate and return the full path to the liveevil glue JavaScript. """ import os.path dirname = os.path.abspath(os.path.dirname(__file__)) return os.path.join(dirname, 'liveevil.js') try: _glueJS = _locateGlueJS() # A static.File resource that can be used from a <link> glueJS = static.File(_glueJS, 'text/javascript') # Inline JavaScript glue. TODO: deprecate this. glue = tags.inlineJS(open(_glueJS).read()) # Glue which tells livepage to only allow clientToServer events, not async serverToClient events inputOnlyGlue = tags.inlineJS( "var auto_open = false; var liveevil_unload = true;\n" + ''.join(open(_glueJS).readlines()[1:])) except EnvironmentError: glueJS = inputOnlyGlue = glue = None warnings.warn("Could not open liveevil.js") ctsTemplate = "nevow_clientToServerEvent('%s',this%s);%s" handledEventPostlude = ' return false;'
def child_static(self, ctx): return static.File("static")
class UI(BaseUI): docFactory = loaders.xmlfile('ui.html') child_styles = static.File('styles') child_images = static.File('images') child_webform_css = webform.defaultCSS def render_starttimer(self, ctx, data): ctx.remember(now(), ITimer) return ctx.tag def render_stoptimer(self, ctx, data): start = ITimer(ctx) return ctx.tag['%s' % (now() - start)] def render_needForms(self, ctx, data): action = ctx.arg('action', 'view') if action == 'edit': form = inevow.IQ(ctx).onePattern('frm') return ctx.tag[form] return ctx.tag.clear() def data_getEntries(self, ctx, data): num = ctx.arg('num', '60') return IBlog(IStore(ctx)).getPosts(int(num)) def render_entries(self, ctx, data): ctx.tag.fillSlots('modification', pptime(data.modified)) ctx.tag.fillSlots('category', data.category) ctx.tag.fillSlots('author', data.author) ctx.tag.fillSlots('title', data.title) ctx.tag.fillSlots('content', data.content) ctx.tag.fillSlots('permaLink', url.root.child('%s' % (data.id))) return ctx.tag def render_insert(self, ctx, data): return ctx.tag def render_editer(self, ctx, data): ctx.tag.fillSlots( 'editPost', url.root.child('%s' % (data.id)).add('action', 'edit')) return ctx.tag def render_insert(self, ctx, data): ctx.tag.fillSlots('insert', url.root.child('insertEntry')) return ctx.tag def child_insertEntry(self, ctx): return NewEntry() def childFactory(self, ctx, segment): id = segment.isdigit() and segment or '-1' if int(id) >= 0: return IBlog(IStore(ctx)).getOne(int(id)) elif segment == 'rpc2': return BlogRPC(IStore(ctx)) elif segment == 'atom.xml': return Atom() def child_thx(self, ctx): return Thx()
def __init__(self, testSuite): super(TestFramework, self).__init__() self.testSuite = testSuite self.children = { 'livetest.css': static.File(util.resource_filename('nevow.livetrial', 'livetest.css')), }
if onKeyUp: self.onKeyUp = onKeyUp def child_canvas_socket(self, ctx): return CanvasSocket() width = 1000 height = 500 onload = None onMouseDown = None onMouseUp = None onMouseMove = None onKeyUp = None onKeyDown = None def render_canvas(self, ctx, data): return canvas(self.width, self.height, self) docFactory = loaders.stan(tags.html[render_canvas]) setattr( Canvas, 'child_nevow_canvas_movie.swf', static.File(os.path.join(os.path.split(__file__)[0], 'Canvas.swf'), 'application/x-shockwave-flash')) #setattr(Canvas, 'child_nevow_canvas_movie.swd', static.File( # os.path.join( # os.path.split(__file__)[0], 'Canvas.swd'), # 'application/x-shockwave-flash'))
class WebMonitor(rend.Page, service.Service): '''Web monitor interface.''' addSlash = True child_images = static.File('monitor/images') docFactory = loaders.xmlfile('monitor/index.html') def __init__(self, application, config, broker): rend.Page.__init__(self) self.setServiceParent(application) self.config = config self.broker = broker def renderHTTP(self, ctx): request = inevow.IRequest(ctx) username, password = request.getUser(), request.getPassword() if (username, password) != (str(self.config['monitor']['username']), str(self.config['monitor']['password'])): request.setHeader( 'WWW-Authenticate', 'Basic realm="' + str(self.config['server']['network']) + '"') request.setResponseCode(http.UNAUTHORIZED) return "Authentication required." return rend.Page.renderHTTP(self, ctx) def data_title(self, context, data): return version.NAME + ' ' + version.VERSION def data_uptime(self, context, data): uptime = long(self.broker.uptime()) mins, secs = divmod(uptime, 60) hours, mins = divmod(mins, 60) days = long(hours / 24) log.debug((days, hours, mins)) hours = hours % 24 return '%d:%02d:%02d:%02d' % \ (days, hours, mins, secs) def data_local_users(self, context, data): return self.broker.users_cached_count() def data_local_online(self, context, data): return self.broker.users_online_count() def data_local_last_week(self, context, data): # TODO return 'n/a' def startService(self): service.Service.startService(self) log.debug("monitor init") self.storage = self.broker.storage self.db = self.broker.db # some static resources self.putChild('favicon.ico', static.File('monitor/favicon.ico')) # create http service factory = appserver.NevowSite(self) fs_service = internet.TCPServer( port=self.config['server']['monitor.bind'][1], factory=factory, interface=self.config['server']['monitor.bind'][0]) fs_service.setServiceParent(self.parent)
def child_www(self, ctx): return static.File('/my/proj/room/www')
def child_tango(self, ctx): return static.File('/usr/share/icons/Tango/32x32')
def child_net(self, ctx): return static.File("nets.html")
def child_images(self, ctx): return static.File("images")
def child_out(self, ctx): return static.File("running/out.png")
"%s-missing-object" % cmd) stream.addEntry( actorUri=user, actorName=graph.value(user, FOAF.name), verbUri=verb, verbEnglish=graph.label(verb, default=verb), objectUri=activityObject, objectName=graph.label(activityObject, default=activityObject), objectIcon=graph.value(activityObject, CL.icon), published=parse(t), entryUri=issue, ) return stream.makeNevowResource() setattr(HomePage, "child_dojo-0.4.2-ajax", static.File("dojo-0.4.2-ajax")) setattr(HomePage, "child_tomato_config.js", static.File("/my/site/magma/tomato_config.js")) class Running(rend.Page): docFactory = loaders.stan(T.img(src="out")) def child_out(self, ctx): return static.File("running/out.png") class BabyKick(stripchart.Chart): title = "Baby kicks" def __init__(self, graph):
self, self.refreshInterval, self.targetTimeoutCount).handleId, "'" else: handleId = 'null' return [ tags.script(type="text/javascript")["var nevow_clientHandleId = ", handleId, ";"], tags.script(type="text/javascript", src=url.here.child('nevow_glue.js')) ] setattr( LivePage, 'child_nevow_glue.js', static.File(util.resource_filename('nevow', 'liveglue.js'), 'text/javascript')) glue = tags.directive('liveglue') ##### BACKWARDS COMPATIBILITY CODE ctsTemplate = "nevow_clientToServerEvent('%s',this,''%s)%s" handledEventPostlude = '; return false;' class handler(object): callme = None args = () identifier = None def __init__(self, *args, **kw):
def child_customlogo(self, ctx): return static.File(self.config['logo'])
def child_houseActivity(self, ctx, fn="houseActivity.html"): f = static.File(fn) f.type = 'application/xhtml+xml' f.encoding = None return f
def child_static(self, ctx): return static.File(util.sibpath(__file__, "static"))
def child_tempchart(self, ctx): return static.File("tempchart")
def childFactory(self, ctx, seg): if seg == "favicon.ico": return static.File(Settings.BaseDir + '/images/favicon.ico') if seg == "whoami": return ThebeName(self.db[-1]) return rend.Page.childFactory(self, ctx, seg)
def child_flot(self, ctx): return static.File("flot")
from formal.widget import * from formal.widgets.restwidget import * from formal.widgets.multiselect import * from formal.form import Form, Field, Group, ResourceMixin, renderForm from formal import iformal def widgetFactory(widgetClass, *a, **k): def _(original): return widgetClass(original, *a, **k) return _ try: import pkg_resources except ImportError: import os.path defaultCSS = static.File(os.path.join(os.path.split(__file__)[0], 'formal.css')) formsJS = static.File(os.path.join(os.path.split(__file__)[0], 'js')) else: from formal.util import LazyResource defaultCSS = LazyResource(lambda: static.File(pkg_resources.resource_filename('formal', 'formal.css'))) formsJS = LazyResource(lambda: static.File(pkg_resources.resource_filename('formal', 'js'))) del LazyResource # Register standard adapters from twisted.python.components import registerAdapter from formal import converters from formal.util import SequenceKeyLabelAdapter registerAdapter(TextInput, String, iformal.IWidget) registerAdapter(TextInput, Integer, iformal.IWidget) registerAdapter(TextInput, Float, iformal.IWidget) registerAdapter(Checkbox, Boolean, iformal.IWidget)
def child_www(self, ctx): return static.File("www")
class static_css(rend.Page): addSlash = True valid_extensions = ["css"] pages = {} pages = { "main.css": static.File(_f('main.css')), "signup.css": static.File(_f('signup.css')), "community.css": static.File(_f('community.css')), "user_homepage.css": static.File(_f('user_homepage.css')), "pagination.css": static.File(_f('pagination.css')), "user_globber.css": static.File(_f('user_globber.css')), "user_image_detail.css": static.File(_f('user_image_detail.css')), "reset_password.css": static.File(_f('reset_password.css')), "terms.css": static.File(_f('terms.css')), "quick_start_guide.css": static.File(_f('quick_start_guide.css')), "privacy.css": static.File(_f('privacy.css')), "fourohfour.css": static.File(_f('fourohfour.css')), "site_down.css": static.File(_f('site_down.css')), "user_permissions.css": static.File(_f('user_permissions.css')), "user_contacts.css": static.File(_f('user_contacts.css')), "user_tags.css": static.File(_f('user_tags.css')), "user_albums.css": static.File(_f('user_albums.css')), "user_messages.css": static.File(_f('user_messages.css')), "developers.css": static.File(_f('developers.css')), "user_settings.css": static.File(_f('user_settings.css')), "main_homepage.css": static.File(_f('main_homepage.css')), "browser_check.css": static.File(_f('browser_check.css')), "features.css": static.File(_f('features.css')), "lightbox.css": static.File(_f('lightbox.css')), "zoto_color.css": static.File(_f('zoto_color.css')), "zoto_font.css": static.File(_f('zoto_font.css')), "zoto_layout.css": static.File(_f('zoto_layout.css')), "zoto_main_page.css": static.File(_f('zoto_main_page.css')), "zoto_white_blue.css": static.File(_f('zoto_white_blue.css')), "zoto_white_gold.css": static.File(_f('zoto_white_gold.css')), "zoto_white_green.css": static.File(_f('zoto_white_green.css')), "zoto_white_grey.css": static.File(_f('zoto_white_grey.css')), "zoto_white_orange.css": static.File(_f('zoto_white_orange.css')), "zoto_white_purple.css": static.File(_f('zoto_white_purple.css')), "zoto_white_pink.css": static.File(_f('zoto_white_pink.css')), "zoto_white_ou.css": static.File(_f('zoto_white_ou.css')), "zoto_black_pink.css": static.File(_f('zoto_black_pink.css')), "zoto_black_blue.css": static.File(_f('zoto_black_blue.css')), "zoto_black_gold.css": static.File(_f('zoto_black_gold.css')), "zoto_black_green.css": static.File(_f('zoto_black_green.css')), "zoto_black_grey.css": static.File(_f('zoto_black_grey.css')), "zoto_black_orange.css": static.File(_f('zoto_black_orange.css')), "zoto_black_purple.css": static.File(_f('zoto_black_purple.css')) } re_VERS = re.compile("^[0-9\.]{5,}$") def locateChild(self, ctx, segments): if self.re_VERS.match(segments[0]): file = '/'.join(segments[1:]) else: file = '/'.join(segments) if file in self.pages.keys(): return self.pages[file], []
import calendar import datetime from nevow import tags as t, url, itaglibrary, rend, static _calendar_css = """ .calendar tbody td.today { background-color: #aaaaaa; } """ calendarCSS = t.style(type_="text/css")[_calendar_css] calendarCSSFile = static.File(_calendar_css, "text/css") class CalendarComponent(object): current_date = None def days(self, year, month): def _(ctx, data): return [[ day and datetime.date(year, month, day) or None for day in row ] for row in calendar.monthcalendar(year, month)] return _ def render_calendarDay(self, ctx, data): options = itaglibrary.ICalendarOptions(ctx, {}) today_class = options.get('today_class', 'today') if data is None: return ctx.tag[''] if self.current_date.day == data.day and \ self.current_date.month == data.month and \
class WebInterface_template(rend.Page): addSlash = True docFactory = loaders.xmlfile('data' + X + 'www' + X + 'template.html') def __init__(self, pytrans): self.pytrans = pytrans def renderHTTP(self, ctx): request = inevow.IRequest(ctx) username = request.getUser() password = request.getPassword() if not username or not password: return self._loginFailed(None, ctx) LogEvent(INFO, msg=repr(username)) jabberPort = 5222 port_sep = username.find("%") if port_sep != -1: jabberPort = int(username[port_sep + 1:]) username = username[0:port_sep] if username: try: j = internJID(username) except InvalidFormat: return self._loginFailed(None, ctx) jabberHost = j.host else: jabberHost = config.mainServer LogEvent(INFO, msg="Port = %r" % jabberPort) p = portal.Portal(XMPPRealm()) p.registerChecker(XMPPChecker(jabberHost, jabberPort, tryonce=1)) creds = credentials.UsernamePassword(username, password) return p.login(creds, None, IXMPPAvatar).addCallback( self._loginSucceeded, ctx).addErrback(self._loginFailed, ctx) def _loginSucceeded(self, avatarInfo, ctx): return rend.Page.renderHTTP(self, ctx) def _loginFailed(self, result, ctx): request = inevow.IRequest(ctx) request.setHeader('WWW-Authenticate', 'Basic realm="PyAIM-t Web Interface"') request.setResponseCode(http.UNAUTHORIZED) return "Authorization required." def render_version(self, ctx, data): return [legacy.version] def render_title(self, ctx, data): return [legacy.name] def render_menu(self, ctx, data): request = inevow.IRequest(ctx) username = request.getUser() ret = T.table(border=0, cellspacing=3, cellpadding=3) row = T.tr(valign="middle") row[T.td(_class="menuentry", width="150", align="center", onclick="self.location='/account/'", onmouseover="this.className='menuentrypressed';", onmouseout="this.className='menuentry';")[T.a( _class="menuentry", href="/account/")["Account"]]] if config.admins.count(username) > 0: row[T.td(_class="menuentry", width="150", align="center", onclick="self.location='/status/'", onmouseover="this.className='menuentrypressed';", onmouseout="this.className='menuentry';")[T.a( _class="menuentry", href="/status/")["Status"]]] row[T.td(_class="menuentry", width="150", align="center", onclick="self.location='/config/'", onmouseover="this.className='menuentrypressed';", onmouseout="this.className='menuentry';")[T.a( _class="menuentry", href="/config/")["Configuration"]]] row[T.td(_class="menuentry", width="150", align="center", onclick="self.location='/controls/'", onmouseover="this.className='menuentrypressed';", onmouseout="this.className='menuentry';")[T.a( _class="menuentry", href="/controls/")["Controls"]]] ret[row] return ret child_images = static.File('data' + X + 'www' + X + 'images' + X) child_css = static.File('data' + X + 'www' + X + 'css' + X) child_avatars = WebInterface_avatars()
if onload: self.onload = onload if onMouseMove: self.onMouseMove = onMouseMove if onMouseDown: self.onMouseDown = onMouseDown if onMouseUp: self.onMouseUp = onMouseUp if onKeyDown: self.onKeyDown = onKeyDown if onKeyUp: self.onKeyUp = onKeyUp def child_canvas_socket(self, ctx): return CanvasSocket() width = 1000 height = 500 onload = None onMouseDown = None onMouseUp = None onMouseMove = None onKeyUp = None onKeyDown = None def render_canvas(self, ctx, data): return canvas(self.width, self.height, self) docFactory = loaders.stan(tags.html[render_canvas]) setattr( Canvas, 'child_nevow_canvas_movie.swf', static.File(util.resource_filename('nevow', 'Canvas.swf'), 'application/x-shockwave-flash'))
T.script(type='text/javascript', src='js/formal.js'), ], T.body[T.h1(data=T.directive('title'), render=rend.data), T.p(data=T.directive('description'), render=rend.data), T.directive('form example'), ], ], ], ) def data_title(self, ctx, data): return self.title def data_description(self, ctx, data): return self.description # Add child_ attributes examples_css = pkg_resources.resource_filename('formal.examples', 'examples.css') setattr(RootPage, 'child_examples.css', static.File(examples_css)) setattr(RootPage, 'child_formal.css', formal.defaultCSS) setattr(RootPage, 'child_js', formal.formsJS) if __name__ == '__main__': import sys from twisted.internet import reactor from twisted.python import log if len(sys.argv) > 1: port = int(sys.argv[1]) else: port = 8000 log.startLogging(sys.stdout)
def createResource(self): return static.File(sibpath(__file__, 'static'))
ArchiveService.addStatic("login", makeDynamicPage(ifpages.LoginPage)) ArchiveService.addStatic("static", ifpages.StaticServer()) ArchiveService.addStatic("robots.txt", makeDynamicPage(ifpages.RobotsTxt)) # make these self-registering? Or write them out somewhere? ArchiveService.addStatic("getRR", metarender.ResourceRecordMaker()) ArchiveService.addStatic('formal.css', formal.defaultCSS) ArchiveService.addStatic('formal.js', formal.formsJS) # Let's see how many more of such JSON things we want to have; for now, # since it's just one, let's do it manually ArchiveService.addStatic('_portaljs', jsonquery.PortalPage()) if base.getConfig("web", "enabletests"): from gavo.web import webtests ArchiveService.addStatic("test", webtests.Tests()) if (base.getConfig("web", "favicon") and os.path.exists(base.getConfig("web", "favicon"))): ArchiveService.addStatic("favicon.ico", static.File(base.getConfig("web", "favicon"))) ArchiveService.parseVanityMap(StringIO(builtinVanity)) loadUserVanity(ArchiveService) root = ArchiveService() site = appserver.NevowSite(root, timeout=300) site.remember(weberrors.DCExceptionHandler()) site.requestFactory = common.Request
return self.clients[clientID] def removeClient(self, clientID): # State-tracking bugs may make it tempting to make the next line a # 'pop', but it really shouldn't be; if the Page instance with this # client ID is already gone, then it should be gone, which means that # this method can't be called with that argument. del self.clients[clientID] if self.noisy: log.msg("Disconnected old LivePage %r" % (clientID, )) def _newClientID(self): return guard._sessionCookie() _thePrivateAthenaResource = static.File( util.resource_filename('nevow', 'athena_private')) class ConnectFailed(Exception): pass class ConnectionLost(Exception): pass CLOSE = u'close' class ReliableMessageDelivery(object): _paused = 0