-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
168 lines (150 loc) · 5.37 KB
/
server.py
File metadata and controls
168 lines (150 loc) · 5.37 KB
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
#!/usr/bin/env python3
"""
smurf - a simple markdown surfer
Authors:
Mitesh Shah <mitesh@oxal.org>
Repository:
https://github.com/oxalorg/smurf
"""
from http.server import SimpleHTTPRequestHandler, HTTPServer
from http import HTTPStatus
import shutil
import posixpath
import os
import argparse
import sys
import urllib
import html
import io
import subprocess
from string import Template
class SmurfRequestHandler(SimpleHTTPRequestHandler):
md_ext = (".html",)
def send_head(self):
# Logic
# check if a file exists on actual path
# if so serve the static file
# if not
# then check if trailing slash exists
# if not then redirect
# if it does
# then find the following path
# path.html path/index.html
path = self.translate_path(self.path)
f = None
parts = urllib.parse.urlsplit(self.path)
print(parts)
print(parts.path[1:-1])
if os.path.isfile(path):
# serve the file
pass
elif os.path.isfile(parts.path[1:-1] + ".html"):
# server the file
path = parts.path[1:-1] + ".html"
elif not parts.path.endswith('/'):
# redirect browser - doing basically what apache does
self.send_response(HTTPStatus.MOVED_PERMANENTLY)
new_parts = (parts[0], parts[1], parts[2] + '/', parts[3],
parts[4])
new_url = urllib.parse.urlunsplit(new_parts)
self.send_header("Location", new_url)
self.end_headers()
return None
elif os.path.isdir(path):
for index in ["index" + ext for ext in self.md_ext]:
# if an html file named "index" or last path url is available in
# a directory, display that instead of the default
# directory listing
index = os.path.join(path, index)
if os.path.exists(index):
path = index
break
# if os.path.exists()
else:
return
# return self.list_directory(path)
try:
f = open(path, 'rb')
except OSError:
self.send_error(HTTPStatus.NOT_FOUND, "File not found")
return None
base, ext = posixpath.splitext(path)
ctype = self.guess_type(path)
try:
self.send_response(HTTPStatus.OK)
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()
f.seek(0)
return f
except:
f.close()
raise
def list_directory(self, path):
try:
list = os.listdir(path)
except OSError:
self.send_error(HTTPStatus.NOT_FOUND,
"No permission to list directory")
return None
list.sort(key=lambda a: a.lower())
try:
displaypath = urllib.parse.unquote(
self.path, errors='surrogatepass')
except UnicodeDecodeError:
displaypath = urllib.parse.unquote(path)
displaypath = html.escape(displaypath, quote=False)
enc = sys.getfilesystemencoding()
title = 'Directory listing for %s' % displaypath
# form the content response i.e. index of the directory
r = []
r.append('<ul>')
for name in list:
fullname = os.path.join(path, name)
displayname = linkname = name
# Append / for directories or @ for symbolic links
if os.path.isdir(fullname):
displayname = name + "/"
linkname = name + "/"
if os.path.islink(fullname):
displayname = name + "@"
# Note: a link to a directory displays with @ and links with /
r.append('<li><a href="%s">%s</a></li>' % (urllib.parse.quote(
linkname, errors='surrogatepass'), html.escape(
displayname, quote=False)))
r.append('</ul>')
r = BASE_TEMPLATE.substitute(content='\n'.join(r), css=CSS, title=title)
encoded = r.encode(enc, 'surrogateescape')
# transform the encoded content to a file like object
f = io.BytesIO()
f.write(encoded)
f.seek(0)
self.send_response(HTTPStatus.OK)
self.send_header("Content-type", "text/html; charset=%s" % enc)
self.send_header("Content-Length", str(len(encoded)))
self.end_headers()
return f
def cli():
parser = argparse.ArgumentParser(
description="a simple markdown surfer",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('dir', help="folder to serve", nargs='?', default=os.getcwd())
args = parser.parse_args()
if not os.path.isdir(args.dir):
print(args.dir, " is not a valid directory")
sys.exit(1)
os.chdir(args.dir)
def main():
cli()
server_address = ('0.0.0.0', 3434)
httpd = HTTPServer(server_address, SmurfRequestHandler)
print("Starting server at http://localhost:3434")
try:
httpd.serve_forever()
except:
httpd.shutdown()
httpd.server_close()
if __name__ == '__main__':
main()