]> arthur.barton.de Git - bup.git/blob - cmd/web-cmd.py
484041ac112c8993fd8e37652451ae7975203133
[bup.git] / cmd / web-cmd.py
1 #!/usr/bin/env python
2 import sys, stat, urllib, mimetypes, posixpath, time
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
147     def _guess_type(self, path):
148         """Guess the type of a file.
149
150         Argument is a PATH (a filename).
151
152         Return value is a string of the form type/subtype,
153         usable for a MIME Content-type header.
154
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.
159         """
160         base, ext = posixpath.splitext(path)
161         if ext in self.extensions_map:
162             return self.extensions_map[ext]
163         ext = ext.lower()
164         if ext in self.extensions_map:
165             return self.extensions_map[ext]
166         else:
167             return self.extensions_map['']
168
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
174         '.py': 'text/plain',
175         '.c': 'text/plain',
176         '.h': 'text/plain',
177         })
178
179     def date_time_string(self, t):
180         return time.strftime('%a, %d %b %Y %H:%M:%S', time.gmtime(t))
181
182
183 optspec = """
184 bup web [[hostname]:port]
185 --
186 human-readable    display human readable file sizes (i.e. 3.9K, 4.7M)
187 """
188 o = options.Options(optspec)
189 (opt, flags, extra) = o.parse(sys.argv[1:])
190
191 if len(extra) > 1:
192     o.fatal("at most one argument expected")
193
194 address = ('127.0.0.1', 8080)
195 if len(extra) > 0:
196     addressl = extra[0].split(':', 1)
197     addressl[1] = int(addressl[1])
198     address = tuple(addressl)
199
200 git.check_repo_or_die()
201 top = vfs.RefList(None)
202
203 settings = dict(
204     debug = 1,
205     template_path = resource_path('web'),
206     static_path = resource_path('web/static')
207 )
208
209 # Disable buffering on stdout, for debug messages
210 sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
211
212 application = tornado.web.Application([
213     (r"(/.*)", BupRequestHandler),
214 ], **settings)
215
216 if __name__ == "__main__":
217     http_server = tornado.httpserver.HTTPServer(application)
218     http_server.listen(address[1], address=address[0])
219
220     try:
221         sock = http_server._socket # tornado < 2.0
222     except AttributeError, e:
223         sock = http_server._sockets.values()[0]
224
225     print "Serving HTTP on %s:%d..." % sock.getsockname()
226     loop = tornado.ioloop.IOLoop.instance()
227     loop.start()
228