Ejemplo n.º 1
0
 def renderHTTP_exception(self, ctx, f):
     try:
         text, code = humanize_failure(f)
     except:
         log.msg("exception in humanize_failure")
         log.msg("argument was %s" % (f, ))
         log.err()
         text, code = str(f), None
     if code is not None:
         return self.simple(ctx, text, code)
     if f.check(server.UnsupportedMethod):
         # twisted.web.server.Request.render() has support for transforming
         # this into an appropriate 501 NOT_IMPLEMENTED or 405 NOT_ALLOWED
         # return code, but nevow does not.
         req = IRequest(ctx)
         method = req.method
         return self.simple(
             ctx, "I don't know how to treat a %s request." % method,
             http.NOT_IMPLEMENTED)
     req = IRequest(ctx)
     accept = req.getHeader("accept")
     if not accept:
         accept = "*/*"
     if "*/*" in accept or "text/*" in accept or "text/html" in accept:
         super = appserver.DefaultExceptionHandler
         return super.renderHTTP_exception(self, ctx, f)
     # use plain text
     traceback = f.getTraceback()
     return self.simple(ctx, traceback, http.INTERNAL_SERVER_ERROR)
Ejemplo n.º 2
0
    def render_login(self, ctx, data):
        """Render the whole login box."""
        # pylint: disable-msg=E1101
        if IRequest(ctx).method == 'POST' and data.is_valid():
            # Simply send a challenge to this email address
            message(
                ctx, u"""Un message de confirmation a été envoyé """
                u"""à l'adresse <%s>.""" % data.email)

            IService(ctx).pretend_email_address(
                must_user(ctx).user, data.email)
            IRequest(ctx).redirect(data.referer)
            IRequest(ctx).finish()
        else:
            return ctx.tag
Ejemplo n.º 3
0
 def render_POST(self, ctx):
     req = IRequest(ctx)
     log.msg(format="User reports incident through web page: %(details)s",
             details=get_arg(req, "details", ""),
             level=log.WEIRD, umid="LkD9Pw")
     req.setHeader("content-type", "text/plain")
     return "Thank you for your report!"
Ejemplo n.º 4
0
    def renderHTTP(self, ctx):
        """Handle HTTP requests."""
        srv = IService(ctx)
        request = IRequest(ctx)

        current = must_user(ctx)
        user = srv.validate_challenge(  # pylint: disable-msg=E1101
            self.challenge, current.session)

        if user:
            message(ctx, u'Bienvenue, %s' % (user.email, ))
            request.redirect("/")
            request.finish()
            return ''

        # Some people simply reuse invitations: don't complain if they
        # are already connected, just redirect them to the main page.
        avatar = maybe_user(ctx)
        if avatar.identified:
            request.redirect("/")
            request.finish()
            return ''

        # pylint: disable-msg=E1101
        self.contentTags = [
            T.h1[u"Cette clé n'est pas valable"],
            T.p[u"Vous pouvez obtenir une nouvelle clé par e-mail.",
                T.div(_class="editable bl")[T.div(_class="br")[T.div(
                    _class="tl")[T.div(_class="tr")[T.div(
                        _class="edcontent")[login.LoginFragment(
                            original=login.LoginInfo(
                                force_reconnect=True))], ]]]]]
        ]

        return BasePage.renderHTTP(self, ctx)
Ejemplo n.º 5
0
Archivo: page.py Proyecto: calston/tums
 def renderer(self, context, name):
     renderMethod = renderer.get(self, name, None)
     if renderMethod is None:
         raise MissingRenderMethod(self, name)
     # XXX Hack to avoid passing context and data to the render method.
     # Eventually the rendering system should just not pass these to us.
     return lambda self, ctx, data: renderMethod(IRequest(ctx), ctx.tag)
Ejemplo n.º 6
0
 def renderHTTP(self, nevow_ctx):
     context = pmap({
         NEVOW_REQUEST: IRequest(nevow_ctx),
     })
     d = execute(context, v(nevow()) + self._interceptors)
     d.addCallback(lambda _: b'')
     return d
