-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
1712 lines (1218 loc) · 59.4 KB
/
app.py
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
from flask import Flask, render_template, request, redirect, url_for, flash, session, jsonify,json
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from datetime import datetime
from sqlalchemy.sql import func
from sqlalchemy import func
import pytz
import uuid
import os
import json
from werkzeug.utils import secure_filename
from sqlalchemy.orm import relationship
app = Flask(__name__)
app.template_folder = 'templates'
app.secret_key = 'secret_key'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
upload_folder_video = os.path.join(app.root_path, 'static', 'upload_video')
upload_folder_images = os.path.join(app.root_path, 'static', 'upload_images')
upload_folder_thumbnail = os.path.join(app.root_path, 'static', 'upload_thumbnail')
upload_folder_attachments = os.path.join(app.root_path, 'static', 'upload_attachments')
app.config['UPLOAD_FOLDER_VIDEO'] = upload_folder_video
app.config['UPLOAD_FOLDER_IMAGES'] = upload_folder_images
app.config['UPLOAD_FOLDER_THUMBNAIL'] = upload_folder_thumbnail
app.config['UPLOAD_FOLDER_ATTACHMENTS'] = upload_folder_attachments
# Define allowed file extensions
ALLOWED_EXTENSIONS = {'mp4', 'avi', 'mkv', 'mov', 'flv', 'jpg', 'svg', 'jpeg', 'png', 'gif', 'webp', 'pdf', 'docx', 'doc'}
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
app.config['TIMEZONE'] = pytz.timezone('Asia/Karachi')
db = SQLAlchemy()
db.init_app(app)
migrate = Migrate(app, db)
# Define the User model
class users(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(50), nullable=False)
password = db.Column(db.String(50), nullable=False)
email = db.Column(db.String(80), unique=True, nullable=False)
role = db.Column(db.String(20), default='user')
profile_picture = db.Column(db.String(255), default='avatar.avif')
uuid = db.Column(db.String(36), unique=True, nullable=False, default=str(uuid.uuid4()))
status = db.Column(db.String(20), default='active')
created_at = db.Column(db.DateTime, default=db.func.now())
deactivated_at = db.Column(db.DateTime, default=None) # Change the default value
videos = db.relationship('Video', backref='users', lazy=True)
liked_videos = db.relationship('VideoLike', backref='user', lazy=True)
def __repr__(self):
return f"{self.id}-{self.username}"
class Video(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100))
description = db.Column(db.Text)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
file_path = db.Column(db.String(100))
category = db.Column(db.String(50))
video_thumbnail = db.Column(db.String(100))
upload_time = db.Column(db.DateTime, default=datetime.utcnow)
views = db.Column(db.Integer, default=0)
likes_count = db.Column(db.Integer, default=0) # New column to store likes count
dislikes_count = db.Column(db.Integer, default=0)
likes = db.relationship('VideoLike', backref='video', lazy=True)
dislikes = db.relationship('VideoDislike', backref='video', lazy=True)
def update_likes_count(self):
self.likes_count = len(self.likes)
def calculate_unique_likes(self):
unique_likes_query = db.session.query(func.count(VideoLike.user_id.distinct())).filter_by(video_id=self.id)
self.likes_count = unique_likes_query.scalar()
def calculate_unique_dislikes(self):
unique_dislikes_query = db.session.query(func.count(VideoDislike.user_id.distinct())).filter_by(video_id=self.id)
self.dislikes_count = unique_dislikes_query.scalar()
class VideoLike(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
video_id = db.Column(db.Integer, db.ForeignKey('video.id'), nullable=False)
class VideoDislike(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
video_id = db.Column(db.Integer, db.ForeignKey('video.id'), nullable=False)
class Course(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
thumbnail_url = db.Column(db.String(200), nullable=False)
category = db.Column(db.String(50))
creator_id = db.Column(db.Integer, db.ForeignKey('users.id'))
creation_timestamp = db.Column(db.DateTime, default=db.func.now())
class Comment(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
email = db.Column(db.String(100), nullable=False)
message = db.Column(db.Text, nullable=False)
timestamp = db.Column(db.DateTime, default=datetime.utcnow)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
course_mention = db.Column(db.String(100), default='none')
user = db.relationship('users', backref=db.backref('comments', lazy=True))
def __init__(self, name, email, message, user_id=None, course_mention='none'):
self.name = name
self.email = email
self.message = message
self.user_id = user_id
self.course_mention = course_mention
class Reply(db.Model):
id = db.Column(db.Integer, primary_key=True)
message = db.Column(db.Text, nullable=False)
timestamp = db.Column(db.DateTime, default=db.func.now())
comment_id = db.Column(db.Integer, db.ForeignKey('comment.id'))
user_id = db.Column(db.Integer, db.ForeignKey('users.id')) # Add a user_id column
user = relationship('users')
def __init__(self, message, comment_id, user_id):
self.message = message
self.comment_id = comment_id
self.user_id = user_id
class BlogPost(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
author = db.Column(db.String(50), nullable=False)
thumbnail_filename = db.Column(db.String(255), nullable=False)
cover_pic_filename = db.Column(db.String(255), nullable=False)
attachments_filename = db.Column(db.String(255))
content = db.Column(db.Text, nullable=False)
blog_category= db.Column(db.String(50), nullable=False)
custom_category = db.Column(db.String(50))
keywords = db.Column(db.String(100))
is_featured = db.Column(db.Boolean, default=False)
status = db.Column(db.String(20), default='draft')
posted_at = db.Column(db.DateTime)
archived_at = db.Column(db.DateTime)
published_at = db.Column(db.DateTime)
user_uuid = db.Column(db.String(36), db.ForeignKey('users.uuid'), nullable=False)
user = db.relationship('users', backref=db.backref('blog_posts', lazy=True))
comments = db.relationship('BlogComment', backref='blog_post', lazy='dynamic')
class BlogComment(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
email = db.Column(db.String(100), nullable=False)
message = db.Column(db.Text, nullable=False)
timestamp = db.Column(db.DateTime, default=datetime.utcnow)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
user = db.relationship('users', foreign_keys=[user_id])
blog_post_id = db.Column(db.Integer, db.ForeignKey('blog_post.id'))
replies = db.relationship('BlogReply', backref='comment', lazy='dynamic')
def __init__(self, name, email, message, user_id=None, blog_post_id=None, course_mention=None):
self.name = name
self.email = email
self.message = message
self.user_id = user_id
self.blog_post_id = blog_post_id
self.course_mention = course_mention
class BlogReply(db.Model):
id = db.Column(db.Integer, primary_key=True)
message = db.Column(db.Text, nullable=False)
timestamp = db.Column(db.DateTime, default=datetime.utcnow)
comment_id = db.Column(db.Integer, db.ForeignKey('blog_comment.id'))
user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
user = db.relationship('users', foreign_keys=[user_id])
def __init__(self, message, comment_id, user_id):
self.message = message
self.comment_id = comment_id
self.user_id = user_id
class Contact(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
teacher_mentioned_id = db.Column(db.Integer, db.ForeignKey('users.id'))
name = db.Column(db.String(100), nullable=False) # Add 'name' column
user_email = db.Column(db.String(80), nullable=False) # Add 'user_email' column
subject = db.Column(db.String(100), nullable=False)
message = db.Column(db.Text, nullable=False)
created_at = db.Column(db.DateTime, default=db.func.now())
user = db.relationship('users', foreign_keys=[user_id], backref='contacts')
teacher_mentioned = db.relationship('users', foreign_keys=[teacher_mentioned_id])
with app.app_context():
db.create_all()
# Define the get_current_user function
def get_current_user():
if 'user_id' in session:
user_id = session['user_id']
user = users.query.get(user_id)
return user
else:
return None # Return None if the user is not logged in
@app.route('/')
def index():
return render_template('Navbar/index.html')
@app.route('/like_video/<int:video_id>', methods=['POST'])
def like_video(video_id):
user = get_current_user()
if not user:
return jsonify({"message": "You must be logged in to like videos."}), 403
video = Video.query.get(video_id)
if not video:
return jsonify({"message": "Video not found."}), 404
existing_like = VideoLike.query.filter_by(user_id=user.id, video_id=video.id).first()
if existing_like:
return jsonify({"message": "You have already liked this video."}), 400
# Create a new VideoLike entry to represent the like
like = VideoLike(user_id=user.id, video_id=video.id)
db.session.add(like)
db.session.commit()
# Calculate the unique likes for the video
video.calculate_unique_likes()
db.session.commit()
return jsonify({"message": "Video liked successfully."}), 200
@app.route('/dislike_video/<int:video_id>', methods=['POST'])
def dislike_video(video_id):
user = get_current_user()
if not user:
return jsonify({"message": "You must be logged in to dislike videos."}), 403
video = Video.query.get(video_id)
if not video:
return jsonify({"message": "Video not found."}), 404
existing_like = VideoLike.query.filter_by(user_id=user.id, video_id=video.id).first()
existing_dislike = VideoDislike.query.filter_by(user_id=user.id, video_id=video.id).first()
if existing_like:
return jsonify({"message": "You have already liked this video. You can't dislike it."}), 400
if existing_dislike:
return jsonify({"message": "You have already disliked this video."}), 400
# Create a new VideoDislike entry to represent the dislike
dislike = VideoDislike(user_id=user.id, video_id=video.id)
db.session.add(dislike)
db.session.commit()
# Calculate the unique dislikes for the video
video.calculate_unique_dislikes()
db.session.commit()
return jsonify({"message": "Video disliked successfully."}), 200
@app.route('/create_course', methods=['GET', 'POST'])
def create_course():
# Check if the user is logged in
user = get_current_user()
if user is None:
return redirect(url_for('login'))
# Check if the user has the 'teacher' role
if user.role not in ['teacher', 'admin']:
flash('You do not have permission to access the course creation form.', 'error')
return redirect(url_for('login'))
if request.method == 'POST':
name = request.form['course_name']
category = request.form['category']
thumbnail = request.files['thumbnail']
if name and thumbnail:
counter = 1
file_extension = os.path.splitext(thumbnail.filename)[1]
while os.path.exists(os.path.join(app.config['UPLOAD_FOLDER_IMAGES'], generate_course_thumbnail_filename(counter, file_extension))):
counter += 1
thumbnail_filename = generate_course_thumbnail_filename(counter, file_extension)
thumbnail.save(os.path.join(app.config['UPLOAD_FOLDER_IMAGES'], thumbnail_filename))
new_course = Course(name=name, thumbnail_url=os.path.join('static', 'upload_images', thumbnail_filename), category=category, creator_id=user.id)
db.session.add(new_course)
db.session.commit()
flash('Course created successfully', 'success')
else:
flash('Please provide a course name and thumbnail', 'error')
return redirect(url_for('create_course'))
return render_template('Dashboards/create_course.html')
def generate_course_thumbnail_filename(counter, file_extension):
return f"course_thumbnail_{counter}{file_extension}"
@app.route('/delete_course/<int:course_id>', methods=['POST'])
def delete_course(course_id):
# Fetch the course to be deleted from the database
course = Course.query.get(course_id)
if course:
# Check if the current user is an "admin" or the course creator
user = get_current_user()
if user and (user.role == 'admin' or user.id == course.creator_id):
# Delete the associated thumbnail image from the filesystem
thumbnail_path = os.path.join(app.config['UPLOAD_FOLDER_IMAGES'], course.thumbnail_url.split("/")[-1])
if os.path.exists(thumbnail_path):
os.remove(thumbnail_path)
# Delete the course from the database
db.session.delete(course)
db.session.commit()
flash('Course and thumbnail deleted successfully', 'success')
else:
flash('You do not have permission to delete this course', 'error')
else:
flash('Course not found', 'error')
return redirect(url_for('course'))
@app.route('/course/<int:course_id>')
def course_details(course_id):
user=get_current_user()
course = Course.query.get(course_id)
videos = Video.query.filter_by(category=course.category).all()
return render_template('Courses/course_details.html',user=user, course=course, videos=videos)
@app.route('/delete_video/<int:video_id>/<int:course_id>', methods=['POST'])
def delete_video(video_id, course_id):
user = get_current_user()
if user is None or user.role != 'teacher':
flash('You do not have permission to delete videos.', 'error')
return redirect(url_for('course_details', course_id=course_id)) # Redirect to the course details page
# Fetch the video to be deleted from the database
video = Video.query.get(video_id)
if video:
# Check if the user is the course creator
if user.id == video.user_id:
# Delete the video from the database
db.session.delete(video)
db.session.commit()
flash('Video deleted successfully', 'success')
else:
flash('You do not have permission to delete this video', 'error')
else:
flash('Video not found', 'error')
return redirect(url_for('course_details', course_id=course_id))
@app.route('/post_comment', methods=['POST'])
def post_comment():
user = get_current_user()
if user is None:
flash('You must be logged in to post a comment.', 'error')
return redirect(url_for('login'))
message = request.form['message']
parent_comment_id = request.form.get('parent_comment_id') # Get the parent comment ID
course_mention = request.form.get('course_mention') # Get the course mention
if message:
comment = Comment(name=user.username, email=user.email, message=message, user_id=user.id, course_mention=course_mention)
db.session.add(comment)
if parent_comment_id:
parent_comment = Comment.query.get(parent_comment_id)
if parent_comment:
comment.parent = parent_comment
db.session.commit()
flash('Comment/reply posted successfully!', 'success')
else:
flash('Please fill in the message field to post a comment/reply.', 'error')
return redirect(url_for('course'))
@app.route('/post_reply', methods=['POST'])
def post_reply():
if 'user_id' in session:
user_id = session['user_id']
user = users.query.get(user_id)
if user:
comment_id = request.form.get('comment_id')
message = request.form.get('reply_message')
if comment_id and message:
reply = Reply(message=message, comment_id=comment_id, user_id=user.id)
db.session.add(reply)
db.session.commit()
flash('Reply posted successfully!', 'success')
else:
flash('Invalid data. Please provide both a comment ID and a message for the reply.', 'error')
return redirect(url_for('course')) # Redirect to the comments page or any other appropriate page
else:
flash('User not found. Please log in to post a reply.', 'error')
else:
flash('Please log in to post a reply.', 'error')
return redirect(url_for('login')) # Redirect to the login page or any other appropriate page
def generate_course_thumbnail_filename(counter, file_extension):
return f"course_thumbnail_{counter}{file_extension}"
@app.route('/delete_comment/<int:comment_id>', methods=['GET', 'POST'])
def delete_comment(comment_id):
user = get_current_user()
if user is None:
flash('You do not have permission to delete comments. Please log in first.', 'error')
return redirect(url_for('login'))
comment = Comment.query.get(comment_id)
if comment is None:
flash('Comment not found.', 'error')
return redirect(url_for('course'))
if user.id == comment.user_id or user.role == 'teacher':
# Check if the user is the owner of the comment or a teacher
# Delete associated replies
replies = Reply.query.filter_by(comment_id=comment_id).all()
for reply in replies:
db.session.delete(reply)
# Delete the comment
db.session.delete(comment)
db.session.commit()
flash('Comment and associated replies deleted successfully.', 'success')
else:
flash('You do not have permission to delete this comment.', 'error')
return redirect(url_for('course'))
@app.route('/delete_reply/<int:reply_id>',methods=['GET', 'POST'])
def delete_reply(reply_id):
user = get_current_user()
if user is None:
flash('You do not have permission to delete replies. Please log in first.', 'error')
return redirect(url_for('login'))
reply = Reply.query.get(reply_id)
if reply is None:
flash('Reply not found.', 'error')
return redirect(url_for('course'))
comment = Comment.query.get(reply.comment_id)
if user.id == reply.user_id or (user.role == 'teacher' and user.id == comment.user_id):
# Check if the user is the owner of the reply or a teacher who can delete replies
db.session.delete(reply)
db.session.commit()
flash('Reply deleted successfully.', 'success')
else:
flash('You do not have permission to delete this reply.', 'error')
return redirect(url_for('course'))
@app.route('/edit_comment/<int:comment_id>', methods=['POST'])
def edit_comment(comment_id):
user = get_current_user()
if user is None:
flash('You do not have permission to edit comments. Please log in first.', 'error')
return redirect(url_for('login'))
comment = Comment.query.get(comment_id)
if comment is None:
flash('Comment not found.', 'error')
return redirect(url_for('course'))
if user.id != comment.user_id:
flash('You do not have permission to edit this comment.', 'error')
return redirect(url_for('course'))
if request.method == 'POST':
edited_message = request.form.get('edited_message')
if edited_message:
comment.message = edited_message
db.session.commit()
flash('Comment edited successfully.', 'success')
else:
flash('Please provide a valid comment.', 'error')
return redirect(url_for('course'))
@app.route('/edit_reply/<int:reply_id>', methods=[ 'POST'])
def edit_reply(reply_id):
user = get_current_user()
if user is None:
flash('You do not have permission to edit replies. Please log in first.', 'error')
return redirect(url_for('login'))
reply = Reply.query.get(reply_id)
if reply is None:
flash('Reply not found.', 'error')
return redirect(url_for('course'))
if user.id == reply.user_id:
# Check if the user is the owner of the reply
if request.method == 'POST':
edited_message = request.form.get('edited_message')
if edited_message:
reply.message = edited_message
db.session.commit()
flash('Reply edited successfully.', 'success')
else:
flash('Please provide a valid reply.', 'error')
return redirect(url_for('course'))
from sqlalchemy.orm import joinedload
from sqlalchemy.orm import joinedload
@app.route('/blog_post/<int:post_id>', methods=['GET', 'POST'])
def blog_post(post_id):
user = get_current_user()
if user is None:
flash('You do not have permission to access the Blog page. Log in first', 'error')
return redirect(url_for('login'))
post = BlogPost.query.filter_by(id=post_id).first_or_404()
# Separate query for comments with eager loading of the user relationship
comments = (
BlogComment.query
.filter_by(blog_post_id=post_id)
.options(joinedload(BlogComment.user))
.all()
)
if request.method == 'POST':
message = request.form.get('message')
comment_id = request.form.get('comment_id') # For replies
if message:
if comment_id:
# This is a reply
blog_reply = BlogReply(message=message, comment_id=comment_id, user_id=user.id)
db.session.add(blog_reply)
else:
# This is a new comment
blog_comment = BlogComment(name=user.username, email=user.email, message=message, user_id=user.id, blog_post_id=post.id)
db.session.add(blog_comment)
db.session.commit()
flash('Comment/reply posted successfully!', 'success')
return redirect(url_for('blog_post', post_id=post.id))
return render_template('Blogs/blog_post.html', post=post, user=user, comments=comments)
@app.route('/post_blog_comment', methods=['POST'])
def post_blog_comment():
user = get_current_user()
if user is None:
flash('You must be logged in to post a blog comment.', 'error')
return redirect(url_for('login'))
message = request.form['message']
blog_post_id = request.form.get('blog_post_id') # Get the blog post ID
if message:
blog_comment = BlogComment(name=user.username, email=user.email, message=message, user_id=user.id, blog_post_id=blog_post_id)
db.session.add(blog_comment)
db.session.commit()
flash('Blog comment posted successfully!', 'success')
else:
flash('Please fill in the message field to post a blog comment.', 'error')
return redirect(url_for('blog_post', blog_post_id=blog_post_id))
@app.route('/post_blog_reply', methods=['POST'])
def post_blog_reply():
if 'user_id' in session:
user_id = session['user_id']
user = users.query.get(user_id)
if user:
comment_id = request.form.get('comment_id')
message = request.form.get('reply_message')
if comment_id and message:
blog_reply = BlogReply(message=message, comment_id=comment_id, user_id=user.id)
db.session.add(blog_reply)
db.session.commit()
flash('Blog reply posted successfully!', 'success')
else:
flash('Invalid data. Please provide both a comment ID and a message for the blog reply.', 'error')
return redirect(url_for('blog_post', blog_post_id=blog_reply.comment.blog_post_id)) # Redirect to the blog post page or any other appropriate page
else:
flash('User not found. Please log in to post a blog reply.', 'error')
else:
flash('Please log in to post a blog reply.', 'error')
return redirect(url_for('login')) # Redirect to the login page or any other appropriate page
@app.route('/delete_blog_comment/<int:comment_id>', methods=['GET', 'POST'])
def delete_blog_comment(comment_id):
user = get_current_user()
if user is None:
flash('You do not have permission to delete blog comments. Please log in first.', 'error')
return redirect(url_for('login'))
blog_comment = BlogComment.query.get(comment_id)
if blog_comment is None:
flash('Blog comment not found.', 'error')
return redirect(url_for('blog'))
if user.id == blog_comment.user_id or user.role == 'teacher':
# Check if the user is the owner of the blog comment or a teacher
# Delete associated blog replies
blog_replies = BlogReply.query.filter_by(comment_id=comment_id).all()
for blog_reply in blog_replies:
db.session.delete(blog_reply)
# Delete the blog comment
db.session.delete(blog_comment)
db.session.commit()
flash('Blog comment and associated replies deleted successfully.', 'success')
else:
flash('You do not have permission to delete this blog comment.', 'error')
return redirect(url_for('blog_post', post_id=blog_comment.blog_post_id))
@app.route('/delete_blog_reply/<int:reply_id>',methods=['GET', 'POST'])
def delete_blog_reply(reply_id):
user = get_current_user()
if user is None:
flash('You do not have permission to delete blog replies. Please log in first.', 'error')
return redirect(url_for('login'))
blog_reply = BlogReply.query.get(reply_id)
if blog_reply is None:
flash('Blog reply not found.', 'error')
return redirect(url_for('blog'))
blog_comment = BlogComment.query.get(blog_reply.comment_id)
if user.id == blog_reply.user_id or (user.role == 'teacher' and user.id == blog_comment.user_id):
# Check if the user is the owner of the blog reply or a teacher who can delete blog replies
db.session.delete(blog_reply)
db.session.commit()
flash('Blog reply deleted successfully.', 'success')
else:
flash('You do not have permission to delete this blog reply.', 'error')
return redirect(url_for('blog_post', post_id=blog_reply.comment.blog_post_id))
@app.route('/edit_blog_comment/<int:comment_id>', methods=['POST'])
def edit_blog_comment(comment_id):
user = get_current_user()
if user is None:
flash('You do not have permission to edit blog comments. Please log in first.', 'error')
return redirect(url_for('login'))
blog_comment = BlogComment.query.get(comment_id)
if blog_comment is None:
flash('Blog comment not found.', 'error')
return redirect(url_for('blog'))
if user.id != blog_comment.user_id:
flash('You do not have permission to edit this blog comment.', 'error')
return redirect(url_for('blog'))
if request.method == 'POST':
edited_message = request.form.get('edited_message')
if edited_message:
blog_comment.message = edited_message
db.session.commit()
flash('Blog comment edited successfully.', 'success')
else:
flash('Please provide a valid blog comment.', 'error')
return redirect(url_for('blog_post', post_id=blog_comment.blog_post_id))
@app.route('/edit_blog_reply/<int:reply_id>', methods=[ 'POST'])
def edit_blog_reply(reply_id):
user = get_current_user()
if user is None:
flash('You do not have permission to edit blog replies. Please log in first.', 'error')
return redirect(url_for('login'))
blog_reply = BlogReply.query.get(reply_id)
if blog_reply is None:
flash('Blog reply not found.', 'error')
return redirect(url_for('blog'))
if user.id == blog_reply.user_id:
# Check if the user is the owner of the blog reply
if request.method == 'POST':
edited_message = request.form.get('edited_message')
if edited_message:
blog_reply.message = edited_message
db.session.commit()
flash('Blog reply edited successfully.', 'success')
else:
flash('Please provide a valid blog reply.', 'error')
return redirect(url_for('blog_post', post_id=blog_reply.comment.blog_post_id))
@app.route('/about')
def about():
return render_template('Navbar/about.html')
@app.route('/course')
def course():
user = get_current_user()
if user is None:
flash('You do not have permission to access the Course page. Please log in first.', 'error')
return redirect(url_for('login'))
courses = Course.query.all()
# Query all comments, ordering them by the timestamp in descending order
comments = Comment.query.order_by(Comment.timestamp.desc()).all()
# Query associated replies for each comment
for comment in comments:
comment.replies = Reply.query.filter_by(comment_id=comment.id).all()
categories = Course.query.with_entities(Course.category, Course.creator_id).distinct().all()
return render_template('Navbar/course.html', user=user, comments=comments, courses=courses,categories=categories)
@app.route('/blog')
def blog():
user = get_current_user()
if user is None:
flash('You do not have permission to access the Blog page. Please login first.', 'error')
return redirect(url_for('login'))
# Assuming you have a function to query and retrieve blog posts from the database
page = request.args.get('page', 1, type=int) # Get the page number from the query parameters
# Set the number of blog posts per page
per_page = 3 # You can adjust this based on your preference
# Query and paginate all blog posts, sorted by posted_at in descending order
blog_posts = BlogPost.query.order_by(BlogPost.posted_at.desc()).paginate(page=page, per_page=per_page, error_out=False)
for post in blog_posts.items:
total_comments = db.session.query(func.count(BlogComment.id)).filter_by(blog_post_id=post.id).scalar()
total_replies = db.session.query(func.count(BlogReply.id)).join(BlogComment).filter(BlogComment.blog_post_id == post.id).scalar()
post.total_comments = total_comments + total_replies
# Define a dictionary to map categories to CSS classes
category_classes = {
'Technology': 'tag-blue',
'Science': 'tag-green',
'Art': 'tag-orange',
'Literature': 'tag-purple',
'History': 'tag-brown',
'Music': 'tag-pink',
'Travel': 'tag-yellow',
'Food': 'tag-red',
'Sports': 'tag-teal',
'Health': 'tag-lime',
'custom': 'tag-custom',
'default': 'tag-default'
}
# Pass the retrieved blog posts and category classes to the template
return render_template('Navbar/blog.html', blog_posts=blog_posts,user=user, category_classes=category_classes)
# Your existing route for the contact page
@app.route('/contact', methods=['GET', 'POST'])
def contact():
user = get_current_user()
if request.method == 'POST':
if user is None:
flash('You do not have permission to submit the contact form. Please log in first.', 'error')
else:
name = request.form['name']
user_email = user.email # Get the user's email directly from the 'user' object
subject = request.form['subject']
message = request.form['message']
teacher_mentioned_id = request.form.get('teacher_mentioned_id')
new_contact = Contact(
user_id=user.id,
teacher_mentioned_id=teacher_mentioned_id,
name=name,
user_email=user_email, # Store the user's email
subject=subject,
message=message
)
db.session.add(new_contact)
db.session.commit()
flash('Your message has been submitted successfully.', 'success')
return redirect(url_for('contact'))
if user is None:
flash('You do not have permission to access the contact page. Please log in first.', 'error')
return redirect(url_for('login'))
teachers = users.query.filter_by(role='teacher').all()
# Pass the 'user' to the template
return render_template('Navbar/contact.html', teachers=teachers, user=user)
@app.route('/htmlcourse')
def htmlcourse():
user = get_current_user()
if user is None:
flash('You do not have permission to access HTML course page. Please log in first.', 'error')
return redirect(url_for('login'))
# Query the database to get all videos with the "htmlcourse" category
videos = Video.query.filter_by(category='htmlcourse').all()
return render_template('Courses/htmlcourse.html', videos=videos)
@app.route('/photography')
def photography():
user = get_current_user()
if user is None:
flash('You do not have permission to access HTML course page. Please log in first.', 'error')
return redirect(url_for('login'))
# Query the database to get all videos with the "Photography" category
videos = Video.query.filter_by(category='photography').all()
return render_template('Courses/photography.html', videos=videos)
@app.route('/driving')
def driving():
user = get_current_user()
if user is None:
flash('You do not have permission to access HTML course page. Please log in first.', 'error')
return redirect(url_for('login'))
# Query the database to get all videos with the "driving" category
videos = Video.query.filter_by(category='driving').all()
return render_template('Courses/driving.html', videos=videos)
@app.route('/writing')
def writing():
user = get_current_user()
if user is None:
flash('You do not have permission to access HTML course page. Please log in first.', 'error')
return redirect(url_for('login'))
# Query the database to get all videos with the "writing" category
videos = Video.query.filter_by(category='writing').all()