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