forked from ajinabraham/bad_python_extract
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
98 lines (82 loc) · 3.02 KB
/
server.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
import os
import io
import errno
import zipfile
from werkzeug.utils import secure_filename
from flask import Flask, flash, request
from config import settings
app = Flask(__name__)
def unzip(zip_file, extraction_path):
"""
code to unzip files
"""
print("[INFO] Unzipping")
try:
files = []
with zipfile.ZipFile(zip_file, "r") as z:
for file_info in z.infolist():
file_name = file_info.filename
dat = z.open(file_name, "r")
files.append(file_name)
outfile = os.path.join(extraction_path, file_name)
if not os.path.exists(os.path.dirname(outfile)):
try:
os.makedirs(os.path.dirname(outfile))
except OSError as exc: # Guard against race condition
if exc.errno != errno.EEXIST:
print("\n[WARN] OS Error: Race Condition")
if not outfile.endswith("/"):
with io.open(outfile, mode='wb') as f:
f.write(dat.read())
dat.close()
return files
except Exception as e:
print("[ERROR] Unzipping Error" + str(e))
def html_escape(text):
"""Produce entities within text."""
html_escape_table = {
"&": "&",
'"': """,
"'": "'",
">": ">",
"<": "<",
}
return "".join(html_escape_table.get(c, c) for c in text)
def allowed_file(filename):
"""Allowed File"""
return '.' in filename and filename.rsplit('.', 1)[1].lower() in settings.ALLOWED_EXTS
@app.route('/upload', methods=['POST'])
def upload():
"""Handle Upload"""
if request.method == 'POST':
extraction_path = os.path.join(os.path.dirname(
os.path.realpath(__file__)), "uploads")
if 'file' not in request.files:
flash('No file part')
return "No File part!"
file_uploaded = request.files['file']
if file_uploaded.filename == '':
flash('No selected file')
return "No File Selected!"
if file_uploaded and allowed_file(file_uploaded.filename):
filename = secure_filename(file_uploaded.filename)
write_to_file = os.path.join(extraction_path, filename)
file_uploaded.save(write_to_file)
unzip(write_to_file, extraction_path)
return "<b>Uploaded to</b> " + html_escape(write_to_file) + "<br>" + "<b>Content Extracted to</b> " + html_escape(extraction_path)
@app.route('/', methods=['GET'])
def main():
"""Home"""
html = '''
<form enctype="multipart/form-data" action="/upload" method="POST">
Choose a file to upload:
<br><br>
<input name="file" type="file" accept=".zip,.apk" />
<br><hr><br>
<input type="submit" value="Upload" />
</form>
'''
return html
if __name__ == '__main__':
app.secret_key = 'super secret key'
app.run(threaded=True, host=settings.HOST, port=settings.PORT, debug=settings.DEBUG)