Ejemplo n.º 7
0
def _flattenElement(element, ctx):
    """
    Use the new flattener implementation to flatten the given L{IRenderable} in
    a manner appropriate for the specified context.
    """
    if ctx.precompile:
        return element

    synchronous = []
    accumulator = []
    request = IRequest(ctx, None)  # XXX None case is DEPRECATED
    finished = deferflatten(request, element, ctx.isAttrib, True,
                            accumulator.append)

    def cbFinished(ignored):
        if synchronous is not None:
            synchronous.append(None)
        return accumulator

    def ebFinished(err):
        if synchronous is not None:
            synchronous.append(err)
        else:
            return err

    finished.addCallbacks(cbFinished, ebFinished)
    if synchronous:
        if synchronous[0] is None:
            return accumulator
        synchronous[0].raiseException()
    synchronous = None
    return finished
Ejemplo n.º 8
0
 def _POST_stream_deep_check(self, ctx):
     verify = boolean_of_arg(get_arg(ctx, "verify", "false"))
     repair = boolean_of_arg(get_arg(ctx, "repair", "false"))
     add_lease = boolean_of_arg(get_arg(ctx, "add-lease", "false"))
     walker = DeepCheckStreamer(ctx, self.node, verify, repair, add_lease)
     monitor = self.node.deep_traverse(walker)
     walker.setMonitor(monitor)
     # register to hear stopProducing. The walker ignores pauseProducing.
     IRequest(ctx).registerProducer(walker, True)
     d = monitor.when_done()
     def _done(res):
         IRequest(ctx).unregisterProducer()
         return res
     d.addBoth(_done)
     def _cancelled(f):
         f.trap(OperationCancelledError)
         return "Operation Cancelled"
     d.addErrback(_cancelled)
     def _error(f):
         # signal the error as a non-JSON "ERROR:" line, plus exception
         msg = "ERROR: %s(%s)\n" % (f.value.__class__.__name__,
                                    ", ".join([str(a) for a in f.value.args]))
         msg += str(f)
         return msg
     d.addErrback(_error)
     return d
Ejemplo n.º 9
0
    def render_GET(self, ctx):
        req = IRequest(ctx)
        # This is where all of the directory-related ?t=* code goes.
        t = get_arg(req, "t", "").strip()

        # t=info contains variable ophandles, t=rename-form contains the name
        # of the child being renamed. Neither is allowed an ETag.
        FIXED_OUTPUT_TYPES =  ["", "json", "uri", "readonly-uri"]
        if not self.node.is_mutable() and t in FIXED_OUTPUT_TYPES:
            si = self.node.get_storage_index()
            if si and req.setETag('DIR:%s-%s' % (base32.b2a(si), t or "")):
                return ""

        if not t:
            # render the directory as HTML, using the docFactory and Nevow's
            # whole templating thing.
            return DirectoryAsHTML(self.node,
                                   self.client.mutable_file_default)

        if t == "json":
            return DirectoryJSONMetadata(ctx, self.node)
        if t == "info":
            return MoreInfo(self.node)
        if t == "uri":
            return DirectoryURI(ctx, self.node)
        if t == "readonly-uri":
            return DirectoryReadonlyURI(ctx, self.node)
        if t == 'rename-form':
            return RenameForm(self.node)

        raise WebError("GET directory: bad t=%s" % t)
Ejemplo n.º 10
0
    def _POST_stream_manifest(self, ctx):
        walker = ManifestStreamer(ctx, self.node)
        monitor = self.node.deep_traverse(walker)
        walker.setMonitor(monitor)
        # register to hear stopProducing. The walker ignores pauseProducing.
        IRequest(ctx).registerProducer(walker, True)
        d = monitor.when_done()

        def _done(res):
            IRequest(ctx).unregisterProducer()
            return res

        d.addBoth(_done)

        def _cancelled(f):
            f.trap(OperationCancelledError)
            return "Operation Cancelled"

        d.addErrback(_cancelled)

        def _error(f):
            # signal the error as a non-JSON "ERROR:" line, plus exception
            msg = "ERROR: %s(%s)\n" % (f.value.__class__.__name__, ", ".join(
                [str(a) for a in f.value.args]))
            msg += str(f)
            return msg

        d.addErrback(_error)
        return d
