This commit is contained in:
september
2025-09-03 06:51:24 -07:00
commit 54a81cbdcf
95 changed files with 17637 additions and 0 deletions

View File

View File

@@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.

View File

@@ -0,0 +1,6 @@
from django.apps import AppConfig
class RoomsConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'apps.rooms'

View File

@@ -0,0 +1,319 @@
# rooms/consumers.py - WebSocket consumer for WebRTC signaling
import json
import logging
from channels.generic.websocket import AsyncWebsocketConsumer
from channels.db import database_sync_to_async
from django.utils import timezone
from apps.rooms.models import RoomManager
logger = logging.getLogger(__name__)
class VideoCallConsumer(AsyncWebsocketConsumer):
"""
WebSocket consumer for handling WebRTC signaling and room management.
Implements secure peer-to-peer connection establishment.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.room_id = None
self.room_group_name = None
self.participant_id = None
async def connect(self):
"""Handle WebSocket connection"""
try:
# Extract room ID from URL
self.room_id = self.scope['url_route']['kwargs']['room_id']
self.room_group_name = f'room_{self.room_id}'
# Get participant ID from session or generate one
session = self.scope.get('session', {})
self.participant_id = session.get('session_key') or f'temp_{timezone.now().timestamp()}'
# Verify room exists and user can join
room_data = await self.get_room_data(self.room_id)
if not room_data:
await self.close(code=4004) # Room not found
return
# Check room capacity
participants = room_data.get('participants', [])
max_participants = room_data.get('max_participants', 2)
if len(participants) >= max_participants and self.participant_id not in participants:
await self.close(code=4003) # Room is full
return
# Join the room group
await self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)
# Accept the WebSocket connection
await self.accept()
# Notify other participants about new user
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'user_joined',
'participant_id': self.participant_id,
'timestamp': timezone.now().isoformat()
}
)
logger.info(f"User {self.participant_id} connected to room {self.room_id}")
except Exception as e:
logger.error(f"WebSocket connection error: {e}")
await self.close(code=4000)
async def disconnect(self, close_code):
"""Handle WebSocket disconnection"""
try:
if self.room_group_name and self.participant_id:
# Notify other participants about user leaving
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'user_left',
'participant_id': self.participant_id,
'timestamp': timezone.now().isoformat()
}
)
# Remove user from room group
await self.channel_layer.group_discard(
self.room_group_name,
self.channel_name
)
# Update room data
await self.leave_room(self.room_id, self.participant_id)
logger.info(f"User {self.participant_id} disconnected from room {self.room_id}")
except Exception as e:
logger.error(f"WebSocket disconnect error: {e}")
async def receive(self, text_data):
"""Handle incoming WebSocket messages"""
try:
data = json.loads(text_data)
message_type = data.get('type')
# Validate message structure
if not message_type:
await self.send_error('Message type is required')
return
# Handle different message types
if message_type == 'offer':
await self.handle_webrtc_offer(data)
elif message_type == 'answer':
await self.handle_webrtc_answer(data)
elif message_type == 'ice_candidate':
await self.handle_ice_candidate(data)
elif message_type == 'ping':
await self.handle_ping()
elif message_type == 'media_state':
await self.handle_media_state(data)
else:
await self.send_error(f'Unknown message type: {message_type}')
except json.JSONDecodeError:
await self.send_error('Invalid JSON format')
except Exception as e:
logger.error(f"WebSocket receive error: {e}")
await self.send_error('Message processing failed')
async def handle_webrtc_offer(self, data):
"""Handle WebRTC offer from peer"""
try:
target_participant = data.get('target')
offer = data.get('offer')
if not offer:
await self.send_error('Offer data is required')
return
# Forward offer to target participant or broadcast to room
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'webrtc_offer',
'offer': offer,
'sender': self.participant_id,
'target': target_participant,
'timestamp': timezone.now().isoformat()
}
)
except Exception as e:
logger.error(f"WebRTC offer handling error: {e}")
await self.send_error('Failed to process offer')
async def handle_webrtc_answer(self, data):
"""Handle WebRTC answer from peer"""
try:
target_participant = data.get('target')
answer = data.get('answer')
if not answer:
await self.send_error('Answer data is required')
return
# Forward answer to target participant
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'webrtc_answer',
'answer': answer,
'sender': self.participant_id,
'target': target_participant,
'timestamp': timezone.now().isoformat()
}
)
except Exception as e:
logger.error(f"WebRTC answer handling error: {e}")
await self.send_error('Failed to process answer')
async def handle_ice_candidate(self, data):
"""Handle ICE candidate exchange"""
try:
target_participant = data.get('target')
candidate = data.get('candidate')
if not candidate:
await self.send_error('ICE candidate data is required')
return
# Forward ICE candidate to target participant
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'ice_candidate',
'candidate': candidate,
'sender': self.participant_id,
'target': target_participant,
'timestamp': timezone.now().isoformat()
}
)
except Exception as e:
logger.error(f"ICE candidate handling error: {e}")
await self.send_error('Failed to process ICE candidate')
async def handle_ping(self):
"""Handle ping message for connection health check"""
await self.send(text_data=json.dumps({
'type': 'pong',
'timestamp': timezone.now().isoformat()
}))
async def handle_media_state(self, data):
"""Handle media state changes (mute/unmute, video on/off)"""
try:
media_state = data.get('state', {})
# Broadcast media state to other participants
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'media_state_update',
'participant_id': self.participant_id,
'state': media_state,
'timestamp': timezone.now().isoformat()
}
)
except Exception as e:
logger.error(f"Media state handling error: {e}")
await self.send_error('Failed to process media state')
# Group message handlers
async def user_joined(self, event):
"""Send user joined notification"""
if event['participant_id'] != self.participant_id:
await self.send(text_data=json.dumps({
'type': 'user_joined',
'participant_id': event['participant_id'],
'timestamp': event['timestamp']
}))
async def user_left(self, event):
"""Send user left notification"""
if event['participant_id'] != self.participant_id:
await self.send(text_data=json.dumps({
'type': 'user_left',
'participant_id': event['participant_id'],
'timestamp': event['timestamp']
}))
async def webrtc_offer(self, event):
"""Forward WebRTC offer to client"""
# Only send to target participant or broadcast if no target specified
if not event.get('target') or event['target'] == self.participant_id:
if event['sender'] != self.participant_id:
await self.send(text_data=json.dumps({
'type': 'webrtc_offer',
'offer': event['offer'],
'sender': event['sender'],
'timestamp': event['timestamp']
}))
async def webrtc_answer(self, event):
"""Forward WebRTC answer to client"""
if event.get('target') == self.participant_id:
await self.send(text_data=json.dumps({
'type': 'webrtc_answer',
'answer': event['answer'],
'sender': event['sender'],
'timestamp': event['timestamp']
}))
async def ice_candidate(self, event):
"""Forward ICE candidate to client"""
# Only send to target participant or broadcast if no target specified
if not event.get('target') or event['target'] == self.participant_id:
if event['sender'] != self.participant_id:
await self.send(text_data=json.dumps({
'type': 'ice_candidate',
'candidate': event['candidate'],
'sender': event['sender'],
'timestamp': event['timestamp']
}))
async def media_state_update(self, event):
"""Forward media state update to client"""
if event['participant_id'] != self.participant_id:
await self.send(text_data=json.dumps({
'type': 'media_state_update',
'participant_id': event['participant_id'],
'state': event['state'],
'timestamp': event['timestamp']
}))
# Helper methods
async def send_error(self, error_message):
"""Send error message to client"""
await self.send(text_data=json.dumps({
'type': 'error',
'message': error_message,
'timestamp': timezone.now().isoformat()
}))
@database_sync_to_async
def get_room_data(self, room_id):
"""Get room data from Redis"""
return RoomManager.get_room_by_id(room_id)
@database_sync_to_async
def leave_room(self, room_id, participant_id):
"""Remove participant from room"""
return RoomManager.leave_room(room_id, participant_id)

View File

@@ -0,0 +1,223 @@
# rooms/models.py - Room management models
import uuid
import string
import secrets
from datetime import timedelta
from django.conf import settings
from django.utils import timezone
class RoomManager:
"""
Manager class for room operations using Redis for temporary storage.
Implements all CRUD operations for video call rooms.
"""
@staticmethod
def _get_redis_client():
"""Get Redis client instance"""
from django.core.cache import cache
return cache
@classmethod
def generate_short_code(cls, length=None):
"""Generate a unique short code for room access"""
length = length or getattr(settings, 'SHORT_CODE_LENGTH', 6)
characters = string.ascii_uppercase + string.digits
# Ensure uniqueness by checking existing codes
cache = cls._get_redis_client()
max_attempts = 100
for _ in range(max_attempts):
code = ''.join(secrets.choice(characters) for _ in range(length))
if not cache.get(f'room_code_{code}'):
return code
raise ValueError("Unable to generate unique short code")
@classmethod
def create_room(cls, creator_ip=None):
"""Create a new video call room"""
cache = cls._get_redis_client()
room_data = {
'room_id': str(uuid.uuid4()),
'short_code': cls.generate_short_code(),
'created_at': timezone.now().isoformat(),
'participants': [],
'is_active': True,
'expires_at': (
timezone.now() +
timedelta(hours=getattr(settings, 'ROOM_EXPIRY_HOURS', 24))
).isoformat(),
'creator_ip': creator_ip,
'max_participants': getattr(settings, 'MAX_PARTICIPANTS_PER_ROOM', 2)
}
# Store room data with expiration
cache.set(
f'room_{room_data["room_id"]}',
room_data,
timeout=getattr(settings, 'ROOM_EXPIRY_HOURS', 24) * 3600
)
# Create code mapping for easy lookup
cache.set(
f'room_code_{room_data["short_code"]}',
room_data["room_id"],
timeout=getattr(settings, 'ROOM_EXPIRY_HOURS', 24) * 3600
)
# Log room creation
from apps.core.models import RoomActivityLog
RoomActivityLog.objects.create(
room_id=room_data["room_id"],
action='created',
ip_address=creator_ip
)
return room_data
@classmethod
def get_room_by_id(cls, room_id):
"""Retrieve room data by room ID"""
cache = cls._get_redis_client()
return cache.get(f'room_{room_id}')
@classmethod
def get_room_by_code(cls, short_code):
"""Retrieve room data by short code"""
cache = cls._get_redis_client()
room_id = cache.get(f'room_code_{short_code}')
if room_id:
return cls.get_room_by_id(room_id)
return None
@classmethod
def join_room(cls, room_identifier, participant_id, participant_ip=None):
"""
Add participant to room.
room_identifier can be either room_id or short_code
"""
cache = cls._get_redis_client()
# Try to get room by ID first, then by code
room_data = cls.get_room_by_id(room_identifier)
if not room_data:
room_data = cls.get_room_by_code(room_identifier)
if not room_data:
return None, "Room not found"
# Check if room is active and not expired
if not room_data.get('is_active', False):
return None, "Room is not active"
expires_at = timezone.datetime.fromisoformat(
room_data['expires_at'].replace('Z', '+00:00')
)
if timezone.now() > expires_at:
cls.delete_room(room_data['room_id'])
return None, "Room has expired"
# Check participant limit
current_participants = room_data.get('participants', [])
max_participants = room_data.get('max_participants', 2)
if len(current_participants) >= max_participants:
return None, "Room is full"
# Add participant if not already in room
if participant_id not in current_participants:
current_participants.append(participant_id)
room_data['participants'] = current_participants
# Update room data
cache.set(
f'room_{room_data["room_id"]}',
room_data,
timeout=getattr(settings, 'ROOM_EXPIRY_HOURS', 24) * 3600
)
# Log participant join
from apps.core.models import RoomActivityLog
RoomActivityLog.objects.create(
room_id=room_data["room_id"],
action='joined',
participant_count=len(current_participants),
ip_address=participant_ip
)
return room_data, "Successfully joined room"
@classmethod
def leave_room(cls, room_id, participant_id):
"""Remove participant from room"""
cache = cls._get_redis_client()
room_data = cls.get_room_by_id(room_id)
if not room_data:
return False
participants = room_data.get('participants', [])
if participant_id in participants:
participants.remove(participant_id)
room_data['participants'] = participants
# Update room data
cache.set(
f'room_{room_id}',
room_data,
timeout=getattr(settings, 'ROOM_EXPIRY_HOURS', 24) * 3600
)
# Log participant leave
from apps.core.models import RoomActivityLog
RoomActivityLog.objects.create(
room_id=room_id,
action='left',
participant_count=len(participants)
)
# Delete room if no participants left
if not participants:
cls.delete_room(room_id)
return True
return False
@classmethod
def delete_room(cls, room_id):
"""Delete room and clean up all associated data"""
cache = cls._get_redis_client()
room_data = cls.get_room_by_id(room_id)
if room_data:
# Remove code mapping
short_code = room_data.get('short_code')
if short_code:
cache.delete(f'room_code_{short_code}')
# Remove room data
cache.delete(f'room_{room_id}')
# Log room deletion
from apps.core.models import RoomActivityLog
RoomActivityLog.objects.create(
room_id=room_id,
action='deleted'
)
return True
return False
@classmethod
def cleanup_expired_rooms(cls):
"""Clean up expired rooms (to be called by scheduled task)"""
# This would typically be implemented as a management command
# or scheduled task using Django-Q or Celery
pass

View File

@@ -0,0 +1,7 @@
# rooms/routing.py - WebSocket URL routing
from django.urls import path
from apps.rooms import consumers
websocket_urlpatterns = [
path('ws/room/<str:room_id>/', consumers.VideoCallConsumer.as_asgi()),
]

View File

@@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

View File

@@ -0,0 +1,14 @@
# rooms/urls.py - Room management URL patterns
from django.urls import path
from . import views
app_name = 'rooms'
urlpatterns = [
path('create/', views.create_room, name='create'),
path('join/', views.join_room, name='join'),
path('<str:room_id>/', views.get_room, name='get'),
path('<str:room_id>/leave/', views.leave_room, name='leave'),
path('<str:room_id>/delete/', views.delete_room, name='delete'),
]

293
backend/apps/rooms/views.py Normal file
View File

@@ -0,0 +1,293 @@
# rooms/views.py - Room management API views
from django.utils import timezone
from django.views.decorators.csrf import csrf_exempt
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework import status
from django_ratelimit.decorators import ratelimit
from apps.rooms.models import RoomManager
from apps.core.views import get_client_ip
import qrcode
import io
import base64
import logging
logger = logging.getLogger(__name__)
def require_auth(view_func):
"""Decorator to require authentication for views"""
def wrapper(request, *args, **kwargs):
if not request.session.get('authenticated'):
logger.warning(f"Unauthenticated access attempt to {request.path}")
return Response(
{'error': 'Authentication required'},
status=status.HTTP_401_UNAUTHORIZED
)
return view_func(request, *args, **kwargs)
return wrapper
@api_view(['POST'])
@permission_classes([AllowAny])
@csrf_exempt
@require_auth
@ratelimit(key='ip', rate='30/min', method='POST', block=True)
def create_room(request):
"""Create a new video call room"""
try:
client_ip = get_client_ip(request)
logger.info(f"Creating room for IP: {client_ip}")
room_data = RoomManager.create_room(creator_ip=client_ip)
# Generate QR code for the room
room_url = f"{request.build_absolute_uri('/')}join/{room_data['short_code']}"
qr = qrcode.QRCode(version=1, box_size=10, border=5)
qr.add_data(room_url)
qr.make(fit=True)
qr_image = qr.make_image(fill_color="black", back_color="white")
buffer = io.BytesIO()
qr_image.save(buffer, format='PNG')
qr_code_data = base64.b64encode(buffer.getvalue()).decode()
response_data = {
'room_id': room_data['room_id'],
'short_code': room_data['short_code'],
'room_url': room_url,
'qr_code': f"data:image/png;base64,{qr_code_data}",
'expires_at': room_data['expires_at'],
'max_participants': room_data['max_participants']
}
logger.info(f"Room created successfully: {room_data['room_id']}")
return Response(response_data, status=status.HTTP_201_CREATED)
except Exception as e:
logger.error(f"Room creation failed: {e}")
return Response(
{'error': 'Failed to create room'},
status=status.HTTP_500_INTERNAL_SERVER_ERROR
)
@api_view(['GET'])
@permission_classes([AllowAny])
@csrf_exempt
@require_auth
def get_room(request, room_id):
"""Get room information by room ID"""
try:
logger.info(f"Getting room info for: {room_id}")
room_data = RoomManager.get_room_by_id(room_id)
if not room_data:
logger.warning(f"Room not found: {room_id}")
return Response(
{'error': 'Room not found'},
status=status.HTTP_404_NOT_FOUND
)
# Check if room has expired
expires_at = timezone.datetime.fromisoformat(
room_data['expires_at'].replace('Z', '+00:00')
)
if timezone.now() > expires_at:
logger.info(f"Room expired, deleting: {room_id}")
RoomManager.delete_room(room_id)
return Response(
{'error': 'Room has expired'},
status=status.HTTP_404_NOT_FOUND
)
response_data = {
'room_id': room_data['room_id'],
'short_code': room_data['short_code'],
'is_active': room_data['is_active'],
'participant_count': len(room_data.get('participants', [])),
'max_participants': room_data.get('max_participants', 2),
'expires_at': room_data['expires_at']
}
logger.info(f"Room info retrieved: {room_id}, participants: {len(room_data.get('participants', []))}")
return Response(response_data)
except Exception as e:
logger.error(f"Failed to retrieve room {room_id}: {e}")
return Response(
{'error': 'Failed to retrieve room'},
status=status.HTTP_500_INTERNAL_SERVER_ERROR
)
@api_view(['POST'])
@permission_classes([AllowAny])
@csrf_exempt
@require_auth
@ratelimit(key='ip', rate='60/min', method='POST', block=True)
def join_room(request):
"""Join a room by room ID or short code"""
try:
room_identifier = request.data.get('room_identifier')
# Ensure we have a session
if not request.session.session_key:
request.session.create()
participant_id = request.session.session_key
if not room_identifier:
return Response(
{'error': 'Room identifier is required'},
status=status.HTTP_400_BAD_REQUEST
)
logger.info(f"Joining room: {room_identifier} with participant: {participant_id}")
client_ip = get_client_ip(request)
room_data, message = RoomManager.join_room(
room_identifier,
participant_id,
client_ip
)
if not room_data:
logger.warning(f"Failed to join room: {room_identifier}, reason: {message}")
return Response(
{'error': message},
status=status.HTTP_400_BAD_REQUEST
)
response_data = {
'success': True,
'message': message,
'room_id': room_data['room_id'],
'short_code': room_data['short_code'],
'participant_count': len(room_data.get('participants', [])),
'participant_id': participant_id
}
logger.info(f"User joined room: {room_data['room_id']}, participant: {participant_id}")
return Response(response_data)
except Exception as e:
logger.error(f"Failed to join room: {e}")
return Response(
{'error': 'Failed to join room'},
status=status.HTTP_500_INTERNAL_SERVER_ERROR
)
@api_view(['POST'])
@permission_classes([AllowAny])
@csrf_exempt
@require_auth
def leave_room(request, room_id):
"""Leave a room"""
try:
# Ensure we have a session
if not request.session.session_key:
logger.warning(f"No session key when trying to leave room: {room_id}")
return Response(
{'success': True, # Return success even if no session, as user wasn't in room anyway
'message': 'No active session found'})
participant_id = request.session.session_key
logger.info(f"Leaving room: {room_id} with participant: {participant_id}")
# Check if room exists first
room_data = RoomManager.get_room_by_id(room_id)
if not room_data:
logger.info(f"Room {room_id} not found when trying to leave")
return Response({
'success': True, # Return success as room doesn't exist anyway
'message': 'Room not found'
})
# Check if participant is actually in the room
participants = room_data.get('participants', [])
if participant_id not in participants:
logger.info(f"Participant {participant_id} not in room {room_id}")
return Response({
'success': True, # Return success as user wasn't in room anyway
'message': 'Not in room'
})
success = RoomManager.leave_room(room_id, participant_id)
if success:
logger.info(f"User left room: {room_id}, participant: {participant_id}")
return Response({
'success': True,
'message': 'Left room successfully'
})
else:
logger.warning(f"Failed to leave room: {room_id}, participant: {participant_id}")
return Response({
'success': True, # Still return success to avoid client errors
'message': 'Room leave processed'
})
except Exception as e:
logger.error(f"Failed to leave room {room_id}: {e}")
return Response(
{'error': 'Failed to leave room'},
status=status.HTTP_500_INTERNAL_SERVER_ERROR
)
@api_view(['DELETE'])
@permission_classes([AllowAny])
@csrf_exempt
@require_auth
def delete_room(request, room_id):
"""Delete a room (only creator or admin can delete)"""
try:
logger.info(f"Deleting room: {room_id}")
# Check if room exists
room_data = RoomManager.get_room_by_id(room_id)
if not room_data:
return Response(
{'error': 'Room not found'},
status=status.HTTP_404_NOT_FOUND
)
# Additional permission check could be added here
success = RoomManager.delete_room(room_id)
if success:
logger.info(f"Room deleted: {room_id}")
return Response({
'success': True,
'message': 'Room deleted successfully'
})
else:
return Response(
{'error': 'Failed to delete room'},
status=status.HTTP_500_INTERNAL_SERVER_ERROR
)
except Exception as e:
logger.error(f"Failed to delete room {room_id}: {e}")
return Response(
{'error': 'Failed to delete room'},
status=status.HTTP_500_INTERNAL_SERVER_ERROR
)
@api_view(['GET'])
@permission_classes([AllowAny])
@csrf_exempt
@require_auth
def health_check(request):
"""API health check endpoint"""
return Response({
'status': 'healthy',
'timestamp': timezone.now().isoformat(),
'authenticated': True,
'session_key': request.session.session_key
})