-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.py
193 lines (151 loc) · 5.2 KB
/
main.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
from flask import Flask
from flask import render_template
from flask import request
from flask import jsonify
from flaskwebgui import FlaskUI
import requests
import json
import concurrent.futures
import multiprocessing
import sys
import logging
# ↓ Set to "False" when debugging then it will output to the terminal ↓
IN_APP_LOGS = True
class OutputCapturer:
output = []
def __enter__(self):
self._stdout = sys.stdout
self._stderr = sys.stderr
sys.stdout = self
sys.stderr = self
return self
def __exit__(self, exc_type, exc_val, exc_tb):
sys.stdout = self._stdout
sys.stderr = self._stderr
def write(self, text):
self.output.append(text)
def flush(self):
pass
app = Flask(__name__)
try:
with open('nanabox.json', 'r') as file:
json_file = json.load(file)
except (FileNotFoundError, json.JSONDecodeError):
json_file = {
"hosts": {
"fileio": {
"url": "https://file.io",
"link": "lambda data: data['link']"
}
},
"history": {}
}
hosts = json_file["hosts"]
def evaluate_function_string(func_str):
def dynamic_function(data):
return eval(func_str)
return dynamic_function
for key, value in hosts.items():
if isinstance(value, str):
hosts[key] = evaluate_function_string(value)
@app.route('/')
def home():
return render_template('index.html')
# GET | Backend logs
@app.route('/logs')
def send_logs():
filtered_output = [line.decode() if isinstance(line, bytes) else line for line in OutputCapturer.output if line.strip()]
return jsonify({'output': filtered_output})
# POST | Upload file(s)
def upload_file(url, file, host):
print("[INFO] Uploading to host " + host)
if host == "filebin":
with requests.post(url, files={'file': (file.filename, file.read())}) as response:
return response.json()
else:
with requests.post(url, files={'file': (file.filename, file.read())}) as response:
return response.json()
@app.route('/upload', methods=['POST'])
def upload():
try:
if 'file' not in request.files:
print("[ERROR] No file provided")
return jsonify({"error": "No file provided"}), 400
file = request.files['file']
if file.filename == '':
print("[ERROR] No file selected")
return jsonify({"error": "No file selected"}), 400
host = hosts.get(request.args.get('host'))
url = host['url']
if not url:
print("[ERROR] Invalid host!")
return jsonify({"error": "Invalid host"}), 400
result_queue = multiprocessing.Queue()
with concurrent.futures.ThreadPoolExecutor() as executor:
future = executor.submit(upload_file, url, file, request.args.get('host'))
future.add_done_callback(lambda future: result_queue.put(future.result()))
data = result_queue.get()
print("[SUCCESS] DATA RECEIVED: " + json.dumps(data))
file_link_fn_str = host['link']
file_link = eval(file_link_fn_str)(data)
file_name = file.filename
json_file["history"][file_name] = file_link
with open('nanabox.json', 'w') as file:
json.dump(json_file, file)
return jsonify({
"Link": file_link
})
except Exception as err:
print(str(err))
return jsonify({
"error": "Host may be down! (check logs for more info)"
})
# POST | Add host
@app.route('/add-host/<name>', methods=['POST'])
def addHost(name):
try:
data = request.json
json_file["hosts"][name] = data.get('get_link_from_json')
with open('nanabox.json', 'w') as file:
json.dump(json_file, file)
return jsonify({
"success": True
})
except Exception as err:
print(str(err))
return jsonify({
"error": "Failed to add host!",
"success": False
})
# GET | Upload history
@app.route('/history', methods=['GET'])
def send_history():
try:
with open('nanabox.json', 'r') as file:
data = json.load(file)
return jsonify(data["history"])
except (FileNotFoundError, json.JSONDecodeError):
return jsonify(["error"]), 404
# POST | Clear file upload history
@app.route('/clear', methods=['DELETE'])
def clear_history():
with open('nanabox.json', 'r+') as file:
data = json.load(file)
data["history"] = {}
file.seek(0)
json.dump(data, file)
file.truncate()
return jsonify({"success": True})
# GET | Array of all hosts
@app.route('/hosts', methods=['GET'])
def send_hosts():
return jsonify(list(hosts.keys()))
if __name__ == '__main__':
if (IN_APP_LOGS):
app.logger.addHandler(logging.StreamHandler(sys.stderr))
app.logger.setLevel(logging.INFO)
with OutputCapturer() as capturer:
FlaskUI(app=app, server="flask", width=400, height=500).run()
else:
# app.run(debug=True) # Uncomment this line and comment the line below when developing (after ensuring "IN_APP_LOGS" is set to False)
FlaskUI(app=app, server="flask", width=400, height=500).run()