Ejemplo n.º 11
0
 def render_POST(self, ctx):
     req = IRequest(ctx)
     log.msg(format="User reports incident through web page: %(details)s",
             details=get_arg(req, "details", ""),
             level=log.WEIRD, umid="LkD9Pw")
     req.setHeader("content-type", "text/plain")
     return "An incident report has been saved to logs/incidents/ in the node directory."
Ejemplo n.º 12
0
    def render_POST(self, ctx):
        req = IRequest(ctx)
        t = get_arg(req, "t", "").strip()
        replace = boolean_of_arg(get_arg(req, "replace", "true"))
        if t == "check":
            d = self._POST_check(req)
        elif t == "upload":
            # like PUT, but get the file data from an HTML form's input field
            # We could get here from POST /uri/mutablefilecap?t=upload,
            # or POST /uri/path/file?t=upload, or
            # POST /uri/path/dir?t=upload&name=foo . All have the same
            # behavior, we just ignore any name= argument
            if self.node.is_mutable():
                d = self.replace_my_contents_with_a_formpost(req)
            else:
                if not replace:
                    raise ExistingChildError()
                assert self.parentnode and self.name
                d = self.replace_me_with_a_formpost(req, self.client, replace)
        else:
            raise WebError("POST to file: bad t=%s" % t)

        when_done = get_arg(req, "when_done", None)
        if when_done:
            d.addCallback(lambda res: url.URL.fromString(when_done))
        return d
Ejemplo n.º 13
0
 def error(f):
     message, code = humanize_failure(f)
     req = IRequest(ctx)
     req.setResponseCode(code)
     return json.dumps({
         "error": message,
     })
Ejemplo n.º 14
0
 def childFactory(self, ctx, name):
     req = IRequest(ctx)
     if should_create_intermediate_directories(req):
         raise WebError("Cannot create directory '%s', because its "
                        "parent is a file, not a directory" % name)
     raise WebError("Files have no children, certainly not named '%s'" %
                    name)
Ejemplo n.º 15
0
    def childFactory(self, ctx, name):
        ophandle = name
        if ophandle not in self.handles:
            raise WebError("unknown/expired handle '%s'" % escape(ophandle),
                           NOT_FOUND)
        (monitor, renderer, when_added) = self.handles[ophandle]

        request = IRequest(ctx)
        t = get_arg(ctx, "t", "status")
        if t == "cancel" and request.method == "POST":
            monitor.cancel()
            # return the status anyways, but release the handle
            self._release_ophandle(ophandle)

        else:
            retain_for = get_arg(ctx, "retain-for", None)
            if retain_for is not None:
                self._set_timer(ophandle, int(retain_for))

            if monitor.is_finished():
                if boolean_of_arg(
                        get_arg(ctx, "release-after-complete", "false")):
                    self._release_ophandle(ophandle)
                if retain_for is None:
                    # this GET is collecting the ophandle, so change its timer
                    self._set_timer(ophandle, self.COLLECTED_HANDLE_LIFETIME)

        status = monitor.get_status()
        if isinstance(status, Failure):
            return defer.fail(status)

        return renderer
Ejemplo n.º 16
0
    def beforeRender(self, ctx):
        """
        Before rendering this page, identify the correct URL for the login to post
        to, and the error message to display (if any), and fill the 'login
        action' and 'error' slots in the template accordingly.
        """
        generator = ixmantissa.ISiteURLGenerator(self.store)
        url = generator.rootURL(IRequest(ctx))
        url = url.child('__login__')
        for seg in self.segments:
            url = url.child(seg)
        for queryKey, queryValues in self.arguments.iteritems():
            for queryValue in queryValues:
                url = url.add(queryKey, queryValue)

        req = inevow.IRequest(ctx)
        err = req.args.get('login-failure', ('', ))[0]

        if 0 < len(err):
            error = inevow.IQ(self.fragment).onePattern('error').fillSlots(
                'error', err)
        else:
            error = ''

        ctx.fillSlots("login-action", url)
        ctx.fillSlots("error", error)
