-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmain.py
More file actions
1495 lines (1260 loc) · 59 KB
/
main.py
File metadata and controls
1495 lines (1260 loc) · 59 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
"""
Main Application Entry Point
Digi Kul Teachers Portal - Complete Route Refactor
"""
# Load environment variables from .env file
from dotenv import load_dotenv
load_dotenv()
from flask import Flask, request, jsonify, send_file, render_template, session, redirect, url_for, flash, make_response
from flask_cors import CORS
try:
from flask_socketio import SocketIO, emit, join_room, leave_room, rooms
except ImportError:
print("Flask-SocketIO not installed. Install with: pip install flask-socketio")
SocketIO = None
emit = join_room = leave_room = rooms = None
from werkzeug.utils import secure_filename
from werkzeug.security import generate_password_hash, check_password_hash
import os
import uuid
import json
import threading
import time
from datetime import datetime, timedelta
from functools import wraps
# Import configuration and utilities
from config import Config
from utils.database_supabase import SupabaseDatabaseManager as DatabaseManager
from utils.compression import compress_audio, compress_image, compress_pdf, get_file_type
# Import new modular components
from middlewares.auth_middleware import AuthMiddleware
from middlewares.cohort_middleware import CohortMiddleware
from services.cohort_service import CohortService
from services.lecture_service import LectureService
from services.quiz_service import QuizService
from services.session_recording_service import SessionRecordingService
from utils.email_service import EmailService
# Import route blueprints
from routes.auth_routes import auth_bp
from routes.cohort_routes import cohort_bp
from routes.lecture_routes import lecture_bp
from routes.quiz_routes import quiz_bp
from routes.super_admin_routes import super_admin_bp
from routes.institution_routes import institution_bp
from routes.institution_admin_routes import institution_admin_bp
from routes.teacher_routes import teacher_bp
from routes.student_routes import student_bp
from routes.chat_routes import chat_bp
from routes.admin_routes import admin_bp
# Initialize the database
db = DatabaseManager()
email_service = EmailService()
# Initialize services
cohort_service = CohortService(db, email_service)
lecture_service = LectureService(db, email_service)
quiz_service = QuizService(db, email_service)
recording_service = SessionRecordingService(db)
# Initialize middleware (will be properly initialized after app creation)
auth_middleware = None
cohort_middleware = None
app = Flask(__name__)
app.config.from_object(Config)
# Initialize middleware with the app
auth_middleware = AuthMiddleware(app, db)
cohort_middleware = CohortMiddleware(app, db)
# Set auth middleware reference in routes
from routes.super_admin_routes import set_auth_middleware
from routes.institution_routes import set_auth_middleware as set_institution_auth_middleware
from routes.teacher_routes import set_auth_middleware as set_teacher_auth_middleware
from routes.student_routes import set_auth_middleware as set_student_auth_middleware
set_auth_middleware(auth_middleware)
set_institution_auth_middleware(auth_middleware)
set_teacher_auth_middleware(auth_middleware)
set_student_auth_middleware(auth_middleware)
# Enhanced session security configuration
app.secret_key = os.environ.get('SECRET_KEY', 'your-secret-key-change-this')
app.permanent_session_lifetime = timedelta(hours=8)
app.config['SESSION_COOKIE_SECURE'] = False # Set to False for localhost testing
app.config['SESSION_COOKIE_HTTPONLY'] = True
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
app.config['SESSION_COOKIE_NAME'] = 'digi_kul_session'
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(hours=8)
# Additional security headers
@app.after_request
def set_security_headers(response):
"""Set security headers for all responses"""
# Prevent caching of sensitive pages
if request.endpoint and any(x in request.endpoint for x in ['dashboard', 'admin', 'teacher', 'student']):
response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate, private'
response.headers['Pragma'] = 'no-cache'
response.headers['Expires'] = '0'
# Security headers
response.headers['X-Content-Type-Options'] = 'nosniff'
response.headers['X-Frame-Options'] = 'DENY'
response.headers['X-XSS-Protection'] = '1; mode=block'
response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'
return response
CORS(app, origins="*", supports_credentials=True)
if SocketIO:
socketio = SocketIO(app, cors_allowed_origins="*", async_mode='threading')
else:
socketio = None
# Global session storage for active sessions
active_sessions = {}
session_participants = {}
online_users = {}
# Map user_id to socket_id for direct WebRTC signaling
user_socket_mapping = {}
def cleanup_session(session_id):
"""Clean up session data when session ends"""
if session_id in active_sessions:
del active_sessions[session_id]
if session_id in session_participants:
del session_participants[session_id]
# Ensure upload directories exist
os.makedirs(os.path.join(app.config['UPLOAD_FOLDER'], 'audio'), exist_ok=True)
os.makedirs(os.path.join(app.config['UPLOAD_FOLDER'], 'images'), exist_ok=True)
os.makedirs(os.path.join(app.config['UPLOAD_FOLDER'], 'documents'), exist_ok=True)
os.makedirs(os.path.join(app.config['COMPRESSED_FOLDER'], 'audio'), exist_ok=True)
os.makedirs(os.path.join(app.config['COMPRESSED_FOLDER'], 'images'), exist_ok=True)
os.makedirs(os.path.join(app.config['COMPRESSED_FOLDER'], 'documents'), exist_ok=True)
# ==================== BLUEPRINT REGISTRATION ====================
# Register blueprints with proper URL prefixes
app.register_blueprint(auth_bp, url_prefix='/api/auth')
app.register_blueprint(cohort_bp, url_prefix='/api/cohorts')
app.register_blueprint(lecture_bp, url_prefix='/api/lectures')
app.register_blueprint(quiz_bp, url_prefix='/api/quiz')
app.register_blueprint(super_admin_bp) # No prefix since it's already defined in the blueprint
app.register_blueprint(institution_bp, url_prefix='/institution')
app.register_blueprint(institution_admin_bp, url_prefix='/institution-admin')
app.register_blueprint(teacher_bp, url_prefix='/api/teacher')
app.register_blueprint(student_bp, url_prefix='/api/student')
app.register_blueprint(admin_bp, url_prefix='/api/admin')
app.register_blueprint(chat_bp, url_prefix='/api')
# Set session globals in teacher_routes so they reference the same objects
from routes.teacher_routes import set_session_globals
set_session_globals(active_sessions, session_participants, socketio)
print(f"[MAIN] Set session globals: active_sessions={id(active_sessions)}, participants={id(session_participants)}")
# ==================== MAIN APPLICATION ROUTES ====================
@app.route('/')
def index():
"""Main login page with institution selection"""
return render_template('index.html')
@app.route('/api/public/institutions', methods=['GET'])
def get_public_institutions():
"""Get all institutions for public display (no authentication required)"""
try:
institutions = db.get_all_institutions()
return jsonify({
'success': True,
'institutions': institutions,
'count': len(institutions) if institutions else 0
}), 200
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/login')
def login_page():
"""Main login page - redirects to appropriate login based on user type"""
return render_template('login.html')
# Super admin login route is handled by the super_admin_bp blueprint
@app.route('/institution/<subdomain>/login')
def institution_login_page(subdomain):
"""Institution-specific login page"""
try:
# Get institution details by subdomain
institution = db.get_institution_by_subdomain(subdomain)
if not institution:
return render_template('error.html',
error="Institution not found",
message=f"No institution found with subdomain: {subdomain}"), 404
return render_template('institution_login.html', institution=institution)
except Exception as e:
return render_template('error.html',
error="Error loading institution",
message=str(e)), 500
@app.route('/institution/<subdomain>/register')
def institution_student_registration(subdomain):
"""Institution-specific student registration page"""
try:
# Get institution details by subdomain
institution = db.get_institution_by_subdomain(subdomain)
if not institution:
return render_template('error.html',
error="Institution not found",
message=f"No institution found with subdomain: {subdomain}"), 404
return render_template('student_registration.html', institution=institution)
except Exception as e:
return render_template('error.html',
error="Error loading institution",
message=str(e)), 500
# Super admin dashboard route is handled by the super_admin_bp blueprint
@app.route('/institution-admin/dashboard')
@auth_middleware.institution_admin_required
def institution_admin_dashboard():
"""Institution admin dashboard"""
return render_template('institution_admin_dashboard.html')
@app.route('/teacher/dashboard')
@auth_middleware.teacher_required
def teacher_dashboard():
"""Teacher dashboard"""
return render_template('teacher_dashboard.html')
@app.route('/student/dashboard')
@auth_middleware.student_required
def student_dashboard():
"""Student dashboard"""
return render_template('student_dashboard.html')
# Removed generic admin dashboard - only super admin and institution admin exist
@app.route('/register')
def register_page():
"""Registration page"""
return render_template('register.html')
@app.route('/logout')
def logout_page():
"""Logout page"""
try:
user_id = session.get('user_id')
user_type = session.get('user_type')
# Remove from online users tracking
if user_id and user_id in online_users:
del online_users[user_id]
# Clear all session data
session.clear()
session.permanent = False
# Create response
response = make_response(render_template('logout.html'))
# Set session cookie to expire immediately
response.set_cookie(
app.config['SESSION_COOKIE_NAME'],
'',
expires=0,
secure=app.config['SESSION_COOKIE_SECURE'],
httponly=app.config['SESSION_COOKIE_HTTPONLY'],
samesite=app.config['SESSION_COOKIE_SAMESITE']
)
# Security headers
response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate, private'
response.headers['Pragma'] = 'no-cache'
response.headers['Expires'] = '0'
return response
except Exception as e:
return redirect(url_for('index'))
# ==================== LIVE SESSION ROUTES ====================
@app.route('/student/<student_id>')
@auth_middleware.student_required
def student_profile(student_id):
"""Student profile page"""
if session.get('user_id') != student_id and session.get('user_type') not in ['admin', 'teacher']:
flash('Access denied.', 'error')
return redirect(url_for('student_dashboard'))
return render_template('student_profile.html', student_id=student_id)
@app.route('/student/join_session/<session_id>')
@auth_middleware.student_required
def student_join_session(session_id):
"""Student join live session page"""
if session_id not in active_sessions:
flash('Session not found or has ended.', 'error')
return redirect(url_for('student_dashboard'))
session_info = active_sessions[session_id]
return render_template('student_live_session.html',
session_id=session_id,
lecture_id=session_info['lecture_id'])
@app.route('/teacher/manage_session/<session_id>')
@auth_middleware.teacher_required
def manage_session_page(session_id):
"""Manage live session page for teachers"""
if session_id not in active_sessions:
flash('Session not found.', 'error')
return redirect(url_for('teacher_dashboard'))
session_info = active_sessions[session_id]
if session_info['teacher_id'] != session['user_id']:
flash('Access denied.', 'error')
return redirect(url_for('teacher_dashboard'))
return render_template('teacher_live_session.html', lecture_id=session_info['lecture_id'])
# ==================== FILE DOWNLOAD ROUTES ====================
@app.route('/api/download/<material_id>')
@auth_middleware.api_auth_required
def download_material(material_id):
"""Download material file"""
try:
# Get material info from database
material = db.get_material_by_id(material_id)
if not material:
return jsonify({'error': 'Material not found'}), 404
# Check if user has access to this material
user_type = session.get('user_type')
user_id = session.get('user_id')
if user_type == 'student':
# Check if student is enrolled in cohorts that have this material
student_cohorts = db.get_student_cohorts(user_id)
cohort_ids = [c['id'] for c in student_cohorts]
if material['cohort_id'] not in cohort_ids:
return jsonify({'error': 'Access denied'}), 403
elif user_type == 'teacher':
# Check if teacher teaches cohorts that have this material
teacher_cohorts = db.get_teacher_cohorts(user_id)
cohort_ids = [c['id'] for c in teacher_cohorts]
if material['cohort_id'] not in cohort_ids:
return jsonify({'error': 'Access denied'}), 403
elif user_type not in ['admin', 'super_admin', 'institution_admin']:
return jsonify({'error': 'Access denied'}), 403
# Resolve download URL (handles Supabase signed URLs and local paths)
download_url, message = db.get_material_download_url(material_id)
if not download_url:
return jsonify({'error': f'Failed to get download URL: {message}'}), 404
# Increment download count
db.increment_material_download_count(material_id)
# If it's a Supabase Storage URL, redirect to it
if download_url.startswith('http'):
return redirect(download_url)
else:
# Fallback for local files with robust path resolution
raw_path = download_url
base_dir = app.config.get('UPLOAD_FOLDER', 'uploads')
filename = os.path.basename(raw_path.rstrip('/\\'))
# Map likely subfolders by type
file_type = (material.get('file_type') or '').lower()
type_folder = None
if file_type in ['pdf', 'doc', 'docx', 'ppt', 'pptx', 'txt']:
type_folder = 'documents'
elif file_type in ['jpg', 'jpeg', 'png', 'gif', 'webp']:
type_folder = 'images'
elif file_type in ['mp3', 'wav', 'm4a', 'aac']:
type_folder = 'audio'
candidates = []
# Absolute as-is
if os.path.isabs(raw_path):
candidates.append(raw_path)
# Relative variants
candidates.extend([
os.path.join(base_dir, raw_path),
os.path.join(base_dir, filename),
os.path.join(base_dir, 'materials', filename),
os.path.join(base_dir, 'documents', filename),
os.path.join(base_dir, 'images', filename),
os.path.join(base_dir, 'audio', filename),
os.path.join('materials', filename),
os.path.join('documents', filename),
os.path.join('images', filename),
os.path.join('audio', filename)
])
if type_folder:
candidates.insert(0, os.path.join(base_dir, type_folder, filename))
found_path = next((p for p in candidates if p and os.path.exists(p)), None)
if not found_path:
return jsonify({'error': 'File not found', 'tried': candidates}), 404
return send_file(
os.path.abspath(found_path),
as_attachment=True,
download_name=material.get('file_name', filename or 'material')
)
except Exception as e:
return jsonify({'error': str(e)}), 500
# ==================== RECORDING ROUTES ====================
@app.route('/api/recordings/start', methods=['POST'])
@auth_middleware.api_teacher_required
def start_recording():
"""Start recording a live session"""
try:
data = request.get_json()
session_id = data.get('session_id')
lecture_id = data.get('lecture_id')
if not session_id or not lecture_id:
return jsonify({'error': 'Session ID and Lecture ID required'}), 400
if session_id not in active_sessions:
return jsonify({'error': 'Session not found'}), 404
# Start recording
recording_id = recording_service.start_recording(
session_id=session_id,
lecture_id=lecture_id,
teacher_id=session['user_id']
)
if recording_id:
return jsonify({
'success': True,
'recording_id': recording_id,
'message': 'Recording started successfully'
}), 200
else:
return jsonify({'error': 'Failed to start recording'}), 500
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/recordings/stop', methods=['POST'])
@auth_middleware.api_teacher_required
def stop_recording():
"""Stop recording a live session"""
try:
data = request.get_json()
recording_id = data.get('recording_id')
if not recording_id:
return jsonify({'error': 'Recording ID required'}), 400
# Stop recording
success = recording_service.stop_recording(recording_id, session['user_id'])
if success:
return jsonify({
'success': True,
'message': 'Recording stopped successfully'
}), 200
else:
return jsonify({'error': 'Failed to stop recording'}), 500
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/recordings/status/<session_id>', methods=['GET'])
@auth_middleware.api_auth_required
def get_recording_status(session_id):
"""Get recording status for a session"""
try:
status = recording_service.get_recording_status(session_id)
return jsonify({
'success': True,
'recording_status': status
}), 200
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/lectures/<lecture_id>/recordings', methods=['GET'])
@auth_middleware.api_auth_required
def get_lecture_recordings(lecture_id):
"""Get all recordings for a lecture"""
try:
user_type = session.get('user_type')
user_id = session.get('user_id')
# Check access permissions
if user_type == 'student':
# Check if student has access to this lecture
student_cohorts = db.get_student_cohorts(user_id)
lecture = db.get_lecture_by_id(lecture_id)
if not lecture or lecture['cohort_id'] not in [c['id'] for c in student_cohorts]:
return jsonify({'error': 'Access denied'}), 403
elif user_type == 'teacher':
# Check if teacher teaches this lecture
lecture = db.get_lecture_by_id(lecture_id)
if not lecture or lecture['teacher_id'] != user_id:
return jsonify({'error': 'Access denied'}), 403
recordings = recording_service.get_lecture_recordings(lecture_id)
return jsonify({
'success': True,
'recordings': recordings
}), 200
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/recordings/<recording_id>', methods=['GET'])
@auth_middleware.api_auth_required
def get_recording(recording_id):
"""Get recording details and download link"""
try:
recording = recording_service.get_recording(recording_id)
if not recording:
return jsonify({'error': 'Recording not found'}), 404
# Check access permissions
user_type = session.get('user_type')
user_id = session.get('user_id')
if user_type == 'student':
# Check if student has access to this recording
student_cohorts = db.get_student_cohorts(user_id)
lecture = db.get_lecture_by_id(recording['lecture_id'])
if not lecture or lecture['cohort_id'] not in [c['id'] for c in student_cohorts]:
return jsonify({'error': 'Access denied'}), 403
elif user_type == 'teacher':
# Check if teacher owns this recording
if recording['teacher_id'] != user_id:
return jsonify({'error': 'Access denied'}), 403
return jsonify({
'success': True,
'recording': recording
}), 200
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/recordings/<recording_id>', methods=['DELETE'])
@auth_middleware.api_teacher_required
def delete_recording(recording_id):
"""Delete a recording"""
try:
recording = recording_service.get_recording(recording_id)
if not recording:
return jsonify({'error': 'Recording not found'}), 404
# Check if teacher owns this recording
if recording['teacher_id'] != session['user_id']:
return jsonify({'error': 'Access denied'}), 403
success = recording_service.delete_recording(recording_id)
if success:
return jsonify({
'success': True,
'message': 'Recording deleted successfully'
}), 200
else:
return jsonify({'error': 'Failed to delete recording'}), 500
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/recordings/cleanup', methods=['POST'])
@auth_middleware.api_auth_required
def cleanup_recordings():
"""Clean up old recordings (admin only)"""
try:
if session.get('user_type') not in ['admin', 'super_admin', 'institution_admin']:
return jsonify({'error': 'Admin access required'}), 403
cleaned_count = recording_service.cleanup_old_recordings()
return jsonify({
'success': True,
'message': f'Cleaned up {cleaned_count} old recordings'
}), 200
except Exception as e:
return jsonify({'error': str(e)}), 500
# ==================== SOCKET.IO EVENTS ====================
if socketio:
@socketio.on('connect')
def handle_connect():
"""Handle client connection"""
print(f'Client connected: {request.sid}')
# Initialize per-socket heartbeat metadata
session['last_heartbeat'] = datetime.now().isoformat()
# Track user_id to socket_id mapping for direct WebRTC signaling
user_id = session.get('user_id')
if user_id:
user_socket_mapping[user_id] = request.sid
print(f'[SOCKET_MAP] User {user_id} mapped to socket {request.sid}')
@socketio.on('disconnect')
def handle_disconnect():
"""Handle client disconnection"""
print(f'Client disconnected: {request.sid}')
# Clean up socket mapping
user_id = session.get('user_id')
if user_id and user_id in user_socket_mapping:
del user_socket_mapping[user_id]
print(f"[SOCKET_MAPPING] Removed mapping for user {user_id} on disconnect")
@socketio.on('heartbeat')
def handle_heartbeat(data):
"""Client heartbeat to measure RTT and keep session active.
Expects: { session_id, sent_at }
Returns ACK: { status, server_time, rtt_ms }
"""
try:
sent_at = data.get('sent_at')
session_id = data.get('session_id')
# Basic validation
if not session_id:
return {'status': 'error', 'message': 'session_id required'}
# Track last heartbeat for uptime metrics
session['last_heartbeat'] = datetime.now().isoformat()
# Compute RTT if client provided sent_at
rtt_ms = None
if sent_at:
try:
client_time = datetime.fromisoformat(sent_at)
rtt_ms = int((datetime.now() - client_time).total_seconds() * 1000)
except Exception:
rtt_ms = None
# Optionally accumulate RTT samples in active_sessions for health analytics
if session_id in active_sessions:
metrics = active_sessions[session_id].setdefault('metrics', {})
rtts = metrics.setdefault('rtt_samples', [])
if rtt_ms is not None:
rtts.append(rtt_ms)
if len(rtts) > 50: # cap list size
metrics['rtt_samples'] = rtts[-50:]
metrics['last_heartbeat'] = session['last_heartbeat']
return {
'status': 'ok',
'server_time': datetime.now().isoformat(),
'rtt_ms': rtt_ms
}
except Exception as e:
return {'status': 'error', 'message': str(e)}
@socketio.on('join_session')
def handle_join_session(data):
"""Handle joining a live session"""
session_id = data.get('session_id')
user_id = session.get('user_id')
user_type = session.get('user_type')
print(f"[JOIN_SESSION] Received request: session_id={session_id}, user_id={user_id}, user_type={user_type}")
print(f"[JOIN_SESSION] active_sessions object ID: {id(active_sessions)}")
print(f"[JOIN_SESSION] Active sessions: {list(active_sessions.keys())}")
if not session_id or not user_id:
error_msg = f"Invalid session or user: session_id={session_id}, user_id={user_id}"
print(f"[JOIN_SESSION] ERROR: {error_msg}")
# Also return ACK-style error for callers expecting a callback
emit('error', {'message': error_msg})
return {'status': 'error', 'message': error_msg}
if session_id not in active_sessions:
error_msg = f"Session not found: {session_id}. Active: {list(active_sessions.keys())}"
print(f"[JOIN_SESSION] ERROR: {error_msg}")
emit('error', {'message': 'Session not found', 'session_id': session_id, 'active_sessions': list(active_sessions.keys())})
return {'status': 'error', 'message': 'Session not found', 'session_id': session_id}
print(f"[JOIN_SESSION] User {user_id} joining session room: {session_id}")
# Join the session room
join_room(session_id)
# Track user_id to socket_id mapping for direct WebRTC signaling
user_socket_mapping[user_id] = request.sid
print(f"[SOCKET_MAPPING] User {user_id} mapped to socket {request.sid}")
# Add to session participants
if session_id not in session_participants:
session_participants[session_id] = []
# Resolve user_name if missing/placeholder
resolved_name = session.get('user_name')
if not resolved_name or resolved_name in ['Unknown', '', None]:
try:
if user_type == 'teacher':
teacher = db.get_teacher_by_id(user_id)
if teacher and teacher.get('name'):
resolved_name = teacher.get('name')
elif user_type == 'student':
student = db.get_student_by_id(user_id)
if student and student.get('name'):
resolved_name = student.get('name')
elif user_type == 'institution_admin':
admin = db.get_institution_admin_by_id(user_id)
if admin and admin.get('name'):
resolved_name = admin.get('name')
# Persist back
if resolved_name:
session['user_name'] = resolved_name
except Exception as _e:
# Keep placeholder if lookup fails
resolved_name = resolved_name or 'User'
participant = {
'user_id': user_id,
'user_type': user_type,
'user_name': resolved_name or 'User',
'name': resolved_name or 'User',
'joined_at': datetime.now().isoformat()
}
# Check if participant already exists and remove if so
session_participants[session_id] = [
p for p in session_participants[session_id] if p['user_id'] != user_id
]
session_participants[session_id].append(participant)
# Notify others in the session
emit('user_joined', {
**participant,
'participants_count': len(session_participants[session_id])
}, room=session_id, include_self=False)
# Send current participants to the new user
emit('session_participants', session_participants[session_id])
print(f"[JOIN_SESSION] SUCCESS: User {resolved_name or user_id} joined session {session_id}. Total participants: {len(session_participants[session_id])}")
# Return ACK payload for reliable clients using callbacks
return {
'status': 'ok',
'session_id': session_id,
'participants': session_participants[session_id],
'participant_count': len(session_participants[session_id])
}
@socketio.on('leave_session')
def handle_leave_session(data):
"""Handle leaving a live session"""
session_id = data.get('session_id')
user_id = session.get('user_id')
user_name = session.get('user_name', 'Unknown')
if session_id and user_id:
leave_room(session_id)
# Remove from socket mapping
if user_id in user_socket_mapping:
del user_socket_mapping[user_id]
print(f"[SOCKET_MAPPING] Removed mapping for user {user_id}")
# Remove from session participants
if session_id in session_participants:
session_participants[session_id] = [
p for p in session_participants[session_id]
if p['user_id'] != user_id
]
# Notify others in the session
emit('user_left', {
'user_id': user_id,
'user_name': user_name,
'participants_count': len(session_participants.get(session_id, []))
}, room=session_id, include_self=False)
@socketio.on('session_message')
def handle_session_message(data):
"""Handle messages in live session"""
session_id = data.get('session_id')
message = data.get('message')
user_id = session.get('user_id')
user_name = session.get('user_name', 'Unknown')
if not session_id or not message or not user_id:
emit('error', {'message': 'Invalid message data'})
return
if session_id not in active_sessions:
emit('error', {'message': 'Session not found'})
return
# Broadcast message to all participants in the session
message_data = {
'user_id': user_id,
'user_name': user_name,
'message': message,
'timestamp': datetime.now().isoformat()
}
emit('session_message', message_data, room=session_id, include_self=False)
@socketio.on('chat_message')
def handle_chat_message(data):
"""Handle chat messages in live session"""
session_id = data.get('session_id')
message = data.get('message')
user_id = session.get('user_id')
user_name = session.get('user_name', 'Unknown')
if not session_id or not message or not user_id:
emit('error', {'message': 'Invalid message data'})
return
if session_id not in active_sessions:
emit('error', {'message': 'Session not found'})
return
print(f"Chat message from {user_name} in session {session_id}: {message}")
# Store message in database
try:
# Get lecture ID from session
lecture_id = active_sessions.get(session_id, {}).get('lecture_id')
if lecture_id:
# Store in discussion_posts table
db.create_discussion_post(
institution_id=session.get('institution_id'),
forum_id=lecture_id,
author_id=user_id,
author_type=session.get('user_type', 'student'),
content=message
)
print(f"Chat message stored in database for lecture {lecture_id}")
except Exception as e:
print(f"Error storing chat message: {e}")
# Broadcast message to all participants in the session
message_data = {
'user_id': user_id,
'user_name': user_name,
'message': message,
'timestamp': datetime.now().isoformat()
}
emit('chat_message', message_data, room=session_id, include_self=False)
print(f"Chat message broadcasted to session {session_id}")
@socketio.on('whiteboard_draw')
def handle_whiteboard_draw(data):
"""Handle whiteboard drawing events"""
session_id = data.get('session_id')
user_id = session.get('user_id')
user_name = session.get('user_name', 'Unknown')
if not session_id or not user_id:
emit('error', {'message': 'Invalid whiteboard data'})
return
if session_id not in active_sessions:
emit('error', {'message': 'Session not found'})
return
# Broadcast drawing data to all participants
drawing_data = {
'user_id': user_id,
'user_name': user_name,
'drawing_data': data.get('drawing_data'),
'timestamp': datetime.now().isoformat()
}
emit('whiteboard_draw', drawing_data, room=session_id, include_self=False)
print(f"Whiteboard drawing from {user_name} broadcasted to session {session_id}")
@socketio.on('whiteboard_clear')
def handle_whiteboard_clear(data):
"""Handle whiteboard clear events"""
session_id = data.get('session_id')
user_id = session.get('user_id')
user_name = session.get('user_name', 'Unknown')
if not session_id or not user_id:
emit('error', {'message': 'Invalid whiteboard data'})
return
if session_id not in active_sessions:
emit('error', {'message': 'Session not found'})
return
# Broadcast clear event to all participants
clear_data = {
'user_id': user_id,
'user_name': user_name,
'timestamp': datetime.now().isoformat()
}
emit('whiteboard_clear', clear_data, room=session_id, include_self=False)
print(f"Whiteboard cleared by {user_name} in session {session_id}")
@socketio.on('screen_share_started')
def handle_screen_share_started(data):
"""Handle screen sharing started events"""
session_id = data.get('session_id')
user_id = session.get('user_id')
user_name = session.get('user_name', 'Unknown')
if not session_id or not user_id:
emit('error', {'message': 'Invalid screen share data'})
return
if session_id not in active_sessions:
emit('error', {'message': 'Session not found'})
return
# Broadcast screen share event to all participants
share_data = {
'user_id': user_id,
'user_name': user_name,
'timestamp': datetime.now().isoformat()
}
emit('screen_share_started', share_data, room=session_id, include_self=False)
print(f"Screen share started by {user_name} in session {session_id}")
@socketio.on('screen_share_stopped')
def handle_screen_share_stopped(data):
"""Handle screen sharing stopped events"""
session_id = data.get('session_id')
user_id = session.get('user_id')
user_name = session.get('user_name', 'Unknown')
if not session_id or not user_id:
emit('error', {'message': 'Invalid screen share data'})
return
if session_id not in active_sessions:
emit('error', {'message': 'Session not found'})
return
# Broadcast screen share stopped event to all participants
share_data = {
'user_id': user_id,
'user_name': user_name,
'timestamp': datetime.now().isoformat()
}
emit('screen_share_stopped', share_data, room=session_id, include_self=False)
print(f"Screen share stopped by {user_name} in session {session_id}")
# WebRTC signaling events
@socketio.on('webrtc_offer')
def handle_webrtc_offer(data):
"""Relay WebRTC offer from one peer to another"""
session_id = data.get('session_id')
target_user_id = data.get('target_user_id')
offer = data.get('offer')
sender_id = session.get('user_id')
sender_name = session.get('user_name', 'Unknown')
if not session_id or not offer:
print(f"WebRTC offer missing session_id or offer data")
emit('error', {'message': 'Invalid WebRTC offer data'})
return
if session_id not in active_sessions:
print(f"WebRTC offer: session {session_id} not found in active_sessions")
emit('error', {'message': 'Session not found'})
return
print(f"[WEBRTC_OFFER] From {sender_name} (user_id: {sender_id}) in session {session_id}")
# Relay offer to target user or broadcast to all in session
relay_data = {
'session_id': session_id,
'from_user_id': sender_id, # Use from_user_id to match template expectations
'user_name': sender_name,
'offer': offer,
'timestamp': datetime.now().isoformat()
}
if target_user_id:
# Direct offer to specific user using socket mapping
relay_data['target_user_id'] = target_user_id
target_socket_id = user_socket_mapping.get(target_user_id)
if target_socket_id:
emit('webrtc_offer', relay_data, to=target_socket_id)
print(f"[WEBRTC_RELAY] Sent offer directly to socket {target_socket_id} (user {target_user_id})")
else: