-
Notifications
You must be signed in to change notification settings - Fork 1
/
web.py
286 lines (252 loc) · 9.85 KB
/
web.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
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
#!/usr/bin/env python
import codecs
import logging
import os
import signal
import subprocess
import sys
from collections import OrderedDict
from io import StringIO
from subprocess import Popen, PIPE, STDOUT, TimeoutExpired
from flask import Flask, request, redirect, render_template, send_from_directory
from flask_caching import Cache
import explainer
import lang_ast
import literal_gen
import nodes
import settings
for node in nodes.nodes:
nodes.nodes[node].run_tests()
sys.stdin = StringIO()
app = Flask(__name__,
template_folder="web_content/template/",
static_folder="web_content/static/")
cache = Cache(app, config={'CACHE_TYPE': 'simple'})
modified_process = Popen(["git",
"log",
"-1",
"--format=%cd",
"--date=local"],
stdout=PIPE)
output, errors = modified_process.communicate()
updated_time = output.decode()[:-1]
is_windows = hasattr(os.sys, 'winver')
if is_windows:
updated_time += ", WINDOWS"
@app.route("/")
def root():
code = request.args.get("code", "")
inp = request.args.get("input", "")
warnings = int(request.args.get("warnings", "1"))
hex = int(request.args.get("hex", "0"))
return render_template("index.html",
last_updated=updated_time,
docs=docs(),
code=code,
input=inp,
warnings=warnings,
hex=hex)
@app.route("/code")
@app.route("/blog")
def rick():
return redirect("http://www.youtube.com/watch?v=dQw4w9WgXcQ")
@app.route("/submit", methods=['POST'])
def submit_code(timeout=5):
code = request.form.get("code", "")
inp = request.form.get("input", "")
print(code, inp)
warnings = int(request.form.get("warnings", "0"), 10)
use_hex = int(request.form.get("hex", "0"), 10)
args = [sys.executable,
'main.py',
'--safe',
'--',
code]
stderr = PIPE
if warnings:
args.insert(2, "--warnings")
stderr = STDOUT
if use_hex:
args.insert(2, "--hex")
with Popen(args,
stdin=PIPE,
stdout=PIPE,
stderr=stderr,
creationflags=is_windows and subprocess.CREATE_NEW_PROCESS_GROUP) as process:
process.stdin.write(bytearray(inp, "utf-8"))
process.stdin.close()
response = ""
try:
process.wait(timeout)
except TimeoutExpired:
response = "Timeout running code.\n"
if is_windows:
os.kill(process.pid, signal.CTRL_BREAK_EVENT)
else:
process.send_signal(signal.SIGTERM)
try:
process.wait(2)
except TimeoutExpired:
response += "Really timed out code\n"
process.kill()
response += process.stdout.read().decode("cp1252", errors="replace")
return response
@app.route("/explain", methods=['POST'])
def explain_code():
code = request.form.get("code", "")
error = ""
try:
hexified = (codecs.encode(bytes([byte]), "hex_codec") for byte in explainer.optimise(bytearray(code, "utf-8")))
except:
error = "Error whilst optimising hex"
hexified = (codecs.encode(bytes([byte]), "hex_codec") for byte in bytearray(code, "utf-8"))
hex_code = b" ".join(hexified).decode("ascii").upper()
try:
return "\n{}\n{}\n{}".format(explainer.Explainer(bytearray(code, "utf-8"), []), error, hex_code).replace("\n", "\n ")
except:
return "\n Error formatting explanation\n {}\n {}".format(error, hex_code)
@app.route("/dictionary")
def dictionary():
return render_template("dictionary.html")
@app.route("/dict_compress", methods=['POST'])
def dict_compress():
inp = request.form.get("compress")
return nodes.nodes["dictionary"].compress(inp)
@app.route("/docs")
@cache.cached(timeout=3600)
def docs():
docs = get_docs()
keys = ["char", "name", "arg_types", "fixed_params", "input", "output", "docs"]
types = ["<br>", "<br>", "<br>", "<br>", "<pre>", "<pre>", "<br>"]
table = []
for func in docs:
row = [func[doc_type] for doc_type in keys]
for i, col in enumerate(row):
try:
if types[i] == "<br>":
row[i] = col.replace("\n", "<br>")
elif types[i] == "<pre>":
row[i] = '<pre class="doc_pre">'+str(col)+"</pre>"
except AttributeError:
pass
table.append(row)
table.sort(key=lambda x: x[0]+x[1])
keys = [key.title().replace("_", " ") for key in keys]
app.jinja_env.autoescape = False
rtn = render_template("docs_table.html",
keys=keys,
funcs=table)
app.jinja_env.autoescape = True
return rtn
def get_docs():
docs = []
for node in nodes.nodes:
if nodes.nodes[node].ignore:
continue
funcs = nodes.nodes[node].get_functions()
for func in funcs:
func_doc = {}
if func.__name__ == "<lambda>":
continue
elif func.__name__ == "func":
func_doc["name"] = node
else:
func_doc["name"] = func.__name__
arg_types_dict = func.__annotations__
func_arg_names = func.__code__.co_varnames[1:func.__code__.co_argcount]
arg_types = OrderedDict()
for arg in func_arg_names:
if arg in arg_types_dict:
annotation = arg_types_dict[arg]
if isinstance(annotation, tuple):
arg_types[arg] = [i.__name__ for i in annotation]
else:
arg_types[arg] = [annotation.__name__]
else:
arg_types[arg] = ["object"]
func_doc["arg_types"] = print_ordered_dict(arg_types)
if func.__code__.co_flags & 4:
if func_doc["arg_types"]:
func_doc["arg_types"] += "\n"
func_doc["arg_types"] += "*args"
cls_init = nodes.nodes[node].__init__
fixed = cls_init.__annotations__
func_doc["fixed_params"] = ""
if fixed:
arg_names = cls_init.__code__.co_varnames[1:cls_init.__code__.co_argcount]
for arg in arg_names:
if arg in fixed:
func_doc["fixed_params"] += fixed[arg]+"\n"
elif nodes.nodes[node].accepts.__module__ != "nodes":
func_doc["fixed_params"] = "custom"
func_doc["docs"] = func.__doc__
if hasattr(nodes.nodes[node], "documentation"):
func_doc["docs"] = nodes.nodes[node].documentation
try:
func_doc["char"] = nodes.nodes[node].char.decode("ascii")
except UnicodeDecodeError:
if nodes.nodes[node].char[0] & 0x80:
func_doc["char"] = "." + chr(nodes.nodes[node].char[0] & 0x7F)
func_doc["input"] = ""
func_doc["output"] = ""
if hasattr(func, "tests"):
try:
nodes.nodes[node].reset_tests()
except AttributeError:
pass
for test in func.tests[::-1]:
try:
inp = literal_gen.stack_literal(test[0])
if isinstance(test[-1], bytearray):
cmd = nodes.nodes[node].char + test[-1]
else:
cmd = nodes.nodes[node].char+bytearray(test[-1].encode("ascii"))
try:
lang_ast.test_code(inp+cmd, test[1])
except AssertionError:
print(func)
raise
except NotImplementedError:
func_doc["input"] = "Literal Undefined\n"
func_doc["output"] = str(test[1])+"\n"
else:
try:
cmd = cmd.decode("ascii")
except UnicodeDecodeError:
if cmd[0] & 0x80:
cmd = "." + chr(cmd[0] & 0x7F) + cmd[1:].decode("ascii")
elif cmd[:1] == b"~":
cmd = "~." + chr(cmd[1] & 0x7F)
try:
func_doc["input"] += (inp.decode("ascii")+cmd+"\n")
func_doc["output"] += (str(test[1])+"\n")
except TypeError:
pass
func_doc["input"] = func_doc["input"][:-1]
func_doc["output"] = func_doc["output"][:-1]
func_doc["output"] = func_doc["output"].replace("<", "<")
func_doc["output"] = func_doc["output"].replace(">", ">")
docs.append(func_doc)
return docs
def print_ordered_dict(ordered):
rtn = ""
for key, value in ordered.items():
rtn += key+": "+str(value).replace("'", "")+"\n"
return rtn[:-1]
@app.route('/static/<path:path>')
def send_js(path):
return send_from_directory('web_content/static', path)
def main(debug=settings.DEBUG, url="127.0.0.1", port=5000):
log = logging.getLogger('werkzeug')
log.setLevel(logging.DEBUG)
file_handler = logging.FileHandler("log.log", "a")
file_handler.setLevel(logging.DEBUG)
log.addHandler(file_handler)
stream_handler = logging.StreamHandler(stream=sys.stderr)
stream_handler.setLevel(logging.DEBUG)
log.addHandler(stream_handler)
app.debug = debug
from waitress import serve
serve(app, host=url, port=port)
if __name__ == '__main__':
main(url="0.0.0.0")