-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
7057 lines (5871 loc) · 284 KB
/
app.py
File metadata and controls
7057 lines (5871 loc) · 284 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 os
import sqlite3
import logging
from datetime import datetime, timedelta
from functools import wraps
from werkzeug.security import generate_password_hash, check_password_hash
from werkzeug.utils import secure_filename
from flask import Flask, render_template, request, redirect, url_for, flash, jsonify, session, send_from_directory, send_file
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
from flask_socketio import SocketIO, emit, join_room, leave_room, rooms
from flask_caching import Cache
from flask_mail import Mail, Message
from threading import Lock
import json
import uuid
from dotenv import load_dotenv
import gemini_ai
from pytubefix import YouTube
import shutil
# Load environment variables
load_dotenv()
# Initialize Flask app
app = Flask(__name__)
app.config['SECRET_KEY'] = os.environ.get('SESSION_SECRET') or 'dev-secret-key-change-in-production'
# Use paths relative to the app file location
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
app.config['UPLOAD_FOLDER'] = os.path.join(BASE_DIR, 'sir_rafique', 'uploads')
app.config['MAX_CONTENT_LENGTH'] = None # No file size limit for videos
# Database configuration
DATABASE = os.path.join(BASE_DIR, 'sir_rafique', 'learnnest.db')
# Initialize extensions
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login' # type: ignore
login_manager.login_message = 'Please log in to access this page.'
socketio = SocketIO(app, cors_allowed_origins="*", async_mode='threading')
# Initialize caching
cache = Cache(app, config={'CACHE_TYPE': 'simple'})
# Initialize mail
mail = Mail(app)
# Register custom Jinja filters and globals
@app.template_filter('nl2br')
def nl2br_filter(s):
"""Convert newlines to HTML line breaks"""
if s is None:
return ''
return str(s).replace('\n', '<br>\n')
# Add custom Jinja2 global functions
@app.template_global()
def max_func(*args):
"""Max function for Jinja2 templates"""
return max(args)
@app.template_global()
def min_func(*args):
"""Min function for Jinja2 templates"""
return min(args)
# CSRF protection helpers
import secrets
import hashlib
def generate_csrf_token():
"""Generate a CSRF token for forms"""
token = secrets.token_urlsafe(32)
session['csrf_token'] = token
return token
def validate_csrf_token(token):
"""Validate CSRF token"""
if not token or token != session.get('csrf_token'):
return False
return True
@app.context_processor
def inject_csrf_token():
"""Make CSRF token available in all templates"""
if 'csrf_token' not in session:
session['csrf_token'] = secrets.token_urlsafe(32)
return dict(csrf_token=session['csrf_token'])
# Thread lock for database operations
db_lock = Lock()
# Create uploads directory
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
os.makedirs(os.path.join(app.config['UPLOAD_FOLDER'], 'assignments'), exist_ok=True)
os.makedirs(os.path.join(app.config['UPLOAD_FOLDER'], 'resources'), exist_ok=True)
os.makedirs(os.path.join(app.config['UPLOAD_FOLDER'], 'payments'), exist_ok=True)
os.makedirs(os.path.join(app.config['UPLOAD_FOLDER'], 'instructor_screenshots'), exist_ok=True)
os.makedirs(os.path.join(app.config['UPLOAD_FOLDER'], 'transcripts'), exist_ok=True)
os.makedirs(os.path.join(app.config['UPLOAD_FOLDER'], 'chat_files'), exist_ok=True)
os.makedirs(os.path.join(app.config['UPLOAD_FOLDER'], 'chat_images'), exist_ok=True)
os.makedirs(os.path.join(app.config['UPLOAD_FOLDER'], 'direct_messages'), exist_ok=True)
os.makedirs(os.path.join(app.config['UPLOAD_FOLDER'], 'forum_media'), exist_ok=True)
os.makedirs(os.path.join(app.config['UPLOAD_FOLDER'], 'profile_pictures'), exist_ok=True)
# File size limits (in bytes)
MAX_CHAT_FILE_SIZE = 100 * 1024 * 1024 # 100 MB per file
MAX_TOTAL_STORAGE_PER_USER = 5 * 1024 * 1024 * 1024 # 5 GB per user
ALLOWED_FILE_TYPES = {
'pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'txt',
'jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg',
'zip', 'rar', '7z', 'tar', 'gz',
'mp4', 'mov', 'avi', 'mkv', 'webm', 'flv',
'mp3', 'wav', 'ogg', 'm4a',
'csv', 'json', 'xml', 'html', 'css', 'js', 'py', 'java', 'cpp', 'c', 'h'
}
# Database connection helper
def get_db_connection():
conn = sqlite3.connect(DATABASE, timeout=30)
conn.execute('PRAGMA journal_mode=WAL;')
conn.execute('PRAGMA synchronous=NORMAL;')
conn.execute('PRAGMA cache_size=10000;')
conn.execute('PRAGMA temp_store=MEMORY;')
conn.row_factory = sqlite3.Row
return conn
def send_notification(user_id, title, message, notification_type='info', related_id=None):
"""Helper function to send notifications to students"""
try:
conn = get_db_connection()
conn.execute('''
INSERT INTO notifications (user_id, title, message, type, related_id, created_at)
VALUES (?, ?, ?, ?, ?, ?)
''', (user_id, title, message, notification_type, related_id, datetime.now()))
conn.commit()
conn.close()
# Emit real-time notification via SocketIO
socketio.emit('notification', {
'title': title,
'message': message,
'type': notification_type
}, to=f'user_{user_id}')
return True
except Exception as e:
logging.error(f"Error sending notification: {e}")
return False
def update_student_progress(conn, student_id, course_id):
"""
Calculate and update student progress for a course based on quiz completions
Progress = (Number of Submitted Quizzes / Total Quizzes) * 100
Note: If manual_progress_override is set by instructor, automatic progress is still calculated and stored
but the manual override value takes precedence for display
"""
try:
# Check if instructor has set manual progress override
enrollment = conn.execute('''
SELECT manual_progress_override
FROM enrollments
WHERE student_id = ? AND course_id = ?
''', (student_id, course_id)).fetchone()
has_manual_override = enrollment and enrollment['manual_progress_override'] is not None
# Get total number of quizzes for this course
total_quizzes = conn.execute('''
SELECT COUNT(*) as count
FROM assignments
WHERE course_id = ? AND assignment_type = 'quiz' AND is_active = 1
''', (course_id,)).fetchone()['count']
if total_quizzes == 0:
# No quizzes, set progress to 0
auto_progress = 0
else:
# Get number of submitted quizzes by student
submitted_quizzes = conn.execute('''
SELECT COUNT(DISTINCT a.id) as count
FROM assignments a
INNER JOIN assignment_submissions sub ON a.id = sub.assignment_id
WHERE a.course_id = ?
AND a.assignment_type = 'quiz'
AND a.is_active = 1
AND sub.student_id = ?
''', (course_id, student_id)).fetchone()['count']
# Calculate progress percentage
auto_progress = (submitted_quizzes / total_quizzes) * 100
# Always update progress_percentage with automatic calculation
# This keeps it in sync even when manual override is active
conn.execute('''
UPDATE enrollments
SET progress_percentage = ?
WHERE student_id = ? AND course_id = ?
''', (auto_progress, student_id, course_id))
conn.commit()
# Return manual override if set, otherwise return automatic progress
if has_manual_override:
return enrollment['manual_progress_override']
else:
return auto_progress
except Exception as e:
print(f"Error updating student progress: {e}")
return 0
# User class for Flask-Login
class User(UserMixin):
def __init__(self, id, username, email, role, full_name, created_at, active_status=True,
instructor_approval_status='approved', approved_by=None, approved_at=None, profile_picture=None):
self.id = id
self.username = username
self.email = email
self.role = role
self.full_name = full_name
self.created_at = created_at
self._is_active = active_status
self.instructor_approval_status = instructor_approval_status
self.approved_by = approved_by
self.approved_at = approved_at
self.profile_picture = profile_picture
def get_id(self):
return str(self.id)
def is_admin(self):
return self.role == 'admin'
def is_instructor(self):
return self.role == 'instructor'
def is_student(self):
return self.role == 'student'
def is_instructor_approved(self):
"""Check if instructor is approved to access instructor features"""
if not self.is_instructor():
return True # Non-instructors don't need approval
return self.instructor_approval_status == 'approved'
def is_instructor_pending(self):
"""Check if instructor is pending approval"""
return self.is_instructor() and self.instructor_approval_status == 'pending'
def is_instructor_rejected(self):
"""Check if instructor was rejected"""
return self.is_instructor() and self.instructor_approval_status == 'rejected'
@login_manager.user_loader
def load_user(user_id):
try:
with db_lock:
conn = get_db_connection()
user = conn.execute(
'SELECT * FROM users WHERE id = ? AND is_active = 1', (user_id,)
).fetchone()
conn.close()
if user:
profile_pic = user['profile_picture'] if 'profile_picture' in user.keys() else None
return User(user['id'], user['username'], user['email'], user['role'],
user['full_name'], user['created_at'], user['is_active'],
user['instructor_approval_status'] if user['instructor_approval_status'] else 'approved',
user['approved_by'],
user['approved_at'],
profile_pic)
except sqlite3.OperationalError:
# Database not yet initialized
pass
return None
# Role-based access control decorators
def admin_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if not current_user.is_authenticated or not current_user.is_admin():
flash('Access denied. Admin privileges required.', 'error')
return redirect(url_for('dashboard'))
return f(*args, **kwargs)
return decorated_function
def instructor_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if not current_user.is_authenticated:
flash('Access denied. Please log in.', 'error')
return redirect(url_for('login'))
# Admins always have access to instructor features
if current_user.is_admin():
return f(*args, **kwargs)
# Check if user is instructor
if not current_user.is_instructor():
flash('Access denied. Instructor privileges required.', 'error')
return redirect(url_for('dashboard'))
# Check if instructor is approved
if not current_user.is_instructor_approved():
flash('Your instructor account is pending approval. Please wait for admin approval.', 'warning')
return redirect(url_for('dashboard'))
return f(*args, **kwargs)
return decorated_function
# Database initialization
def init_db():
print("🔄 Initializing database...")
with db_lock:
try:
conn = get_db_connection()
# Users table
conn.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
email TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'student',
full_name TEXT NOT NULL,
bio TEXT,
profile_image TEXT,
instructor_approval_status TEXT DEFAULT 'approved',
approved_by INTEGER,
approved_at TIMESTAMP,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
last_login TIMESTAMP,
is_active BOOLEAN DEFAULT 1,
FOREIGN KEY (approved_by) REFERENCES users (id)
)
''')
# Add columns if they don't exist
try:
conn.execute('ALTER TABLE users ADD COLUMN instructor_approval_status TEXT DEFAULT "approved"')
except sqlite3.OperationalError:
pass
try:
conn.execute('ALTER TABLE users ADD COLUMN approved_by INTEGER')
except sqlite3.OperationalError:
pass
try:
conn.execute('ALTER TABLE users ADD COLUMN approved_at TIMESTAMP')
except sqlite3.OperationalError:
pass
try:
conn.execute('ALTER TABLE courses ADD COLUMN enrollment_key_hash TEXT')
except sqlite3.OperationalError:
pass
try:
conn.execute('ALTER TABLE users ADD COLUMN instructor_screenshot TEXT')
except sqlite3.OperationalError:
pass
# Courses table
conn.execute('''
CREATE TABLE IF NOT EXISTS courses (
id INTEGER PRIMARY KEY AUTOINCREMENT,
course_code TEXT UNIQUE NOT NULL,
title TEXT NOT NULL,
description TEXT,
syllabus TEXT,
instructor_id INTEGER NOT NULL,
category TEXT,
max_students INTEGER DEFAULT 50,
start_date DATE,
end_date DATE,
enrollment_key_hash TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
is_active BOOLEAN DEFAULT 1,
FOREIGN KEY (instructor_id) REFERENCES users (id)
)
''')
# Enrollments table
conn.execute('''
CREATE TABLE IF NOT EXISTS enrollments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
student_id INTEGER NOT NULL,
course_id INTEGER NOT NULL,
status TEXT NOT NULL DEFAULT 'pending',
payment_screenshot TEXT,
enrolled_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
approved_at TIMESTAMP,
progress_percentage REAL DEFAULT 0,
manual_progress_override REAL DEFAULT NULL,
FOREIGN KEY (student_id) REFERENCES users (id),
FOREIGN KEY (course_id) REFERENCES courses (id),
UNIQUE(student_id, course_id)
)
''')
# Add manual_progress_override column if it doesn't exist
try:
conn.execute('ALTER TABLE enrollments ADD COLUMN manual_progress_override REAL DEFAULT NULL')
except sqlite3.OperationalError:
pass
# Assignments table
conn.execute('''
CREATE TABLE IF NOT EXISTS assignments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
course_id INTEGER NOT NULL,
title TEXT NOT NULL,
description TEXT,
instructions TEXT,
due_date DATETIME,
max_points INTEGER DEFAULT 100,
allow_late_submission BOOLEAN DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (course_id) REFERENCES courses (id)
)
''')
# Add new columns to assignments table for advanced features
try:
conn.execute('ALTER TABLE assignments ADD COLUMN assignment_type TEXT DEFAULT "quiz"')
except sqlite3.OperationalError:
pass
try:
conn.execute('ALTER TABLE assignments ADD COLUMN status TEXT DEFAULT "draft"')
except sqlite3.OperationalError:
pass
try:
conn.execute('ALTER TABLE assignments ADD COLUMN published_at TIMESTAMP')
except sqlite3.OperationalError:
pass
try:
conn.execute('ALTER TABLE assignments ADD COLUMN ai_context TEXT')
except sqlite3.OperationalError:
pass
# Assignment assets table for file uploads
conn.execute('''
CREATE TABLE IF NOT EXISTS assignment_assets (
id INTEGER PRIMARY KEY AUTOINCREMENT,
assignment_id INTEGER NOT NULL,
file_name TEXT NOT NULL,
file_path TEXT NOT NULL,
file_type TEXT,
file_size INTEGER,
uploaded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (assignment_id) REFERENCES assignments (id)
)
''')
# Assignment submissions table
conn.execute('''
CREATE TABLE IF NOT EXISTS assignment_submissions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
assignment_id INTEGER NOT NULL,
student_id INTEGER NOT NULL,
submission_text TEXT,
file_path TEXT,
submitted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
grade REAL,
ai_feedback TEXT,
instructor_feedback TEXT,
graded_at TIMESTAMP,
FOREIGN KEY (assignment_id) REFERENCES assignments (id),
FOREIGN KEY (student_id) REFERENCES users (id),
UNIQUE(assignment_id, student_id)
)
''')
# Quiz questions table
conn.execute('''
CREATE TABLE IF NOT EXISTS quiz_questions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
assignment_id INTEGER NOT NULL,
question_text TEXT NOT NULL,
question_type TEXT NOT NULL DEFAULT 'mcq',
points INTEGER DEFAULT 1,
correct_answer TEXT,
explanation TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (assignment_id) REFERENCES assignments (id)
)
''')
# Question options table
conn.execute('''
CREATE TABLE IF NOT EXISTS question_options (
id INTEGER PRIMARY KEY AUTOINCREMENT,
question_id INTEGER NOT NULL,
option_letter TEXT NOT NULL,
option_text TEXT NOT NULL,
is_correct BOOLEAN DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (question_id) REFERENCES quiz_questions (id)
)
''')
# Student MCQ answers table
conn.execute('''
CREATE TABLE IF NOT EXISTS student_mcq_answers (
id INTEGER PRIMARY KEY AUTOINCREMENT,
submission_id INTEGER NOT NULL,
question_id INTEGER NOT NULL,
selected_option TEXT,
is_correct BOOLEAN,
points_earned REAL DEFAULT 0,
answered_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (submission_id) REFERENCES assignment_submissions (id),
FOREIGN KEY (question_id) REFERENCES quiz_questions (id),
UNIQUE(submission_id, question_id)
)
''')
# Forums table
conn.execute('''
CREATE TABLE IF NOT EXISTS forums (
id INTEGER PRIMARY KEY AUTOINCREMENT,
course_id INTEGER NOT NULL,
title TEXT NOT NULL,
description TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
is_active BOOLEAN DEFAULT 1,
FOREIGN KEY (course_id) REFERENCES courses (id)
)
''')
# Forum topics table
conn.execute('''
CREATE TABLE IF NOT EXISTS forum_topics (
id INTEGER PRIMARY KEY AUTOINCREMENT,
forum_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
title TEXT NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
is_pinned BOOLEAN DEFAULT 0,
view_count INTEGER DEFAULT 0,
FOREIGN KEY (forum_id) REFERENCES forums (id),
FOREIGN KEY (user_id) REFERENCES users (id)
)
''')
# Forum replies table
conn.execute('''
CREATE TABLE IF NOT EXISTS forum_replies (
id INTEGER PRIMARY KEY AUTOINCREMENT,
topic_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
is_ai_generated BOOLEAN DEFAULT 0,
FOREIGN KEY (topic_id) REFERENCES forum_topics (id),
FOREIGN KEY (user_id) REFERENCES users (id)
)
''')
# Chat messages table
conn.execute('''
CREATE TABLE IF NOT EXISTS chat_messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
course_id INTEGER,
sender_id INTEGER NOT NULL,
recipient_id INTEGER,
message TEXT NOT NULL,
message_type TEXT DEFAULT 'text',
file_path TEXT,
file_name TEXT,
file_size INTEGER DEFAULT 0,
is_image BOOLEAN DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
is_read BOOLEAN DEFAULT 0,
FOREIGN KEY (course_id) REFERENCES courses (id),
FOREIGN KEY (sender_id) REFERENCES users (id),
FOREIGN KEY (recipient_id) REFERENCES users (id)
)
''')
# Direct messages table
conn.execute('''
CREATE TABLE IF NOT EXISTS direct_messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
sender_id INTEGER NOT NULL,
recipient_id INTEGER NOT NULL,
message TEXT NOT NULL,
message_type TEXT DEFAULT 'text',
file_path TEXT,
file_name TEXT,
is_image BOOLEAN DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
is_read BOOLEAN DEFAULT 0,
FOREIGN KEY (sender_id) REFERENCES users (id),
FOREIGN KEY (recipient_id) REFERENCES users (id)
)
''')
# File uploads table
conn.execute('''
CREATE TABLE IF NOT EXISTS file_uploads (
id INTEGER PRIMARY KEY AUTOINCREMENT,
uploader_id INTEGER NOT NULL,
file_name TEXT NOT NULL,
file_path TEXT NOT NULL,
file_size INTEGER,
file_type TEXT,
message_id INTEGER,
direct_message_id INTEGER,
forum_reply_id INTEGER,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (uploader_id) REFERENCES users (id),
FOREIGN KEY (message_id) REFERENCES chat_messages (id),
FOREIGN KEY (direct_message_id) REFERENCES direct_messages (id),
FOREIGN KEY (forum_reply_id) REFERENCES forum_replies (id)
)
''')
# Notifications table
conn.execute('''
CREATE TABLE IF NOT EXISTS notifications (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
title TEXT NOT NULL,
message TEXT NOT NULL,
type TEXT DEFAULT 'info',
related_id INTEGER,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
is_read BOOLEAN DEFAULT 0,
FOREIGN KEY (user_id) REFERENCES users (id)
)
''')
# Course resources table
conn.execute('''
CREATE TABLE IF NOT EXISTS course_resources (
id INTEGER PRIMARY KEY AUTOINCREMENT,
course_id INTEGER NOT NULL,
title TEXT NOT NULL,
description TEXT,
file_path TEXT,
file_type TEXT,
upload_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
uploaded_by INTEGER NOT NULL,
FOREIGN KEY (course_id) REFERENCES courses (id),
FOREIGN KEY (uploaded_by) REFERENCES users (id)
)
''')
# Course meeting links table
conn.execute('''
CREATE TABLE IF NOT EXISTS course_meeting_links (
id INTEGER PRIMARY KEY AUTOINCREMENT,
course_id INTEGER NOT NULL,
title TEXT NOT NULL,
meeting_link TEXT NOT NULL,
description TEXT,
scheduled_time TIMESTAMP,
created_by INTEGER NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
is_active BOOLEAN DEFAULT 1,
FOREIGN KEY (course_id) REFERENCES courses (id),
FOREIGN KEY (created_by) REFERENCES users (id)
)
''')
# Course video playlists table
conn.execute('''
CREATE TABLE IF NOT EXISTS course_video_playlists (
id INTEGER PRIMARY KEY AUTOINCREMENT,
course_id INTEGER NOT NULL,
title TEXT NOT NULL,
video_url TEXT NOT NULL,
description TEXT,
thumbnail_url TEXT,
duration TEXT,
notes_file_path TEXT,
order_index INTEGER DEFAULT 0,
created_by INTEGER NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
is_active BOOLEAN DEFAULT 1,
FOREIGN KEY (course_id) REFERENCES courses (id),
FOREIGN KEY (created_by) REFERENCES users (id)
)
''')
# Add transcript column if needed
try:
conn.execute('ALTER TABLE course_video_playlists ADD COLUMN transcript_file_path TEXT')
except sqlite3.OperationalError:
pass
# Student video playlists table
conn.execute('''
CREATE TABLE IF NOT EXISTS student_video_playlists (
id INTEGER PRIMARY KEY AUTOINCREMENT,
student_id INTEGER NOT NULL,
title TEXT NOT NULL,
video_url TEXT NOT NULL,
description TEXT,
thumbnail_url TEXT,
duration TEXT,
order_index INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
is_active BOOLEAN DEFAULT 1,
FOREIGN KEY (student_id) REFERENCES users (id)
)
''')
# AI Notes table
conn.execute('''
CREATE TABLE IF NOT EXISTS ai_notes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
course_id INTEGER NOT NULL,
topic TEXT NOT NULL,
content TEXT NOT NULL,
pdf_path TEXT,
created_by INTEGER NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
is_instructor_note BOOLEAN DEFAULT 0,
sent_to_students BOOLEAN DEFAULT 0,
FOREIGN KEY (course_id) REFERENCES courses (id),
FOREIGN KEY (created_by) REFERENCES users (id)
)
''')
# Add media columns to forum_topics if needed
try:
conn.execute('ALTER TABLE forum_topics ADD COLUMN media_type TEXT')
except sqlite3.OperationalError:
pass
try:
conn.execute('ALTER TABLE forum_topics ADD COLUMN media_path TEXT')
except sqlite3.OperationalError:
pass
try:
conn.execute('ALTER TABLE forum_topics ADD COLUMN media_filename TEXT')
except sqlite3.OperationalError:
pass
# Add media columns to forum_replies if needed
try:
conn.execute('ALTER TABLE forum_replies ADD COLUMN media_type TEXT')
except sqlite3.OperationalError:
pass
try:
conn.execute('ALTER TABLE forum_replies ADD COLUMN media_path TEXT')
except sqlite3.OperationalError:
pass
try:
conn.execute('ALTER TABLE forum_replies ADD COLUMN media_filename TEXT')
except sqlite3.OperationalError:
pass
# Create indexes
conn.execute('CREATE INDEX IF NOT EXISTS idx_users_email ON users(email)')
conn.execute('CREATE INDEX IF NOT EXISTS idx_users_role ON users(role)')
conn.execute('CREATE INDEX IF NOT EXISTS idx_users_approval_status ON users(instructor_approval_status)')
conn.execute('CREATE INDEX IF NOT EXISTS idx_enrollments_student ON enrollments(student_id)')
conn.execute('CREATE INDEX IF NOT EXISTS idx_enrollments_course ON enrollments(course_id)')
conn.execute('CREATE INDEX IF NOT EXISTS idx_assignments_course ON assignments(course_id)')
conn.execute('CREATE INDEX IF NOT EXISTS idx_submissions_assignment ON assignment_submissions(assignment_id)')
conn.execute('CREATE INDEX IF NOT EXISTS idx_quiz_questions_assignment ON quiz_questions(assignment_id)')
conn.execute('CREATE INDEX IF NOT EXISTS idx_question_options_question ON question_options(question_id)')
conn.execute('CREATE INDEX IF NOT EXISTS idx_student_answers_submission ON student_mcq_answers(submission_id)')
conn.execute('CREATE INDEX IF NOT EXISTS idx_student_answers_question ON student_mcq_answers(question_id)')
conn.execute('CREATE INDEX IF NOT EXISTS idx_chat_course ON chat_messages(course_id)')
conn.execute('CREATE INDEX IF NOT EXISTS idx_notifications_user ON notifications(user_id)')
conn.execute('CREATE INDEX IF NOT EXISTS idx_meeting_links_course ON course_meeting_links(course_id)')
conn.execute('CREATE INDEX IF NOT EXISTS idx_video_playlists_course ON course_video_playlists(course_id)')
# Create default admin user
admin_exists = conn.execute('SELECT id FROM users WHERE role = "admin"').fetchone()
if not admin_exists:
admin_password = generate_password_hash('admin123')
conn.execute('''
INSERT INTO users (username, email, password_hash, role, full_name, bio)
VALUES (?, ?, ?, ?, ?, ?)
''', ('admin', 'admin@learnnest.com', admin_password, 'admin',
'System Administrator', 'Default system administrator account'))
conn.commit()
conn.close()
print("✅ Database initialized successfully!")
return True
except Exception as e:
print(f"❌ Database initialization error: {e}")
import traceback
traceback.print_exc()
return False
# Routes
@app.route('/')
def index():
if current_user.is_authenticated:
return redirect(url_for('dashboard'))
return redirect(url_for('login'))
@app.route('/login', methods=['GET', 'POST'])
def login():
if current_user.is_authenticated:
return redirect(url_for('dashboard'))
if request.method == 'POST':
# Validate CSRF token
csrf_token = request.form.get('csrf_token')
if not validate_csrf_token(csrf_token):
flash('Invalid security token. Please try again.', 'error')
return render_template('auth/login.html')
email = request.form['email'].lower().strip()
password = request.form['password']
remember = bool(request.form.get('remember'))
with db_lock:
conn = get_db_connection()
user = conn.execute(
'SELECT * FROM users WHERE email = ? AND is_active = 1', (email,)
).fetchone()
conn.close()
if user and check_password_hash(user['password_hash'], password):
# Update last login
with db_lock:
conn = get_db_connection()
conn.execute(
'UPDATE users SET last_login = CURRENT_TIMESTAMP WHERE id = ?', (user['id'],)
)
conn.commit()
conn.close()
user_obj = User(user['id'], user['username'], user['email'], user['role'],
user['full_name'], user['created_at'], user['is_active'],
user['instructor_approval_status'] if user['instructor_approval_status'] else 'approved',
user['approved_by'],
user['approved_at'])
login_user(user_obj, remember=remember)
flash(f'Welcome back, {user["full_name"]}!', 'success')
next_page = request.args.get('next')
return redirect(next_page) if next_page else redirect(url_for('dashboard'))
else:
flash('Invalid email or password', 'error')
return render_template('auth/login.html')
@app.route('/register', methods=['GET', 'POST'])
def register():
if current_user.is_authenticated:
return redirect(url_for('dashboard'))
if request.method == 'POST':
# Validate CSRF token
csrf_token = request.form.get('csrf_token')
if not validate_csrf_token(csrf_token):
flash('Invalid security token. Please try again.', 'error')
return render_template('auth/register.html')
username = request.form['username'].strip()
email = request.form['email'].lower().strip()
password = request.form['password']
confirm_password = request.form['confirm_password']
full_name = request.form['full_name'].strip()
role = request.form.get('role', 'student')
# Handle instructor screenshot upload
screenshot_filename = None
if role == 'instructor' and 'instructor_screenshot' in request.files:
screenshot = request.files['instructor_screenshot']
if screenshot and screenshot.filename:
# Create instructor_screenshots directory if it doesn't exist
screenshots_dir = os.path.join(app.config['UPLOAD_FOLDER'], 'instructor_screenshots')
os.makedirs(screenshots_dir, exist_ok=True)
# Validate file type
allowed_extensions = {'png', 'jpg', 'jpeg', 'gif', 'webp'}
file_ext = screenshot.filename.rsplit('.', 1)[1].lower() if '.' in screenshot.filename else ''
if file_ext not in allowed_extensions:
flash('Invalid file type. Please upload PNG, JPG, JPEG, GIF, or WebP images only.', 'error')
return render_template('auth/register.html')
# Validate file size (max 5MB)
screenshot.seek(0, 2) # Seek to end
file_size = screenshot.tell()
screenshot.seek(0) # Reset seek position
if file_size > 5 * 1024 * 1024:
flash('File size too large. Please upload images smaller than 5MB.', 'error')
return render_template('auth/register.html')
# Generate secure filename and save
filename = secure_filename(f"{username}_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{screenshot.filename}")
screenshot_path = os.path.join(screenshots_dir, filename)
try:
screenshot.save(screenshot_path)
screenshot_filename = filename
except Exception as e:
flash('Error saving screenshot. Please try again.', 'error')
return render_template('auth/register.html')
# Validation
if password != confirm_password:
flash('Passwords do not match', 'error')
return render_template('auth/register.html')
if len(password) < 6:
flash('Password must be at least 6 characters long', 'error')
return render_template('auth/register.html')
# Validate instructor screenshot
if role == 'instructor' and not screenshot_filename:
flash('Screenshot upload is required for instructor accounts', 'error')
return render_template('auth/register.html')
with db_lock:
conn = get_db_connection()
# Check if user already exists
existing_user = conn.execute(
'SELECT id FROM users WHERE email = ? OR username = ?', (email, username)
).fetchone()
if existing_user:
flash('User with this email or username already exists', 'error')
conn.close()
return render_template('auth/register.html')
# Create new user
password_hash = generate_password_hash(password)
# Set instructor approval status based on role
instructor_approval_status = 'pending' if role == 'instructor' else 'approved'
conn.execute('''
INSERT INTO users (username, email, password_hash, role, full_name, instructor_approval_status, instructor_screenshot)
VALUES (?, ?, ?, ?, ?, ?, ?)
''', (username, email, password_hash, role, full_name, instructor_approval_status, screenshot_filename))
conn.commit()
conn.close()
# Flash appropriate message based on role
if role == 'instructor':
flash('Registration successful! Your instructor account is pending admin approval. You will be notified once approved.', 'info')
else:
flash('Registration successful! Please log in.', 'success')
return redirect(url_for('login'))
return render_template('auth/register.html')
@app.route('/logout')
@login_required
def logout():
logout_user()
flash('You have been logged out successfully.', 'info')
return redirect(url_for('login'))
@app.route('/dashboard')
@login_required
def dashboard():
with db_lock:
conn = get_db_connection()
if current_user.is_admin():
# Admin dashboard data
stats = {
'total_users': conn.execute('SELECT COUNT(*) FROM users WHERE is_active = 1').fetchone()[0],
'total_students': conn.execute('SELECT COUNT(*) FROM users WHERE role = "student" AND is_active = 1').fetchone()[0],
'total_courses': conn.execute('SELECT COUNT(*) FROM courses WHERE is_active = 1').fetchone()[0],
'total_enrollments': conn.execute('SELECT COUNT(*) FROM enrollments WHERE status = "approved"').fetchone()[0],
'pending_enrollments': conn.execute('SELECT COUNT(*) FROM enrollments WHERE status = "pending"').fetchone()[0],
'pending_instructors': conn.execute('SELECT COUNT(*) FROM users WHERE role = "instructor" AND instructor_approval_status = "pending" AND is_active = 1').fetchone()[0],
'total_instructors': conn.execute('SELECT COUNT(*) FROM users WHERE role = "instructor" AND is_active = 1').fetchone()[0]
}
# Recent enrollments
recent_enrollments = conn.execute('''
SELECT e.*, u.full_name as student_name, c.title as course_title
FROM enrollments e
JOIN users u ON e.student_id = u.id
JOIN courses c ON e.course_id = c.id
ORDER BY e.enrolled_at DESC
LIMIT 10
''').fetchall()