]> git.mxchange.org Git - quix0rs-apt-p2p.git/blob - HTTPServer.py
Added new HTTPServer that serves static files.
[quix0rs-apt-p2p.git] / HTTPServer.py
1 import os.path, time
2 from twisted.web2 import server, http, resource, channel
3 from twisted.web2 import static, http_headers, responsecode
4
5 class FileDownloader(static.File):
6     def render(self, req):
7         resp = super(FileDownloader, self).render(req)
8         if resp != responsecode.NOT_FOUND:
9             return resp
10         
11         return http.Response(
12             200,
13             {'content-type': http_headers.MimeType('text', 'html')},
14             """<html><body>
15             <h2>Finding</h2>
16             <p>TODO: eventually this will trigger a search for that file.</body></html>""")
17         
18
19 class Toplevel(resource.Resource):
20     addSlash = True
21     
22     def __init__(self, directory):
23         self.directory = directory
24         self.subdirs = []
25
26     def addDirectory(self, directory):
27         path = "~" + str(len(self.subdirs))
28         self.subdirs.append(directory)
29         return path
30     
31     def removeDirectory(self, directory):
32         loc = self.subdirs.index(directory)
33         self.subdirs[loc] = ''
34         
35     def render(self, ctx):
36         return http.Response(
37             200,
38             {'content-type': http_headers.MimeType('text', 'html')},
39             """<html><body>
40             <h2>Statistics</h2>
41             <p>TODO: eventually some stats will be shown here.</body></html>""")
42
43     def locateChild(self, request, segments):
44         name = segments[0]
45         if len(name) > 1 and name[0] == '~':
46             try:
47                 loc = int(name[1:])
48             except:
49                 return None, ()
50             
51             if loc >= 0 and loc < len(self.subdirs) and self.subdirs[loc]:
52                 return static.File(self.subdirs[loc]), segments[1:]
53             else:
54                 return None, ()
55         
56         if len(name) > 1:
57             return FileDownloader(self.directory), segments[0:]
58         else:
59             return self, ()
60         
61 if __name__ == '__builtin__':
62     # Running from twistd -y
63     t = Toplevel('/home')
64     t.addDirectory('/tmp')
65     t.addDirectory('/var/log')
66     site = server.Site(t)
67     
68     # Standard twisted application Boilerplate
69     from twisted.application import service, strports
70     application = service.Application("demoserver")
71     s = strports.service('tcp:18080', channel.HTTPFactory(site))
72     s.setServiceParent(application)