-
Notifications
You must be signed in to change notification settings - Fork 0
/
http-server-mod
executable file
·347 lines (304 loc) · 10.8 KB
/
http-server-mod
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
#!/usr/bin/env python
"""Simple HTTP Server.
This module builds on BaseHTTPServer by implementing the standard GET
and HEAD requests in a fairly straightforward manner.
"""
__version__ = "0.6"
__all__ = ["SimpleHTTPRequestHandler"]
import os
import posixpath
import BaseHTTPServer
import urllib
import urlparse
import cgi
import sys
import shutil
import mimetypes
import re
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
# Reid's API key
tmdbAPIKey = "3d801b6df71aa2ccd644d6dc38ec53ce"
class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
"""Simple HTTP request handler with GET and HEAD commands.
This serves files from the current directory and any of its
subdirectories. The MIME type for files is determined by
calling the .guess_type() method.
The GET and HEAD requests are identical except that the HEAD
request omits the actual contents of the file.
"""
server_version = "SimpleHTTP/" + __version__
def do_GET(self):
"""Serve a GET request."""
f = self.send_html()
if f:
try:
self.copyfile(f, self.wfile)
finally:
f.close()
def do_HEAD(self):
"""Serve a HEAD request."""
f = self.send_html()
if f:
f.close()
def send_html(self):
"""Common code for GET and HEAD commands.
This sends the response code and MIME headers.
Return value is either a file object (which has to be copied
to the outputfile by the caller unless the command was HEAD,
and must be closed by the caller under all circumstances), or
None, in which case the caller has nothing further to do.
"""
path = self.translate_path(self.path)
f = None
if os.path.isdir(path):
parts = urlparse.urlsplit(self.path)
if not parts.path.endswith('/'):
# redirect browser - doing basically what apache does
self.send_response(301)
new_parts = (parts[0], parts[1], parts[2] + '/',
parts[3], parts[4])
new_url = urlparse.urlunsplit(new_parts)
self.send_header("Location", new_url)
self.end_headers()
return None
for index in "index.html", "index.htm":
index = os.path.join(path, index)
if os.path.exists(index):
path = index
break
else:
return self.list_directory(path)
ctype = self.guess_type(path)
try:
# Always read in binary mode. Opening files in text mode may cause
# newline translations, making the actual size of the content
# transmitted *less* than the content-length!
f = open(path, 'rb')
except IOError:
self.send_error(404, "File not found: \"%s\"" % path)
return None
try:
self.send_response(200)
self.send_header("Content-type", ctype)
fs = os.fstat(f.fileno())
self.send_header("Content-Length", str(fs[6]))
self.send_header("Last-Modified", self.date_time_string(fs.st_mtime))
self.end_headers()
return f
except:
f.close()
raise
def list_directory(self, path):
"""Helper to produce a directory listing (absent index.html).
Return value is either a file object, or None (indicating an
error). In either case, the headers are sent, making the
interface the same as for send_html().
"""
def uninteresting(str):
return not (
# strip out temporary files, dot files, subtitles and executables
str.startswith("#") or str.startswith(".") or str.endswith(".srt")
or str.endswith(".sub") or str.endswith(".idx") or str.endswith(".txt")
or str.endswith(".vtt") or str.endswith(".exe")
)
try:
paths = os.listdir(path)
paths = filter(uninteresting, paths)
paths = [path + file for file in paths]
paths = sorted(paths, key=os.path.getmtime, reverse=True)
except os.error:
self.send_error(404, "No permission to list directory %s" % path)
return None
# list.sort(key=lambda a: a.lower())
f = StringIO()
displaypath = cgi.escape(urllib.unquote(self.path))
f.write("""
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<title>%s</title>
<style>
body {
padding: 0 .5em 0 .5em;
margin: .2em 0 0 0;
text-indent: 0;
font-size: 1em;
}
a {
text-decoration: none;
}
h1 {
background-color: black;
color: white;
font-size: 3em;
padding: 8px;
margin: .2em 0 0 0;
}
h2 {
padding: 8px 8px 8px 3em;
margin: .2em 0 0 0;
background-color: darkgrey;
color: white;
font-size: 6em;
font-weight: bold;
}
p {
margin: .2em 0 0 0;
padding: 0;
font-size: 1.5em;
font-family: monaco courier fixed;
}
.size {
padding: 0 .3em 0 .3em;
margin: 0;
background-color: darkgrey;
color: white;
/* display: inline-block; */
width: 4em;
height: 1em;
}
.file {
margin: 0;
font-size: 3em;
font-family: palatino helvetica;
text-indent: -4em;
margin-left: 4em;
}
.info {
font-size: 0.6em;
color: #800;
font-family: palatino helvetica;
font-style: italic;
}
.dir {
font-size: 3em;
font-family: palatino helvetica;
background-color: lightblue;
}
</style>
<body>
<h1><code>%s</code></h2>
<h2><a href="..">↑</a></h1>
""" % (displaypath[1:-1], displaypath[1:-1]))
for name in paths:
fullname = os.path.join(path, name)
displayname = linkname = name
# callthis on `urllib.quote(displayname)`?
# https://api.themoviedb.org/3/search/movie?api_key=3d801b6df71aa2ccd644d6dc38ec53ce&query=%s
size = os.stat(fullname).st_size
sizeStr = "{} bytes".format(size, "d")
k=1000.0
m=k*k
g=m*k
fmt=".1f"
if size > g:
sizeStr = format(size/g, fmt) + "G"
elif size > m:
sizeStr = format(size/m, fmt) + "M"
elif size > k:
sizeStr = format(size/k, fmt) + "k"
displayname = displayname[len(path):]
linkname = displayname
classStr=""
# Append / for directories or @ for symbolic links
if os.path.isdir(fullname):
displayname = displayname + "/"
linkname = displayname
sizeStr = ""
classStr=" class=\"dir\""
else:
sizeStr = "<span class=\"size\">%4s</span> " % sizeStr
classStr=" class=\"file\""
if os.path.islink(fullname):
displayname = displayname + "@"
# Note: a link to a directory displays with @ and links with /
f.write('<p%s><code>%s%s</code></p>\n'
% (classStr, sizeStr, self.pretty(urllib.quote(linkname), displayname)))
f.write("</body>\n</html>\n")
length = f.tell()
f.seek(0)
self.send_response(200)
encoding = sys.getfilesystemencoding()
self.send_header("Content-type", "text/html; charset=%s" % encoding)
self.send_header("Content-Length", str(length))
self.end_headers()
return f
def translate_path(self, path):
"""Translate a /-separated PATH to the local filename syntax.
Components that mean special things to the local file system
(e.g. drive or directory names) are ignored. (XXX They should
probably be diagnosed.)
"""
# abandon query parameters
path = path.split('?',1)[0]
path = path.split('#',1)[0]
# Don't forget explicit trailing slash when normalizing. Issue17324
trailing_slash = path.rstrip().endswith('/')
path = posixpath.normpath(urllib.unquote(path))
words = path.split('/')
words = filter(None, words)
path = os.getcwd()
for word in words:
if os.path.dirname(word) or word in (os.curdir, os.pardir):
# Ignore components that are not a simple file/directory name
continue
path = os.path.join(path, word)
if trailing_slash:
path += '/'
return path
def copyfile(self, source, outputfile):
"""Copy all data between two file objects.
The SOURCE argument is a file object open for reading
(or anything with a read() method) and the DESTINATION
argument is a file object open for writing (or
anything with a write() method).
The only reason for overriding this would be to change
the block size or perhaps to replace newlines by CRLF
-- note however that this the default server uses this
to copy binary data as well.
"""
shutil.copyfileobj(source, outputfile)
def guess_type(self, path):
"""Guess the type of a file.
Argument is a PATH (a filename).
Return value is a string of the form type/subtype,
usable for a MIME Content-type header.
The default implementation looks the file's extension
up in the table self.extensions_map, using application/octet-stream
as a default; however it would be permissible (if
slow) to look inside the data to make a better guess.
"""
base, ext = posixpath.splitext(path)
if ext in self.extensions_map:
return self.extensions_map[ext]
ext = ext.lower()
if ext in self.extensions_map:
return self.extensions_map[ext]
else:
return self.extensions_map['']
def pretty(self, link, name):
newName = name
pattern = re.compile(r'^(.*)\.(\d\d\d\d)\.(.*)\.\w+$')
if pattern.match(name):
sub = pattern.search(name)
newName = ("<a href=\"%s\">%s (%s)</a> <span class=\"info\">%s</span>"
% (link, cgi.escape(sub.group(1)), cgi.escape(sub.group(2)), cgi.escape(sub.group(3))))
else:
newName = "<a href=\"%s\">%s</a>" % (link, name)
return newName
if not mimetypes.inited:
mimetypes.init() # try to read system mime.types
extensions_map = mimetypes.types_map.copy()
extensions_map.update({
'': 'application/octet-stream', # Default
'.py': 'text/plain',
'.c': 'text/plain',
'.h': 'text/plain',
})
def test(HandlerClass = SimpleHTTPRequestHandler,
ServerClass = BaseHTTPServer.HTTPServer):
BaseHTTPServer.test(HandlerClass, ServerClass)
if __name__ == '__main__':
test()