-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.py
executable file
·592 lines (504 loc) · 19.4 KB
/
app.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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
#!/usr/bin/env python3
import os
import platform
import shutil
import json
import string
import secrets
import time
from slugify import slugify
import xmpp
import phonenumbers
import random
import flask
import werkzeug.security
import flask_login
DEFAULT_STL_PATH = 'static/stl_src/default-amogus-ev-7393.stl'
DEFAULT_STL_URL = '/stl_src/default-amogus-ev-7393.stl'
os.makedirs('data/users', exist_ok=True)
os.makedirs('data/generated', exist_ok=True)
def write_config(config):
with open('data/config.json', 'w') as f:
json.dump(config, f, indent=2)
try:
with open('data/config.json', 'r') as f:
config = json.load(f)
except:
config = {}
write_config(config)
if 'color_of_the_day' not in config:
config['color_of_the_day'] = '#ff00ff'
write_config(config)
if 'queue_limit' not in config:
config['queue_limit'] = 12
write_config(config)
app = flask.Flask(__name__, static_url_path='')
#app = Flask(__name__)
if 'app.secret_key' in config:
app.secret_key = config['app.secret_key']
else:
print('warning: app.secret_key not provided in config.json, falling back to hardcoded value')
app.secret_key = 'Rfewi89h13uhfevrh9#$8302ieufn'
login_manager = flask_login.LoginManager()
login_manager.init_app(app)
#may throw an exception
def standardize_phone_number(number):
# convert phone number to +12345678900 format
return phonenumbers.format_number(phonenumbers.parse(number, 'US'), phonenumbers.PhoneNumberFormat.E164)
#may throw a variety of exceptions (phone # format, failed to send sms, etc.)
def send_sms(number, message):
number = standardize_phone_number(number)
jabberid = config['xmpp_user'] #"[email protected]"
password = config['xmpp_pass']
receiver = f'{number}@cheogram.com' #"[email protected]"
jid = xmpp.protocol.JID(jabberid)
connection = xmpp.Client(server=jid.getDomain()) #, debug=debug)
connection.connect()
connection.auth(user=jid.getNode(), password=password, resource=jid.getResource())
connection.send(xmpp.protocol.Message(to=receiver, body=message))
def list_users():
return sorted(os.listdir('data/users'))
def get_user_data(username):
with open(f'data/users/{username}/data.json') as f:
return json.load(f)
def set_user_data(username, user_data):
with open(f'data/users/{username}/data.json', 'w') as f:
json.dump(user_data, f)
def create_user(username, password):
os.mkdir(f'data/users/{username}')
os.mkdir(f'data/users/{username}/stl_files')
shutil.copyfile('amogus-custom.scad', f'data/users/{username}/amogus-custom.scad')
with open(f'data/users/{username}/data.json', 'w') as f:
json.dump({'password': password}, f)
def random_password(length):
return ''.join(secrets.choice(string.ascii_letters + string.digits) for i in range(length))
class User(flask_login.UserMixin):
pass
def is_valid_username(username):
return username in list_users() or username == 'admin'
@login_manager.user_loader
def user_loader(username):
if not is_valid_username(username):
return
user = User()
user.id = username
return user
@login_manager.request_loader
def request_loader(request):
username = request.form.get('username')
if not is_valid_username(username):
return
user = User()
user.id = username
return user
def scad_escape(s):
return s.replace('\\', '\\\\').replace('"', '\\"')
@app.route('/gen_stl')
@flask_login.login_required
def gen_stl():
top_text = flask.request.args.get('top_text', '')
bottom_text = flask.request.args.get('bottom_text', '')
shoes = flask.request.args.get('shoes', '')
if shoes != 'true':
shoes = 'false'
username = flask_login.current_user.id
user_data = get_user_data(username)
user_data['generated_stl_options'] = {'top_text': top_text, 'bottom_text': bottom_text, 'shoes': shoes}
# print(top_text, bottom_text)
shoes_slug = ''
if shoes == 'true':
shoes_slug = 'shoes'
slug = slugify(f'amogus {top_text} {bottom_text} {shoes_slug}')
stl_file = get_stl_path(username, slug)
# print(stl_file)
with open(f'data/users/{username}/parameters.scad', 'w') as f:
f.write(f'dir = "../../.."; top_text = "{scad_escape(top_text)}"; bottom_text = "{scad_escape(bottom_text)}"; shoes = {shoes};')
if platform.system() == "Darwin":
os.system(f'/Applications/OpenSCAD.app/Contents/MacOS/OpenSCAD data/users/{username}/amogus-custom.scad -o {stl_file}')
else:
os.system(f'openscad data/users/{username}/amogus-custom.scad -o {stl_file}')
# return send_file('{stl_file}')
user_data['generated_stl'] = stl_file
set_user_data(username, user_data)
return get_stl_url_from_path(stl_file)
@app.route('/gen_stl2')
def gen_stl2():
top_text = flask.request.args.get('top_text', '')
bottom_text = flask.request.args.get('bottom_text', '')
shoes = flask.request.args.get('shoes', '')
if shoes != 'true':
shoes = 'false'
shoes_slug = ''
if shoes == 'true':
shoes_slug = 'shoes'
slug = slugify(f'amogus {top_text} {bottom_text} {shoes_slug}')
stl_id = ''.join(random.choice('0123456789abcdef') for _ in range(10)) #10 digit hex
stl_dir = f'data/generated/{stl_id}'
stl_file = f'{stl_dir}/{slug}.stl'
os.makedirs(stl_dir, exist_ok=True)
# stl_url = stl_file[len('data'):]
stl_url = f'/generated/{stl_id}/{slug}.stl'
shutil.copyfile('amogus-custom.scad', f'{stl_dir}/amogus-custom.scad')
with open(f'{stl_dir}/parameters.scad', 'w') as f:
f.write(f'dir = "../../.."; top_text = "{scad_escape(top_text)}"; bottom_text = "{scad_escape(bottom_text)}"; shoes = {shoes};')
if platform.system() == "Darwin":
os.system(f'/Applications/OpenSCAD.app/Contents/MacOS/OpenSCAD {stl_dir}/amogus-custom.scad -o {stl_file}')
else:
os.system(f'openscad {stl_dir}/amogus-custom.scad -o {stl_file}')
# return send_file('{stl_file}')
return stl_url
@app.route('/generated/<stl_id>/<stl_name>')
def generated(stl_id, stl_name):
stl_id = stl_id.replace('/', '')
stl_name = stl_name.replace('/', '')
return flask.send_file(f'data/generated/{stl_id}/{stl_name}')
@app.route('/submit')
@flask_login.login_required
def submit():
username = flask_login.current_user.id
user_data = get_user_data(username)
if 'submitted_stl' in user_data:
return 'already submitted'
if 'expired' in user_data and user_data['expired']:
return 'expired'
if calculate_queue_length() >= config['queue_limit']:
user_data['submit_but_queue_full'] = True
set_user_data(username, user_data)
return 'queue full'
user_data['submit_but_queue_full'] = False
# config['queue_length'] += 1
write_config(config)
user_data['submitted_stl'] = user_data.get('generated_stl', DEFAULT_STL_PATH)
if 'generated_stl_options' in user_data:
user_data['submitted_stl_options'] = user_data['generated_stl_options']
user_data['submitted_time'] = int(time.time() * 1000)
set_user_data(username, user_data)
return 'ok'
@app.route('/admin/undo_submit')
@flask_login.login_required
def admin_undo_submit():
if flask_login.current_user.id != 'admin':
return unauthorized_handler()
username = flask.request.args.get('username')
user_data = get_user_data(username)
if 'submitted_stl' in user_data:
del user_data['submitted_stl']
if 'submit_but_queue_full' in user_data:
del user_data['submit_but_queue_full']
if 'submitted_stl_options' in user_data:
del user_data['submitted_stl_options']
if 'submitted_stl_options' in user_data:
del user_data['submitted_time']
set_user_data(username, user_data)
return 'ok'
def get_stl_path(username, filename):
username = username.replace('/', '').replace('.', '')
filename = filename.replace('/', '').replace('.', '')
return f'data/users/{username}/stl_files/{filename}.stl'
def get_stl_url_from_path(filepath):
if filepath == DEFAULT_STL_PATH:
return DEFAULT_STL_URL
# f'data/users/{username}/stl_files/{filename}.stl'
username = filepath.split('/')[2]
filename = filepath.split('/')[4].split('.')[0]
return f'/get_stl/{username}/{filename}'
@app.route('/get_stl/<username>/<filename>')
@flask_login.login_required
def get_stl(username, filename):
if flask_login.current_user.id == username or flask_login.current_user.id == 'admin':
filepath = get_stl_path(username, filename)
return flask.send_file(filepath)
else:
return unauthorized_handler()
@app.route('/login', methods=['GET', 'POST'])
def login():
username = flask.request.form.get('username', flask.request.args.get('username'))
password = flask.request.form.get('password', flask.request.args.get('password'))
user = User()
user.id = username
if username == 'admin' and werkzeug.security.check_password_hash(config['admin_password_hash'], password):
flask_login.login_user(user)
return flask.redirect(flask.url_for('admin'))
if username in list_users():
user_data = get_user_data(username)
if user_data.get('password') == password:
flask_login.login_user(user)
user_data['logged_in'] = True
set_user_data(username, user_data)
return flask.redirect(flask.url_for('user'))
return flask.render_template('login.html')
@app.route('/user/info')
@flask_login.login_required
def user_info():
username = flask_login.current_user.id
user_data = get_user_data(username)
if 'submitted_stl' in user_data:
status = 'submitted'
stl_url = get_stl_url_from_path(user_data['submitted_stl'])
stl_options = user_data.get('submitted_stl_options', {})
elif 'generated_stl' in user_data:
status = 'generated'
stl_url = get_stl_url_from_path(user_data['generated_stl'])
stl_options = user_data.get('generated_stl_options', {})
else:
status = 'default'
stl_url = DEFAULT_STL_URL
stl_options = {}
return json.dumps({
'team': user_data.get('team', ''),
'phone': user_data.get('phone', ''),
'status': status,
'stl_url': stl_url,
'stl_options': stl_options,
'printed': user_data.get('printed', False),
'taken': user_data.get('taken', False),
'expired': user_data.get('expired', False)
})
@app.route('/team')
@flask_login.login_required
def team():
username = flask_login.current_user.id
team = flask.request.args.get('team')
phone = flask.request.args.get('phone', '')
user_data = get_user_data(username)
user_data['team'] = team
phone_return = ''
if phone == '':
if 'phone' in user_data:
del user_data['phone']
else:
try:
user_data['phone'] = standardize_phone_number(phone)
except Exception as e:
print(f'error reading phone number: {e}')
phone_return = 'invalid'
if 'phone' in user_data:
del user_data['phone']
set_user_data(username, user_data)
return user_data.get('phone', phone_return)
@app.route('/logout')
def logout():
flask_login.logout_user()
return flask.redirect(flask.url_for('login'))
# return 'Logged out'
@login_manager.unauthorized_handler
def unauthorized_handler():
return '<h1>Unauthorized</h1><a href="/login">login</a><br/><br/><img style="width: min(90vw, 500px)" alt="card swipe task among us" src="/img/among-us-card-swipe.gif" />', 401
@app.route('/admin')
@flask_login.login_required
def admin():
if flask_login.current_user.id != 'admin':
return unauthorized_handler()
return flask.render_template('admin.html')
@app.route('/admin/user_creds')
@flask_login.login_required
def admin_user_creds():
if flask_login.current_user.id != 'admin':
return unauthorized_handler()
user_creds = {}
for username in list_users():
user_creds[username] = get_user_data(username)
if 'submitted_stl' in user_creds[username]:
user_creds[username]['submitted_stl_url'] = get_stl_url_from_path(user_creds[username]['submitted_stl'])
return user_creds
@app.route('/admin/new_users')
@flask_login.login_required
def admin_new_users():
if flask_login.current_user.id != 'admin':
return unauthorized_handler()
num_new_users = int(flask.request.args.get('num'))
new_usernames = []
for i in range(num_new_users):
config['user_num'] = 1 + config.get('user_num', 0)
write_config(config)
username = str(config['user_num']).zfill(8)
create_user(username, random_password(16))
new_usernames.append(username)
return json.dumps(new_usernames)
@app.route('/admin/expire_user')
@flask_login.login_required
def admin_expire_user():
if flask_login.current_user.id != 'admin':
return unauthorized_handler()
username = flask.request.args.get('username').replace('.', '')
user_data = get_user_data(username)
user_data['expired'] = True
set_user_data(username, user_data)
return 'ok'
@app.route('/admin/undo_expire_user')
@flask_login.login_required
def admin_undo_expire_user():
if flask_login.current_user.id != 'admin':
return unauthorized_handler()
username = flask.request.args.get('username').replace('.', '')
user_data = get_user_data(username)
if 'expired' in user_data:
del user_data['expired']
set_user_data(username, user_data)
return 'ok'
@app.route('/admin/delete_user')
@flask_login.login_required
def admin_delete_user():
if flask_login.current_user.id != 'admin':
return unauthorized_handler()
username = flask.request.args.get('username').replace('.', '')
user_data = get_user_data(username)
# if 'submitted_stl' in user_data:
# if not ('printed' in user_data and user_data['printed']):
# config['queue_length'] -= 1
write_config(config)
shutil.rmtree(f'data/users/{username}', ignore_errors=True)
return 'ok'
@app.route('/admin/print_started')
@flask_login.login_required
def admin_print_started():
if flask_login.current_user.id != 'admin':
return unauthorized_handler()
username = flask.request.args.get('username')
user_data = get_user_data(username)
user_data['started_printing'] = True
set_user_data(username, user_data)
return 'ok'
@app.route('/admin/undo_print_started')
@flask_login.login_required
def admin_undo_print_started():
if flask_login.current_user.id != 'admin':
return unauthorized_handler()
username = flask.request.args.get('username')
user_data = get_user_data(username)
if 'started_printing' in user_data:
del user_data['started_printing']
set_user_data(username, user_data)
return 'ok'
@app.route('/admin/print_done')
@flask_login.login_required
def admin_print_done():
if flask_login.current_user.id != 'admin':
return unauthorized_handler()
username = flask.request.args.get('username')
user_data = get_user_data(username)
if 'printed' in user_data and user_data['printed']:
return 'already set as done'
# config['queue_length'] -= 1
write_config(config)
user_data['printed'] = True
if 'phone' in user_data:
try:
send_sms(user_data['phone'], "Your custom among us figure is done 3D printing! Come pick it up from FTC 7393's pit area.")
except Exception as e:
print(f'error sending SMS: {e}')
set_user_data(username, user_data)
return 'ok'
@app.route('/admin/undo_print_done')
@flask_login.login_required
def admin_undo_print_done():
if flask_login.current_user.id != 'admin':
return unauthorized_handler()
username = flask.request.args.get('username')
user_data = get_user_data(username)
if 'printed' in user_data:
del user_data['printed']
set_user_data(username, user_data)
return 'ok'
@app.route('/admin/taken')
@flask_login.login_required
def admin_taken():
if flask_login.current_user.id != 'admin':
return unauthorized_handler()
username = flask.request.args.get('username')
user_data = get_user_data(username)
user_data['taken'] = True
set_user_data(username, user_data)
return 'ok'
@app.route('/admin/undo_taken')
@flask_login.login_required
def admin_undo_taken():
if flask_login.current_user.id != 'admin':
return unauthorized_handler()
username = flask.request.args.get('username')
user_data = get_user_data(username)
if 'taken' in user_data:
del user_data['taken']
set_user_data(username, user_data)
return 'ok'
@app.route('/color_of_the_day')
def color_of_the_day():
return config['color_of_the_day']
@app.route('/admin/set_color_of_the_day')
@flask_login.login_required
def admin_set_color_of_the_day():
if flask_login.current_user.id != 'admin':
return unauthorized_handler()
config['color_of_the_day'] = flask.request.args['color_of_the_day']
write_config(config)
return 'ok'
@app.route('/queue_limit')
@flask_login.login_required
def queue_limit():
return str(config['queue_limit'])
@app.route('/queue_length')
@flask_login.login_required
def queue_length():
return str(calculate_queue_length())
@app.route('/queue_status')
@flask_login.login_required
def queue_status():
queue_length = calculate_queue_length()
queue_limit = config['queue_limit']
return f'{queue_length}/{queue_limit}'
@app.route('/queue_spots_left')
@flask_login.login_required
def queue_spots_left():
queue_length = calculate_queue_length()
queue_limit = config['queue_limit']
spots_left = queue_limit - queue_length
return str(spots_left)
def calculate_queue_length():
queue_length = 0
for username in list_users():
user_data = get_user_data(username)
if 'submitted_stl' in user_data and not 'printed' in user_data:
queue_length += 1
return queue_length
@app.route('/admin/set_queue_limit')
@flask_login.login_required
def admin_set_queue_limit():
if flask_login.current_user.id != 'admin':
return unauthorized_handler()
try:
config['queue_limit'] = int(flask.request.args['queue_limit'])
write_config(config)
except Exception as e:
print(f'queue_limit error: {e}')
return 'error'
return str(config['queue_limit'])
#TODO max char length on server and client
#TODO don't accept requests when busy generating an STL already
#TODO cache the stl files based on exact top/bottom text and avoid rebuilding
@app.route('/user')
@flask_login.login_required
def user():
if flask_login.current_user.id == 'admin': #don't allow the admin to access the user page
return unauthorized_handler()
return flask.send_from_directory('frontend/dist', 'index.html')
# return flask.render_template('user.html')
@app.route('/assets/<path:path>')
# @flask_login.login_required
def send_svelte(path):
# if flask_login.current_user.id == 'admin': #don't allow the admin to access the user page
# return unauthorized_handler()
if os.path.exists(f'frontend/dist/assets/{path}'):
return flask.send_from_directory('frontend/dist/assets', path)
else:
return flask.send_from_directory('frontend-index/dist/assets', path)
@app.route('/')
def index():
return flask.send_from_directory('frontend-index/dist', 'index.html')
# return flask.render_template('index.html')
# return flask.redirect(flask.url_for('login'))
@app.route('/base_url')
def get_base_url():
return config['base_url']
if __name__ == "__main__":
# app.run(debug=True)
app.run(host='0.0.0.0', debug=True)