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