2 import sys, stat, urllib, mimetypes, posixpath, time, webbrowser
4 from bup import options, git, vfs
5 from bup.helpers import *
7 import tornado.httpserver
11 log('error: cannot find the python "tornado" module; please install it\n')
17 def _compute_breadcrumbs(path, show_hidden=False):
18 """Returns a list of breadcrumb objects for a path."""
20 breadcrumbs.append(('[root]', '/'))
21 path_parts = path.split('/')[1:-1]
23 for part in path_parts:
24 full_path += part + "/"
27 url_append = '?hidden=1'
28 breadcrumbs.append((part, full_path+url_append))
32 def _contains_hidden_files(n):
33 """Return True if n contains files starting with a '.', False otherwise."""
36 if len(name)>1 and name.startswith('.'):
42 def _compute_dir_contents(n, path, show_hidden=False):
43 """Given a vfs node, returns an iterator for display info of all subs."""
46 url_append = "?hidden=1"
49 yield('..', '../' + url_append, '')
52 link = urllib.quote(sub.name)
54 # link should be based on fully resolved type to avoid extra
56 if stat.S_ISDIR(sub.try_resolve().mode):
59 if not show_hidden and len(display)>1 and display.startswith('.'):
63 if stat.S_ISDIR(sub.mode):
65 elif stat.S_ISLNK(sub.mode):
69 size = (opt.human_readable and format_filesize(size)) or size
71 yield (display, link + url_append, size)
74 class BupRequestHandler(tornado.web.RequestHandler):
76 return self._process_request(path)
79 return self._process_request(path)
81 @tornado.web.asynchronous
82 def _process_request(self, path):
83 path = urllib.unquote(path)
84 print 'Handling request for %s' % path
87 except vfs.NoSuchFile:
91 if stat.S_ISDIR(n.mode):
92 self._list_directory(path, n)
94 self._get_file(path, n)
96 def _list_directory(self, path, n):
97 """Helper to produce a directory listing.
99 Return value is either a file object, or None (indicating an
100 error). In either case, the headers are sent.
102 if not path.endswith('/') and len(path) > 0:
103 print 'Redirecting from %s to %s' % (path, path + '/')
104 return self.redirect(path + '/', permanent=True)
107 show_hidden = int(self.request.arguments.get('hidden', [0])[-1])
108 except ValueError, e:
112 'list-directory.html',
114 breadcrumbs=_compute_breadcrumbs(path, show_hidden),
115 files_hidden=_contains_hidden_files(n),
116 hidden_shown=show_hidden,
117 dir_contents=_compute_dir_contents(n, path, show_hidden))
119 def _get_file(self, path, n):
120 """Process a request on a file.
122 Return value is either a file object, or None (indicating an error).
123 In either case, the headers are sent.
125 ctype = self._guess_type(path)
127 self.set_header("Last-Modified", self.date_time_string(n.mtime))
128 self.set_header("Content-Type", ctype)
130 self.set_header("Content-Length", str(size))
131 assert(len(n.hash) == 20)
132 self.set_header("Etag", n.hash.encode('hex'))
134 if self.request.method != 'HEAD':
141 except StopIteration:
145 self.request.connection.stream.write(blob,
146 callback=lambda: me(me))
147 write_more(write_more)
151 def _guess_type(self, path):
152 """Guess the type of a file.
154 Argument is a PATH (a filename).
156 Return value is a string of the form type/subtype,
157 usable for a MIME Content-type header.
159 The default implementation looks the file's extension
160 up in the table self.extensions_map, using application/octet-stream
161 as a default; however it would be permissible (if
162 slow) to look inside the data to make a better guess.
164 base, ext = posixpath.splitext(path)
165 if ext in self.extensions_map:
166 return self.extensions_map[ext]
168 if ext in self.extensions_map:
169 return self.extensions_map[ext]
171 return self.extensions_map['']
173 if not mimetypes.inited:
174 mimetypes.init() # try to read system mime.types
175 extensions_map = mimetypes.types_map.copy()
176 extensions_map.update({
177 '': 'text/plain', # Default
183 def date_time_string(self, t):
184 return time.strftime('%a, %d %b %Y %H:%M:%S', time.gmtime(t))
188 bup web [[hostname]:port]
190 human-readable display human readable file sizes (i.e. 3.9K, 4.7M)
191 browser open the site in the default browser
193 o = options.Options(optspec)
194 (opt, flags, extra) = o.parse(sys.argv[1:])
197 o.fatal("at most one argument expected")
199 address = ('127.0.0.1', 8080)
201 addressl = extra[0].split(':', 1)
202 addressl[1] = int(addressl[1])
203 address = tuple(addressl)
205 git.check_repo_or_die()
206 top = vfs.RefList(None)
210 template_path = resource_path('web'),
211 static_path = resource_path('web/static')
214 # Disable buffering on stdout, for debug messages
215 sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
217 application = tornado.web.Application([
218 (r"(/.*)", BupRequestHandler),
221 if __name__ == "__main__":
222 http_server = tornado.httpserver.HTTPServer(application)
223 http_server.listen(address[1], address=address[0])
226 sock = http_server._socket # tornado < 2.0
227 except AttributeError, e:
228 sock = http_server._sockets.values()[0]
230 print "Serving HTTP on %s:%d..." % sock.getsockname()
232 loop = tornado.ioloop.IOLoop.instance()
234 browser_addr = 'http://' + address[0] + ':' + str(address[1])
235 loop.add_callback(lambda : webbrowser.open(browser_addr))