|
|
|
@ -3,6 +3,7 @@ from uuid import UUID |
|
|
|
|
from db.model import db, User, Course, Enrollment,Chat |
|
|
|
|
from utils.auth import auth_required |
|
|
|
|
import requests |
|
|
|
|
from sqlalchemy import desc |
|
|
|
|
|
|
|
|
|
chat = Blueprint('chat', __name__) |
|
|
|
|
|
|
|
|
@ -124,3 +125,59 @@ def create_chat(): |
|
|
|
|
|
|
|
|
|
except Exception as e: |
|
|
|
|
return jsonify({"error": f"An error occurred: {str(e)}"}), 500 |
|
|
|
|
|
|
|
|
|
@chat.route("/get", methods=["GET"]) |
|
|
|
|
@auth_required() |
|
|
|
|
def get_chat_history(): |
|
|
|
|
""" |
|
|
|
|
Fetch chat history for a course. |
|
|
|
|
""" |
|
|
|
|
current_user = g.current_user # Logged-in user |
|
|
|
|
course_id = request.args.get("course_id") |
|
|
|
|
limit = int(request.args.get("limit", 20)) # Default to 20 messages |
|
|
|
|
offset = int(request.args.get("offset", 0)) # Default to no offset (latest chats) |
|
|
|
|
|
|
|
|
|
if not course_id: |
|
|
|
|
return jsonify({"error": "Course ID is required."}), 400 |
|
|
|
|
|
|
|
|
|
try: |
|
|
|
|
# Verify the course exists |
|
|
|
|
course = db.session.query(Course).filter_by(id=course_id).first() |
|
|
|
|
if not course: |
|
|
|
|
return jsonify({"error": "Invalid course ID."}), 404 |
|
|
|
|
|
|
|
|
|
# Check if the user is enrolled in the course |
|
|
|
|
is_enrolled = db.session.query(Course).join(Enrollment).filter( |
|
|
|
|
Enrollment.userID == current_user.id, |
|
|
|
|
Enrollment.courseID == course_id |
|
|
|
|
).first() |
|
|
|
|
|
|
|
|
|
if not is_enrolled: |
|
|
|
|
return jsonify({"error": "You are not enrolled in this course."}), 403 |
|
|
|
|
|
|
|
|
|
# Fetch the latest chat messages with limit and offset |
|
|
|
|
chats = ( |
|
|
|
|
db.session.query(Chat) |
|
|
|
|
.filter_by(courseID=course_id) |
|
|
|
|
.order_by(desc(Chat.chatDate)) |
|
|
|
|
.offset(offset) |
|
|
|
|
.limit(limit) |
|
|
|
|
.all() |
|
|
|
|
) |
|
|
|
|
|
|
|
|
|
# Format the chat messages |
|
|
|
|
chat_history = [ |
|
|
|
|
{ |
|
|
|
|
"id": str(chat.id), |
|
|
|
|
"textContent": chat.textContent, |
|
|
|
|
"userID": str(chat.userID), |
|
|
|
|
"chatDate": chat.chatDate.isoformat(), |
|
|
|
|
"is_mine": chat.userID == current_user.id, |
|
|
|
|
} |
|
|
|
|
for chat in chats |
|
|
|
|
] |
|
|
|
|
|
|
|
|
|
return jsonify({"chats": chat_history}), 200 |
|
|
|
|
|
|
|
|
|
except Exception as e: |
|
|
|
|
return jsonify({"error": f"An error occurred: {str(e)}"}), 500 |