]> arthur.barton.de Git - bup.git/blob - cmd/web-cmd.py
If not directory root, prepend list with ".."
[bup.git] / cmd / web-cmd.py
1 #!/usr/bin/env python
2 import sys, stat, urllib, mimetypes, posixpath, time
3 import tornado.httpserver
4 import tornado.ioloop
5 import tornado.web
6 from bup import options, git, vfs
7 from bup.helpers import *
8
9 handle_ctrl_c()
10
11
12 def _compute_breadcrumbs(path, show_hidden=False):
13     """Returns a list of breadcrumb objects for a path."""
14     breadcrumbs = []
15     breadcrumbs.append(('[root]', '/'))
16     path_parts = path.split('/')[1:-1]
17     full_path = '/'
18     for part in path_parts:
19         full_path += part + "/"
20         url_append = ""
21         if show_hidden:
22             url_append = '?hidden=1'
23         breadcrumbs.append((part, full_path+url_append))
24     return breadcrumbs
25
26
27 def _contains_hidden_files(n):
28     """Return True if n contains files starting with a '.', False otherwise."""
29     for sub in n:
30         name = sub.name
31         if len(name)>1 and name.startswith('.'):
32             return True
33
34     return False
35
36
37 def _compute_dir_contents(n, path, show_hidden=False):
38     """Given a vfs node, returns an iterator for display info of all subs."""
39     url_append = ""
40     if show_hidden:
41         url_append = "?hidden=1"
42
43     if path != "/":
44         yield('..', '../' + url_append, '')
45     for sub in n:
46         display = link = sub.name
47
48         # link should be based on fully resolved type to avoid extra
49         # HTTP redirect.
50         if stat.S_ISDIR(sub.try_resolve().mode):
51             link = sub.name + "/"
52
53         if not show_hidden and len(display)>1 and display.startswith('.'):
54             continue
55
56         size = None
57         if stat.S_ISDIR(sub.mode):
58             display = sub.name + '/'
59         elif stat.S_ISLNK(sub.mode):
60             display = sub.name + '@'
61         else:
62             size = sub.size()
63
64         yield (display, link + url_append, size)
65
66
67 class BupRequestHandler(tornado.web.RequestHandler):
68     def get(self, path):
69         return self._process_request(path)
70
71     def head(self, path):
72         return self._process_request(path)
73     
74     @tornado.web.asynchronous
75     def _process_request(self, path):
76         path = urllib.unquote(path)
77         print 'Handling request for %s' % path
78         try:
79             n = top.resolve(path)
80         except vfs.NoSuchFile:
81             self.send_error(404)
82             return
83         f = None
84         if stat.S_ISDIR(n.mode):
85             self._list_directory(path, n)
86         else:
87             self._get_file(path, n)
88
89     def _list_directory(self, path, n):
90         """Helper to produce a directory listing.
91
92         Return value is either a file object, or None (indicating an
93         error).  In either case, the headers are sent.
94         """
95         if not path.endswith('/') and len(path) > 0:
96             print 'Redirecting from %s to %s' % (path, path + '/')
97             return self.redirect(path + '/', permanent=True)
98
99         try:
100             show_hidden = int(self.request.arguments.get('hidden', [0])[-1])
101         except ValueError, e:
102             show_hidden = False
103
104         self.render(
105             'list-directory.html',
106             path=path,
107             breadcrumbs=_compute_breadcrumbs(path, show_hidden),
108             files_hidden=_contains_hidden_files(n),
109             hidden_shown=show_hidden,
110             dir_contents=_compute_dir_contents(n, path, show_hidden))
111
112     def _get_file(self, path, n):
113         """Process a request on a file.
114
115         Return value is either a file object, or None (indicating an error).
116         In either case, the headers are sent.
117         """
118         ctype = self._guess_type(path)
119
120         self.set_header("Last-Modified", self.date_time_string(n.mtime))
121         self.set_header("Content-Type", ctype)
122         size = n.size()
123         self.set_header("Content-Length", str(size))
124         assert(len(n.hash) == 20)
125         self.set_header("Etag", n.hash.encode('hex'))
126
127         if self.request.method != 'HEAD':
128             self.flush()
129             f = n.open()
130             it = chunkyreader(f)
131             def write_more(me):
132                 try:
133                     blob = it.next()
134                 except StopIteration:
135                     f.close()
136                     self.finish()
137                     return
138                 self.request.connection.stream.write(blob,
139                                                      callback=lambda: me(me))
140             write_more(write_more)
141
142     def _guess_type(self, path):
143         """Guess the type of a file.
144
145         Argument is a PATH (a filename).
146
147         Return value is a string of the form type/subtype,
148         usable for a MIME Content-type header.
149
150         The default implementation looks the file's extension
151         up in the table self.extensions_map, using application/octet-stream
152         as a default; however it would be permissible (if
153         slow) to look inside the data to make a better guess.
154         """
155         base, ext = posixpath.splitext(path)
156         if ext in self.extensions_map:
157             return self.extensions_map[ext]
158         ext = ext.lower()
159         if ext in self.extensions_map:
160             return self.extensions_map[ext]
161         else:
162             return self.extensions_map['']
163
164     if not mimetypes.inited:
165         mimetypes.init() # try to read system mime.types
166     extensions_map = mimetypes.types_map.copy()
167     extensions_map.update({
168         '': 'text/plain', # Default
169         '.py': 'text/plain',
170         '.c': 'text/plain',
171         '.h': 'text/plain',
172         })
173
174     def date_time_string(self, t):
175         return time.strftime('%a, %d %b %Y %H:%M:%S', time.gmtime(t))
176
177
178 optspec = """
179 bup web [[hostname]:port]
180 --
181 """
182 o = options.Options('bup web', optspec)
183 (opt, flags, extra) = o.parse(sys.argv[1:])
184
185 if len(extra) > 1:
186     o.fatal("at most one argument expected")
187
188 address = ('127.0.0.1', 8080)
189 if len(extra) > 0:
190     addressl = extra[0].split(':', 1)
191     addressl[1] = int(addressl[1])
192     address = tuple(addressl)
193
194 git.check_repo_or_die()
195 top = vfs.RefList(None)
196
197 settings = dict(
198     debug = 1,
199     template_path = resource_path('web'),
200     static_path = resource_path('web/static')
201 )
202
203 # Disable buffering on stdout, for debug messages
204 sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
205
206 application = tornado.web.Application([
207     (r"(/.*)", BupRequestHandler),
208 ], **settings)
209
210 if __name__ == "__main__":
211     http_server = tornado.httpserver.HTTPServer(application)
212     http_server.listen(address[1], address=address[0])
213
214     print "Serving HTTP on %s:%d..." % http_server._socket.getsockname()
215     loop = tornado.ioloop.IOLoop.instance()
216     loop.start()
217