2 import sys, stat, urllib, mimetypes, posixpath, time, webbrowser
3 from bup import options, git, vfs
4 from bup.helpers import *
6 import tornado.httpserver
10 log('error: cannot find the python "tornado" module; please install it\n')
16 def _compute_breadcrumbs(path, show_hidden=False):
17 """Returns a list of breadcrumb objects for a path."""
19 breadcrumbs.append(('[root]', '/'))
20 path_parts = path.split('/')[1:-1]
22 for part in path_parts:
23 full_path += part + "/"
26 url_append = '?hidden=1'
27 breadcrumbs.append((part, full_path+url_append))
31 def _contains_hidden_files(n):
32 """Return True if n contains files starting with a '.', False otherwise."""
35 if len(name)>1 and name.startswith('.'):
41 def _compute_dir_contents(n, path, show_hidden=False):
42 """Given a vfs node, returns an iterator for display info of all subs."""
45 url_append = "?hidden=1"
48 yield('..', '../' + url_append, '')
50 display = link = sub.name
52 # link should be based on fully resolved type to avoid extra
54 if stat.S_ISDIR(sub.try_resolve().mode):
57 if not show_hidden and len(display)>1 and display.startswith('.'):
61 if stat.S_ISDIR(sub.mode):
62 display = sub.name + '/'
63 elif stat.S_ISLNK(sub.mode):
64 display = sub.name + '@'
67 size = (opt.human_readable and format_filesize(size)) or size
69 yield (display, link + url_append, size)
72 class BupRequestHandler(tornado.web.RequestHandler):
74 return self._process_request(path)
77 return self._process_request(path)
79 @tornado.web.asynchronous
80 def _process_request(self, path):
81 path = urllib.unquote(path)
82 print 'Handling request for %s' % path
85 except vfs.NoSuchFile:
89 if stat.S_ISDIR(n.mode):
90 self._list_directory(path, n)
92 self._get_file(path, n)
94 def _list_directory(self, path, n):
95 """Helper to produce a directory listing.
97 Return value is either a file object, or None (indicating an
98 error). In either case, the headers are sent.
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)
105 show_hidden = int(self.request.arguments.get('hidden', [0])[-1])
106 except ValueError, e:
110 'list-directory.html',
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))
117 def _get_file(self, path, n):
118 """Process a request on a file.
120 Return value is either a file object, or None (indicating an error).
121 In either case, the headers are sent.
123 ctype = self._guess_type(path)
125 self.set_header("Last-Modified", self.date_time_string(n.mtime))
126 self.set_header("Content-Type", ctype)
128 self.set_header("Content-Length", str(size))
129 assert(len(n.hash) == 20)
130 self.set_header("Etag", n.hash.encode('hex'))
132 if self.request.method != 'HEAD':
139 except StopIteration:
143 self.request.connection.stream.write(blob,
144 callback=lambda: me(me))
145 write_more(write_more)
147 def _guess_type(self, path):
148 """Guess the type of a file.
150 Argument is a PATH (a filename).
152 Return value is a string of the form type/subtype,
153 usable for a MIME Content-type header.
155 The default implementation looks the file's extension
156 up in the table self.extensions_map, using application/octet-stream
157 as a default; however it would be permissible (if
158 slow) to look inside the data to make a better guess.
160 base, ext = posixpath.splitext(path)
161 if ext in self.extensions_map:
162 return self.extensions_map[ext]
164 if ext in self.extensions_map:
165 return self.extensions_map[ext]
167 return self.extensions_map['']
169 if not mimetypes.inited:
170 mimetypes.init() # try to read system mime.types
171 extensions_map = mimetypes.types_map.copy()
172 extensions_map.update({
173 '': 'text/plain', # Default
179 def date_time_string(self, t):
180 return time.strftime('%a, %d %b %Y %H:%M:%S', time.gmtime(t))
184 bup web [[hostname]:port]
186 human-readable display human readable file sizes (i.e. 3.9K, 4.7M)
187 browser open the site in the default browser
189 o = options.Options(optspec)
190 (opt, flags, extra) = o.parse(sys.argv[1:])
193 o.fatal("at most one argument expected")
195 address = ('127.0.0.1', 8080)
197 addressl = extra[0].split(':', 1)
198 addressl[1] = int(addressl[1])
199 address = tuple(addressl)
201 git.check_repo_or_die()
202 top = vfs.RefList(None)
206 template_path = resource_path('web'),
207 static_path = resource_path('web/static')
210 # Disable buffering on stdout, for debug messages
211 sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
213 application = tornado.web.Application([
214 (r"(/.*)", BupRequestHandler),
217 if __name__ == "__main__":
218 http_server = tornado.httpserver.HTTPServer(application)
219 http_server.listen(address[1], address=address[0])
222 sock = http_server._socket # tornado < 2.0
223 except AttributeError, e:
224 sock = http_server._sockets.values()[0]
226 print "Serving HTTP on %s:%d..." % sock.getsockname()
228 loop = tornado.ioloop.IOLoop.instance()
230 browser_addr = 'http://' + address[0] + ':' + str(address[1])
231 loop.add_callback(lambda : webbrowser.open(browser_addr))