Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
508 lines (438 loc) · 19 KB
/
Copy pathapp.py
File metadata and controls
508 lines (438 loc) · 19 KB
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
from flask import (
Flask, render_template, request, redirect, url_for,
make_response, send_from_directory, render_template_string,
flash, get_flashed_messages, Response, send_file,
)
import io
import os
import re
import uuid
import zipfile
import calls2
import data_io as dio
app = Flask(__name__)
FILES_FOLDER = os.path.dirname(__file__)
app.secret_key = os.environ.get('FLASK_SECRET_KEY') or os.urandom(24)
# -------------------- File Helpers --------------------
from functools import wraps
from flask import session, redirect, url_for
@app.before_request
def ensure_user_id():
user_id = request.cookies.get("user_id")
if not user_id:
new_id = str(uuid.uuid4())
resp = make_response(redirect(request.url))
resp.set_cookie("user_id", new_id)
return resp
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if not session.get('logged_in'):
return redirect(url_for('login'))
return f(*args, **kwargs)
return decorated_function
DATA_DIR = os.path.join(FILES_FOLDER, "data")
os.makedirs(DATA_DIR, exist_ok=True)
def _relative_data_path(prefix, user_id):
return f"data/{prefix}_{user_id}.txt"
def _data_file(prefix):
user_id = request.cookies.get("user_id")
return os.path.join(FILES_FOLDER, _relative_data_path(prefix, user_id))
def get_student_file():
return _data_file("students")
def get_teacher_file():
return _data_file("teachers")
def get_output_file():
return _data_file("output")
def get_outputsch_file():
return _data_file("outputsch")
def get_teacher_class_lists_file():
return _data_file("teacher_class_lists")
def read_students():
students = []
STUDENTS_FILE = get_student_file()
if os.path.exists(STUDENTS_FILE):
with open(STUDENTS_FILE) as f:
for line in f:
parts = line.strip().split(',')
if parts and parts[0]:
students.append(parts)
return students
def write_students(students, backup=True):
path = get_student_file()
if backup:
dio.backup_file(path)
content = ''.join(','.join(s) + '\n' for s in students)
dio.atomic_write(path, content)
def read_teachers():
TEACHERS_FILE = get_teacher_file()
teachers = []
if os.path.exists(TEACHERS_FILE):
with open(TEACHERS_FILE) as f:
for line in f:
line = line.strip()
if not line:
continue
# Split once on the first comma to separate teacher id
tid, rest = line.split(',', 1)
pairs = []
# Now split rest by '),(' but first strip starting and ending parentheses
# e.g. (math1,20),(math2,21) => math1,20 math2,21
rest = rest.strip()
if rest.startswith('(') and rest.endswith(')'):
rest = rest[1:-1]
# split pairs safely:
raw_pairs = rest.split('),(')
for p in raw_pairs:
# now p should be like "math1,20"
if ',' not in p:
continue
subject, size = p.split(',', 1)
pairs.append([subject.strip(), size.strip()])
teachers.append([tid.strip(), pairs])
return teachers
def write_teachers(teachers, backup=True):
path = get_teacher_file()
if backup:
dio.backup_file(path)
lines = []
for t in teachers:
tid = t[0]
pairs = [f"({sub},{size})" for sub, size in t[1]]
lines.append(','.join([tid] + pairs) + '\n')
dio.atomic_write(path, ''.join(lines))
# -------------------- Students Page --------------------
PASSWORD = "" # change to your password
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
if request.form.get('password') == PASSWORD:
session['logged_in'] = True
return redirect(url_for('index'))
else:
return "Wrong password", 401
return '''
<form method="post">
<input type="password" name="password" placeholder="Password" required>
<input type="submit" value="Login">
</form>
'''
@app.route('/download')
def download():
user_id = request.cookies.get("user_id")
files = [
_relative_data_path("output", user_id),
_relative_data_path("outputsch", user_id),
_relative_data_path("teacher_class_lists", user_id),
_relative_data_path("students", user_id),
_relative_data_path("teachers", user_id),
]
return render_template_string('''
<h1>Downloads</h1>
<h2>Export (recommended)</h2>
<ul>
<li><a href="{{ url_for('export_all') }}">Everything (.zip)</a></li>
<li><a href="{{ url_for('export_students_csv') }}">Students (.csv)</a></li>
<li><a href="{{ url_for('export_teachers_csv') }}">Teachers (.csv)</a></li>
<li><a href="{{ url_for('export_schedule_csv') }}">Schedule (.csv, one row per student)</a></li>
</ul>
<h2>Raw internal files</h2>
<ul>
{% for file in files %}
<li><a href="{{ url_for('download_file', filename=file) }}">{{ file }}</a></li>
{% endfor %}
</ul>
<a href="{{ url_for('index') }}">Back to Main Page</a>
''', files=files)
@app.route('/download/<path:filename>')
def download_file(filename):
user_id = request.cookies.get("user_id")
allowed_files = {
_relative_data_path("output", user_id),
_relative_data_path("outputsch", user_id),
_relative_data_path("teacher_class_lists", user_id),
_relative_data_path("students", user_id),
_relative_data_path("teachers", user_id),
}
if filename in allowed_files:
return send_from_directory(FILES_FOLDER, filename, as_attachment=True)
return "File not allowed", 403
@app.route('/students', methods=['GET', 'POST'])
def students():
students = read_students()
if request.method == 'POST':
action = request.form.get('action')
if action == 'save':
student_ids = request.form.getlist('student_id')
num_subjects = len(students[0]) - 1 if students else 7
new_students = []
emptied = []
for sid in student_ids:
subjects = []
for i in range(num_subjects):
val = request.form.get(f'student_{sid}_subject_{i}', '')
subjects.append(val.strip())
subjects = [s for s in subjects if s]
if subjects:
new_students.append([sid] + subjects)
else:
emptied.append(sid)
write_students(new_students)
flash(f"Saved {len(new_students)} student(s).", "success")
if emptied:
flash(f"Removed {', '.join(emptied)} — all their subjects were cleared.", "error")
elif action == 'delete':
del_id = request.form.get('delete_id')
remaining = [s for s in students if s[0] != del_id]
if len(remaining) == len(students):
flash(f"Student '{del_id}' not found.", "error")
else:
write_students(remaining)
flash(f"Deleted student '{del_id}'.", "success")
elif action == 'add':
new_id = (request.form.get('new_id') or '').strip()
new_subjects = [v.strip() for v in
(request.form.get(f'new_subject_{i}', '') for i in range(7)) if v.strip()]
if not new_id:
flash("Student ID is required.", "error")
elif any(s[0] == new_id for s in students):
flash(f"Student ID '{new_id}' already exists.", "error")
elif not new_subjects:
flash("At least one subject is required.", "error")
else:
students.append([new_id] + new_subjects)
students.sort(key=lambda x: int(x[0]) if x[0].isdigit() else x[0])
write_students(students)
flash(f"Added student '{new_id}'.", "success")
return redirect(url_for('students'))
return render_template('students.html', students=students)
# -------------------- Teachers Page --------------------
@app.route('/teachers', methods=['GET', 'POST'])
def teachers():
teachers = read_teachers()
if request.method == 'POST':
action = request.form.get('action')
if action == 'save':
teacher_ids = request.form.getlist('teacher_id')
new_teachers = []
emptied = []
for tid in teacher_ids:
pairs = []
i = 0
while True:
subject = request.form.get(f'teacher_{tid}_subject_{i}')
size = request.form.get(f'teacher_{tid}_size_{i}')
if subject is None or size is None:
break
subject = subject.strip()
size = size.strip()
if subject and size and size.isdigit() and int(size) > 0:
pairs.append([subject, size])
i += 1
if pairs:
new_teachers.append([tid, pairs])
else:
emptied.append(tid)
write_teachers(new_teachers)
flash(f"Saved {len(new_teachers)} teacher(s).", "success")
if emptied:
flash(f"Removed {', '.join(emptied)} — all their classes were cleared or invalid.", "error")
elif action == 'delete':
del_id = request.form.get('delete_id')
remaining = [t for t in teachers if t[0] != del_id]
if len(remaining) == len(teachers):
flash(f"Teacher '{del_id}' not found.", "error")
else:
write_teachers(remaining)
flash(f"Deleted teacher '{del_id}'.", "success")
elif action == 'add':
new_id = (request.form.get('new_id') or '').strip()
pairs = []
invalid_sizes = []
for i in range(10):
subject = request.form.get(f'new_subject_{i}', '').strip()
size = request.form.get(f'new_size_{i}', '').strip()
if subject and size:
if size.isdigit() and int(size) > 0:
pairs.append([subject, size])
else:
invalid_sizes.append(subject)
if not new_id:
flash("Teacher ID is required.", "error")
elif any(t[0] == new_id for t in teachers):
flash(f"Teacher ID '{new_id}' already exists.", "error")
elif not pairs:
flash("At least one subject with a valid class size is required.", "error")
else:
teachers.append([new_id, pairs])
teachers.sort(key=lambda x: int(x[0]) if x[0].isdigit() else x[0])
write_teachers(teachers)
flash(f"Added teacher '{new_id}'.", "success")
if invalid_sizes:
flash(f"Skipped subjects with invalid class size: {', '.join(invalid_sizes)}.", "error")
return redirect(url_for('teachers'))
return render_template('teachers.html', teachers=teachers)
# -------------------- Run Page --------------------
# @app.route('/run')
#make a button that when pressed will do call2.main(loops)
def _file_has_content(path):
return os.path.exists(path) and os.path.getsize(path) > 0
@app.route('/run', methods=['GET', 'POST'])
def run():
if request.method == 'POST':
if not _file_has_content(get_teacher_file()) or not _file_has_content(get_student_file()):
return "Please add at least one teacher and one student before running.", 400
loops = int(request.form.get('loops', 1)) # get loops from form, default 1
result = calls2.start(loops, get_teacher_file(), get_student_file(),get_output_file(),get_outputsch_file(),get_teacher_class_lists_file()) # run your function
# You can render result or just confirm success
return render_template_string('''
<h2>Function run with loops={{loops}}</h2>
<p>Result: {{result}}</p>
<a href="{{ url_for('run') }}">Go back</a>
''', loops=loops, result=result)
# GET method: show the button and input for loops
return render_template_string('''
<form method="POST">
<label for="loops">Number of loops:</label>
<input type="number" id="loops" name="loops" value="1" min="1" max="100000" required oninput="updateETA()">
<span id="eta">ETA: 0.5 seconds</span>
<br><br>
<button type="submit">Run</button>
<br>
<a href="{{ url_for('index') }}">Back to Main Page</a>
</form>
<script>
function updateETA() {
const loops = document.getElementById('loops').value;
const eta = loops * 0.5; // seconds
document.getElementById('eta').innerText = `ETA: ${eta} seconds. Note: The Webpage will load for about the ETA feel free to switch tabs just leave this tab open`;
}
updateETA(); // set initial value
</script>
''')
MAX_IMPORT_ERRORS_SHOWN = 25
@app.route('/import', methods=['GET', 'POST'])
def import_page():
if request.method == 'POST':
file_type = request.form.get('file_type') # 'students' or 'teachers'
if file_type not in ('students', 'teachers'):
flash("Choose whether you're importing students or teachers.", "error")
return redirect(url_for('import_page'))
upload = request.files.get('file')
if upload and upload.filename:
text_content = upload.read().decode('utf-8', errors='replace')
else:
text_content = request.form.get('file_content') or ''
if not text_content.strip():
flash("No file selected and no text pasted — nothing to import.", "error")
return redirect(url_for('import_page'))
if file_type == 'students':
parsed, errors = dio.parse_students_csv(text_content)
else:
parsed, errors = dio.parse_teachers_csv(text_content)
if errors:
flash(f"Import rejected: {len(errors)} problem(s) found. Nothing was changed.", "error")
for e in errors[:MAX_IMPORT_ERRORS_SHOWN]:
flash(e, "error")
if len(errors) > MAX_IMPORT_ERRORS_SHOWN:
flash(f"...and {len(errors) - MAX_IMPORT_ERRORS_SHOWN} more.", "error")
return redirect(url_for('import_page'))
if file_type == 'students':
write_students(parsed)
else:
write_teachers(parsed)
flash(f"Imported {len(parsed)} {file_type} successfully. "
f"A backup of the previous data was saved and can be restored below.", "success")
return redirect(url_for('import_page'))
return render_template(
'import.html',
student_backups=dio.list_backups(get_student_file()),
teacher_backups=dio.list_backups(get_teacher_file()),
)
@app.route('/import/restore', methods=['POST'])
def import_restore():
kind = request.form.get('kind')
backup_path = request.form.get('backup_path') or ''
path = {'students': get_student_file, 'teachers': get_teacher_file}.get(kind)
if path is None:
flash("Invalid restore request.", "error")
return redirect(url_for('import_page'))
path = path()
# Defense in depth: the backup must belong to this exact user's file,
# not merely live in the shared backups/ directory.
if not os.path.basename(backup_path).startswith(os.path.basename(path) + "."):
flash("Invalid backup selection.", "error")
return redirect(url_for('import_page'))
try:
dio.restore_backup(path, backup_path)
flash(f"Restored {kind} from backup.", "success")
except (ValueError, OSError) as e:
flash(f"Could not restore backup: {e}", "error")
return redirect(url_for('import_page'))
# -------------------- Export --------------------
def _parse_output_rows(path):
rows = []
if os.path.exists(path):
with open(path) as f:
for line in f:
parts = line.strip().split(',')
if len(parts) == 4:
rows.append(tuple(parts))
return rows
def _csv_response(text, filename):
return Response(text, mimetype='text/csv',
headers={'Content-Disposition': f'attachment; filename={filename}'})
@app.route('/export/students.csv')
def export_students_csv():
return _csv_response(dio.students_to_csv(read_students()), 'students.csv')
@app.route('/export/teachers.csv')
def export_teachers_csv():
return _csv_response(dio.teachers_to_csv(read_teachers()), 'teachers.csv')
@app.route('/export/schedule.csv')
def export_schedule_csv():
rows = _parse_output_rows(get_output_file())
if not rows:
flash("No schedule yet — run the scheduler first.", "error")
return redirect(url_for('download'))
return _csv_response(dio.schedule_to_csv(rows), 'schedule.csv')
@app.route('/export/all')
def export_all():
buf = io.BytesIO()
with zipfile.ZipFile(buf, 'w', zipfile.ZIP_DEFLATED) as zf:
zf.writestr('students.csv', dio.students_to_csv(read_students()))
zf.writestr('teachers.csv', dio.teachers_to_csv(read_teachers()))
rows = _parse_output_rows(get_output_file())
if rows:
zf.writestr('schedule.csv', dio.schedule_to_csv(rows))
for arcname, getter in (
('roster.txt', get_teacher_class_lists_file),
('raw_output.txt', get_output_file),
('raw_teacher_schedule.txt', get_outputsch_file),
):
path = getter()
if os.path.exists(path):
zf.write(path, arcname)
buf.seek(0)
return send_file(buf, mimetype='application/zip', as_attachment=True,
download_name='autoclassscheduler_export.zip')
# -------------------- Home --------------------
@app.route('/')
def index():
return render_template('index.html')
class PrefixMiddleware:
"""Lets Flask generate correct URLs when reverse-proxied under a path prefix
(Caddy's handle_path strips the prefix before forwarding to this app)."""
def __init__(self, wsgi_app, prefix):
self.wsgi_app = wsgi_app
self.prefix = prefix
def __call__(self, environ, start_response):
environ['SCRIPT_NAME'] = self.prefix
return self.wsgi_app(environ, start_response)
if __name__ == '__main__':
if os.environ.get('URL_PREFIX'):
app.wsgi_app = PrefixMiddleware(app.wsgi_app, os.environ['URL_PREFIX'])
port = int(os.environ.get('PORT', 1124))
# Default to loopback-only, since this deployment sits behind a reverse
# proxy; set HOST=0.0.0.0 to expose it directly (e.g. standalone self-hosting).
host = os.environ.get('HOST', '127.0.0.1')
app.run(debug=False, host=host, port=port, threaded=True)