]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/web/common.py
web: move plural() to common.py
[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 plural(sequence_or_length):
85     if isinstance(sequence_or_length, int):
86         length = sequence_or_length
87     else:
88         length = len(sequence_or_length)
89     if length == 1:
90         return ""
91     return "s"
92
93 def text_plain(text, ctx):
94     req = IRequest(ctx)
95     req.setHeader("content-type", "text/plain")
96     req.setHeader("content-length", len(text))
97     return text
98
99 class WebError(Exception):
100     def __init__(self, text, code=http.BAD_REQUEST):
101         self.text = text
102         self.code = code
103
104 # XXX: to make UnsupportedMethod return 501 NOT_IMPLEMENTED instead of 500
105 # Internal Server Error, we either need to do that ICanHandleException trick,
106 # or make sure that childFactory returns a WebErrorResource (and never an
107 # actual exception). The latter is growing increasingly annoying.
108
109 def should_create_intermediate_directories(req):
110     t = get_arg(req, "t", "").strip()
111     return bool(req.method in ("PUT", "POST") and
112                 t not in ("delete", "rename", "rename-form", "check"))
113
114
115 class MyExceptionHandler(appserver.DefaultExceptionHandler):
116     def simple(self, ctx, text, code=http.BAD_REQUEST):
117         req = IRequest(ctx)
118         req.setResponseCode(code)
119         req.setHeader("content-type", "text/plain;charset=utf-8")
120         if isinstance(text, unicode):
121             text = text.encode("utf-8")
122         req.write(text)
123         # TODO: consider putting the requested URL here
124         req.finishRequest(False)
125
126     def renderHTTP_exception(self, ctx, f):
127         if f.check(ExistingChildError):
128             return self.simple(ctx,
129                                "There was already a child by that "
130                                "name, and you asked me to not "
131                                "replace it.",
132                                http.CONFLICT)
133         elif f.check(NoSuchChildError):
134             name = f.value.args[0]
135             return self.simple(ctx,
136                                "No such child: %s" % name.encode("utf-8"),
137                                http.NOT_FOUND)
138         elif f.check(NotEnoughSharesError):
139             return self.simple(ctx, str(f), http.GONE)
140         elif f.check(WebError):
141             return self.simple(ctx, f.value.text, f.value.code)
142         elif f.check(FileTooLargeError):
143             return self.simple(ctx, str(f.value), http.REQUEST_ENTITY_TOO_LARGE)
144         elif f.check(server.UnsupportedMethod):
145             # twisted.web.server.Request.render() has support for transforming
146             # this into an appropriate 501 NOT_IMPLEMENTED or 405 NOT_ALLOWED
147             # return code, but nevow does not.
148             req = IRequest(ctx)
149             method = req.method
150             return self.simple(ctx,
151                                "I don't know how to treat a %s request." % method,
152                                http.NOT_IMPLEMENTED)
153         super = appserver.DefaultExceptionHandler
154         return super.renderHTTP_exception(self, ctx, f)
155
156 class NeedOperationHandleError(WebError):
157     pass
158
159 class RenderMixin:
160
161     def renderHTTP(self, ctx):
162         request = IRequest(ctx)
163
164         # if we were using regular twisted.web Resources (and the regular
165         # twisted.web.server.Request object) then we could implement
166         # render_PUT and render_GET. But Nevow's request handler
167         # (NevowRequest.gotPageContext) goes directly to renderHTTP. Copy
168         # some code from the Resource.render method that Nevow bypasses, to
169         # do the same thing.
170         m = getattr(self, 'render_' + request.method, None)
171         if not m:
172             from twisted.web.server import UnsupportedMethod
173             raise UnsupportedMethod(getattr(self, 'allowedMethods', ()))
174         return m(ctx)