mirror of
https://github.com/suitenumerique/meet.git
synced 2026-11-16 21:03:10 +00:00
Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b8992156da |
@@ -17,6 +17,7 @@ and this project adheres to
|
||||
|
||||
### Changed
|
||||
|
||||
- ✨(backend) create LiveKit rooms server-side before handing out join tokens
|
||||
- ⬆️(frontend) upgrade livekit-client to 2.23.0
|
||||
- ✨(backend) expose LiveKit reconnection settings in the config
|
||||
- ✨(backend) keep recordings cut short by LiveKit egress
|
||||
|
||||
@@ -4,6 +4,12 @@ redis:
|
||||
keys:
|
||||
devkey: secret
|
||||
|
||||
# The backend creates rooms before it hands out a join token, so LiveKit must not
|
||||
# create them on join. This also lets Meet share its LiveKit instance with
|
||||
# services that require this setting.
|
||||
room:
|
||||
auto_create: false
|
||||
|
||||
webhook:
|
||||
api_key: devkey
|
||||
urls:
|
||||
|
||||
@@ -129,6 +129,8 @@ Accessibility follows these patterns:
|
||||
|
||||
The pass is the LiveKit access token the backend signs for each participant; the browser connects to LiveKit with it, as [Joining a meeting](../overview/how-meet-works.md#joining-a-meeting) describes.
|
||||
|
||||
Before issuing a pass, the backend makes sure the room exists in LiveKit, creating it with the room's configuration and access level as metadata. LiveKit is thus never asked to create a room on join, so its `room.auto_create` setting can stay `false`.
|
||||
|
||||
[`generate_token()`](https://github.com/suitenumerique/meet/blob/main/src/backend/core/utils.py) in `core/utils.py` builds it. The token's name is the participant's display name, and it carries three attributes: `room_role`, `is_authenticated` and `color`, the last derived from the participant's identity.
|
||||
|
||||
Owners and administrators get LiveKit's `room_admin` grant, which lets them moderate.
|
||||
@@ -147,6 +149,7 @@ sequenceDiagram
|
||||
participant LiveKit
|
||||
|
||||
Browser->>Backend: POST /api/v1.0/rooms/{id}/join/ {username}
|
||||
Backend->>LiveKit: Create the room if it does not exist
|
||||
Backend-->>Browser: room, with livekit {url, token, room}
|
||||
Browser->>LiveKit: WebSocket with the token
|
||||
Browser->>LiveKit: publish microphone and camera
|
||||
@@ -160,6 +163,7 @@ Every call goes through the client that [`create_livekit_client()`](https://gith
|
||||
|
||||
| What | Backend side | What the frontend does with it |
|
||||
|---|---|---|
|
||||
| Creating a room before handing out a pass, and creating the rooms of unregistered links and connection tests | `RoomManagement.create_room()` and `ensure_room()` in [`core/services/room_management.py`](https://github.com/suitenumerique/meet/blob/main/src/backend/core/services/room_management.py) | Nothing: the pass only works once the room exists |
|
||||
| Room metadata: the room's configuration and access level, and the recording state | `RoomManagement.update_metadata()` in [`core/services/room_management.py`](https://github.com/suitenumerique/meet/blob/main/src/backend/core/services/room_management.py) | [`RoomMetadataSynchronizer`](https://github.com/suitenumerique/meet/blob/main/src/frontend/src/features/rooms/livekit/components/RoomMetadataSynchronizer.tsx) copies the configuration and access level into the cached room, and [`useRecordingStatuses`](https://github.com/suitenumerique/meet/blob/main/src/frontend/src/features/recording/hooks/useRecordingStatuses.ts) reads the recording state |
|
||||
| Data messages to every participant, such as someone waiting to enter | `notify_participants()` in [`core/utils.py`](https://github.com/suitenumerique/meet/blob/main/src/backend/core/utils.py) | [`MainNotificationToast.tsx`](https://github.com/suitenumerique/meet/blob/main/src/frontend/src/features/notifications/MainNotificationToast.tsx) turns them into toasts and sounds |
|
||||
| Muting, removing and updating a participant | [`core/services/participants_management.py`](https://github.com/suitenumerique/meet/blob/main/src/backend/core/services/participants_management.py) | LiveKit applies it to the participant's connection |
|
||||
|
||||
@@ -4,6 +4,11 @@
|
||||
livekit:
|
||||
keys:
|
||||
meet: <LIVEKIT_API_SECRET>
|
||||
# Meet creates rooms before handing out join tokens, so LiveKit must not
|
||||
# create them on join. This also lets it share an instance with services
|
||||
# that require this setting to be false for security reasons.
|
||||
room:
|
||||
auto_create: false
|
||||
# Your Redis, the one Meet uses
|
||||
redis:
|
||||
address: redis-master.meet.svc.cluster.local:6379
|
||||
|
||||
@@ -3,6 +3,11 @@ redis:
|
||||
address: redis:6379
|
||||
keys:
|
||||
meet: <your livekit secret key>
|
||||
# The backend creates rooms before it hands out a join token, so LiveKit must not
|
||||
# create them on join. This also lets Meet share its LiveKit instance with
|
||||
# services that require this setting to be false for security reasons.
|
||||
room:
|
||||
auto_create: false
|
||||
# WebRTC configuration
|
||||
rtc:
|
||||
# # when set, LiveKit will attempt to use a UDP mux so all UDP traffic goes through
|
||||
|
||||
@@ -64,7 +64,7 @@ Each piece's ports are in [Firewall & Ports](../self-hosting/configuration/firew
|
||||
- **Signaling and media.** Signaling is the control talk of a call, such as joining or who publishes what, over a WebSocket on port 443. Media is the audio and video, over UDP, or TCP when UDP is blocked. See [Getting through firewalls](#firewalls).
|
||||
- **[Simulcast](https://bloggeek.me/webrtcglossary/simulcast/) and [SVC](https://bloggeek.me/webrtcglossary/svc/).** Each camera sends its video at up to three qualities, and LiveKit forwards to each viewer the one that fits their connection and the size their video is shown at.
|
||||
- **The LiveKit pass.** What the browser shows LiveKit to join a meeting: a signed [JWT](https://datatracker.ietf.org/doc/html/rfc7519) the backend issues. See [What happens when someone joins?](#joining-a-meeting)
|
||||
- **Room and meeting.** A room is the lasting record, its code, settings and roles, kept in the PostgreSQL database. A meeting is the live session LiveKit opens when the first person joins the room and closes when the last one leaves. See [What happens when a meeting ends?](#when-the-meeting-ends)
|
||||
- **Room and meeting.** A room is the lasting record, its code, settings and roles, kept in the PostgreSQL database. A meeting is the live session the backend opens in LiveKit when someone asks to join the room, and LiveKit closes it when the last participant leaves. See [What happens when a meeting ends?](#when-the-meeting-ends).
|
||||
- **Roles and access levels.** A role ties a user to a room: owner, co-host or member. The access level decides who walks straight in and who waits. See [Who can do what?](#who-gets-in)
|
||||
- **The waiting room.** **Lobby** in the app: where a visitor waits until a host admits them. See [Who can do what?](#who-gets-in)
|
||||
- **Webhooks.** LiveKit calls the backend over HTTP when a meeting starts or ends, someone leaves, or a recording changes state. These calls feed recordings, phone dial-in, the clean-up after a meeting and the [room purge](../self-hosting/configuration/room-purge.md#how-a-room-becomes-purgeable); see [Webhook](../self-hosting/configuration/livekit.md#webhook).
|
||||
@@ -107,6 +107,8 @@ A meeting lives at a room code, such as `meet.example.com/abc-defg-hij`. When yo
|
||||
- It names you, the room and what you may publish: microphone, camera, screen share.
|
||||
- It stays valid for 6 hours.
|
||||
|
||||
Before handing it out, the backend creates the room in LiveKit if it does not exist yet. LiveKit can therefore run with `room.auto_create: false`, as sharing an instance with services that require this setting to be false for security reasons.
|
||||
|
||||
If you may not walk straight in, you go through the [waiting room](#who-gets-in) first. With the pass, the browser opens a WebSocket to LiveKit and starts sending and receiving audio and video.
|
||||
|
||||
Sign-in decides who you *are*; the pass decides what you may *do* in the room.
|
||||
@@ -176,6 +178,7 @@ sequenceDiagram
|
||||
end
|
||||
H->>BE: Admit the visitor
|
||||
V->>BE: POST …/request-entry/ again
|
||||
BE->>LK: Create the room if it does not exist
|
||||
BE-->>V: Admitted, with the LiveKit pass
|
||||
V->>LK: Join the meeting
|
||||
```
|
||||
@@ -276,9 +279,11 @@ sequenceDiagram
|
||||
participant SIP as LiveKit SIP
|
||||
participant P as Phone
|
||||
|
||||
B->>LK: First person joins
|
||||
B->>BE: Join the room
|
||||
BE->>LK: Create the room
|
||||
LK-->>BE: Webhook: room started
|
||||
BE->>LK: Create the rule: this PIN → this room
|
||||
B->>LK: Join the meeting
|
||||
P->>SIP: Call the number, type the PIN
|
||||
SIP->>LK: Join the meeting, audio only
|
||||
Note over B,P: The last person leaves
|
||||
@@ -286,7 +291,7 @@ sequenceDiagram
|
||||
BE->>LK: Delete the rule
|
||||
```
|
||||
|
||||
Meeting-room video systems dial in over SIP the same way, through Roomkit. For them, LiveKit SIP first sends the PIN to the backend, at `POST /api/v1.0/roomkit/join/`. The backend finds the room with that PIN and, if the room has no rule yet, creates one on the spot. The device can then open a meeting nobody has joined yet.
|
||||
Meeting-room video systems dial in over SIP the same way, through Roomkit. For them, LiveKit SIP first sends the PIN to the backend, at `POST /api/v1.0/roomkit/join/`. The backend finds the room with that PIN, then creates the room in LiveKit and its dispatch rule, so the device can open a meeting nobody has joined yet.
|
||||
|
||||
Setup is in [Telephony](../self-hosting/configuration/telephony.md).
|
||||
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
LiveKit is the media server: every participant sends it their audio and video, and it forwards each stream to the others. The [Deployment Guide](../compose/deployment-guide.md)'s [`livekit-server.yaml`](https://github.com/suitenumerique/meet/blob/main/docs/examples/meet/livekit-server.yaml) works as shipped. The backend's LiveKit variables are in [Environment Variables: LiveKit](../../reference/env-variables.md#livekit).
|
||||
|
||||
That file sets `room.auto_create: false`: Meet creates each room through LiveKit's API before it hands out a join token. Keep this setting. It is what lets Meet share its LiveKit instance with services that require room creation to stay under their control.
|
||||
|
||||
## How media connects
|
||||
|
||||
[Signaling](../../overview/how-meet-works.md#key-concepts) goes through your reverse proxy on 443 to LiveKit's port 7880, which stays [private](firewall.md#never-public). Media goes straight between the browser and LiveKit, on the first path the network allows:
|
||||
|
||||
@@ -596,6 +596,13 @@ class RoomViewSet( # pylint: disable=too-many-public-methods
|
||||
|
||||
room, slug = self._get_object_or_unregistered_slug()
|
||||
if room is None:
|
||||
try:
|
||||
RoomManagement.create_room(slug)
|
||||
except RoomManagementException as e:
|
||||
raise drf_exceptions.APIException(
|
||||
"Could not create the room, please try again."
|
||||
) from e
|
||||
|
||||
return drf_response.Response(
|
||||
{
|
||||
**self._get_unregistered_room_data(slug),
|
||||
@@ -611,6 +618,13 @@ class RoomViewSet( # pylint: disable=too-many-public-methods
|
||||
).data
|
||||
|
||||
if LobbyService.can_bypass_lobby(room=room, user=request.user, role=role):
|
||||
try:
|
||||
RoomManagement.ensure_room(room)
|
||||
except RoomManagementException as e:
|
||||
raise drf_exceptions.APIException(
|
||||
"Could not create the room, please try again."
|
||||
) from e
|
||||
|
||||
data["livekit"] = utils.generate_livekit_config(
|
||||
room_id=str(room.id),
|
||||
user=request.user,
|
||||
@@ -640,11 +654,17 @@ class RoomViewSet( # pylint: disable=too-many-public-methods
|
||||
room = self.get_object()
|
||||
lobby_service = LobbyService()
|
||||
|
||||
participant, livekit = lobby_service.request_entry(
|
||||
room=room,
|
||||
user=request.user,
|
||||
**serializer.validated_data,
|
||||
)
|
||||
try:
|
||||
participant, livekit = lobby_service.request_entry(
|
||||
room=room,
|
||||
user=request.user,
|
||||
**serializer.validated_data,
|
||||
)
|
||||
except RoomManagementException as e:
|
||||
raise drf_exceptions.APIException(
|
||||
"Could not create the room, please try again."
|
||||
) from e
|
||||
|
||||
return drf_response.Response(
|
||||
{
|
||||
**participant.to_dict(),
|
||||
@@ -1731,6 +1751,13 @@ class DiagnosticsViewSet(viewsets.ViewSet):
|
||||
room = f"{settings.CONNECTION_TEST_ROOM_PREFIX}-{uuid4()}"
|
||||
expires_in = settings.CONNECTION_TEST_TOKEN_TTL_SECONDS
|
||||
|
||||
try:
|
||||
RoomManagement.create_room(room)
|
||||
except RoomManagementException as e:
|
||||
raise drf_exceptions.APIException(
|
||||
"Could not create the connection test room, please try again."
|
||||
) from e
|
||||
|
||||
# LiveKit refreshes tokens for connected clients, so JWT TTL alone does not
|
||||
# eject someone who stays connected. Schedule a hard DeleteRoom when Celery
|
||||
# is available.
|
||||
|
||||
@@ -16,6 +16,7 @@ from rest_framework import (
|
||||
from core import analytics, models
|
||||
from core.api import permissions, throttling
|
||||
from core.api.feature_flag import FeatureFlag
|
||||
from core.services.room_management import RoomManagement, RoomManagementException
|
||||
from core.services.sip_management import SIPException, SIPManagement
|
||||
|
||||
from . import authentication, serializers
|
||||
@@ -64,7 +65,10 @@ class RoomKitViewSet(viewsets.ViewSet):
|
||||
raise drf_exceptions.NotFound("No room found for this PIN code.") from e
|
||||
|
||||
try:
|
||||
RoomManagement.ensure_room(room)
|
||||
created = SIPManagement().ensure_dispatch_rule(room)
|
||||
except RoomManagementException as e:
|
||||
raise drf_exceptions.APIException("Could not create the room.") from e
|
||||
except SIPException as e:
|
||||
raise drf_exceptions.APIException("Could not create dispatch rule.") from e
|
||||
|
||||
|
||||
@@ -358,8 +358,9 @@ class LiveKitEventsService:
|
||||
def _close_deleted_room(room_id):
|
||||
"""Close a LiveKit room recreated after its room was soft deleted.
|
||||
|
||||
LiveKit auto-creates a room on join, so a participant still holding a
|
||||
valid token can bring a deleted room back to life until the token expires.
|
||||
A participant still holding a valid token can bring a deleted room back
|
||||
to life until the token expires when the LiveKit server auto-creates
|
||||
rooms on join.
|
||||
"""
|
||||
|
||||
logger.warning(
|
||||
|
||||
@@ -12,6 +12,7 @@ from django.core.cache import cache
|
||||
from django.utils import timezone
|
||||
|
||||
from core import models, utils
|
||||
from core.services.room_management import RoomManagement
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -194,6 +195,7 @@ class LobbyService:
|
||||
self.clear_participant_cache(room.id, participant.id)
|
||||
participant.status = LobbyParticipantStatus.ACCEPTED
|
||||
|
||||
RoomManagement.ensure_room(room)
|
||||
livekit_config = utils.generate_livekit_config(
|
||||
room_id=room_id,
|
||||
user=user,
|
||||
@@ -216,6 +218,7 @@ class LobbyService:
|
||||
|
||||
elif participant.status == LobbyParticipantStatus.ACCEPTED:
|
||||
# wrongly named, contains access token to join a room
|
||||
RoomManagement.ensure_room(room)
|
||||
livekit_config = utils.generate_livekit_config(
|
||||
room_id=room_id,
|
||||
user=user,
|
||||
|
||||
@@ -11,6 +11,7 @@ from django.conf import settings
|
||||
|
||||
from asgiref.sync import async_to_sync
|
||||
from livekit.api import (
|
||||
CreateRoomRequest,
|
||||
DeleteRoomRequest,
|
||||
ListRoomsRequest,
|
||||
TwirpError,
|
||||
@@ -37,6 +38,70 @@ class RoomNotFoundException(RoomManagementException):
|
||||
class RoomManagement:
|
||||
"""Service for managing LiveKit rooms."""
|
||||
|
||||
@staticmethod
|
||||
def _metadata_for_room(room: Room) -> Dict:
|
||||
"""Build the LiveKit metadata describing a room."""
|
||||
return {
|
||||
"configuration": room.configuration,
|
||||
"access_level": room.access_level,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
@async_to_sync
|
||||
async def create_room(cls, room_name: str, metadata: Optional[Dict] = None):
|
||||
"""Ensure a LiveKit room exists, creating it if it does not.
|
||||
|
||||
This is what lets the server keep `room.auto_create: false`, since a
|
||||
room then has to be created before a participant is given a token for it.
|
||||
|
||||
The room is only created when missing: LiveKit's CreateRoom updates the
|
||||
metadata of an existing room, which would wipe the recording state the
|
||||
room carries while a recording is in progress.
|
||||
|
||||
The `room_name` corresponds to the LiveKit room identifier
|
||||
(i.e. the Room model's UUID as a string, or an unregistered room's slug).
|
||||
|
||||
Raises:
|
||||
RoomManagementException: the room could not be created.
|
||||
"""
|
||||
|
||||
lkapi = utils.create_livekit_client()
|
||||
|
||||
try:
|
||||
response = await lkapi.room.list_rooms(ListRoomsRequest(names=[room_name]))
|
||||
|
||||
if response.rooms:
|
||||
return
|
||||
|
||||
await lkapi.room.create_room(
|
||||
CreateRoomRequest(
|
||||
name=room_name,
|
||||
metadata=json.dumps(metadata) if metadata is not None else "",
|
||||
)
|
||||
)
|
||||
|
||||
except (TwirpError, TimeoutError) as e:
|
||||
# A concurrent join may have created the room between the check and
|
||||
# the call; that is the outcome we want anyway.
|
||||
if isinstance(e, TwirpError) and e.code == TwirpErrorCode.ALREADY_EXISTS:
|
||||
logger.debug("LiveKit room %s already exists", room_name)
|
||||
return
|
||||
|
||||
logger.exception("Unexpected error ensuring room %s exists", room_name)
|
||||
raise RoomManagementException("Could not create room") from e
|
||||
|
||||
finally:
|
||||
await lkapi.aclose()
|
||||
|
||||
@classmethod
|
||||
def ensure_room(cls, room: Room):
|
||||
"""Create a room's LiveKit room, carrying its current settings.
|
||||
|
||||
Raises:
|
||||
RoomManagementException: the room could not be created.
|
||||
"""
|
||||
cls.create_room(str(room.id), metadata=cls._metadata_for_room(room))
|
||||
|
||||
@classmethod
|
||||
@async_to_sync
|
||||
async def update_metadata(
|
||||
@@ -178,15 +243,10 @@ class RoomManagement:
|
||||
should never fail the request that triggered the update.
|
||||
"""
|
||||
|
||||
metadata = {
|
||||
"configuration": room.configuration,
|
||||
"access_level": room.access_level,
|
||||
}
|
||||
|
||||
try:
|
||||
cls.update_metadata(
|
||||
room_name=str(room.id),
|
||||
metadata=metadata,
|
||||
metadata=cls._metadata_for_room(room),
|
||||
)
|
||||
except RoomNotFoundException:
|
||||
logger.info(
|
||||
|
||||
@@ -9,11 +9,21 @@ from unittest import mock
|
||||
import pytest
|
||||
|
||||
from ...factories import RoomFactory
|
||||
from ...services.room_management import RoomManagementException
|
||||
from ...services.sip_management import SIPException
|
||||
|
||||
pytestmark = pytest.mark.django_db
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def mock_room_creation():
|
||||
"""Mock the LiveKit room creation performed before the device dials in."""
|
||||
with mock.patch(
|
||||
"core.services.room_management.RoomManagement.create_room"
|
||||
) as mock_create_room:
|
||||
yield mock_create_room
|
||||
|
||||
|
||||
@mock.patch("core.roomkit.viewsets.SIPManagement")
|
||||
def test_join_anonymous(mock_sip_management, settings, client):
|
||||
"""Requests without an Authorization header should be rejected."""
|
||||
@@ -202,8 +212,8 @@ def test_join_unknown_pin(mock_sip_management, settings, client):
|
||||
|
||||
|
||||
@mock.patch("core.roomkit.viewsets.SIPManagement")
|
||||
def test_join_success(mock_sip_management, settings, client):
|
||||
"""Requests with a valid PIN should create the dispatch rule."""
|
||||
def test_join_success(mock_sip_management, settings, client, mock_room_creation):
|
||||
"""Requests with a valid PIN should create the room and its dispatch rule."""
|
||||
|
||||
mock_sip_instance = mock_sip_management.return_value
|
||||
|
||||
@@ -221,9 +231,41 @@ def test_join_success(mock_sip_management, settings, client):
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"status": "success"}
|
||||
mock_room_creation.assert_called_once_with(
|
||||
str(room.id),
|
||||
metadata={
|
||||
"configuration": room.configuration,
|
||||
"access_level": room.access_level,
|
||||
},
|
||||
)
|
||||
mock_sip_instance.ensure_dispatch_rule.assert_called_once_with(room)
|
||||
|
||||
|
||||
@mock.patch("core.roomkit.viewsets.SIPManagement")
|
||||
def test_join_room_creation_failure(
|
||||
mock_sip_management, settings, client, mock_room_creation
|
||||
):
|
||||
"""A LiveKit room that cannot be created fails the join before the rule."""
|
||||
|
||||
mock_sip_instance = mock_sip_management.return_value
|
||||
|
||||
settings.ROOMKIT_ENABLED = True
|
||||
settings.ROOMKIT_SERVER_TO_SERVER_API_TOKEN = "testAuthToken"
|
||||
|
||||
room = RoomFactory(pin_code="1234567890")
|
||||
mock_room_creation.side_effect = RoomManagementException("Could not create room")
|
||||
|
||||
response = client.post(
|
||||
"/api/v1.0/roomkit/join/",
|
||||
{"pin_code": room.pin_code},
|
||||
HTTP_AUTHORIZATION="Bearer testAuthToken",
|
||||
)
|
||||
|
||||
assert response.status_code == 500
|
||||
assert response.json() == {"detail": "Could not create the room."}
|
||||
mock_sip_instance.ensure_dispatch_rule.assert_not_called()
|
||||
|
||||
|
||||
@mock.patch("core.roomkit.viewsets.SIPManagement")
|
||||
def test_join_dispatch_rule_already_exists(mock_sip_management, settings, client):
|
||||
"""Requests should succeed when the dispatch rule already exists (idempotency)."""
|
||||
|
||||
@@ -21,11 +21,22 @@ from ...factories import (
|
||||
UserResourceAccessFactory,
|
||||
)
|
||||
from ...models import RoleChoices, RoomAccessLevel
|
||||
from ...services.room_management import RoomManagementException
|
||||
from ..utils import generate_user_access_token
|
||||
|
||||
fake = Faker()
|
||||
pytestmark = pytest.mark.django_db
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def mock_room_creation():
|
||||
"""Mock the LiveKit room creation performed before a token is issued."""
|
||||
with mock.patch(
|
||||
"core.services.room_management.RoomManagement.create_room"
|
||||
) as mock_create_room:
|
||||
yield mock_create_room
|
||||
|
||||
|
||||
livekit_token = fake.sha256()
|
||||
|
||||
ANONYMOUS = "anonymous"
|
||||
@@ -146,6 +157,40 @@ def test_api_rooms_join_by_slug(mock_token):
|
||||
mock_token.assert_called_once()
|
||||
|
||||
|
||||
def test_api_rooms_join_creates_livekit_room(mock_room_creation):
|
||||
"""Joining creates the LiveKit room with its current settings."""
|
||||
room = RoomFactory(
|
||||
access_level=RoomAccessLevel.PUBLIC,
|
||||
configuration={"everyone_can_mute": True},
|
||||
)
|
||||
|
||||
response = APIClient().post(join_url(room.id), {}, format="json")
|
||||
|
||||
assert response.status_code == 200
|
||||
mock_room_creation.assert_called_once_with(
|
||||
str(room.id),
|
||||
metadata={
|
||||
"configuration": {"everyone_can_mute": True},
|
||||
"access_level": RoomAccessLevel.PUBLIC,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("lookup", ["id", "unregistered-room"])
|
||||
def test_api_rooms_join_room_creation_failure(mock_room_creation, lookup, settings):
|
||||
"""The join fails when its LiveKit room cannot be created."""
|
||||
settings.ALLOW_UNREGISTERED_ROOMS = True
|
||||
mock_room_creation.side_effect = RoomManagementException("Could not create room")
|
||||
room = RoomFactory(access_level=RoomAccessLevel.PUBLIC)
|
||||
|
||||
response = APIClient().post(
|
||||
join_url(room.id if lookup == "id" else lookup), {}, format="json"
|
||||
)
|
||||
|
||||
assert response.status_code == 500
|
||||
assert response.json() == {"detail": "Could not create the room, please try again."}
|
||||
|
||||
|
||||
@mock.patch("core.utils.generate_token", return_value=livekit_token)
|
||||
def test_api_rooms_join_members_num_queries(mock_token, django_assert_num_queries):
|
||||
"""The role of the requester should only be looked up once."""
|
||||
@@ -195,7 +240,9 @@ def test_api_rooms_join_get_not_allowed():
|
||||
|
||||
@pytest.mark.parametrize("authenticated", [False, True])
|
||||
@mock.patch("core.utils.generate_token", return_value=livekit_token)
|
||||
def test_api_rooms_join_unregistered_allowed(mock_token, authenticated, settings):
|
||||
def test_api_rooms_join_unregistered_allowed(
|
||||
mock_token, mock_room_creation, authenticated, settings
|
||||
):
|
||||
"""
|
||||
Joining an unregistered room should return LiveKit credentials for the
|
||||
room named after the slug, when unregistered rooms are allowed.
|
||||
@@ -223,6 +270,7 @@ def test_api_rooms_join_unregistered_allowed(mock_token, authenticated, settings
|
||||
"token": livekit_token,
|
||||
},
|
||||
}
|
||||
mock_room_creation.assert_called_once_with("unregistered-room")
|
||||
mock_token.assert_called_once_with(
|
||||
room="unregistered-room",
|
||||
user=user,
|
||||
|
||||
@@ -17,10 +17,20 @@ from ... import utils
|
||||
from ...factories import RoomFactory, UserFactory
|
||||
from ...models import RoomAccessLevel
|
||||
from ...services.lobby import LobbyService
|
||||
from ...services.room_management import RoomManagementException
|
||||
|
||||
pytestmark = pytest.mark.django_db
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def mock_room_creation():
|
||||
"""Mock the LiveKit room creation performed before a token is issued."""
|
||||
with mock.patch(
|
||||
"core.services.room_management.RoomManagement.create_room"
|
||||
) as mock_create_room:
|
||||
yield mock_create_room
|
||||
|
||||
|
||||
def _lobby_signer():
|
||||
"""Use the polling credential's dedicated signing namespace."""
|
||||
return signing.Signer(salt="core.lobby.participant")
|
||||
@@ -203,7 +213,7 @@ def test_request_entry_with_existing_participants(settings):
|
||||
|
||||
|
||||
@freeze_time("2025-01-01 10:00:00")
|
||||
def test_request_entry_public_room(settings):
|
||||
def test_request_entry_public_room(settings, mock_room_creation):
|
||||
"""Entry requests to public rooms should return ACCEPTED status with LiveKit config."""
|
||||
room = RoomFactory(access_level=RoomAccessLevel.PUBLIC)
|
||||
client = APIClient()
|
||||
@@ -244,6 +254,28 @@ def test_request_entry_public_room(settings):
|
||||
|
||||
assert not cache.keys(f"mocked-cache-prefix_{room.id}_*")
|
||||
assert not LobbyService()._index_members(room.id)
|
||||
mock_room_creation.assert_called_once_with(
|
||||
str(room.id),
|
||||
metadata={
|
||||
"configuration": room.configuration,
|
||||
"access_level": room.access_level,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@freeze_time("2025-01-01 10:00:00")
|
||||
def test_request_entry_room_creation_failure(mock_room_creation, settings):
|
||||
"""A room that cannot be created in LiveKit fails the entry request."""
|
||||
room = RoomFactory(access_level=RoomAccessLevel.PUBLIC)
|
||||
mock_room_creation.side_effect = RoomManagementException("Could not create room")
|
||||
|
||||
response = APIClient().post(
|
||||
f"/api/v1.0/rooms/{room.id}/request-entry/",
|
||||
{"username": "test_user"},
|
||||
)
|
||||
|
||||
assert response.status_code == 500
|
||||
assert response.json() == {"detail": "Could not create the room, please try again."}
|
||||
|
||||
|
||||
@freeze_time("2025-01-01 10:00:00")
|
||||
|
||||
@@ -30,6 +30,15 @@ from core.utils import NotificationError
|
||||
pytestmark = pytest.mark.django_db
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def mock_room_creation():
|
||||
"""Mock the LiveKit room creation performed before a token is issued."""
|
||||
with mock.patch(
|
||||
"core.services.room_management.RoomManagement.create_room"
|
||||
) as mock_create_room:
|
||||
yield mock_create_room
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def lobby_service():
|
||||
"""Return a LobbyService instance."""
|
||||
@@ -218,7 +227,12 @@ def test_can_bypass_lobby_private_room_with_any_role(role, lobby_service):
|
||||
|
||||
@mock.patch("core.utils.generate_livekit_config")
|
||||
def test_request_entry_public_room(
|
||||
mock_generate_config, lobby_service, participant_id, username, settings
|
||||
mock_generate_config,
|
||||
mock_room_creation,
|
||||
lobby_service,
|
||||
participant_id,
|
||||
username,
|
||||
settings,
|
||||
):
|
||||
"""Test requesting entry to a public room."""
|
||||
settings.LOBBY_KEY_PREFIX = "mocked-cache-prefix"
|
||||
@@ -255,6 +269,13 @@ def test_request_entry_public_room(
|
||||
participant_id=participant_id,
|
||||
role=None,
|
||||
)
|
||||
mock_room_creation.assert_called_once_with(
|
||||
str(room.id),
|
||||
metadata={
|
||||
"configuration": room.configuration,
|
||||
"access_level": room.access_level,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@mock.patch("core.utils.generate_livekit_config")
|
||||
@@ -366,7 +387,12 @@ def test_request_entry_waiting_participant(
|
||||
|
||||
@mock.patch("core.utils.generate_livekit_config")
|
||||
def test_request_entry_accepted_participant(
|
||||
mock_generate_config, lobby_service, participant_id, username, settings
|
||||
mock_generate_config,
|
||||
mock_room_creation,
|
||||
lobby_service,
|
||||
participant_id,
|
||||
username,
|
||||
settings,
|
||||
):
|
||||
"""Test requesting entry for an accepted participant."""
|
||||
settings.LOBBY_KEY_PREFIX = "mocked-cache-prefix"
|
||||
@@ -402,6 +428,13 @@ def test_request_entry_accepted_participant(
|
||||
participant_id="test-participant-id",
|
||||
role=None,
|
||||
)
|
||||
mock_room_creation.assert_called_once_with(
|
||||
str(room.id),
|
||||
metadata={
|
||||
"configuration": room.configuration,
|
||||
"access_level": room.access_level,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@mock.patch("core.utils.generate_livekit_config")
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"""Tests for the RoomManagement service."""
|
||||
|
||||
import json
|
||||
from unittest import mock
|
||||
|
||||
from django.db import connection
|
||||
@@ -17,6 +18,123 @@ from core.services.room_management import (
|
||||
from core.services.sip_management import SIPException, SIPManagement
|
||||
|
||||
|
||||
def _mock_livekit_api(mock_create_livekit_client, rooms=None):
|
||||
"""Return a mocked LiveKit client whose room store holds `rooms`."""
|
||||
mock_api = mock.MagicMock()
|
||||
mock_api.room.list_rooms = mock.AsyncMock(
|
||||
return_value=mock.Mock(rooms=rooms if rooms is not None else [])
|
||||
)
|
||||
mock_api.room.create_room = mock.AsyncMock()
|
||||
mock_api.aclose = mock.AsyncMock()
|
||||
mock_create_livekit_client.return_value = mock_api
|
||||
return mock_api
|
||||
|
||||
|
||||
@mock.patch("core.services.room_management.utils.create_livekit_client")
|
||||
def test_create_room_calls_livekit(mock_create_livekit_client):
|
||||
"""A missing room is created through the LiveKit API with its metadata."""
|
||||
mock_api = _mock_livekit_api(mock_create_livekit_client)
|
||||
|
||||
RoomManagement.create_room(
|
||||
"room-abc",
|
||||
metadata={
|
||||
"configuration": {"everyone_can_mute": True},
|
||||
"access_level": "public",
|
||||
},
|
||||
)
|
||||
|
||||
list_request = mock_api.room.list_rooms.await_args.args[0]
|
||||
assert list_request.names == ["room-abc"]
|
||||
|
||||
create_request = mock_api.room.create_room.await_args.args[0]
|
||||
assert create_request.name == "room-abc"
|
||||
assert json.loads(create_request.metadata) == {
|
||||
"configuration": {"everyone_can_mute": True},
|
||||
"access_level": "public",
|
||||
}
|
||||
mock_api.aclose.assert_awaited_once()
|
||||
|
||||
|
||||
@mock.patch("core.services.room_management.utils.create_livekit_client")
|
||||
def test_create_room_keeps_existing_room_metadata(mock_create_livekit_client):
|
||||
"""An existing room is left alone, so its recording state is not wiped."""
|
||||
mock_api = _mock_livekit_api(mock_create_livekit_client, rooms=[mock.Mock()])
|
||||
|
||||
RoomManagement.create_room("room-abc", metadata={"access_level": "public"})
|
||||
|
||||
mock_api.room.create_room.assert_not_awaited()
|
||||
mock_api.aclose.assert_awaited_once()
|
||||
|
||||
|
||||
@mock.patch("core.services.room_management.utils.create_livekit_client")
|
||||
def test_create_room_without_metadata(mock_create_livekit_client):
|
||||
"""A room without settings still gets an empty metadata, not a null one."""
|
||||
mock_api = _mock_livekit_api(mock_create_livekit_client)
|
||||
|
||||
RoomManagement.create_room("room-abc")
|
||||
|
||||
request = mock_api.room.create_room.await_args.args[0]
|
||||
assert request.metadata == ""
|
||||
mock_api.aclose.assert_awaited_once()
|
||||
|
||||
|
||||
@mock.patch("core.services.room_management.utils.create_livekit_client")
|
||||
def test_create_room_tolerates_already_exists(mock_create_livekit_client):
|
||||
"""A room created by a concurrent join is the expected outcome."""
|
||||
mock_api = _mock_livekit_api(mock_create_livekit_client)
|
||||
mock_api.room.create_room.side_effect = TwirpError(
|
||||
"already_exists", "room already exists", status=409
|
||||
)
|
||||
|
||||
RoomManagement.create_room("room-abc")
|
||||
|
||||
mock_api.aclose.assert_awaited_once()
|
||||
|
||||
|
||||
@mock.patch("core.services.room_management.utils.create_livekit_client")
|
||||
def test_create_room_raises_management_exception(mock_create_livekit_client):
|
||||
"""Unexpected Twirp errors raise RoomManagementException."""
|
||||
mock_api = _mock_livekit_api(mock_create_livekit_client)
|
||||
mock_api.room.create_room.side_effect = TwirpError("internal", "boom", status=500)
|
||||
|
||||
with pytest.raises(RoomManagementException):
|
||||
RoomManagement.create_room("room-abc")
|
||||
|
||||
mock_api.aclose.assert_awaited_once()
|
||||
|
||||
|
||||
@mock.patch("core.services.room_management.utils.create_livekit_client")
|
||||
def test_create_room_raises_when_listing_fails(mock_create_livekit_client):
|
||||
"""The room cannot be checked, so the join cannot be prepared."""
|
||||
mock_api = _mock_livekit_api(mock_create_livekit_client)
|
||||
mock_api.room.list_rooms.side_effect = TwirpError("internal", "boom", status=500)
|
||||
|
||||
with pytest.raises(RoomManagementException):
|
||||
RoomManagement.create_room("room-abc")
|
||||
|
||||
mock_api.room.create_room.assert_not_awaited()
|
||||
mock_api.aclose.assert_awaited_once()
|
||||
|
||||
|
||||
@mock.patch.object(RoomManagement, "create_room")
|
||||
def test_ensure_room_passes_room_settings(mock_create_room):
|
||||
"""Ensuring a room forwards its configuration and access level."""
|
||||
room = RoomFactory.build(
|
||||
access_level=RoomAccessLevel.RESTRICTED,
|
||||
configuration={"everyone_can_mute": True},
|
||||
)
|
||||
|
||||
RoomManagement.ensure_room(room)
|
||||
|
||||
mock_create_room.assert_called_once_with(
|
||||
str(room.id),
|
||||
metadata={
|
||||
"configuration": {"everyone_can_mute": True},
|
||||
"access_level": RoomAccessLevel.RESTRICTED,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@mock.patch("core.services.room_management.utils.create_livekit_client")
|
||||
def test_delete_room_calls_livekit(mock_create_livekit_client):
|
||||
"""DeleteRoom is forwarded to the LiveKit API."""
|
||||
|
||||
@@ -15,10 +15,20 @@ from core.api.throttling import (
|
||||
ConnectionTestUserRateThrottle,
|
||||
)
|
||||
from core.factories import UserFactory
|
||||
from core.services.room_management import RoomManagementException
|
||||
|
||||
pytestmark = pytest.mark.django_db
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def mock_room_creation():
|
||||
"""Mock the LiveKit room creation performed before a token is issued."""
|
||||
with mock.patch(
|
||||
"core.services.room_management.RoomManagement.create_room"
|
||||
) as mock_create_room:
|
||||
yield mock_create_room
|
||||
|
||||
|
||||
def test_api_diagnostics_connection_url():
|
||||
"""The connection check is exposed under the diagnostics namespace."""
|
||||
assert reverse("diagnostics-connection") == "/api/v1.0/diagnostics/connection/"
|
||||
@@ -32,7 +42,9 @@ def test_api_diagnostics_connection_rejects_get():
|
||||
assert response.status_code == 405
|
||||
|
||||
|
||||
def test_api_diagnostics_connection_returns_ephemeral_livekit_config(settings, client):
|
||||
def test_api_diagnostics_connection_returns_ephemeral_livekit_config(
|
||||
settings, client, mock_room_creation
|
||||
):
|
||||
"""Each request gets a dedicated room and a short-lived token."""
|
||||
|
||||
settings.CONNECTION_TEST_TOKEN_TTL_SECONDS = 600
|
||||
@@ -59,6 +71,22 @@ def test_api_diagnostics_connection_returns_ephemeral_livekit_config(settings, c
|
||||
assert data_a["livekit"]["token"]
|
||||
assert data_a["livekit"]["expires_in"] == 600
|
||||
assert data_a["livekit"]["token"] != data_b["livekit"]["token"]
|
||||
assert [call.args[0] for call in mock_room_creation.call_args_list] == [
|
||||
room_a,
|
||||
room_b,
|
||||
]
|
||||
|
||||
|
||||
def test_api_diagnostics_connection_room_creation_failure(client, mock_room_creation):
|
||||
"""The test cannot start when its dedicated LiveKit room cannot be created."""
|
||||
mock_room_creation.side_effect = RoomManagementException("Could not create room")
|
||||
|
||||
response = client.post("/api/v1.0/diagnostics/connection/")
|
||||
|
||||
assert response.status_code == 500
|
||||
assert response.json() == {
|
||||
"detail": "Could not create the connection test room, please try again."
|
||||
}
|
||||
|
||||
|
||||
def test_api_diagnostics_connection_token_is_short_lived_for_user(settings, client):
|
||||
|
||||
@@ -156,6 +156,10 @@ def generate_livekit_config( # noqa: PLR0917
|
||||
) -> dict:
|
||||
"""Generate LiveKit configuration for room access.
|
||||
|
||||
The LiveKit room must already exist: with `room.auto_create: false`, a
|
||||
token is only usable once the room is there. Callers create it first through
|
||||
`RoomManagement.ensure_room()` or `RoomManagement.create_room()`.
|
||||
|
||||
Args:
|
||||
room_id: Room identifier
|
||||
user: User instance requesting access
|
||||
|
||||
Reference in New Issue
Block a user