]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/web/directory.py
web: stop using absolute links (or url.here) in forms and pages, since they break...
[tahoe-lafs/tahoe-lafs.git] / src / allmydata / web / directory.py
1
2 import simplejson
3 import urllib
4 import time
5
6 from twisted.internet import defer
7 from twisted.python.failure import Failure
8 from twisted.web import http, html
9 from nevow import url, rend, tags as T
10 from nevow.inevow import IRequest
11
12 from foolscap.eventual import fireEventually
13
14 from allmydata.util import log, base32
15 from allmydata.uri import from_string_verifier, from_string_dirnode, \
16      CHKFileVerifierURI
17 from allmydata.interfaces import IDirectoryNode, IFileNode, IMutableFileNode, \
18      ExistingChildError
19 from allmydata.web.common import text_plain, WebError, IClient, \
20      boolean_of_arg, get_arg, should_create_intermediate_directories, \
21      getxmlfile, RenderMixin
22 from allmydata.web.filenode import ReplaceMeMixin, \
23      FileNodeHandler, PlaceHolderNodeHandler
24
25 class BlockingFileError(Exception):
26     # TODO: catch and transform
27     """We cannot auto-create a parent directory, because there is a file in
28     the way"""
29
30 def make_handler_for(node, parentnode=None, name=None):
31     if parentnode:
32         assert IDirectoryNode.providedBy(parentnode)
33     if IFileNode.providedBy(node):
34         return FileNodeHandler(node, parentnode, name)
35     if IMutableFileNode.providedBy(node):
36         return FileNodeHandler(node, parentnode, name)
37     if IDirectoryNode.providedBy(node):
38         return DirectoryNodeHandler(node, parentnode, name)
39     raise WebError("Cannot provide handler for '%s'" % node)
40
41 class DirectoryNodeHandler(RenderMixin, rend.Page, ReplaceMeMixin):
42     addSlash = True
43
44     def __init__(self, node, parentnode=None, name=None):
45         rend.Page.__init__(self)
46         assert node
47         self.node = node
48         self.parentnode = parentnode
49         self.name = name
50
51     def childFactory(self, ctx, name):
52         req = IRequest(ctx)
53         name = name.decode("utf-8")
54         d = self.node.get(name)
55         d.addBoth(self.got_child, ctx, name)
56         # got_child returns a handler resource: FileNodeHandler or
57         # DirectoryNodeHandler
58         return d
59
60     def got_child(self, node_or_failure, ctx, name):
61         DEBUG = False
62         if DEBUG: print "GOT_CHILD", name, node_or_failure
63         req = IRequest(ctx)
64         method = req.method
65         nonterminal = len(req.postpath) > 1
66         t = get_arg(req, "t", "").strip()
67         if isinstance(node_or_failure, Failure):
68             f = node_or_failure
69             f.trap(KeyError)
70             # No child by this name. What should we do about it?
71             if DEBUG: print "no child", name
72             if DEBUG: print "postpath", req.postpath
73             if nonterminal:
74                 if DEBUG: print " intermediate"
75                 if should_create_intermediate_directories(req):
76                     # create intermediate directories
77                     if DEBUG: print " making intermediate directory"
78                     d = self.node.create_empty_directory(name)
79                     d.addCallback(make_handler_for, self.node, name)
80                     return d
81             else:
82                 if DEBUG: print " terminal"
83                 # terminal node
84                 if (method,t) in [ ("POST","mkdir"), ("PUT","mkdir") ]:
85                     if DEBUG: print " making final directory"
86                     # final directory
87                     d = self.node.create_empty_directory(name)
88                     d.addCallback(make_handler_for, self.node, name)
89                     return d
90                 if (method,t) in ( ("PUT",""), ("PUT","uri"), ):
91                     if DEBUG: print " PUT, making leaf placeholder"
92                     # we were trying to find the leaf filenode (to put a new
93                     # file in its place), and it didn't exist. That's ok,
94                     # since that's the leaf node that we're about to create.
95                     # We make a dummy one, which will respond to the PUT
96                     # request by replacing itself.
97                     return PlaceHolderNodeHandler(self.node, name)
98             if DEBUG: print " 404"
99             # otherwise, we just return a no-such-child error
100             return rend.FourOhFour()
101
102         node = node_or_failure
103         if nonterminal and should_create_intermediate_directories(req):
104             if not IDirectoryNode.providedBy(node):
105                 # we would have put a new directory here, but there was a
106                 # file in the way.
107                 if DEBUG: print "blocking"
108                 raise WebError("Unable to create directory '%s': "
109                                "a file was in the way" % name,
110                                http.CONFLICT)
111         if DEBUG: print "good child"
112         return make_handler_for(node, self.node, name)
113
114     def render_DELETE(self, ctx):
115         assert self.parentnode and self.name
116         d = self.parentnode.delete(self.name)
117         d.addCallback(lambda res: self.node.get_uri())
118         return d
119
120     def render_GET(self, ctx):
121         client = IClient(ctx)
122         req = IRequest(ctx)
123         # This is where all of the directory-related ?t=* code goes.
124         t = get_arg(req, "t", "").strip()
125         if not t:
126             # render the directory as HTML, using the docFactory and Nevow's
127             # whole templating thing.
128             return DirectoryAsHTML(self.node)
129
130         if t == "json":
131             return DirectoryJSONMetadata(ctx, self.node)
132         if t == "uri":
133             return DirectoryURI(ctx, self.node)
134         if t == "readonly-uri":
135             return DirectoryReadonlyURI(ctx, self.node)
136         if t == "manifest":
137             return Manifest(self.node)
138         if t == "deep-size":
139             return DeepSize(ctx, self.node)
140         if t == "deep-stats":
141             return DeepStats(ctx, self.node)
142         if t == 'rename-form':
143             return RenameForm(self.node)
144
145         raise WebError("GET directory: bad t=%s" % t)
146
147     def render_PUT(self, ctx):
148         req = IRequest(ctx)
149         t = get_arg(req, "t", "").strip()
150         replace = boolean_of_arg(get_arg(req, "replace", "true"))
151         if t == "mkdir":
152             # our job was done by the traversal/create-intermediate-directory
153             # process that got us here.
154             return text_plain(self.node.get_uri(), ctx) # TODO: urlencode
155         if t == "uri":
156             if not replace:
157                 # they're trying to set_uri and that name is already occupied
158                 # (by us).
159                 raise ExistingChildError()
160             d = self.parentnode.replace_me_with_a_childcap(ctx, replace)
161             # TODO: results
162             return d
163
164         raise WebError("PUT to a directory")
165
166     def render_POST(self, ctx):
167         req = IRequest(ctx)
168         t = get_arg(req, "t", "").strip()
169         if t == "mkdir":
170             d = self._POST_mkdir(req)
171         elif t == "mkdir-p":
172             # TODO: docs, tests
173             d = self._POST_mkdir_p(req)
174         elif t == "upload":
175             d = self._POST_upload(ctx) # this one needs the context
176         elif t == "uri":
177             d = self._POST_uri(req)
178         elif t == "delete":
179             d = self._POST_delete(req)
180         elif t == "rename":
181             d = self._POST_rename(req)
182         elif t == "check":
183             d = self._POST_check(req)
184         elif t == "set_children":
185             # TODO: docs
186             d = self._POST_set_children(req)
187         else:
188             raise WebError("POST to a directory with bad t=%s" % t)
189
190         when_done = get_arg(req, "when_done", None)
191         if when_done:
192             d.addCallback(lambda res: url.URL.fromString(when_done))
193         return d
194
195     def _POST_mkdir(self, req):
196         name = get_arg(req, "name", "")
197         if not name:
198             # our job is done, it was handled by the code in got_child
199             # which created the final directory (i.e. us)
200             return defer.succeed(self.node.get_uri()) # TODO: urlencode
201         name = name.decode("utf-8")
202         replace = boolean_of_arg(get_arg(req, "replace", "true"))
203         d = self.node.create_empty_directory(name, overwrite=replace)
204         d.addCallback(lambda child: child.get_uri()) # TODO: urlencode
205         return d
206
207     def _POST_mkdir_p(self, req):
208         path = get_arg(req, "path")
209         if not path:
210             raise WebError("mkdir-p requires a path")
211         path_ = tuple([seg.decode("utf-8") for seg in path.split('/') if seg ])
212         # TODO: replace
213         d = self._get_or_create_directories(self.node, path_)
214         d.addCallback(lambda node: node.get_uri())
215         return d
216
217     def _get_or_create_directories(self, node, path):
218         if not IDirectoryNode.providedBy(node):
219             # unfortunately it is too late to provide the name of the
220             # blocking directory in the error message.
221             raise BlockingFileError("cannot create directory because there "
222                                     "is a file in the way")
223         if not path:
224             return defer.succeed(node)
225         d = node.get(path[0])
226         def _maybe_create(f):
227             f.trap(KeyError)
228             return node.create_empty_directory(path[0])
229         d.addErrback(_maybe_create)
230         d.addCallback(self._get_or_create_directories, path[1:])
231         return d
232
233     def _POST_upload(self, ctx):
234         req = IRequest(ctx)
235         charset = get_arg(req, "_charset", "utf-8")
236         contents = req.fields["file"]
237         assert contents.filename is None or isinstance(contents.filename, str)
238         name = get_arg(req, "name")
239         name = name or contents.filename
240         if name is not None:
241             name = name.strip()
242         if not name:
243             # this prohibts empty, missing, and all-whitespace filenames
244             raise WebError("upload requires a name")
245         assert isinstance(name, str)
246         name = name.decode(charset)
247         if "/" in name:
248             raise WebError("name= may not contain a slash", http.BAD_REQUEST)
249         assert isinstance(name, unicode)
250
251         # since POST /uri/path/file?t=upload is equivalent to
252         # POST /uri/path/dir?t=upload&name=foo, just do the same thing that
253         # childFactory would do. Things are cleaner if we only do a subset of
254         # them, though, so we don't do: d = self.childFactory(ctx, name)
255
256         d = self.node.get(name)
257         def _maybe_got_node(node_or_failure):
258             if isinstance(node_or_failure, Failure):
259                 f = node_or_failure
260                 f.trap(KeyError)
261                 # create a placeholder which will see POST t=upload
262                 return PlaceHolderNodeHandler(self.node, name)
263             else:
264                 node = node_or_failure
265                 return make_handler_for(node, self.node, name)
266         d.addBoth(_maybe_got_node)
267         # now we have a placeholder or a filenodehandler, and we can just
268         # delegate to it. We could return the resource back out of
269         # DirectoryNodeHandler.renderHTTP, and nevow would recurse into it,
270         # but the addCallback() that handles when_done= would break.
271         d.addCallback(lambda child: child.renderHTTP(ctx))
272         return d
273
274     def _POST_uri(self, req):
275         childcap = get_arg(req, "uri")
276         if not childcap:
277             raise WebError("set-uri requires a uri")
278         name = get_arg(req, "name")
279         if not name:
280             raise WebError("set-uri requires a name")
281         charset = get_arg(req, "_charset", "utf-8")
282         name = name.decode(charset)
283         replace = boolean_of_arg(get_arg(req, "replace", "true"))
284         d = self.node.set_uri(name, childcap, overwrite=replace)
285         d.addCallback(lambda res: childcap)
286         return d
287
288     def _POST_delete(self, req):
289         name = get_arg(req, "name")
290         if name is None:
291             # apparently an <input type="hidden" name="name" value="">
292             # won't show up in the resulting encoded form.. the 'name'
293             # field is completely missing. So to allow deletion of an
294             # empty file, we have to pretend that None means ''. The only
295             # downide of this is a slightly confusing error message if
296             # someone does a POST without a name= field. For our own HTML
297             # thisn't a big deal, because we create the 'delete' POST
298             # buttons ourselves.
299             name = ''
300         charset = get_arg(req, "_charset", "utf-8")
301         name = name.decode(charset)
302         d = self.node.delete(name)
303         d.addCallback(lambda res: "thing deleted")
304         return d
305
306     def _POST_rename(self, req):
307         charset = get_arg(req, "_charset", "utf-8")
308         from_name = get_arg(req, "from_name")
309         if from_name is not None:
310             from_name = from_name.strip()
311             from_name = from_name.decode(charset)
312             assert isinstance(from_name, unicode)
313         to_name = get_arg(req, "to_name")
314         if to_name is not None:
315             to_name = to_name.strip()
316             to_name = to_name.decode(charset)
317             assert isinstance(to_name, unicode)
318         if not from_name or not to_name:
319             raise WebError("rename requires from_name and to_name")
320         for k,v in [ ('from_name', from_name), ('to_name', to_name) ]:
321             if v and "/" in v:
322                 raise WebError("%s= may not contain a slash" % k,
323                                http.BAD_REQUEST)
324
325         replace = boolean_of_arg(get_arg(req, "replace", "true"))
326         d = self.node.move_child_to(from_name, self.node, to_name, replace)
327         d.addCallback(lambda res: "thing renamed")
328         return d
329
330     def _POST_check(self, req):
331         # check this directory
332         d = self.node.check()
333         def _done(res):
334             log.msg("checked %s, results %s" % (self.node, res),
335                     facility="tahoe.webish", level=log.NOISY)
336             return str(res)
337         d.addCallback(_done)
338         # TODO: results
339         return d
340
341     def _POST_set_children(self, req):
342         replace = boolean_of_arg(get_arg(req, "replace", "true"))
343         req.content.seek(0)
344         body = req.content.read()
345         try:
346             children = simplejson.loads(body)
347         except ValueError, le:
348             le.args = tuple(le.args + (body,))
349             # TODO test handling of bad JSON
350             raise
351         cs = []
352         for name, (file_or_dir, mddict) in children.iteritems():
353             cap = str(mddict.get('rw_uri') or mddict.get('ro_uri'))
354             cs.append((name, cap, mddict.get('metadata')))
355         d = self.node.set_children(cs, replace)
356         d.addCallback(lambda res: "Okay so I did it.")
357         # TODO: results
358         return d
359
360 def abbreviated_dirnode(dirnode):
361     u = from_string_dirnode(dirnode.get_uri())
362     si = u.get_filenode_uri().storage_index
363     si_s = base32.b2a(si)
364     return si_s[:6]
365
366 class DirectoryAsHTML(rend.Page):
367     # The remainder of this class is to render the directory into
368     # human+browser -oriented HTML.
369     docFactory = getxmlfile("directory.xhtml")
370     addSlash = True
371
372     def __init__(self, node):
373         rend.Page.__init__(self)
374         self.node = node
375
376     def render_title(self, ctx, data):
377         si_s = abbreviated_dirnode(self.node)
378         header = ["Directory SI=%s" % si_s]
379         return ctx.tag[header]
380
381     def render_header(self, ctx, data):
382         si_s = abbreviated_dirnode(self.node)
383         header = ["Directory SI=%s" % si_s]
384         if self.node.is_readonly():
385             header.append(" (readonly)")
386         return ctx.tag[header]
387
388     def get_root(self, ctx):
389         req = IRequest(ctx)
390         # the addSlash=True gives us one extra (empty) segment
391         depth = len(req.prepath) + len(req.postpath) - 1
392         link = "/".join([".."] * depth)
393         return link
394
395     def render_welcome(self, ctx, data):
396         link = self.get_root(ctx)
397         return T.div[T.a(href=link)["Return to Welcome page"]]
398
399     def data_children(self, ctx, data):
400         d = self.node.list()
401         d.addCallback(lambda dict: sorted(dict.items()))
402         def _stall_some(items):
403             # Deferreds don't optimize out tail recursion, and the way
404             # Nevow's flattener handles Deferreds doesn't take this into
405             # account. As a result, large lists of Deferreds that fire in the
406             # same turn (i.e. the output of defer.succeed) will cause a stack
407             # overflow. To work around this, we insert a turn break after
408             # every 100 items, using foolscap's fireEventually(). This gives
409             # the stack a chance to be popped. It would also work to put
410             # every item in its own turn, but that'd be a lot more
411             # inefficient. This addresses ticket #237, for which I was never
412             # able to create a failing unit test.
413             output = []
414             for i,item in enumerate(items):
415                 if i % 100 == 0:
416                     output.append(fireEventually(item))
417                 else:
418                     output.append(item)
419             return output
420         d.addCallback(_stall_some)
421         return d
422
423     def render_row(self, ctx, data):
424         name, (target, metadata) = data
425         name = name.encode("utf-8")
426         assert not isinstance(name, unicode)
427
428         root = self.get_root(ctx)
429         here = "%s/uri/%s/" % (root, urllib.quote(self.node.get_uri()))
430         if self.node.is_readonly():
431             delete = "-"
432             rename = "-"
433         else:
434             # this creates a button which will cause our child__delete method
435             # to be invoked, which deletes the file and then redirects the
436             # browser back to this directory
437             delete = T.form(action=here, method="post")[
438                 T.input(type='hidden', name='t', value='delete'),
439                 T.input(type='hidden', name='name', value=name),
440                 T.input(type='hidden', name='when_done', value="."),
441                 T.input(type='submit', value='del', name="del"),
442                 ]
443
444             rename = T.form(action=here, method="get")[
445                 T.input(type='hidden', name='t', value='rename-form'),
446                 T.input(type='hidden', name='name', value=name),
447                 T.input(type='hidden', name='when_done', value="."),
448                 T.input(type='submit', value='rename', name="rename"),
449                 ]
450
451         ctx.fillSlots("delete", delete)
452         ctx.fillSlots("rename", rename)
453         if IDirectoryNode.providedBy(target):
454             check_url = "%s/uri/%s/" % (root, urllib.quote(target.get_uri()))
455             check_done_url = "../../uri/%s/" % urllib.quote(self.node.get_uri())
456         else:
457             check_url = "%s/uri/%s" % (root, urllib.quote(target.get_uri()))
458             check_done_url = "../uri/%s/" % urllib.quote(self.node.get_uri())
459         check = T.form(action=check_url, method="post")[
460             T.input(type='hidden', name='t', value='check'),
461             T.input(type='hidden', name='when_done', value=check_done_url),
462             T.input(type='submit', value='check', name="check"),
463             ]
464         ctx.fillSlots("overwrite",
465                       self.build_overwrite_form(ctx, name, target))
466         ctx.fillSlots("check", check)
467
468         times = []
469         TIME_FORMAT = "%H:%M:%S %d-%b-%Y"
470         if "ctime" in metadata:
471             ctime = time.strftime(TIME_FORMAT,
472                                   time.localtime(metadata["ctime"]))
473             times.append("c: " + ctime)
474         if "mtime" in metadata:
475             mtime = time.strftime(TIME_FORMAT,
476                                   time.localtime(metadata["mtime"]))
477             if times:
478                 times.append(T.br())
479                 times.append("m: " + mtime)
480         ctx.fillSlots("times", times)
481
482         assert (IFileNode.providedBy(target)
483                 or IDirectoryNode.providedBy(target)
484                 or IMutableFileNode.providedBy(target)), target
485
486         quoted_uri = urllib.quote(target.get_uri())
487
488         if IMutableFileNode.providedBy(target):
489             # to prevent javascript in displayed .html files from stealing a
490             # secret directory URI from the URL, send the browser to a URI-based
491             # page that doesn't know about the directory at all
492             dlurl = "%s/file/%s/@@named=/%s" % (root, quoted_uri, urllib.quote(name))
493
494             ctx.fillSlots("filename",
495                           T.a(href=dlurl)[html.escape(name)])
496             ctx.fillSlots("type", "SSK")
497
498             ctx.fillSlots("size", "?")
499
500             text_plain_url = "%s/file/%s/@@named=/foo.txt" % (root, quoted_uri)
501             text_plain_tag = T.a(href=text_plain_url)["text/plain"]
502
503         elif IFileNode.providedBy(target):
504             dlurl = "%s/file/%s/@@named=/%s" % (root, quoted_uri, urllib.quote(name))
505
506             ctx.fillSlots("filename",
507                           T.a(href=dlurl)[html.escape(name)])
508             ctx.fillSlots("type", "FILE")
509
510             ctx.fillSlots("size", target.get_size())
511
512             text_plain_url = "%s/file/%s/@@named=/foo.txt" % (root, quoted_uri)
513             text_plain_tag = T.a(href=text_plain_url)["text/plain"]
514
515
516         elif IDirectoryNode.providedBy(target):
517             # directory
518             uri_link = "%s/uri/%s/" % (root, urllib.quote(target.get_uri()))
519             ctx.fillSlots("filename",
520                           T.a(href=uri_link)[html.escape(name)])
521             if target.is_readonly():
522                 dirtype = "DIR-RO"
523             else:
524                 dirtype = "DIR"
525             ctx.fillSlots("type", dirtype)
526             ctx.fillSlots("size", "-")
527             text_plain_tag = None
528
529         childdata = [T.a(href="%s?t=json" % name)["JSON"], ", ",
530                      T.a(href="%s?t=uri" % name)["URI"], ", ",
531                      T.a(href="%s?t=readonly-uri" % name)["readonly-URI"],
532                      ]
533         if text_plain_tag:
534             childdata.extend([", ", text_plain_tag])
535
536         ctx.fillSlots("data", childdata)
537
538         try:
539             checker = IClient(ctx).getServiceNamed("checker")
540         except KeyError:
541             checker = None
542         if checker:
543             d = defer.maybeDeferred(checker.checker_results_for,
544                                     target.get_verifier())
545             def _got(checker_results):
546                 recent_results = reversed(checker_results[-5:])
547                 if IFileNode.providedBy(target):
548                     results = ("[" +
549                                ", ".join(["%d/%d" % (found, needed)
550                                           for (when,
551                                                (needed, total, found, sharemap))
552                                           in recent_results]) +
553                                "]")
554                 elif IDirectoryNode.providedBy(target):
555                     results = ("[" +
556                                "".join([{True:"+",False:"-"}[res]
557                                         for (when, res) in recent_results]) +
558                                "]")
559                 else:
560                     results = "%d results" % len(checker_results)
561                 return results
562             d.addCallback(_got)
563             results = d
564         else:
565             results = "--"
566         # TODO: include a link to see more results, including timestamps
567         # TODO: use a sparkline
568         ctx.fillSlots("checker_results", results)
569
570         return ctx.tag
571
572     def render_forms(self, ctx, data):
573         if self.node.is_readonly():
574             return T.div["No upload forms: directory is read-only"]
575         mkdir = T.form(action=".", method="post",
576                        enctype="multipart/form-data")[
577             T.fieldset[
578             T.input(type="hidden", name="t", value="mkdir"),
579             T.input(type="hidden", name="when_done", value="."),
580             T.legend(class_="freeform-form-label")["Create a new directory"],
581             "New directory name: ",
582             T.input(type="text", name="name"), " ",
583             T.input(type="submit", value="Create"),
584             ]]
585
586         upload = T.form(action=".", method="post",
587                         enctype="multipart/form-data")[
588             T.fieldset[
589             T.input(type="hidden", name="t", value="upload"),
590             T.input(type="hidden", name="when_done", value="."),
591             T.legend(class_="freeform-form-label")["Upload a file to this directory"],
592             "Choose a file to upload: ",
593             T.input(type="file", name="file", class_="freeform-input-file"),
594             " ",
595             T.input(type="submit", value="Upload"),
596             " Mutable?:",
597             T.input(type="checkbox", name="mutable"),
598             ]]
599
600         mount = T.form(action=".", method="post",
601                         enctype="multipart/form-data")[
602             T.fieldset[
603             T.input(type="hidden", name="t", value="uri"),
604             T.input(type="hidden", name="when_done", value="."),
605             T.legend(class_="freeform-form-label")["Attach a file or directory"
606                                                    " (by URI) to this"
607                                                    " directory"],
608             "New child name: ",
609             T.input(type="text", name="name"), " ",
610             "URI of new child: ",
611             T.input(type="text", name="uri"), " ",
612             T.input(type="submit", value="Attach"),
613             ]]
614         return [T.div(class_="freeform-form")[mkdir],
615                 T.div(class_="freeform-form")[upload],
616                 T.div(class_="freeform-form")[mount],
617                 ]
618
619     def build_overwrite_form(self, ctx, name, target):
620         if IMutableFileNode.providedBy(target) and not target.is_readonly():
621             root = self.get_root(ctx)
622             action = "%s/uri/%s" % (root, urllib.quote(target.get_uri()))
623             done_url = "../uri/%s/" % urllib.quote(self.node.get_uri())
624             overwrite = T.form(action=action, method="post",
625                                enctype="multipart/form-data")[
626                 T.fieldset[
627                 T.input(type="hidden", name="t", value="upload"),
628                 T.input(type='hidden', name='when_done', value=done_url),
629                 T.legend(class_="freeform-form-label")["Overwrite"],
630                 "Choose new file: ",
631                 T.input(type="file", name="file", class_="freeform-input-file"),
632                 " ",
633                 T.input(type="submit", value="Overwrite")
634                 ]]
635             return [T.div(class_="freeform-form")[overwrite],]
636         else:
637             return []
638
639     def render_results(self, ctx, data):
640         req = IRequest(ctx)
641         return get_arg(req, "results", "")
642
643
644 def DirectoryJSONMetadata(ctx, dirnode):
645     d = dirnode.list()
646     def _got(children):
647         kids = {}
648         for name, (childnode, metadata) in children.iteritems():
649             if childnode.is_readonly():
650                 rw_uri = None
651                 ro_uri = childnode.get_uri()
652             else:
653                 rw_uri = childnode.get_uri()
654                 ro_uri = childnode.get_readonly_uri()
655             if IFileNode.providedBy(childnode):
656                 kiddata = ("filenode", {'size': childnode.get_size(),
657                                         'metadata': metadata,
658                                         })
659             else:
660                 assert IDirectoryNode.providedBy(childnode), (childnode,
661                                                               children,)
662                 kiddata = ("dirnode", {'metadata': metadata})
663             if ro_uri:
664                 kiddata[1]["ro_uri"] = ro_uri
665             if rw_uri:
666                 kiddata[1]["rw_uri"] = rw_uri
667             kiddata[1]['mutable'] = childnode.is_mutable()
668             kids[name] = kiddata
669         if dirnode.is_readonly():
670             drw_uri = None
671             dro_uri = dirnode.get_uri()
672         else:
673             drw_uri = dirnode.get_uri()
674             dro_uri = dirnode.get_readonly_uri()
675         contents = { 'children': kids }
676         if dro_uri:
677             contents['ro_uri'] = dro_uri
678         if drw_uri:
679             contents['rw_uri'] = drw_uri
680         contents['mutable'] = dirnode.is_mutable()
681         data = ("dirnode", contents)
682         return simplejson.dumps(data, indent=1)
683     d.addCallback(_got)
684     d.addCallback(text_plain, ctx)
685     return d
686
687 def DirectoryURI(ctx, dirnode):
688     return text_plain(dirnode.get_uri(), ctx)
689
690 def DirectoryReadonlyURI(ctx, dirnode):
691     return text_plain(dirnode.get_readonly_uri(), ctx)
692
693 class RenameForm(rend.Page):
694     addSlash = True
695     docFactory = getxmlfile("rename-form.xhtml")
696
697     def render_title(self, ctx, data):
698         return ctx.tag["Directory SI=%s" % abbreviated_dirnode(self.original)]
699
700     def render_header(self, ctx, data):
701         header = ["Rename "
702                   "in directory SI=%s" % abbreviated_dirnode(self.original),
703                   ]
704
705         if self.original.is_readonly():
706             header.append(" (readonly!)")
707         header.append(":")
708         return ctx.tag[header]
709
710     def render_when_done(self, ctx, data):
711         return T.input(type="hidden", name="when_done", value=".")
712
713     def render_get_name(self, ctx, data):
714         req = IRequest(ctx)
715         name = get_arg(req, "name", "")
716         ctx.tag.attributes['value'] = name
717         return ctx.tag
718
719
720 class Manifest(rend.Page):
721     docFactory = getxmlfile("manifest.xhtml")
722
723     def render_title(self, ctx):
724         return T.title["Manifest of SI=%s" % abbreviated_dirnode(self.original)]
725
726     def render_header(self, ctx):
727         return T.p["Manifest of SI=%s" % abbreviated_dirnode(self.original)]
728
729     def data_items(self, ctx, data):
730         return self.original.build_manifest()
731
732     def render_row(self, ctx, refresh_cap):
733         ctx.fillSlots("refresh_capability", refresh_cap)
734         return ctx.tag
735
736 def DeepSize(ctx, dirnode):
737     d = dirnode.build_manifest()
738     def _measure_size(manifest):
739         total = 0
740         for verifiercap in manifest:
741             u = from_string_verifier(verifiercap)
742             if isinstance(u, CHKFileVerifierURI):
743                 total += u.size
744         return str(total)
745     d.addCallback(_measure_size)
746     d.addCallback(text_plain, ctx)
747     return d
748
749 def DeepStats(ctx, dirnode):
750     d = dirnode.deep_stats()
751     d.addCallback(simplejson.dumps, indent=1)
752     d.addCallback(text_plain, ctx)
753     return d