-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.py
More file actions
9838 lines (8667 loc) · 339 KB
/
Copy pathapp.py
File metadata and controls
9838 lines (8667 loc) · 339 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
import eventlet
eventlet.monkey_patch()
from flask import Flask, g, render_template, request, redirect, url_for, render_template_string, session, abort, send_file, jsonify
from datetime import datetime, timedelta
from pathlib import Path
import os
import shutil
import sqlite3
import calendar
import time
from urllib.parse import quote
import uuid
import json
import io
import base64
from werkzeug.utils import secure_filename
from werkzeug.security import generate_password_hash, check_password_hash
from functools import wraps
import re
from flask_socketio import SocketIO, join_room, disconnect, emit
from pywebpush import webpush, WebPushException
from cryptography.hazmat.primitives import serialization
def _is_vercel() -> bool:
return bool(os.getenv("VERCEL") == "1" or os.getenv("VERCEL_ENV"))
def _load_dotenv_file(path: Path) -> None:
try:
raw = path.read_text(encoding="utf-8")
except Exception:
return
for line in raw.splitlines():
line = line.strip()
if not line or line.startswith("#"):
continue
if "=" not in line:
continue
key, val = line.split("=", 1)
key = key.strip()
if not key or key in os.environ:
continue
val = val.strip()
if len(val) >= 2 and val[0] == val[-1] and val[0] in {"'", '"'}:
val = val[1:-1]
os.environ[key] = val
_load_dotenv_file(Path(__file__).with_name(".env"))
BASE_DIR = Path(__file__).resolve().parent
DEFAULT_STATIC_DIR = BASE_DIR / "static"
IS_VERCEL = _is_vercel()
RUNTIME_DIR = Path(os.getenv("VERCEL_DATA_DIR", "/tmp/eduportal")) if IS_VERCEL else None
if IS_VERCEL:
try:
RUNTIME_DIR.mkdir(parents=True, exist_ok=True)
except Exception:
pass
runtime_static = RUNTIME_DIR / "static"
try:
if DEFAULT_STATIC_DIR.exists():
shutil.copytree(DEFAULT_STATIC_DIR, runtime_static, dirs_exist_ok=True)
except Exception:
pass
STATIC_DIR = runtime_static
else:
STATIC_DIR = DEFAULT_STATIC_DIR
app = Flask(__name__, static_folder=str(STATIC_DIR))
app.secret_key = os.getenv("SECRET_KEY", "dev-secret-key")
socketio = SocketIO(
app,
async_mode="eventlet",
cors_allowed_origins="*",
)
CHAT_ROOM = "group_chat"
@app.template_filter("time12")
def _time12_filter(value: str) -> str:
raw = (value or "").strip()
m = re.match(r"^(\d{1,2}):(\d{2})$", raw)
if not m:
return raw
try:
hh = int(m.group(1))
mm = int(m.group(2))
except Exception:
return raw
if hh < 0 or hh > 23 or mm < 0 or mm > 59:
return raw
ampm = "AM" if hh < 12 else "PM"
hh12 = hh % 12
if hh12 == 0:
hh12 = 12
return f"{hh12}:{mm:02d} {ampm}"
if IS_VERCEL:
DB_PATH = RUNTIME_DIR / "eduportal.db"
repo_db = BASE_DIR / "eduportal.db"
try:
if not DB_PATH.exists() and repo_db.exists():
shutil.copyfile(repo_db, DB_PATH)
except Exception:
pass
else:
DB_PATH = BASE_DIR / "eduportal.db"
STATIC_UPLOAD_ROOT = Path(app.static_folder) / "uploads"
VAULT_UPLOAD_ROOT = (RUNTIME_DIR / "uploads") if IS_VERCEL else (BASE_DIR / "uploads")
NEWS_UPLOAD_DIR = STATIC_UPLOAD_ROOT / "news"
CHAT_UPLOAD_DIR = STATIC_UPLOAD_ROOT / "chat"
VAULT_UPLOAD_DIR = VAULT_UPLOAD_ROOT / "vault"
FACULTY_VAULT_UPLOAD_DIR = VAULT_UPLOAD_ROOT / "faculty_vault"
def save_news_attachment(upload) -> tuple[str, str, str] | None:
if upload is None:
return None
original = (upload.filename or "").strip()
if not original:
return None
NEWS_UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
safe = secure_filename(original)
if not safe:
return None
unique = f"{uuid.uuid4().hex}_{safe}"
abs_path = NEWS_UPLOAD_DIR / unique
upload.save(abs_path)
rel_path = f"uploads/news/{unique}"
mime = (getattr(upload, "mimetype", None) or "").strip()
return (rel_path, original, mime)
def save_chat_attachment(upload) -> tuple[str, str, str] | None:
if upload is None:
return None
original = (upload.filename or "").strip()
if not original:
return None
CHAT_UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
safe = secure_filename(original)
if not safe:
return None
unique = f"{uuid.uuid4().hex}_{safe}"
abs_path = CHAT_UPLOAD_DIR / unique
upload.save(abs_path)
rel_path = f"uploads/chat/{unique}"
mime = (getattr(upload, "mimetype", None) or "").strip()
return (rel_path, original, mime)
def ensure_group_chat_schema(db: sqlite3.Connection) -> None:
db.execute(
"""
CREATE TABLE IF NOT EXISTS group_chat_messages (
id INTEGER PRIMARY KEY,
created_at TEXT NOT NULL,
actor_type TEXT NOT NULL,
actor_id INTEGER NOT NULL,
actor_name TEXT NOT NULL,
message TEXT,
attachment_path TEXT,
attachment_name TEXT,
attachment_mime TEXT,
is_deleted INTEGER NOT NULL DEFAULT 0,
edited_at TEXT,
edited_by_type TEXT,
edited_by_id INTEGER,
kind TEXT NOT NULL DEFAULT 'text',
poll_id INTEGER
)
"""
)
cols = {row[1] for row in db.execute("PRAGMA table_info(group_chat_messages)").fetchall()}
if "kind" not in cols:
db.execute("ALTER TABLE group_chat_messages ADD COLUMN kind TEXT NOT NULL DEFAULT 'text'")
if "poll_id" not in cols:
db.execute("ALTER TABLE group_chat_messages ADD COLUMN poll_id INTEGER")
ensure_chat_poll_schema(db)
ensure_chat_pin_schema(db)
def ensure_chat_poll_schema(db: sqlite3.Connection) -> None:
db.execute(
"""
CREATE TABLE IF NOT EXISTS chat_polls (
id INTEGER PRIMARY KEY,
question TEXT NOT NULL,
poll_type TEXT NOT NULL,
actor_type TEXT NOT NULL,
actor_id INTEGER NOT NULL,
created_at TEXT NOT NULL,
is_closed INTEGER NOT NULL DEFAULT 0
)
"""
)
db.execute(
"""
CREATE TABLE IF NOT EXISTS chat_poll_options (
id INTEGER PRIMARY KEY,
poll_id INTEGER NOT NULL,
label TEXT NOT NULL,
position INTEGER NOT NULL,
FOREIGN KEY(poll_id) REFERENCES chat_polls(id) ON DELETE CASCADE
)
"""
)
db.execute(
"""
CREATE TABLE IF NOT EXISTS chat_poll_votes (
id INTEGER PRIMARY KEY,
poll_id INTEGER NOT NULL,
option_id INTEGER NOT NULL,
actor_type TEXT NOT NULL,
actor_id INTEGER NOT NULL,
created_at TEXT NOT NULL,
UNIQUE(poll_id, option_id, actor_type, actor_id),
FOREIGN KEY(poll_id) REFERENCES chat_polls(id) ON DELETE CASCADE,
FOREIGN KEY(option_id) REFERENCES chat_poll_options(id) ON DELETE CASCADE
)
"""
)
def ensure_chat_pin_schema(db: sqlite3.Connection) -> None:
db.execute(
"""
CREATE TABLE IF NOT EXISTS chat_pinned_message (
id INTEGER PRIMARY KEY CHECK (id = 1),
message_id INTEGER NOT NULL,
pinned_by_type TEXT NOT NULL,
pinned_by_id INTEGER NOT NULL,
pinned_at TEXT NOT NULL
)
"""
)
cols = {row[1] for row in db.execute("PRAGMA table_info(group_chat_messages)").fetchall()}
if "edited_at" not in cols:
db.execute("ALTER TABLE group_chat_messages ADD COLUMN edited_at TEXT")
if "edited_by_type" not in cols:
db.execute("ALTER TABLE group_chat_messages ADD COLUMN edited_by_type TEXT")
if "edited_by_id" not in cols:
db.execute("ALTER TABLE group_chat_messages ADD COLUMN edited_by_id INTEGER")
def ensure_chat_meta_schema(db: sqlite3.Connection) -> None:
db.execute(
"""
CREATE TABLE IF NOT EXISTS chat_meta (
id INTEGER PRIMARY KEY CHECK (id = 1),
revision INTEGER NOT NULL,
updated_at TEXT
)
"""
)
row = db.execute("SELECT id FROM chat_meta WHERE id = 1").fetchone()
if not row:
now = datetime.now().isoformat(timespec="seconds")
db.execute(
"INSERT INTO chat_meta (id, revision, updated_at) VALUES (1, 0, ?)",
(now,),
)
db.commit()
def get_chat_revision(db: sqlite3.Connection) -> int:
ensure_chat_meta_schema(db)
row = db.execute("SELECT revision FROM chat_meta WHERE id = 1").fetchone()
try:
return int(row[0]) if row else 0
except Exception:
return 0
def bump_chat_revision(db: sqlite3.Connection) -> int:
ensure_chat_meta_schema(db)
now = datetime.now().isoformat(timespec="seconds")
db.execute(
"UPDATE chat_meta SET revision = revision + 1, updated_at = ? WHERE id = 1",
(now,),
)
db.commit()
row = db.execute("SELECT revision FROM chat_meta WHERE id = 1").fetchone()
try:
return int(row[0]) if row else 0
except Exception:
return 0
def ensure_chat_access_requests_schema(db: sqlite3.Connection) -> None:
db.execute(
"""
CREATE TABLE IF NOT EXISTS chat_access_requests (
id INTEGER PRIMARY KEY,
student_id INTEGER NOT NULL,
created_at TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending'
)
"""
)
db.commit()
def ensure_push_schema(db: sqlite3.Connection) -> None:
db.execute(
"""
CREATE TABLE IF NOT EXISTS push_subscriptions (
id INTEGER PRIMARY KEY,
actor_type TEXT NOT NULL,
actor_id INTEGER NOT NULL,
endpoint TEXT NOT NULL UNIQUE,
p256dh TEXT NOT NULL,
auth TEXT NOT NULL,
enabled INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL,
updated_at TEXT
)
"""
)
def _get_actor_from_session(db: sqlite3.Connection) -> dict | None:
aid = get_current_admin_id()
if aid is not None:
admin_user = db.execute("SELECT * FROM admin_users WHERE id = ?", (int(aid),)).fetchone()
if admin_user:
return {"type": "admin", "id": int(aid), "name": str(admin_user["full_name"] or "Admin")}
fid = get_current_faculty_id()
if fid is not None:
ensure_faculty_users_schema(db)
faculty_user = db.execute("SELECT * FROM faculty_users WHERE id = ?", (int(fid),)).fetchone()
if faculty_user:
return {"type": "faculty", "id": int(fid), "name": str(faculty_user["full_name"] or "Faculty")}
sid = get_current_student_id()
if sid is not None:
student = db.execute("SELECT * FROM students WHERE id = ?", (int(sid),)).fetchone()
if student:
return {"type": "student", "id": int(sid), "name": str(student["name"] or "Student")}
return None
def _actor_name_from_type_id(db: sqlite3.Connection, actor_type: str, actor_id: int) -> str:
t = (actor_type or "").strip().lower()
if t == "admin":
row = db.execute("SELECT full_name FROM admin_users WHERE id = ?", (int(actor_id),)).fetchone()
return str(row["full_name"] or "Admin") if row else "Admin"
if t == "faculty":
ensure_faculty_users_schema(db)
row = db.execute("SELECT full_name FROM faculty_users WHERE id = ?", (int(actor_id),)).fetchone()
return str(row["full_name"] or "Faculty") if row else "Faculty"
row = db.execute("SELECT name FROM students WHERE id = ?", (int(actor_id),)).fetchone()
return str(row["name"] or "Student") if row else "Student"
def _poll_payload(db: sqlite3.Connection, poll_id: int, actor: dict | None = None) -> dict | None:
if not poll_id:
return None
poll = db.execute("SELECT * FROM chat_polls WHERE id = ?", (int(poll_id),)).fetchone()
if not poll:
return None
options = db.execute(
"""
SELECT id, label, position
FROM chat_poll_options
WHERE poll_id = ?
ORDER BY position ASC, id ASC
""",
(int(poll_id),),
).fetchall()
counts_rows = db.execute(
"""
SELECT option_id, COUNT(*) as c
FROM chat_poll_votes
WHERE poll_id = ?
GROUP BY option_id
""",
(int(poll_id),),
).fetchall()
counts = {int(r["option_id"]): int(r["c"]) for r in counts_rows}
total_voters_row = db.execute(
"""
SELECT COUNT(DISTINCT actor_type || ':' || actor_id) AS c
FROM chat_poll_votes
WHERE poll_id = ?
""",
(int(poll_id),),
).fetchone()
total_voters = int(total_voters_row["c"] or 0) if total_voters_row else 0
user_votes: list[int] = []
if actor:
rows = db.execute(
"""
SELECT option_id
FROM chat_poll_votes
WHERE poll_id = ? AND actor_type = ? AND actor_id = ?
""",
(int(poll_id), str(actor.get("type")), int(actor.get("id") or 0)),
).fetchall()
user_votes = [int(r["option_id"]) for r in rows]
return {
"id": int(poll["id"]),
"question": str(poll["question"] or ""),
"poll_type": str(poll["poll_type"] or "single"),
"is_closed": bool(int(poll["is_closed"] or 0) == 1),
"created_at": str(poll["created_at"] or ""),
"options": [
{
"id": int(o["id"]),
"label": str(o["label"] or ""),
"position": int(o["position"] or 0),
"count": int(counts.get(int(o["id"]), 0)),
}
for o in options
],
"total_voters": int(total_voters),
"user_votes": user_votes,
}
def _chat_row_to_msg(db: sqlite3.Connection, row: sqlite3.Row, actor: dict | None = None) -> dict:
created_at = str(row["created_at"] or "")
dk = _chat_date_key(created_at)
mime = (row["attachment_mime"] or "") if ("attachment_mime" in row.keys()) else ""
is_img = bool(mime and str(mime).startswith("image/"))
ap = row["attachment_path"]
kind = str(row["kind"] or "text") if ("kind" in row.keys()) else "text"
poll_id = int(row["poll_id"] or 0) if ("poll_id" in row.keys()) and row["poll_id"] is not None else None
return {
"id": int(row["id"]),
"created_at": created_at,
"edited_at": str(row["edited_at"] or "") if ("edited_at" in row.keys()) else "",
"date_key": dk,
"date_label": _chat_date_label(dk),
"time_label": fmt_chat_time(created_at),
"edited_label": fmt_chat_time(str(row["edited_at"] or "")) if ("edited_at" in row.keys() and row["edited_at"]) else "",
"actor_type": str(row["actor_type"] or ""),
"actor_id": int(row["actor_id"] or 0),
"actor_name": str(row["actor_name"] or ""),
"message": str(row["message"] or ""),
"attachment_path": ap,
"attachment_name": row["attachment_name"],
"attachment_mime": row["attachment_mime"],
"attachment_is_image": is_img,
"attachment_url": url_for("static", filename=ap) if ap else None,
"kind": kind,
"poll_id": poll_id,
"poll": _poll_payload(db, int(poll_id), actor) if kind == "poll" and poll_id else None,
}
def _push_send_to_actor(db: sqlite3.Connection, actor_type: str, actor_id: int, payload: dict) -> None:
ensure_push_schema(db)
pub = (os.getenv("VAPID_PUBLIC_KEY", "") or "").strip()
priv = (os.getenv("VAPID_PRIVATE_KEY", "") or "").strip()
if not pub or not priv:
return
priv = _normalize_vapid_private_key(priv)
if not priv:
return
rows = db.execute(
"""
SELECT * FROM push_subscriptions
WHERE actor_type = ? AND actor_id = ? AND enabled = 1
""",
(str(actor_type), int(actor_id)),
).fetchall()
if not rows:
return
data = json.dumps(payload)
now = datetime.now().isoformat(timespec="seconds")
for r in rows:
sub_info = {
"endpoint": str(r["endpoint"]),
"keys": {"p256dh": str(r["p256dh"]), "auth": str(r["auth"])},
}
try:
webpush(
sub_info,
data=data,
vapid_private_key=priv,
vapid_claims={"sub": "mailto:admin@example.com"},
)
db.execute(
"UPDATE push_subscriptions SET updated_at = ? WHERE id = ?",
(now, int(r["id"])),
)
except WebPushException as exc:
status = getattr(getattr(exc, "response", None), "status_code", None)
if status in {404, 410}:
db.execute("DELETE FROM push_subscriptions WHERE id = ?", (int(r["id"]),))
else:
app.logger.warning("Push send failed: %s", exc)
except Exception as exc:
app.logger.warning("Push send error: %s", exc)
continue
db.commit()
def _push_broadcast_chat(db: sqlite3.Connection, actor: dict, payload: dict) -> None:
ensure_push_schema(db)
rows = db.execute(
"""
SELECT DISTINCT actor_type, actor_id
FROM push_subscriptions
WHERE enabled = 1
"""
).fetchall()
for r in rows:
t = str(r["actor_type"] or "")
i = int(r["actor_id"] or 0)
p = dict(payload or {})
if not p.get("url"):
p["url"] = _chat_url_for_actor(t)
_push_send_to_actor(db, t, i, p)
def _chat_url_for_actor(actor_type: str) -> str:
t = (actor_type or "").strip().lower()
if t == "admin":
return "/admin/chat"
if t == "faculty":
return "/faculty/chat"
return "/chat"
def _normalize_vapid_private_key(priv: str) -> str:
if not priv:
return ""
if "\\n" in priv:
priv = priv.replace("\\n", "\n")
if "-----BEGIN" in priv:
return priv
if not re.fullmatch(r"[A-Za-z0-9+/=_\-]+", priv or ""):
return priv
# If it's a raw 32-byte base64url key, keep as-is for pywebpush.
try:
padded = priv.replace("-", "+").replace("_", "/")
padded += "=" * ((4 - (len(padded) % 4)) % 4)
raw = base64.b64decode(padded)
if len(raw) == 32:
return priv
except Exception:
pass
# Otherwise assume DER base64 and convert to PEM.
b64 = priv.replace("-", "+").replace("_", "/")
b64 += "=" * ((4 - (len(b64) % 4)) % 4)
try:
der = base64.b64decode(b64)
key = serialization.load_der_private_key(der, password=None)
pem = key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption(),
)
return pem.decode("utf-8")
except Exception:
return "-----BEGIN EC PRIVATE KEY-----\n" + "\n".join([b64[i : i + 64] for i in range(0, len(b64), 64)]) + "\n-----END EC PRIVATE KEY-----\n"
@app.get("/sw.js")
def service_worker():
sw = Path(__file__).with_name("static") / "sw.js"
if not sw.exists():
abort(404)
return send_file(sw, mimetype="application/javascript")
@app.get("/push/vapid-public-key")
def push_vapid_public_key():
pub = (os.getenv("VAPID_PUBLIC_KEY", "") or "").strip()
return jsonify({"ok": True, "public_key": pub})
@app.get("/push/status")
def push_status():
db = get_db()
actor = _get_actor_from_session(db)
if not actor:
return jsonify({"ok": False, "error": "Not logged in"}), 401
ensure_push_schema(db)
row = db.execute(
"""
SELECT enabled FROM push_subscriptions
WHERE actor_type = ? AND actor_id = ?
ORDER BY updated_at DESC, created_at DESC
LIMIT 1
""",
(str(actor["type"]), int(actor["id"])),
).fetchone()
enabled = bool(row and int(row["enabled"] or 0) == 1)
return jsonify({"ok": True, "enabled": enabled})
@app.post("/push/subscribe")
def push_subscribe():
db = get_db()
actor = _get_actor_from_session(db)
if not actor:
return jsonify({"ok": False, "error": "Not logged in"}), 401
ensure_push_schema(db)
body = request.get_json(silent=True) or {}
sub = body.get("subscription") or {}
endpoint = str(sub.get("endpoint") or "").strip()
keys = sub.get("keys") or {}
p256dh = str(keys.get("p256dh") or "").strip()
auth = str(keys.get("auth") or "").strip()
if not endpoint or not p256dh or not auth:
return jsonify({"ok": False, "error": "Invalid subscription"}), 400
now = datetime.now().isoformat(timespec="seconds")
existing = db.execute(
"SELECT id FROM push_subscriptions WHERE endpoint = ?",
(endpoint,),
).fetchone()
if existing:
db.execute(
"""
UPDATE push_subscriptions
SET actor_type = ?, actor_id = ?, p256dh = ?, auth = ?, enabled = 1, updated_at = ?
WHERE endpoint = ?
""",
(str(actor["type"]), int(actor["id"]), p256dh, auth, now, endpoint),
)
else:
db.execute(
"""
INSERT INTO push_subscriptions (actor_type, actor_id, endpoint, p256dh, auth, enabled, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, 1, ?, ?)
""",
(str(actor["type"]), int(actor["id"]), endpoint, p256dh, auth, now, now),
)
db.commit()
return jsonify({"ok": True})
@app.post("/push/unsubscribe")
def push_unsubscribe():
db = get_db()
actor = _get_actor_from_session(db)
if not actor:
return jsonify({"ok": False, "error": "Not logged in"}), 401
ensure_push_schema(db)
body = request.get_json(silent=True) or {}
endpoint = str(body.get("endpoint") or "").strip()
if not endpoint:
return jsonify({"ok": False, "error": "Missing endpoint"}), 400
db.execute(
"DELETE FROM push_subscriptions WHERE endpoint = ? AND actor_type = ? AND actor_id = ?",
(endpoint, str(actor["type"]), int(actor["id"])),
)
db.commit()
return jsonify({"ok": True})
@app.post("/push/toggle")
def push_toggle():
db = get_db()
actor = _get_actor_from_session(db)
if not actor:
return jsonify({"ok": False, "error": "Not logged in"}), 401
ensure_push_schema(db)
body = request.get_json(silent=True) or {}
enabled = 1 if bool(body.get("enabled")) else 0
now = datetime.now().isoformat(timespec="seconds")
db.execute(
"""
UPDATE push_subscriptions
SET enabled = ?, updated_at = ?
WHERE actor_type = ? AND actor_id = ?
""",
(enabled, now, str(actor["type"]), int(actor["id"])),
)
db.commit()
return jsonify({"ok": True, "enabled": bool(enabled)})
@socketio.on("connect")
def socket_connect():
db = get_db()
ensure_group_chat_schema(db)
ensure_chat_access_requests_schema(db)
actor = _get_actor_from_session(db)
if not actor:
disconnect()
return
join_room(CHAT_ROOM)
@socketio.on("chat:sync")
def socket_chat_sync(payload=None):
db = get_db()
ensure_group_chat_schema(db)
actor = _get_actor_from_session(db)
if not actor:
disconnect()
return
body = payload or {}
try:
client_rev = int(body.get("revision") or 0)
except Exception:
client_rev = 0
server_rev = get_chat_revision(db)
if client_rev == server_rev:
emit("chat:rev", {"revision": int(server_rev)})
return
rows, oldest_id, has_more = _chat_fetch_recent(db, 15)
items = build_group_chat_items(rows, db=db, actor=actor)
items = _chat_items_to_json(items)
emit(
"chat:snapshot",
{
"revision": int(server_rev),
"items": items,
"oldest_id": int(oldest_id) if oldest_id else None,
"has_more": bool(has_more),
},
)
def fmt_chat_time(value: str) -> str:
if not value:
return ""
try:
dt = datetime.fromisoformat(str(value).replace("Z", ""))
except Exception:
return ""
return dt.strftime("%I:%M %p")
def _chat_date_key(value: str) -> str:
if not value:
return ""
try:
dt = datetime.fromisoformat(str(value).replace("Z", ""))
except Exception:
return ""
return dt.date().isoformat()
def _chat_date_label(date_key: str) -> str:
if not date_key:
return ""
try:
d = datetime.fromisoformat(date_key).date()
except Exception:
return date_key
today = datetime.now().date()
if d == today:
return "Today"
if d == (today - timedelta(days=1)):
return "Yesterday"
return d.strftime("%d %b %Y")
def build_group_chat_items(
rows: list[sqlite3.Row],
last_date: str | None = None,
db: sqlite3.Connection | None = None,
actor: dict | None = None,
) -> list[dict]:
items: list[dict] = []
for r in rows:
created_at = str(r["created_at"] or "")
dk = _chat_date_key(created_at)
if dk and dk != last_date:
items.append({"kind": "date", "date_key": dk, "label": _chat_date_label(dk)})
last_date = dk
msg = _chat_row_to_msg(db, r, actor) if db else _chat_row_to_msg(get_db(), r, actor)
items.append(
{
"kind": "msg",
"msg": msg,
}
)
return items
def ensure_news_posts_rich_schema(db: sqlite3.Connection) -> None:
cols = {row[1] for row in db.execute("PRAGMA table_info(news_posts)").fetchall()}
if "body_is_html" not in cols:
db.execute("ALTER TABLE news_posts ADD COLUMN body_is_html INTEGER NOT NULL DEFAULT 0")
if "attachment_path" not in cols:
db.execute("ALTER TABLE news_posts ADD COLUMN attachment_path TEXT")
if "attachment_name" not in cols:
db.execute("ALTER TABLE news_posts ADD COLUMN attachment_name TEXT")
if "attachment_mime" not in cols:
db.execute("ALTER TABLE news_posts ADD COLUMN attachment_mime TEXT")
def ensure_news_posts_faculty_author_schema(db: sqlite3.Connection) -> None:
cols = {row[1] for row in db.execute("PRAGMA table_info(news_posts)").fetchall()}
if "author_faculty_id" not in cols:
db.execute("ALTER TABLE news_posts ADD COLUMN author_faculty_id INTEGER")
def ensure_faculty_weekly_timetable_schema(db: sqlite3.Connection) -> None:
db.execute(
"""
CREATE TABLE IF NOT EXISTS faculty_weekly_timetable (
id INTEGER PRIMARY KEY,
faculty_id INTEGER NOT NULL,
day_of_week INTEGER NOT NULL,
start_time TEXT NOT NULL,
end_time TEXT NOT NULL,
subject TEXT NOT NULL,
room TEXT NOT NULL,
created_at TEXT NOT NULL,
updated_at TEXT,
FOREIGN KEY(faculty_id) REFERENCES faculty_users(id) ON DELETE CASCADE
)
"""
)
cols = {row[1] for row in db.execute("PRAGMA table_info(faculty_weekly_timetable)").fetchall()}
if "program" not in cols:
db.execute("ALTER TABLE faculty_weekly_timetable ADD COLUMN program TEXT")
if "department" not in cols:
db.execute("ALTER TABLE faculty_weekly_timetable ADD COLUMN department TEXT")
if "branch" not in cols:
db.execute("ALTER TABLE faculty_weekly_timetable ADD COLUMN branch TEXT")
if "year" not in cols:
db.execute("ALTER TABLE faculty_weekly_timetable ADD COLUMN year TEXT")
if "semester" not in cols:
db.execute("ALTER TABLE faculty_weekly_timetable ADD COLUMN semester TEXT")
def ensure_library_resources_faculty_author_schema(db: sqlite3.Connection) -> None:
cols = {row[1] for row in db.execute("PRAGMA table_info(library_resources)").fetchall()}
if "author_faculty_id" not in cols:
db.execute("ALTER TABLE library_resources ADD COLUMN author_faculty_id INTEGER")
def ensure_library_resources_student_author_schema(db: sqlite3.Connection) -> None:
cols = {row[1] for row in db.execute("PRAGMA table_info(library_resources)").fetchall()}
if "author_student_id" not in cols:
db.execute("ALTER TABLE library_resources ADD COLUMN author_student_id INTEGER")
def ensure_students_permissions_schema(db: sqlite3.Connection) -> None:
cols = {row[1] for row in db.execute("PRAGMA table_info(students)").fetchall()}
if "can_share_resource" not in cols:
db.execute("ALTER TABLE students ADD COLUMN can_share_resource INTEGER NOT NULL DEFAULT 1")
if "can_upload_resource" not in cols:
db.execute("ALTER TABLE students ADD COLUMN can_upload_resource INTEGER NOT NULL DEFAULT 0")
if "can_chat" not in cols:
db.execute("ALTER TABLE students ADD COLUMN can_chat INTEGER NOT NULL DEFAULT 0")
if "can_use_vault" not in cols:
db.execute("ALTER TABLE students ADD COLUMN can_use_vault INTEGER NOT NULL DEFAULT 0")
def _student_can_use_vault(db: sqlite3.Connection, student_id: int | None) -> bool:
ensure_students_permissions_schema(db)
try:
sid = int(student_id or 0)
except Exception:
return False
if sid <= 0:
return False
row = db.execute("SELECT can_use_vault FROM students WHERE id = ?", (sid,)).fetchone()
if not row:
return False
try:
return int(row["can_use_vault"] or 0) == 1
except Exception:
return False
def student_vault_required(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
sid = get_current_student_id()
if sid is None:
return redirect(url_for("login"))
db = get_db()
if not _student_can_use_vault(db, sid):
return redirect(url_for("dashboard", error=quote("Vault access is disabled. Please contact admin.")))
return fn(*args, **kwargs)
return wrapper
@app.context_processor
def _inject_student_permissions():
try:
sid = get_current_student_id()
if sid is None:
return {"vault_enabled": False}
db = get_db()
return {"vault_enabled": bool(_student_can_use_vault(db, sid))}
except Exception:
return {"vault_enabled": False}
def ensure_faculty_vault_schema(db: sqlite3.Connection) -> None:
db.execute(
"""
CREATE TABLE IF NOT EXISTS faculty_vault_folders (
id INTEGER PRIMARY KEY,
faculty_id INTEGER NOT NULL,
name TEXT NOT NULL,
created_at TEXT NOT NULL,
UNIQUE(faculty_id, name),
FOREIGN KEY(faculty_id) REFERENCES faculty_users(id) ON DELETE CASCADE
)
"""
)
db.execute(
"""
CREATE TABLE IF NOT EXISTS faculty_vault_files (
id INTEGER PRIMARY KEY,
faculty_id INTEGER NOT NULL,
folder_id INTEGER NOT NULL,
original_name TEXT NOT NULL,
stored_path TEXT NOT NULL,
mime TEXT,
size_bytes INTEGER NOT NULL DEFAULT 0,
uploaded_at TEXT NOT NULL,
FOREIGN KEY(faculty_id) REFERENCES faculty_users(id) ON DELETE CASCADE,
FOREIGN KEY(folder_id) REFERENCES faculty_vault_folders(id) ON DELETE CASCADE
)
"""
)
def save_vault_file(upload, student_id: int) -> tuple[str, str, str, int] | None:
if upload is None:
return None
original = (upload.filename or "").strip()
if not original:
return None
safe = secure_filename(original)
if not safe:
return None
VAULT_UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
unique = f"{uuid.uuid4().hex}_{safe}"
abs_path = VAULT_UPLOAD_DIR / str(int(student_id)) / unique
abs_path.parent.mkdir(parents=True, exist_ok=True)
upload.save(str(abs_path))
rel_path = f"vault/{int(student_id)}/{unique}"
mime = (getattr(upload, "mimetype", None) or "").strip()
size_bytes = int(abs_path.stat().st_size) if abs_path.exists() else 0
return (rel_path, original, mime, size_bytes)
def get_vault_abs_path(stored_path: str) -> Path | None:
stored = (stored_path or "").strip()
if not stored.startswith("vault/"):
return None
return VAULT_UPLOAD_ROOT / stored
def delete_vault_physical_file(stored_path: str) -> None:
abs_path = get_vault_abs_path(stored_path)
if abs_path is None:
return
try: