-
Notifications
You must be signed in to change notification settings - Fork 0
/
fakeserver.py
222 lines (211 loc) · 5.47 KB
/
fakeserver.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
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
import typing
import os
import json
import sys
from game import Game, Player, MoveForwardsCard, TurnCard, ChangeLevelCard, ShootCard, RevengeCard
class URLQuery:
def __init__(self, q):
self.orig = q
self.fields = {}
for f in q.split("&"):
s = f.split("=")
if len(s) >= 2:
self.fields[s[0]] = s[1]
def get(self, key):
if key in self.fields:
return self.fields[key]
else:
return ''
def read_file(filename: str) -> bytes:
"""Read a file and return the contents."""
f = open(filename, "rb")
t = f.read()
f.close()
return t
def write_file(filename: str, content: bytes):
"""Write data to a file."""
f = open(filename, "wb")
f.write(content)
f.close()
class HttpResponse(typing.TypedDict):
"""A dict containing an HTTP response."""
status: int
headers: dict[str, str]
content: str | bytes
class HttpResponseStrict(typing.TypedDict):
"""A dict containing an HTTP response. The content field is required to be bytes and not str."""
status: int
headers: dict[str, str]
content: bytes
game: Game = Game()
# game.addPlayer(Player("someone"))
# game.addPlayer(Player("someone else"))
# game.addPlayer(Player("a third person"))
def get(path: str, query: URLQuery) -> HttpResponse:
# playername = query.get("name")
if path == "/script.js":
return {
"status": 200,
"headers": {
"Content-Type": "text/javascript"
},
"content": read_file("public_files/script.js").replace(b"x.send(body)", b'x.send(body.replaceAll("\\n", "\\\\n"))')
}
elif os.path.isfile("public_files" + path):
return {
"status": 200,
"headers": {
"Content-Type": {
"html": "text/html",
"js": "text/javascript",
"css": "text/css",
"svg": "image/svg+xml",
"ico": "image/x-icon"
}[path.split(".")[-1]]
},
"content": read_file("public_files" + path)
}
elif os.path.isdir("public_files" + path):
return {
"status": 200,
"headers": {
"Content-Type": "text/html"
},
"content": read_file("public_files" + path + "index.html")
}
elif path == "/status":
return {
"status": 200,
"headers": {
"Content-Type": "application/json"
},
"content": json.dumps(game.toDict(), indent='\t')
}
elif path == "/status_mod":
return {
"status": 200,
"headers": {
"Content-Type": "text/html"
},
"content": f"""<p>Status: <b>{game.status}</b></p><p>Players:</p><ul>{"".join(["<li><button onclick='sendServerMsg("+'"r'+str(game.players.index(p))+'"'+")'>Remove</button> "+p.name+"</li>" for p in game.players])}</ul>"""
}
else: # 404 page
print("404 GET " + path, file=sys.stderr)
return {
"status": 404,
"headers": {
"Content-Type": "text/html"
},
"content": ""
}
def post(path: str, body: str) -> HttpResponse:
bodydata = body.split("\n")
if path == "/join_game":
game.addPlayer(Player(bodydata[0]))
return {
"status": 200,
"headers": {},
"content": ""
}
elif path == "/ready":
game.readyPlayer(bodydata[0])
return {
"status": 200,
"headers": {},
"content": ""
}
elif path == "/submit_plan":
game.setPlan(bodydata)
return {
"status": 200,
"headers": {},
"content": ""
}
elif path == "/mod":
if bodydata[0][0] == "r":
game.removePlayer(int(bodydata[0][1:]))
return {
"status": 200,
"headers": {},
"content": ""
}
else:
print("404 POST " + path, file=sys.stderr)
return {
"status": 404,
"headers": {
"Content-Type": "text/html"
},
"content": ""
}
class MyServer:
def read_packet(self) -> bytes:
headers = b""
newChar = b""
while newChar != b".":
headers += newChar
newChar = sys.stdin.buffer.read(1)
length = int(headers)
content = b""
for i in range(length):
content += sys.stdin.buffer.read(1)
return content
def handle_request(self):
method = self.read_packet()
path = self.read_packet().decode("UTF-8")
body = self.read_packet().decode("UTF-8")
body = body.replace("\\n", "\n")
res: HttpResponseStrict = {
"status": 404,
"headers": {},
"content": b""
}
if method == b"GET":
res = self.do_GET(path)
if method == b"POST":
res = self.do_POST(path, body)
s: list[bytes] = [
str(res["status"]).encode("UTF-8"),
",".join([f"{a}:{b}" for a, b in res["headers"].items()]).encode("UTF-8"),
res["content"]
]
for data in s:
self.send_packet(data)
# time.sleep(0.3)
def send_packet(self, info: bytes):
sys.stdout.buffer.write(str(len(info)).encode("UTF-8"))
sys.stdout.buffer.write(b".")
sys.stdout.buffer.write(info)
sys.stdout.buffer.flush()
# try: print("Printed[", str(len(info)), '.', info.decode("UTF-8"), "]", sep="", file=sys.stderr)
# except UnicodeDecodeError: print("Printed[", str(len(info)), '.', info, "]", sep="", file=sys.stderr)
def do_GET(self, path: str) -> HttpResponseStrict:
splitpath = path.split("?")
res = get(splitpath[0], URLQuery(''.join(splitpath[1:])))
c: str | bytes = res["content"]
if isinstance(c, str): c = c.encode("utf-8")
return {
"status": res["status"],
"headers": res["headers"],
"content": c
}
def do_POST(self, path: str, body: str) -> HttpResponseStrict:
res = post(path, body)
c: str | bytes = res["content"]
if isinstance(c, str): c = c.encode("utf-8")
return {
"status": res["status"],
"headers": res["headers"],
"content": c
}
if __name__ == "__main__":
running = True
webServer = MyServer()
print(f"Fake server started", file=sys.stderr)
# sys.stdout.flush()
while running:
try:
webServer.handle_request()
except KeyboardInterrupt:
running = False
print("Server stopped", file=sys.stderr)