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