-
Notifications
You must be signed in to change notification settings - Fork 0
/
lfsa_1.0.0.py
executable file
·183 lines (162 loc) · 5.55 KB
/
lfsa_1.0.0.py
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
#!/usr/bin/python
import sys
# Python 3.
try:
from http.server import HTTPServer
from http.server import SimpleHTTPRequestHandler
# Python 2.
except ImportError:
from BaseHTTPServer import HTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
import glob
import os
import base64
class HTTPRequestHandler(SimpleHTTPRequestHandler):
# Implementation.
def do_GET(self):
tool.process(self)
def do_POST(self):
tool.process(self)
def listFiles(path):
items = []
fileNames = glob.glob(path + "/*")
fileNames.sort()
for fileName in fileNames:
file = { }
# Path.
file["path"] = os.path.basename(fileName)
# Type.
file["type"] = None
if (os.path.isdir(fileName)):
file["type"] = "dir"
elif (os.path.isfile(fileName)):
file["type"] = "file";
items.append(file)
return items
def fileListToJSON(fileList):
out = ""
for file in fileList:
if (len(out)):
out += ","
out += "{\"path\":\"%s\",\"type\":\"%s\"}" % (file["path"], file["type"])
return "[" + out + "]"
def jsonToPathContents(json):
# This function takes `abc` and `def` from string of the following format:
# `{"path": "abc", "contents": "def"}`.
parts = json.split('"')
if (len(parts) == 9):
return (parts[3], parts[7])
return (None, None)
class Tool(object):
# Configuration.
def __init__(self, arguments):
self.arguments = arguments
self.PORT = 8000
self.serverHost = ""
# Main execution sequence.
def run(self):
self.validateArguments()
self.parseArguments()
self.printArguments()
self.runServer()
# Implementation.
def validateArguments(self):
if (len(self.arguments) < 2):
print(
(
"Usage: %s DIR [PORT]"
"\n\n"
"\tPORT defaults to 8000"
) % self.arguments[0]
)
sys.exit(1)
def printArguments(self):
print("DIR: '%s'" % self.DIR)
print("PORT: '%s'" % self.PORT)
def parseArguments(self):
self.DIR = self.arguments[1]
# Override default port if specified.
if (len(self.arguments) >= 3):
self.PORT = self.arguments[2]
def runServer(self):
addr = (self.serverHost, int(self.PORT))
self.httpd = HTTPServer(addr, HTTPRequestHandler)
self.httpd.serve_forever()
def process(self, requestHandler):
if (requestHandler.path == "/path"):
self.processPath(requestHandler)
if (requestHandler.path == "/list"):
self.processFileList(requestHandler)
if (requestHandler.path == "/read"):
self.processReadFile(requestHandler)
if (requestHandler.path == "/write"):
self.processWriteFile(requestHandler)
def processPath(self, request):
request.send_response(200)
request.send_header("Access-Control-Allow-Origin", "*")
request.end_headers()
data = self.DIR.encode()
request.wfile.write(data)
def processFileList(self, request):
request.send_response(200)
request.send_header("Access-Control-Allow-Origin", "*")
request.end_headers()
size = int(request.headers["Content-Length"])
path = request.rfile.read(size)
path = path.decode()
absPath = "%s/%s" % (self.DIR, path)
fileList = listFiles(absPath)
fileListJSON = fileListToJSON(fileList)
data = fileListJSON.encode()
request.wfile.write(data)
def processReadFile(self, request):
request.send_response(200)
request.send_header("Access-Control-Allow-Origin", "*")
request.end_headers()
size = int(request.headers["Content-Length"])
path = request.rfile.read(size)
path = path.decode()
absPath = "%s/%s" % (self.DIR, path)
print("Reading '%s'" % absPath)
f = open(absPath, "r")
contents = f.read()
f.close()
# Perform Python3 compatible encoding.
# If this crashes for Python2 (when there are non-ASCII symbols),
# it's probably fine for `contents` to stay intact.
try:
contents = contents.encode()
except:
pass
request.wfile.write(contents)
def processWriteFile(self, request):
request.send_response(200)
request.send_header("Access-Control-Allow-Origin", "*")
request.end_headers()
size = int(request.headers["Content-Length"])
data = request.rfile.read(size)
# Extract path and contents.
(path, contents) = jsonToPathContents(data)
if ((path is None) or (contents is None)):
print("ERROR Writing failed due to corrupt incoming data")
# Try to convert using pre-Python2.4 API.
try:
contents = base64.decodestring(contents)
# Resort to Python2.4+ API.
except:
contents = base64.b64decode(contents)
# Perform Python3 compatible DEcoding.
# If this crashes for Python2 (when there are non-ASCII symbols),
# it's probably fine for `contents` to stay intact.
try:
contents = contents.decode()
except:
pass
# Write.
absPath = "%s/%s" % (self.DIR, path)
print("Writing '%s'" % absPath)
f = open(absPath, "w")
f.write(contents)
f.close()
tool = Tool(sys.argv)
tool.run()