Ejemplo n.º 17
0
 def locateChild(self, ctx, segments):
     """
     Return a clone of this page that remembers its segments, so that URLs like
     /login/private/stuff will redirect the user to /private/stuff after
     login has completed.
     """
     arguments = IRequest(ctx).args
     return self.__class__(self.store, segments, arguments), ()
Ejemplo n.º 18
0
 def render_HEAD(self, ctx):
     req = IRequest(ctx)
     t = get_arg(req, "t", "").strip()
     if t:
         raise WebError("HEAD file: bad t=%s" % t)
     filename = get_arg(req, "filename", self.name) or "unknown"
     d = self.node.get_best_readable_version()
     d.addCallback(lambda dn: FileDownloader(dn, filename))
     return d
Ejemplo n.º 19
0
 def renderHTTP(self, context):
     """
     Render C{self.resource} through a L{StylesheetRewritingRequestWrapper}.
     """
     request = IRequest(context)
     request = StylesheetRewritingRequestWrapper(
         request, self.installedOfferingNames, self.rootURL)
     context.remember(request, IRequest)
     return self.resource.renderHTTP(context)
Ejemplo n.º 20
0
 def childFactory(self, ctx, name):
     req = IRequest(ctx)
     if isinstance(self.node, ProhibitedNode):
         raise FileProhibited(self.node.reason)
     if should_create_intermediate_directories(req):
         raise WebError("Cannot create directory %s, because its "
                        "parent is a file, not a directory" % quote_output(name, encoding='utf-8'))
     raise WebError("Files have no children, certainly not named %s"
                    % quote_output(name, encoding='utf-8'))
Ejemplo n.º 21
0
 def beforeRender(self, ctx):
     """
     Before rendering, retrieve the hostname from the request being
     responded to and generate an URL which will serve as the root for
     all JavaScript modules to be loaded.
     """
     request = IRequest(ctx)
     root = self.webSite.rootURL(request)
     self._moduleRoot = root.child('__jsmodule__')
Ejemplo n.º 22
0
    def renderHTTP(self, ctx):  # pylint: disable-msg=C0103
        """Handle HTTP requests."""
        request = IRequest(ctx)

        if request.method == 'POST':  # pylint: disable-msg=E1101
            session.destroy_session(ctx)
            request.redirect('/')
            return ''
        return BasePage.renderHTTP(self, ctx)
Ejemplo n.º 23
0
    def render_GET(self, ctx):
        req = IRequest(ctx)
        t = get_arg(req, "t", "").strip()

        # t=info contains variable ophandles, so is not allowed an ETag.
        FIXED_OUTPUT_TYPES = ["", "json", "uri", "readonly-uri"]
        if not self.node.is_mutable() and t in FIXED_OUTPUT_TYPES:
            # if the client already has the ETag then we can
            # short-circuit the whole process.
            si = self.node.get_storage_index()
            if si and req.setETag('%s-%s' % (base32.b2a(si), t or "")):
                return ""

        if not t:
            # just get the contents
            # the filename arrives as part of the URL or in a form input
            # element, and will be sent back in a Content-Disposition header.
            # Different browsers use various character sets for this name,
            # sometimes depending upon how language environment is
            # configured. Firefox sends the equivalent of
            # urllib.quote(name.encode("utf-8")), while IE7 sometimes does
            # latin-1. Browsers cannot agree on how to interpret the name
            # they see in the Content-Disposition header either, despite some
            # 11-year old standards (RFC2231) that explain how to do it
            # properly. So we assume that at least the browser will agree
            # with itself, and echo back the same bytes that we were given.
            filename = get_arg(req, "filename", self.name) or "unknown"
            d = self.node.get_best_readable_version()
            d.addCallback(lambda dn: FileDownloader(dn, filename))
            return d
        if t == "json":
            # We do this to make sure that fields like size and
            # mutable-type (which depend on the file on the grid and not
            # just on the cap) are filled in. The latter gets used in
            # tests, in particular.
            #
            # TODO: Make it so that the servermap knows how to update in
            # a mode specifically designed to fill in these fields, and
            # then update it in that mode.
            if self.node.is_mutable():
                d = self.node.get_servermap(MODE_READ)
            else:
                d = defer.succeed(None)
            if self.parentnode and self.name:
                d.addCallback(lambda ignored: self.parentnode.get_metadata_for(
                    self.name))
            else:
                d.addCallback(lambda ignored: None)
            d.addCallback(lambda md: FileJSONMetadata(ctx, self.node, md))
            return d
        if t == "info":
            return MoreInfo(self.node)
        if t == "uri":
            return FileURI(ctx, self.node)
        if t == "readonly-uri":
            return FileReadOnlyURI(ctx, self.node)
        raise WebError("GET file: bad t=%s" % t)
