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