@ -97,11 +97,40 @@ class CourseLiveSessionRoomCreateAPIView(GenericAPIView):
raise AppAPIException ( { ' message ' : str ( exc ) } , status_code = 500 )
raise AppAPIException ( { ' message ' : str ( exc ) } , status_code = 500 )
# 5. Database Logic
# 5. Database Logic
# CRITICAL FIX: Also filter by ended_at__isnull=True to avoid reusing ended sessions
session , created = CourseLiveSession . objects . get_or_create (
course = course , room_id = room_id , ended_at__isnull = True ,
defaults = { ' subject ' : subject , ' started_at ' : timezone . now ( ) }
# Strategy:
# 1. Try to find active session (ended_at is NULL)
# 2. If not found, try to find ended session with same room_id and reactivate it
# 3. If not found, create new session
try :
# Try to get active session first
session = CourseLiveSession . objects . get (
course = course , room_id = room_id , ended_at__isnull = True
)
created = False
logger . info ( f " [LiveSession Create] Reusing active session - session_id={session.id} room_id={room_id} " )
except CourseLiveSession . DoesNotExist :
# No active session, check if there's an old one with same room_id
try :
session = CourseLiveSession . objects . get (
course = course , room_id = room_id
)
# Reactivate the old session
session . ended_at = None
session . started_at = timezone . now ( )
session . subject = subject
session . save ( update_fields = [ ' ended_at ' , ' started_at ' , ' subject ' , ' updated_at ' ] )
created = False
logger . info ( f " [LiveSession Create] Reactivated ended session - session_id={session.id} room_id={room_id} " )
except CourseLiveSession . DoesNotExist :
# No session exists at all, create new one
session = CourseLiveSession . objects . create (
course = course ,
room_id = room_id ,
subject = subject ,
started_at = timezone . now ( )
)
)
created = True
logger . info ( f " [LiveSession Create] Created new session - session_id={session.id} room_id={room_id} " )
return Response ( {
return Response ( {
' success ' : True ,
' success ' : True ,