Ejemplo n.º 24
0
 def locateChild(self, context, segments):
     """
     Unwrap the wrapped resource if HTTPS is already being used, otherwise
     wrap it in a helper which will preserve the wrapping all the way down
     to the final resource.
     """
     request = IRequest(context)
     if request.isSecure():
         return self.wrappedResource, segments
     return _SecureWrapper(self.urlGenerator, self.wrappedResource), segments
Ejemplo n.º 25
0
 def render_login_warnings(self, ctx, data):
     """Render the login errors."""
     # pylint: disable-msg=E1101
     if IRequest(ctx).method == 'POST' and data.warnings:
         if not data.email:
             return ctx.tag[u"Vous n'avez pas fourni votre adresse email."]
         if not validate_email(data.email):
             return ctx.tag[u"Votre adresse email est incorrecte."]
         if not data.known:
             return ctx.tag[u'Cette adresse email est inconnue.']
     return ''
Ejemplo n.º 26
0
 def render_GET(self, ctx):
     req = IRequest(ctx)
     uri = get_arg(req, "uri", None)
     if uri is None:
         raise WebError("GET /uri requires uri=")
     there = url.URL.fromContext(ctx)
     there = there.clear("uri")
     # I thought about escaping the childcap that we attach to the URL
     # here, but it seems that nevow does that for us.
     there = there.child(uri)
     return there
Ejemplo n.º 27
0
 def renderHTTP(self, context):
     """
     Render the wrapped resource if HTTPS is already being used, otherwise
     invoke a helper which may generate a redirect.
     """
     request = IRequest(context)
     if request.isSecure():
         renderer = self.wrappedResource
     else:
         renderer = _SecureWrapper(self.urlGenerator, self.wrappedResource)
     return renderer.renderHTTP(context)
Ejemplo n.º 28
0
 def renderHTTP(self, ctx):
     req = IRequest(ctx)
     if req.method == 'GET':
         req.setHeader('Content-Type', 'text/plain')
         return 'PUT data here to create an object.'
     elif req.method == 'PUT':
         return self.handlePUT(req)
     else:
         req.setResponseCode(http.NOT_ALLOWED)
         req.setHeader('Content-Type', 'text/plain')
         return 'Method not allowed'
Ejemplo n.º 29
0
 def simple(self, ctx, text, code=http.BAD_REQUEST):
     req = IRequest(ctx)
     req.setResponseCode(code)
     #req.responseHeaders.setRawHeaders("content-encoding", [])
     #req.responseHeaders.setRawHeaders("content-disposition", [])
     req.setHeader("content-type", "text/plain;charset=utf-8")
     if isinstance(text, unicode):
         text = text.encode("utf-8")
     req.setHeader("content-length", b"%d" % len(text))
     req.write(text)
     # TODO: consider putting the requested URL here
     req.finishRequest(False)
Ejemplo n.º 30
0
 def locateChild(self, ctx, segments):
     try:
         impl = self.mapping[segments[0]]
     except KeyError:
         return rend.NotFound
     else:
         req = IRequest(ctx)
     implgz = impl + '.gz'
     if self.canCompress(req) and os.path.exists(implgz):
         impl = implgz
         req.setHeader('content-encoding', 'gzip')
     return self.resourceFactory(impl), []