]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/web/common.py
#527: support HTTP 'Range:' requests, using a cachefile. Adds filenode.read(consumer...
[tahoe-lafs/tahoe-lafs.git] / src / allmydata / web / common.py
1
2 from twisted.web import http, server
3 from zope.interface import Interface
4 from nevow import loaders, appserver
5 from nevow.inevow import IRequest
6 from nevow.util import resource_filename
7 from allmydata.interfaces import ExistingChildError, NoSuchChildError, \
8      FileTooLargeError, NotEnoughSharesError
9
10 class IClient(Interface):
11     pass
12 class IOpHandleTable(Interface):
13     pass
14
15 def getxmlfile(name):
16     return loaders.xmlfile(resource_filename('allmydata.web', '%s' % name))
17
18 def boolean_of_arg(arg):
19     # TODO: ""
20     assert arg.lower() in ("true", "t", "1", "false", "f", "0", "on", "off")
21     return arg.lower() in ("true", "t", "1", "on")
22
23 def get_root(ctx_or_req):
24     req = IRequest(ctx_or_req)
25     # the addSlash=True gives us one extra (empty) segment
26     depth = len(req.prepath) + len(req.postpath) - 1
27     link = "/".join([".."] * depth)
28     return link
29
30 def get_arg(ctx_or_req, argname, default=None, multiple=False):
31     """Extract an argument from either the query args (req.args) or the form
32     body fields (req.fields). If multiple=False, this returns a single value
33     (or the default, which defaults to None), and the query args take
34     precedence. If multiple=True, this returns a tuple of arguments (possibly
35     empty), starting with all those in the query args.
36     """
37     req = IRequest(ctx_or_req)
38     results = []
39     if argname in req.args:
40         results.extend(req.args[argname])
41     if req.fields and argname in req.fields:
42         results.append(req.fields[argname].value)
43     if multiple:
44         return tuple(results)
45     if results:
46         return results[0]
47     return default
48
49 def abbreviate_time(data):
50     # 1.23s, 790ms, 132us
51     if data is None:
52         return ""
53     s = float(data)
54     if s >= 1.0:
55         return "%.2fs" % s
56     if s >= 0.01:
57         return "%dms" % (1000*s)
58     if s >= 0.001:
59         return "%.1fms" % (1000*s)
60     return "%dus" % (1000000*s)
61
62 def abbreviate_rate(data):
63     # 21.8kBps, 554.4kBps 4.37MBps
64     if data is None:
65         return ""
66     r = float(data)
67     if r > 1000000:
68         return "%1.2fMBps" % (r/1000000)
69     if r > 1000:
70         return "%.1fkBps" % (r/1000)
71     return "%dBps" % r
72
73 def abbreviate_size(data):
74     # 21.8kB, 554.4kB 4.37MB
75     if data is None:
76         return ""
77     r = float(data)
78     if r > 1000000000:
79         return "%1.2fGB" % (r/1000000000)
80     if r > 1000000:
81         return "%1.2fMB" % (r/1000000)
82     if r > 1000:
83         return "%.1fkB" % (r/1000)
84     return "%dB" % r
85
86 def text_plain(text, ctx):
87     req = IRequest(ctx)
88     req.setHeader("content-type", "text/plain")
89     req.setHeader("content-length", len(text))
90     return text
91
92 class WebError(Exception):
93     def __init__(self, text, code=http.BAD_REQUEST):
94         self.text = text
95         self.code = code
96
97 # XXX: to make UnsupportedMethod return 501 NOT_IMPLEMENTED instead of 500
98 # Internal Server Error, we either need to do that ICanHandleException trick,
99 # or make sure that childFactory returns a WebErrorResource (and never an
100 # actual exception). The latter is growing increasingly annoying.
101
102 def should_create_intermediate_directories(req):
103     t = get_arg(req, "t", "").strip()
104     return bool(req.method in ("PUT", "POST") and
105                 t not in ("delete", "rename", "rename-form", "check"))
106
107
108 class MyExceptionHandler(appserver.DefaultExceptionHandler):
109     def simple(self, ctx, text, code=http.BAD_REQUEST):
110         req = IRequest(ctx)
111         req.setResponseCode(code)
112         req.setHeader("content-type", "text/plain;charset=utf-8")
113         if isinstance(text, unicode):
114             text = text.encode("utf-8")
115         req.write(text)
116         # TODO: consider putting the requested URL here
117         req.finishRequest(False)
118
119     def renderHTTP_exception(self, ctx, f):
120         if f.check(ExistingChildError):
121             return self.simple(ctx,
122                                "There was already a child by that "
123                                "name, and you asked me to not "
124                                "replace it.",
125                                http.CONFLICT)
126         elif f.check(NoSuchChildError):
127             name = f.value.args[0]
128             return self.simple(ctx,
129                                "No such child: %s" % name.encode("utf-8"),
130                                http.NOT_FOUND)
131         elif f.check(NotEnoughSharesError):
132             return self.simple(ctx, str(f), http.GONE)
133         elif f.check(WebError):
134             return self.simple(ctx, f.value.text, f.value.code)
135         elif f.check(FileTooLargeError):
136             return self.simple(ctx, str(f.value), http.REQUEST_ENTITY_TOO_LARGE)
137         elif f.check(server.UnsupportedMethod):
138             # twisted.web.server.Request.render() has support for transforming
139             # this into an appropriate 501 NOT_IMPLEMENTED or 405 NOT_ALLOWED
140             # return code, but nevow does not.
141             req = IRequest(ctx)
142             method = req.method
143             return self.simple(ctx,
144                                "I don't know how to treat a %s request." % method,
145                                http.NOT_IMPLEMENTED)
146         super = appserver.DefaultExceptionHandler
147         return super.renderHTTP_exception(self, ctx, f)
148
149 class NeedOperationHandleError(WebError):
150     pass
151
152 class RenderMixin:
153
154     def renderHTTP(self, ctx):
155         request = IRequest(ctx)
156
157         # if we were using regular twisted.web Resources (and the regular
158         # twisted.web.server.Request object) then we could implement
159         # render_PUT and render_GET. But Nevow's request handler
160         # (NevowRequest.gotPageContext) goes directly to renderHTTP. Copy
161         # some code from the Resource.render method that Nevow bypasses, to
162         # do the same thing.
163         m = getattr(self, 'render_' + request.method, None)
164         if not m:
165             from twisted.web.server import UnsupportedMethod
166             raise UnsupportedMethod(getattr(self, 'allowedMethods', ()))
167         return m(ctx)