-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
1925 lines (1712 loc) · 66.7 KB
/
Copy pathserver.py
File metadata and controls
1925 lines (1712 loc) · 66.7 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
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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import argparse
import base64
import hashlib
import json
import os
import re
import secrets
import shutil
import threading
from datetime import datetime, timedelta
from http import HTTPStatus
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import urlparse, unquote
APP_DIR = Path(__file__).resolve().parent
INDEX_FILE = APP_DIR / "index.html"
SIGNIN_FILE = APP_DIR / "signin.html"
LANDING_FILE = APP_DIR / "landing.html"
ABOUT_FILE = APP_DIR / "about.html"
USER_PAGE_FILE = APP_DIR / "user.html"
DATA_FILE = APP_DIR / "orbit-data.json"
USER_FILE = APP_DIR / "orbit-user.json"
CHAT_DIR = APP_DIR / "orbit-chats"
ASSET_DIR = APP_DIR / "assets"
CHAT_KEY_FILE = APP_DIR / "orbit-chat.key"
FEEDBACK_DIR = APP_DIR / "feedback"
FEEDBACK_BLOCKLIST_FILE = FEEDBACK_DIR / "blocked.txt"
SESSION_COOKIE = "orbit_session"
SESSIONS = {}
DAYS = ["Mon", "Tue", "Wed", "Thu", "Fri"]
MAX_BODY_BYTES = 5 * 1024 * 1024
DEMO_PASSWORD = "orbitdemo"
DEMO_USERNAMES = ["jordan", "avery", "riley"]
CHAT_RETENTION_DAYS = 30
MAX_AVATAR_CHARS = 1_500_000
MAX_SCHOOL_CHARS = 120
MAX_GRADE_CHARS = 32
CHAT_KEY_CACHE = None
FILE_IO_LOCK = threading.RLock()
def is_demo_allowed():
value = os.environ.get("ORBIT_ALLOW_DEMO", "")
return value.lower() in ("1", "true", "yes", "on")
def normalize_username(value):
return str(value or "").strip()
def resolve_username(name, users=None):
name = normalize_username(name)
if not name:
return None
if users is None:
users = load_users().get("users", {})
if name in users:
return name
lowered = name.lower()
for username in users.keys():
if username.lower() == lowered:
return username
return None
def chat_encryption_key():
global CHAT_KEY_CACHE
if CHAT_KEY_CACHE:
return CHAT_KEY_CACHE
value = os.environ.get("ORBIT_CHAT_KEY", "").strip()
if value:
CHAT_KEY_CACHE = value
return CHAT_KEY_CACHE
try:
if CHAT_KEY_FILE.exists():
value = CHAT_KEY_FILE.read_text(encoding="utf-8").strip()
if value:
CHAT_KEY_CACHE = value
return CHAT_KEY_CACHE
except Exception:
pass
value = secrets.token_urlsafe(32)
CHAT_KEY_CACHE = value
try:
CHAT_KEY_FILE.write_text(value, encoding="utf-8")
try:
os.chmod(CHAT_KEY_FILE, 0o600)
except Exception:
pass
except Exception:
pass
return CHAT_KEY_CACHE
def ensure_chat_dir():
CHAT_DIR.mkdir(parents=True, exist_ok=True)
def ensure_feedback_dir():
FEEDBACK_DIR.mkdir(parents=True, exist_ok=True)
def load_feedback_blocklist():
if not FEEDBACK_BLOCKLIST_FILE.exists():
return set()
blocked = set()
try:
for line in FEEDBACK_BLOCKLIST_FILE.read_text(encoding="utf-8").splitlines():
cleaned = line.strip()
if not cleaned or cleaned.startswith("#"):
continue
blocked.add(cleaned.lower())
except Exception:
return set()
return blocked
def feedback_entry_path(username, created_at):
ensure_feedback_dir()
safe_user = safe_username(username) or "user"
stamp = created_at.strftime("%Y%m%dT%H%M%SZ")
token = secrets.token_hex(3)
return FEEDBACK_DIR / f"feedback-{stamp}-{safe_user}-{token}.json"
def safe_username(username):
return re.sub(r"[^A-Za-z0-9_.-]+", "_", username)
def chat_store_path(username):
ensure_chat_dir()
return CHAT_DIR / f"{safe_username(username)}.json"
def xor_bytes(data, key_bytes):
return bytes(byte ^ key_bytes[index % len(key_bytes)] for index, byte in enumerate(data))
def load_chat_store(username):
path = chat_store_path(username)
if not path.exists():
return {"threads": {}}, None
record = load_json(path)
if not isinstance(record, dict):
return {"threads": {}}, None
payload = record.get("payload")
if record.get("encrypted"):
key = chat_encryption_key()
if not key:
return {"threads": {}}, "locked"
try:
key_bytes = hashlib.sha256(key.encode("utf-8")).digest()
raw = base64.b64decode(payload or "")
decoded = xor_bytes(raw, key_bytes)
data = json.loads(decoded.decode("utf-8"))
except Exception:
return {"threads": {}}, None
else:
if isinstance(payload, str):
try:
data = json.loads(payload)
except Exception:
data = {}
elif isinstance(payload, dict):
data = payload
else:
data = record
if not isinstance(data, dict):
return {"threads": {}}, None
threads = data.get("threads")
if isinstance(threads, dict):
return {"threads": threads}, None
return {"threads": {}}, None
def save_chat_store(username, threads):
path = chat_store_path(username)
data = {"threads": threads}
raw = json.dumps(data).encode("utf-8")
key = chat_encryption_key()
if key:
key_bytes = hashlib.sha256(key.encode("utf-8")).digest()
encrypted = xor_bytes(raw, key_bytes)
record = {"encrypted": True, "payload": base64.b64encode(encrypted).decode("ascii")}
else:
record = {"encrypted": False, "payload": raw.decode("utf-8")}
write_json(path, record)
try:
os.chmod(path, 0o600)
except Exception:
pass
def parse_message_timestamp(value):
if not value:
return None
try:
cleaned = str(value).replace("Z", "")
return datetime.fromisoformat(cleaned)
except Exception:
return None
def prune_chat_threads(threads):
cutoff = datetime.utcnow() - timedelta(days=CHAT_RETENTION_DAYS)
changed = False
for class_id, thread in list(threads.items()):
if not isinstance(thread, list):
threads[class_id] = []
changed = True
continue
filtered = []
for message in thread:
if not isinstance(message, dict):
changed = True
continue
timestamp = parse_message_timestamp(message.get("created_at"))
if timestamp and timestamp < cutoff:
changed = True
continue
filtered.append(message)
if len(filtered) != len(thread):
changed = True
threads[class_id] = filtered
return changed
def dm_thread_id(user_a, user_b):
pair = sorted([user_a, user_b], key=lambda item: item.lower())
return f"dm:{pair[0]}:{pair[1]}"
def group_thread_id(group_id):
return f"group:{group_id}"
def guess_content_type(path):
suffix = path.suffix.lower()
if suffix == ".png":
return "image/png"
if suffix in (".jpg", ".jpeg"):
return "image/jpeg"
if suffix == ".svg":
return "image/svg+xml"
if suffix == ".webp":
return "image/webp"
return "application/octet-stream"
def default_study_data():
return {
"sets": [],
"cards": [],
"progress": {},
"activeSet": None,
}
def sanitize_schedule_profile(value):
normalized = str(value or "").strip().lower()
if normalized in ("daily", "ab", "block", "custom"):
return normalized
return "custom"
def default_data():
return {
"classes": [],
"schedule": {day: [] for day in DAYS},
"scheduleProfile": "custom",
"todos": [],
"study": default_study_data(),
}
def sanitize_todos(todos_in):
if not isinstance(todos_in, list):
return []
clean = []
seen_ids = set()
for entry in todos_in:
if not isinstance(entry, dict):
continue
class_id = str(entry.get("classId") or "").strip()
title = str(entry.get("title") or "").strip()
if not class_id or not title:
continue
todo_id = str(entry.get("id") or "").strip()
if not todo_id:
todo_id = f"todo-{secrets.token_hex(4)}"
if todo_id in seen_ids:
continue
seen_ids.add(todo_id)
due_date = str(entry.get("dueDate") or "").strip()
if due_date:
try:
datetime.strptime(due_date, "%Y-%m-%d")
except ValueError:
due_date = ""
clean.append(
{
"id": todo_id,
"classId": class_id,
"title": title,
"dueDate": due_date,
"notes": str(entry.get("notes") or "").strip(),
"completed": bool(entry.get("completed")),
}
)
return clean
def sanitize_study(study_in):
if not isinstance(study_in, dict):
return default_study_data()
sets_in = study_in.get("sets")
cards_in = study_in.get("cards")
progress_in = study_in.get("progress")
active_set_in = study_in.get("activeSet")
clean_sets = []
set_ids = set()
if isinstance(sets_in, list):
for entry in sets_in:
if not isinstance(entry, dict):
continue
set_id = str(entry.get("id") or "").strip()
title = str(entry.get("title") or "").strip()
if not set_id or not title or set_id in set_ids:
continue
set_ids.add(set_id)
created_at = str(entry.get("createdAt") or "").strip() or datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
visibility = "public" if str(entry.get("visibility") or "").strip().lower() == "public" else "private"
clean_sets.append(
{
"id": set_id,
"title": title,
"description": str(entry.get("description") or "").strip(),
"createdAt": created_at,
"visibility": visibility,
}
)
clean_cards = []
card_ids = set()
if isinstance(cards_in, list):
for entry in cards_in:
if not isinstance(entry, dict):
continue
card_id = str(entry.get("id") or "").strip()
set_id = str(entry.get("setId") or "").strip()
term = str(entry.get("term") or "").strip()
definition = str(entry.get("definition") or "").strip()
if not card_id or not set_id or set_id not in set_ids or not term or not definition:
continue
if card_id in card_ids:
continue
card_ids.add(card_id)
clean_cards.append(
{
"id": card_id,
"setId": set_id,
"term": term,
"definition": definition,
"starred": bool(entry.get("starred")),
}
)
clean_progress = {}
if isinstance(progress_in, dict):
for key, value in progress_in.items():
card_id = str(key or "").strip()
if card_id not in card_ids or not isinstance(value, dict):
continue
seen = value.get("seenCount", 0)
correct = value.get("correctCount", 0)
wrong = value.get("wrongCount", 0)
mastery = value.get("mastery", 0)
try:
seen = max(0, int(seen))
except Exception:
seen = 0
try:
correct = max(0, int(correct))
except Exception:
correct = 0
try:
wrong = max(0, int(wrong))
except Exception:
wrong = 0
try:
mastery = float(mastery)
except Exception:
mastery = 0
mastery = max(0.0, min(1.0, mastery))
clean_progress[card_id] = {
"cardId": card_id,
"seenCount": seen,
"correctCount": correct,
"wrongCount": wrong,
"mastery": mastery,
}
for card in clean_cards:
card_id = card["id"]
if card_id not in clean_progress:
clean_progress[card_id] = {
"cardId": card_id,
"seenCount": 0,
"correctCount": 0,
"wrongCount": 0,
"mastery": 0,
}
active_set = str(active_set_in or "").strip()
if active_set not in set_ids:
active_set = clean_sets[0]["id"] if clean_sets else None
return {
"sets": clean_sets,
"cards": clean_cards,
"progress": clean_progress,
"activeSet": active_set,
}
def demo_data_template(username):
base_classes = [
{"id": "math", "name": "Algebra II", "room": "B214", "teacher": "Ms. Patel", "color": "#4ac8ff"},
{"id": "bio", "name": "Biology", "room": "C110", "teacher": "Mr. Rivera", "color": "#2de2a6"},
{"id": "hist", "name": "World History", "room": "D301", "teacher": "Dr. Chen", "color": "#ffb347"},
{"id": "eng", "name": "English Lit", "room": "A102", "teacher": "Mrs. Quinn", "color": "#ff6b6b"},
]
if username == "avery":
base_classes.append(
{"id": "cs", "name": "AP Computer Science", "room": "Lab 3", "teacher": "Mr. Ortiz", "color": "#9b7bff"}
)
if username == "riley":
base_classes.append(
{"id": "chem", "name": "Chemistry", "room": "Lab 2", "teacher": "Ms. Liu", "color": "#ffd166"}
)
schedule = {day: [] for day in DAYS}
schedule["Mon"] = [
{"id": "event-1", "classId": "math", "start": "08:10", "end": "09:00", "location": "B214"},
{"id": "event-2", "classId": "bio", "start": "09:10", "end": "10:00", "location": "C110"},
{"id": "event-3", "classId": "hist", "start": "10:15", "end": "11:05", "location": "D301"},
]
schedule["Tue"] = [
{"id": "event-4", "classId": "eng", "start": "08:10", "end": "09:00", "location": "A102"},
{"id": "event-5", "classId": "math", "start": "09:10", "end": "10:00", "location": "B214"},
]
schedule["Wed"] = [
{"id": "event-6", "classId": "bio", "start": "08:10", "end": "09:00", "location": "C110"},
{"id": "event-7", "classId": "hist", "start": "09:10", "end": "10:00", "location": "D301"},
]
schedule["Thu"] = [
{"id": "event-8", "classId": "eng", "start": "08:10", "end": "09:00", "location": "A102"},
{"id": "event-9", "classId": "math", "start": "09:10", "end": "10:00", "location": "B214"},
]
schedule["Fri"] = [
{"id": "event-10", "classId": "bio", "start": "08:10", "end": "09:00", "location": "C110"},
{"id": "event-11", "classId": "hist", "start": "09:10", "end": "10:00", "location": "D301"},
]
if username == "avery":
schedule["Wed"].append(
{"id": "event-12", "classId": "cs", "start": "10:15", "end": "11:05", "location": "Lab 3"}
)
if username == "riley":
schedule["Tue"].append(
{"id": "event-13", "classId": "chem", "start": "10:15", "end": "11:05", "location": "Lab 2"}
)
return {"classes": base_classes, "schedule": schedule}
def is_demo_user(user):
return bool(user and user.get("demo"))
def load_json(path):
if not path.exists():
return None
with FILE_IO_LOCK:
try:
return json.loads(path.read_text(encoding="utf-8"))
except Exception:
return None
def write_json(path, payload):
serialized = json.dumps(payload, indent=2, sort_keys=True)
with FILE_IO_LOCK:
tmp_path = path.with_name(f"{path.name}.tmp")
tmp_path.write_text(serialized, encoding="utf-8")
os.replace(tmp_path, path)
def load_users():
data = load_json(USER_FILE)
payload = {"users": {}}
if isinstance(data, dict):
if isinstance(data.get("users"), dict):
payload = data
elif data.get("username") and data.get("password_hash") and data.get("salt"):
payload["users"][data["username"]] = {
"username": data.get("username"),
"salt": data.get("salt"),
"password_hash": data.get("password_hash"),
"created_at": data.get("created_at"),
"demo": False,
}
if ensure_demo_users(payload):
payload["updated_at"] = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
write_json(USER_FILE, payload)
return payload
def ensure_demo_users(payload):
users = payload.setdefault("users", {})
changed = False
for username in DEMO_USERNAMES:
if username in users:
if users[username].get("demo") is not True:
users[username]["demo"] = True
changed = True
continue
users[username] = create_user(username, DEMO_PASSWORD, demo=True)
changed = True
return changed
def save_users(payload):
payload["updated_at"] = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
write_json(USER_FILE, payload)
def get_user_record(username):
users_payload = load_users()
users = users_payload.get("users", {})
return users.get(username)
def user_configured():
users_payload = load_users()
users = users_payload.get("users", {})
return any(user for user in users.values() if user and not user.get("demo"))
def hash_password(password, salt):
return hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, 160_000)
def create_user(username, password, demo=False):
salt = secrets.token_bytes(16)
pw_hash = hash_password(password, salt)
return {
"username": username,
"salt": base64.b64encode(salt).decode("ascii"),
"password_hash": base64.b64encode(pw_hash).decode("ascii"),
"created_at": datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ"),
"demo": demo,
}
def register_account(username, password):
if not username or len(password) < 6:
return HTTPStatus.BAD_REQUEST, {"error": "username and 6+ char password required"}
users_payload = load_users()
users = users_payload.get("users", {})
existing = resolve_username(username, users)
if existing:
return HTTPStatus.BAD_REQUEST, {"error": "username already exists"}
user = create_user(username, password, demo=False)
users_payload.setdefault("users", {})[username] = user
save_users(users_payload)
store, changed = ensure_user_data(username)
if changed:
save_data_store(store)
return HTTPStatus.OK, {"username": username}
def verify_user(username, password):
user = get_user_record(username)
if not user:
return False
try:
salt = base64.b64decode(user.get("salt", ""))
stored_hash = base64.b64decode(user.get("password_hash", ""))
except Exception:
return False
computed = hash_password(password, salt)
return secrets.compare_digest(stored_hash, computed)
def load_data_store():
data = load_json(DATA_FILE)
if not isinstance(data, dict):
backup_data = load_json(APP_DIR / "orbit-data.backup.json")
if isinstance(backup_data, dict):
data = backup_data
if not isinstance(data, dict):
return {"users": {}}
if isinstance(data.get("users"), dict):
return data
if "classes" in data or "schedule" in data:
return {"users": {"__legacy__": sanitize_data(data)}, "updated_at": data.get("updated_at")}
return {"users": {}}
def save_data_store(store):
if DATA_FILE.exists():
backup_path = APP_DIR / "orbit-data.backup.json"
try:
shutil.copy2(DATA_FILE, backup_path)
except Exception:
pass
store["updated_at"] = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
write_json(DATA_FILE, store)
def ensure_demo_data(store):
users_payload = load_users()
users = users_payload.get("users", {})
data_users = store.setdefault("users", {})
changed = False
for username, user in users.items():
if not is_demo_user(user):
continue
template = sanitize_data(demo_data_template(username))
entry = data_users.get(username)
if not isinstance(entry, dict):
data_users[username] = template
changed = True
continue
classes = entry.get("classes")
if not isinstance(classes, list) or not classes:
entry["classes"] = template["classes"]
changed = True
schedule = entry.get("schedule")
schedule_empty = True
if isinstance(schedule, dict):
schedule_empty = all(not isinstance(schedule.get(day), list) or not schedule.get(day) for day in DAYS)
if schedule_empty:
entry["schedule"] = template["schedule"]
changed = True
if ensure_account_data_fields(entry):
changed = True
return changed
def ensure_user_data(username):
store = load_data_store()
users = store.setdefault("users", {})
if username in users:
return store, False
if "__legacy__" in users:
users[username] = users.pop("__legacy__")
return store, True
users[username] = default_data()
return store, True
def get_user_entry(username):
store = load_data_store()
changed = False
if ensure_demo_data(store):
changed = True
users = store.setdefault("users", {})
if username not in users:
if "__legacy__" in users:
users[username] = users.pop("__legacy__")
else:
users[username] = default_data()
changed = True
entry = users.get(username)
if not isinstance(entry, dict):
entry = default_data()
users[username] = entry
changed = True
if ensure_account_data_fields(entry):
changed = True
return store, entry, changed
def get_user_chats(username):
store, entry, changed = get_user_entry(username)
chat_store, error = load_chat_store(username)
threads = chat_store.get("threads", {})
if isinstance(entry.get("chats"), dict):
for class_id, messages in entry["chats"].items():
if not isinstance(messages, list):
continue
threads.setdefault(class_id, []).extend(messages)
entry.pop("chats", None)
changed = True
if prune_chat_threads(threads):
save_chat_store(username, threads)
if changed:
save_data_store(store)
return store, threads, error
def append_message_to_users(usernames, thread_id, message):
for username in usernames:
store, chats, error = get_user_chats(username)
if error == "locked":
return "locked"
thread = chats.get(thread_id)
if not isinstance(thread, list):
thread = []
chats[thread_id] = thread
thread.append(message)
prune_chat_threads(chats)
save_chat_store(username, chats)
return None
def get_user_friends(username):
store, entry, changed = get_user_entry(username)
friends = entry.get("friends")
if not isinstance(friends, list):
friends = []
entry["friends"] = friends
changed = True
return store, friends, changed
def get_user_settings(username):
store, entry, changed = get_user_entry(username)
settings = entry.get("settings")
if not isinstance(settings, dict):
settings = {}
entry["settings"] = settings
changed = True
return store, settings, changed
def save_user_settings(username, settings):
store, entry, changed = get_user_entry(username)
entry["settings"] = settings if isinstance(settings, dict) else {}
save_data_store(store)
def get_user_groups(username):
store, entry, changed = get_user_entry(username)
groups = entry.get("groups")
if not isinstance(groups, list):
groups = []
entry["groups"] = groups
changed = True
return store, groups, changed
def sanitize_profile(profile):
if not isinstance(profile, dict):
return {"bio": "", "avatar": "", "school": "", "grade": ""}
bio = str(profile.get("bio") or "").strip()
avatar = str(profile.get("avatar") or "").strip()
school = str(profile.get("school") or "").strip()
grade = str(profile.get("grade") or "").strip()
if len(avatar) > MAX_AVATAR_CHARS:
avatar = ""
if len(school) > MAX_SCHOOL_CHARS:
school = school[:MAX_SCHOOL_CHARS]
if len(grade) > MAX_GRADE_CHARS:
grade = grade[:MAX_GRADE_CHARS]
return {"bio": bio, "avatar": avatar, "school": school, "grade": grade}
def get_user_profile(username):
store, entry, changed = get_user_entry(username)
profile = entry.get("profile")
if not isinstance(profile, dict):
return store, {"bio": "", "avatar": "", "school": "", "grade": ""}, changed
return store, sanitize_profile(profile), changed
def save_user_profile(username, profile):
store, entry, changed = get_user_entry(username)
entry["profile"] = sanitize_profile(profile)
save_data_store(store)
def ensure_store_user_entry(store, username):
users = store.setdefault("users", {})
if username not in users:
if "__legacy__" in users:
users[username] = users.pop("__legacy__")
else:
users[username] = default_data()
entry = users.get(username)
if not isinstance(entry, dict):
entry = default_data()
users[username] = entry
ensure_account_data_fields(entry)
return entry
def ensure_request_data(entry):
requests = entry.get("friend_requests")
changed = False
if not isinstance(requests, dict):
requests = {"incoming": [], "outgoing": []}
entry["friend_requests"] = requests
changed = True
incoming = requests.get("incoming")
if not isinstance(incoming, list):
incoming = []
requests["incoming"] = incoming
changed = True
outgoing = requests.get("outgoing")
if not isinstance(outgoing, list):
outgoing = []
requests["outgoing"] = outgoing
changed = True
return incoming, outgoing, changed
def get_user_requests(username):
store, entry, changed = get_user_entry(username)
incoming, outgoing, updated = ensure_request_data(entry)
return store, incoming, outgoing, changed or updated
def add_friend_entry(entry, other_username):
friends = entry.get("friends")
if not isinstance(friends, list):
friends = []
entry["friends"] = friends
existing = get_friend_usernames(friends)
if other_username.lower() in existing:
return None
friend = {
"id": f"friend-{secrets.token_hex(4)}",
"name": other_username,
"username": other_username,
"created_at": datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ"),
}
friends.append(friend)
return friend
def pop_request_by_id(requests, request_id):
if not request_id:
return None
for index, item in enumerate(requests):
if isinstance(item, dict) and item.get("id") == request_id:
return requests.pop(index)
return None
def pop_request_by_user(requests, username, key):
if not username:
return None
for index, item in enumerate(requests):
if not isinstance(item, dict):
continue
value = normalize_username(item.get(key))
if value and value.lower() == username.lower():
return requests.pop(index)
return None
def send_friend_request(user, target_name):
users_payload = load_users()
users = users_payload.get("users", {})
target_user = resolve_username(target_name, users)
if not target_user:
return HTTPStatus.BAD_REQUEST, {"error": "user not found"}
if target_user == user:
return HTTPStatus.BAD_REQUEST, {"error": "cannot add yourself"}
store = load_data_store()
ensure_demo_data(store)
entry_user = ensure_store_user_entry(store, user)
entry_target = ensure_store_user_entry(store, target_user)
friends = entry_user.get("friends", [])
if target_user.lower() in get_friend_usernames(friends):
return HTTPStatus.BAD_REQUEST, {"error": "friend already added"}
incoming_user, outgoing_user, _ = ensure_request_data(entry_user)
incoming_target, outgoing_target, _ = ensure_request_data(entry_target)
if any(
isinstance(req, dict) and normalize_username(req.get("to")).lower() == target_user.lower()
for req in outgoing_user
):
return HTTPStatus.BAD_REQUEST, {"error": "request already sent"}
if any(
isinstance(req, dict) and normalize_username(req.get("from")).lower() == target_user.lower()
for req in incoming_user
):
return HTTPStatus.BAD_REQUEST, {"error": "request already received"}
if any(
isinstance(req, dict) and normalize_username(req.get("from")).lower() == user.lower()
for req in incoming_target
):
return HTTPStatus.BAD_REQUEST, {"error": "request already pending"}
request = {
"id": f"req-{secrets.token_hex(4)}",
"from": user,
"to": target_user,
"created_at": datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ"),
}
outgoing_user.append(request)
incoming_target.append(request)
save_data_store(store)
return HTTPStatus.OK, {"request": request}
def get_friend_usernames(friends):
usernames = set()
for friend in friends:
if not isinstance(friend, dict):
continue
value = friend.get("username") or friend.get("name") or ""
value = normalize_username(value)
if value:
usernames.add(value.lower())
return usernames
def user_is_friend(viewer, target):
if not viewer or not target:
return False
if viewer.lower() == target.lower():
return True
store, friends, changed = get_user_friends(viewer)
if changed:
save_data_store(store)
friend_names = get_friend_usernames(friends)
return target.lower() in friend_names
def parse_member_list(value):
if isinstance(value, list):
raw = value
elif isinstance(value, str):
raw = value.split(",")
else:
raw = []
members = []
for entry in raw:
name = normalize_username(entry)
if name:
members.append(name)
return members
def add_group_to_user(store, username, group):
users = store.setdefault("users", {})
entry = users.get(username)
if not isinstance(entry, dict):
entry = default_data()
users[username] = entry
groups = entry.get("groups")
if not isinstance(groups, list):
groups = []
entry["groups"] = groups
if not any(isinstance(item, dict) and item.get("id") == group.get("id") for item in groups):
groups.append(group)
def load_user_data(username):
store = load_data_store()
changed = False
if ensure_demo_data(store):
changed = True
users = store.setdefault("users", {})
if username not in users:
if "__legacy__" in users:
users[username] = users.pop("__legacy__")
else:
users[username] = default_data()
changed = True
entry = users.get(username)
if not isinstance(entry, dict):
entry = default_data()
users[username] = entry
changed = True
fields_changed = ensure_account_data_fields(entry)
if fields_changed:
changed = True
if changed:
save_data_store(store)
return entry
def sanitize_data(data):
if not isinstance(data, dict):
return default_data()
classes_in = data.get("classes") if isinstance(data.get("classes"), list) else []
clean_classes = []
class_ids = set()
for entry in classes_in:
if not isinstance(entry, dict):
continue