Compare commits

..

1 Commits

Author SHA1 Message Date
lebaudantoine 867a14d0a3 🐛(frontend) promote the active speaker in the carousel layout
The stage stopped re-rendering on ActiveSpeakersChanged when useTracks
moved to `updateOnlyOn: []`, a change made to avoid re-rendering the
whole stage on every speaker update. useVisualStableUpdate promotes
speakers only when the layout renders, so in the focus layout's
carousel a speaker outside the visible tiles was no longer brought
into view. The grid layout already had a fix,
useSpeakerPromotionTrigger, but the carousel did not.

Fix: the carousel now uses the same tripwire on the tiles it
guarantees to show. The tripwire also ignores speakers with no tile in
the layout (e.g. the pinned participant, shown in the focus view);
otherwise they would trigger a useless render on every speaker event.

Enhancement: the active speaker is now pinned near the top of the
column instead of landing anywhere in the visible span:
- the local camera stays first and the top speaker's camera second;
  the rest is still ordered by useVisualStableUpdate
- the top speaker is the loudest remote participant with a tile;
  the local participant is never promoted
- the slot is sticky through silence, and a new speaker only takes it
  after the current one has held it for 2s and only if still speaking,
  so a back-and-forth doesn't make tiles flip
- the slot is reserved before anyone speaks, so the first promotion
  doesn't reshuffle the whole column
- the tripwire still promotes other hidden speakers into the rest

Re-renders: useTopSpeaker only renders when the top speaker changes.
It runs on the same event as the tripwire, and React 18 merges their
updates into a single render.

The ordering (splitCarouselTiles) and the slot timing
(watchTopSpeaker) are framework-free.
2026-10-12 00:19:48 +02:00
49 changed files with 311 additions and 1381 deletions
+1 -2
View File
@@ -13,7 +13,6 @@ and this project adheres to
- ✨(frontend) let users pick the recording encoding
- ✨(backend) introduce a token exchange endpoint for iframe embeds
- ⚡️(backend) send recording notification emails from a Celery task
- ✨(backend) add room soft-deletion to the external API
### Changed
@@ -22,7 +21,6 @@ and this project adheres to
- ♻️️️(backend) use a dedicated auth scheme for LiveKit token auth
- ♻️(all) stop relying on cookies for the lobby flow
- ♿️(frontend) show a visible focus outline on menu items #1797
- ⬆️(backend) upgrade pylint to 4.1.3
### Fixed
@@ -33,6 +31,7 @@ and this project adheres to
- 🐛(frontend) omit the default speaker id sent to LiveKit
- 🐛(frontend) play the speaker test when no output is picked
- 🐛(frontend) keep the admin panel in place when changing a setting #1804
- 🐛(frontend) promote the active speaker in the carousel layout
## [1.34.0] - 2026-10-07
-8
View File
@@ -16,14 +16,6 @@ the following command inside your docker container:
## [Unreleased]
### Purging deleted rooms
Deleting a room now only soft deletes it: it is hidden but keeps its slug and PIN code. The `purge_inactive_rooms` command also permanently deletes soft-deleted rooms. See [the room purge documentation](docs/features/room-purge.md).
- Inactive soft-deleted rooms are purged along with the other inactive rooms: if `ROOM_INACTIVITY_DELETION_DAYS` is already set, nothing else is needed.
- The new `ROOM_DELETED_RETENTION_DAYS` setting purges soft-deleted rooms that many days after their deletion, whether they are inactive or not. It is unset by default.
- As for inactive rooms, a deleted room holding a saved recording its users may still access is kept until that recording expires.
### Marketing / Brevo integration now uses `django-lasuite`
The in-house marketing service (`core.services.marketing`) has been removed and
+5 -11
View File
@@ -1,6 +1,6 @@
# Room purge
Rooms pile up over time and most of them are only used once. The `purge_inactive_rooms` management command permanently deletes the rooms that have not been started for a configurable number of days, and the rooms deleted by their owner for longer than a configurable retention period. It is disabled by default.
Rooms pile up over time and most of them are only used once. The `purge_inactive_rooms` management command permanently deletes the rooms that have not been started for a configurable number of days. It is disabled by default.
## How it works
@@ -12,21 +12,16 @@ A room is inactive when:
Rooms that existed before this feature was deployed are considered started on the day of the release, so none of them can be purged before a full inactivity period has elapsed.
Deleting a room through the API only soft deletes it: the room is hidden, its link tells visitors the meeting was deleted, and it keeps its slug and PIN code. A soft-deleted room is purged:
- when it is inactive, as described above: a deleted room is never considered started again, so its inactivity period keeps running, or
- when it was deleted more than `ROOM_DELETED_RETENTION_DAYS` days ago.
The command is meant to run once a day. The Helm chart schedules it in `backend.cronjobs` (`purge-inactive-rooms`, 01:00); it does nothing until `ROOM_INACTIVITY_DELETION_DAYS` or `ROOM_DELETED_RETENTION_DAYS` is set.
The command is meant to run once a day. The Helm chart schedules it in `backend.cronjobs` (`purge-inactive-rooms`, 01:00); it does nothing until `ROOM_INACTIVITY_DELETION_DAYS` is set.
```bash
python manage.py purge_inactive_rooms # delete the inactive and deleted rooms
python manage.py purge_inactive_rooms # delete the inactive rooms
python manage.py purge_inactive_rooms --dry-run # only list the rooms that would be deleted
```
## Rooms that are kept
A recording can only be reached through its room. A room is kept, past its inactivity or retention period, as long as it holds a saved recording its users may still access:
A recording can only be reached through its room. An inactive room is kept as long as it holds a saved recording its users may still access:
- with `RECORDING_EXPIRATION_DAYS` set, a saved recording created less than that many days ago,
- with `RECORDING_EXPIRATION_DAYS` unset, any saved recording.
@@ -38,8 +33,7 @@ The room is deleted from the database, along with its accesses, its telephony PI
The recording **files in the bucket are left untouched**: the backend never deletes anything from the storage, it only drops the database entries pointing at it. Removing the files is the job of the bucket lifecycle policy, which should match `RECORDING_EXPIRATION_DAYS` (see the [recording documentation](recording.md)). When the two do not match, the purge leaves objects behind: they become unreachable, since serving a recording requires its database entry, but they keep costing storage.
⚠️ When a room is purged, all it's configuration and access rights are also deleted. Its slug becomes available again
and can be reused when a meeting is created from that same URL. This also applies to a soft-deleted room: once purged, its link
no longer tells visitors the meeting was deleted, and its PIN code can be given to another room.
and can be reused when a meeting is created from that same URL.
* With `ALLOW_UNREGISTERED_ROOMS=false`, only an authenticated user can navigate to a previously existing link after the room has been purged. Doing so recreates the room in the database with a fresh configuration, with that user associated with it and granted admin rights.
-1
View File
@@ -408,7 +408,6 @@ These are the environmental options available on meet backend.
| RESOURCE_DEFAULT_ACCESS_LEVEL | Default resource access level for rooms | public |
| ALLOW_UNREGISTERED_ROOMS | Allow usage of unregistered rooms | true |
| ROOM_INACTIVITY_DELETION_DAYS | Days without being started after which a room is purged. Unset to never purge | |
| ROOM_DELETED_RETENTION_DAYS | Days after its deletion after which a room is purged. Unset to purge deleted rooms only once inactive | |
| RECORDING_ENABLE | Record meeting option | false |
| RECORDING_OUTPUT_FOLDER | Folder to store meetings | recordings |
| RECORDING_WORKER_CLASSES | Worker classes for recording | {"screen_recording": "core.recording.worker.services.VideoCompositeEgressService","transcript": "core.recording.worker.services.AudioCompositeEgressService"} |
+6
View File
@@ -24,6 +24,12 @@
"matchManagers": ["pep621"],
"matchPackageNames": ["redis"]
},
{
"groupName": "allowed pylint versions",
"matchManagers": ["pep621"],
"matchPackageNames": ["pylint"],
"allowedVersions": "<4.0.0"
},
{
"groupName": "allowed django versions",
"matchManagers": ["pep621"],
+4
View File
@@ -31,6 +31,10 @@ persistent=yes
# Specify a configuration file.
#rcfile=
# When enabled, pylint would attempt to guess common misconfiguration and emit
# user-friendly hints instead of false-positive error messages
suggestion-mode=yes
# Allow loading of arbitrary C extensions. Extensions are imported into the
# active Python interpreter and may run arbitrary code.
unsafe-load-any-extension=no
+2 -9
View File
@@ -286,16 +286,9 @@ class RoomAdmin(admin.ModelAdmin):
"get_owner",
"created_at",
"last_started_at",
"deleted_at",
]
list_filter = ["access_level", "created_at", "last_started_at", "deleted_at"]
readonly_fields = [
"id",
"created_at",
"updated_at",
"last_started_at",
"deleted_at",
]
list_filter = ["access_level", "created_at", "last_started_at"]
readonly_fields = ["id", "created_at", "updated_at", "last_started_at"]
def get_queryset(self, request):
"""Optimize queries by prefetching related access and user data to avoid N+1 queries."""
-1
View File
@@ -9,7 +9,6 @@ class AnalyticsEvent(StrEnum):
# Rooms
ROOM_CREATED = "room_created"
ROOM_UPDATED = "room_updated"
ROOM_DELETED = "room_deleted"
# Roomkit (meeting-room SIP devices)
ROOMKIT_JOINED = "roomkit_joined"
-30
View File
@@ -1,30 +0,0 @@
"""Exceptions and guards shared by the API endpoints."""
from django.utils.translation import gettext_lazy as _
from rest_framework import exceptions, status
from core import models
class RoomSoftDeleted(exceptions.APIException):
"""Raised when the requested room has been soft deleted."""
status_code = status.HTTP_410_GONE
default_detail = _("This room has been deleted.")
default_code = "room_deleted"
def ensure_room_not_deleted(resource):
"""Raise a 410 Gone if the resource is a soft-deleted room.
Accepts a room or its parent resource, as referenced by accesses. Call it
after permissions are checked, to avoid revealing room.
"""
if isinstance(resource, models.Room):
room = resource
else:
room = getattr(resource, "room", None)
if room is not None and room.is_deleted:
raise RoomSoftDeleted()
-2
View File
@@ -26,7 +26,6 @@ from rest_framework.exceptions import PermissionDenied
from timezone_field.rest_framework import TimeZoneSerializerField
from core import models, utils
from core.api.exceptions import ensure_room_not_deleted
logger = logging.getLogger(__name__)
@@ -115,7 +114,6 @@ class ResourceAccessSerializerMixin:
_("You must be administrator or owner of a room to add accesses to it.")
)
ensure_room_not_deleted(resource)
return resource
+5 -33
View File
@@ -42,7 +42,6 @@ from rest_framework.settings import api_settings
from core import analytics, enums, models, utils
from core.api import throttling
from core.api.exceptions import ensure_room_not_deleted
from core.api.filters import ListFileFilter
from core.enums import MEDIA_STORAGE_URL_PATTERN
from core.recording.enums import FileExtension
@@ -78,7 +77,7 @@ from core.services.participants_management import (
ParticipantsManagementException,
)
from core.services.room_creation import RoomCreation
from core.services.room_management import RoomManagement, RoomManagementException
from core.services.room_management import RoomManagement
from core.services.room_roles import (
RoomRoleError,
RoomRoleService,
@@ -262,7 +261,7 @@ class UserViewSet(
return drf_response.Response(data)
class RoomViewSet( # pylint: disable=too-many-public-methods
class RoomViewSet(
mixins.CreateModelMixin,
mixins.DestroyModelMixin,
mixins.UpdateModelMixin,
@@ -288,9 +287,10 @@ class RoomViewSet( # pylint: disable=too-many-public-methods
filter_kwargs = {"pk": self.kwargs["pk"]}
except ValueError:
filter_kwargs = {"slug": slugify(self.kwargs["pk"])}
obj = get_object_or_404(models.Room.all_objects, **filter_kwargs)
queryset = self.filter_queryset(self.get_queryset())
obj = get_object_or_404(queryset, **filter_kwargs)
# May raise a permission denied
self.check_object_permissions(self.request, obj)
ensure_room_not_deleted(obj)
return obj
def retrieve(self, request, *args, **kwargs):
@@ -342,27 +342,6 @@ class RoomViewSet( # pylint: disable=too-many-public-methods
serializer = self.get_serializer(queryset, many=True)
return drf_response.Response(serializer.data)
def perform_destroy(self, instance):
"""Soft delete the room and close its LiveKit room.
The room and its recordings are kept in database for traceability.
"""
try:
RoomManagement.soft_delete(instance)
except RoomManagementException as e:
raise drf_exceptions.APIException(
"Could not delete the room, please try again."
) from e
analytics.capture(
self.request.user,
analytics.AnalyticsEvent.ROOM_DELETED,
{
"room_id": str(instance.pk),
"access_level": instance.access_level,
},
)
def perform_create(self, serializer):
"""Set the current user as owner of the newly created room.
@@ -1060,13 +1039,6 @@ class ResourceAccessViewSet(
return queryset
def get_object(self):
"""Accesses to a soft-deleted room can be read but no longer modified."""
access = super().get_object()
if self.request.method not in drf_permissions.SAFE_METHODS:
ensure_room_not_deleted(access.resource)
return access
class RecordingViewSet(
mixins.DestroyModelMixin,
+2 -30
View File
@@ -21,13 +21,11 @@ from rest_framework import (
from rest_framework import (
status as drf_status,
)
from rest_framework.generics import get_object_or_404
from core import analytics, api, models
from core.api.exceptions import ensure_room_not_deleted
from core.api.feature_flag import FeatureFlag
from core.services.jwt_token import JwtTokenService
from core.services.room_management import RoomManagement, RoomManagementException
from core.services.room_management import RoomManagement
from core.services.transit_code import TransitCodeService
from ..services.provisional_user_service import (
@@ -144,7 +142,6 @@ class ApplicationViewSet(viewsets.ViewSet):
class RoomViewSet(
mixins.CreateModelMixin,
mixins.DestroyModelMixin,
mixins.RetrieveModelMixin,
mixins.ListModelMixin,
mixins.UpdateModelMixin,
@@ -162,13 +159,9 @@ class RoomViewSet(
- create: Create a new room owned by the user (requires 'rooms:create' scope)
- partial_update: Update a room's access level and configuration, for
administrators and owners only (requires 'rooms:update' scope)
- destroy: Soft delete a room and close its LiveKit room, for owners only
(requires 'rooms:delete' scope)
Detail operations on a soft-deleted room answer 410 Gone.
"""
http_method_names = ["get", "post", "patch", "delete", "head", "options"]
http_method_names = ["get", "post", "patch", "head", "options"]
authentication_classes = [
authentication.ApplicationJWTAuthentication,
@@ -183,17 +176,6 @@ class RoomViewSet(
queryset = models.Room.objects.all()
serializer_class = serializers.RoomSerializer
def get_object(self):
"""Get the room, answer 410 if it has been deleted.
Permissions are checked first so a deleted room is only revealed to
users who would have been granted access to it.
"""
room = get_object_or_404(models.Room.all_objects, pk=self.kwargs["pk"])
self.check_object_permissions(self.request, room)
ensure_room_not_deleted(room)
return room
def list(self, request, *args, **kwargs):
"""Limit listed rooms to the ones related to the authenticated user."""
@@ -257,16 +239,6 @@ class RoomViewSet(
self._track_room_event(room, analytics.AnalyticsEvent.ROOM_CREATED)
def perform_destroy(self, instance):
"""Soft delete the room, close its LiveKit room, then log and track it."""
try:
RoomManagement.soft_delete(instance)
except RoomManagementException as e:
raise drf_exceptions.APIException(
"Could not delete the room, please try again."
) from e
self._track_room_event(instance, analytics.AnalyticsEvent.ROOM_DELETED)
def perform_update(self, serializer: serializers.RoomSerializer):
"""Persist the room update, sync it to LiveKit, then log and track it."""
+1 -1
View File
@@ -50,4 +50,4 @@ class SecretField(models.CharField):
setattr(model_instance, self.attname, hashed_secret)
return hashed_secret
return super().pre_save(model_instance, add) # pylint: disable=no-member
return super().pre_save(model_instance, add)
@@ -1,8 +1,6 @@
"""Purge inactive and soft-deleted rooms."""
"""Purge inactive rooms."""
import operator
from datetime import timedelta
from functools import reduce
from itertools import batched
from logging import getLogger
@@ -24,12 +22,10 @@ class Command(BaseCommand):
- rooms which were last started before that period
- rooms never started and created before that period
Also delete rooms soft deleted more than ROOM_DELETED_RETENTION_DAYS days ago.
Rooms holding a saved recording that has not expired are kept.
"""
help = "Purge inactive and soft-deleted rooms"
help = "Purge inactive rooms"
def add_arguments(self, parser):
parser.add_argument(
@@ -39,68 +35,53 @@ class Command(BaseCommand):
)
def handle(self, *args, **options):
"""Browse purgeable rooms and delete them chunk by chunk."""
"""Browse inactive rooms and delete them chunk by chunk."""
if not (
settings.ROOM_INACTIVITY_DELETION_DAYS
or settings.ROOM_DELETED_RETENTION_DAYS
):
if not settings.ROOM_INACTIVITY_DELETION_DAYS:
self.stdout.write(
"Purging rooms is disabled (neither ROOM_INACTIVITY_DELETION_DAYS "
"nor ROOM_DELETED_RETENTION_DAYS is set)."
"Purging inactive rooms is disabled "
"(ROOM_INACTIVITY_DELETION_DAYS is not set)."
)
return
now = timezone.now()
purgeable_rooms = self.get_purgeable_rooms(now)
inactive_rooms = self.get_inactive_rooms(now)
purgeable_count = purgeable_rooms.count()
if not purgeable_count:
self.stdout.write("No room to purge.")
inactive_count = inactive_rooms.count()
if not inactive_count:
self.stdout.write("No inactive room to purge.")
return
if options["dry_run"]:
self.stdout.write(f"[dry-run] {purgeable_count} room(s) would be purged:")
rooms = purgeable_rooms.values_list("name", "deleted_at")
for name, deleted_at in rooms.iterator(chunk_size=CHUNK_SIZE):
self.stdout.write(f"- {name}{' (deleted)' if deleted_at else ''}")
self.stdout.write(
f"[dry-run] {inactive_count} inactive room(s) would be purged:"
)
names = inactive_rooms.values_list("name", flat=True)
for name in names.iterator(chunk_size=CHUNK_SIZE):
self.stdout.write(f"- {name}")
return
purged_count = 0
rooms = purgeable_rooms.values_list("pk", "slug", "deleted_at").iterator(
chunk_size=CHUNK_SIZE
)
rooms = inactive_rooms.values_list("pk", "slug").iterator(chunk_size=CHUNK_SIZE)
for chunk in batched(rooms, CHUNK_SIZE, strict=False):
for room_id, slug, deleted_at in chunk:
state = "deleted" if deleted_at else "inactive"
logger.info("Purging %s room %s (%s)", state, room_id, slug)
for room_id, slug in chunk:
logger.info("Purging inactive room %s (%s)", room_id, slug)
_, deleted_by_model = purgeable_rooms.filter(
pk__in=[room_id for room_id, _, _ in chunk]
_, deleted_by_model = inactive_rooms.filter(
pk__in=[room_id for room_id, _ in chunk]
).delete()
purged_count += deleted_by_model.get("core.Room", 0)
self.stdout.write(f"Purged {purged_count} room(s).")
self.stdout.write(f"Purged {purged_count} inactive room(s).")
@staticmethod
def get_purgeable_rooms(now):
"""Return the inactive or long-deleted rooms that no recording protects.
def get_inactive_rooms(now):
"""Return the rooms inactive for too long that no recording protects."""
Soft-deleted rooms are hidden by `Room.objects`, hence `Room.all_objects`.
"""
conditions = []
if settings.ROOM_INACTIVITY_DELETION_DAYS:
threshold = now - timedelta(days=settings.ROOM_INACTIVITY_DELETION_DAYS)
conditions.append(
Q(last_started_at__lt=threshold)
| Q(last_started_at__isnull=True, created_at__lt=threshold)
)
if settings.ROOM_DELETED_RETENTION_DAYS:
deleted_before = now - timedelta(days=settings.ROOM_DELETED_RETENTION_DAYS)
conditions.append(Q(deleted_at__lt=deleted_before))
if not conditions:
return Room.all_objects.none()
threshold = now - timedelta(days=settings.ROOM_INACTIVITY_DELETION_DAYS)
is_inactive = Q(last_started_at__lt=threshold) | Q(
last_started_at__isnull=True, created_at__lt=threshold
)
protected_recordings = Recording.objects.filter(
room=OuterRef("pk"), status__in=RecordingStatusChoices.saved_statuses()
@@ -110,6 +91,4 @@ class Command(BaseCommand):
created_at__gte=now - timedelta(days=settings.RECORDING_EXPIRATION_DAYS)
)
return Room.all_objects.filter(
reduce(operator.or_, conditions), ~Exists(protected_recordings)
)
return Room.objects.filter(is_inactive, ~Exists(protected_recordings))
@@ -1,29 +0,0 @@
# Generated by Django 5.2.14 on 2026-09-16 10:00
import django.db.models.manager
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0026_alter_application_scopes'),
]
operations = [
migrations.AddField(
model_name='room',
name='deleted_at',
field=models.DateTimeField(blank=True, null=True),
),
migrations.AlterModelOptions(
name='room',
options={'default_manager_name': 'all_objects', 'ordering': ('name',), 'verbose_name': 'Room', 'verbose_name_plural': 'Rooms'},
),
migrations.AlterModelManagers(
name='room',
managers=[
('all_objects', django.db.models.manager.Manager()),
],
),
]
+1 -51
View File
@@ -407,33 +407,6 @@ class ResourceAccess(BaseModel):
return super().delete(*args, **kwargs)
class RoomQuerySet(models.QuerySet):
"""QuerySet exposing the room lifecycle filters."""
def active(self):
"""Rooms that have not been soft deleted."""
return self.filter(deleted_at__isnull=True)
def deleted(self):
"""Rooms that have been soft deleted."""
return self.filter(deleted_at__isnull=False)
class RoomManager(models.Manager.from_queryset(RoomQuerySet)):
"""Manager hiding soft-deleted rooms, exposed as ``Room.objects``.
It is deliberately not the model's default manager: Django relies on
``_default_manager`` for unique validation, which must see deleted rooms as
they still guard their slug and pin code. Other object relations (e.g.
``recording.room``) go through the base manager and still resolve deleted
rooms, which keeps recordings and their notifications working.
"""
def get_queryset(self):
"""Exclude soft-deleted rooms."""
return super().get_queryset().active()
class Room(Resource):
"""Model for one room"""
@@ -457,7 +430,6 @@ class Room(Resource):
verbose_name=_("Visio room configuration"),
help_text=_("Values for Visio parameters to configure the room."),
)
deleted_at = models.DateTimeField(null=True, blank=True)
pin_code = models.CharField(
max_length=None,
unique=True,
@@ -474,13 +446,8 @@ class Room(Resource):
editable=False,
)
# Managers
objects = RoomManager()
all_objects = models.Manager.from_queryset(RoomQuerySet)()
class Meta:
db_table = "meet_room"
default_manager_name = "all_objects"
ordering = ("name",)
verbose_name = _("Room")
verbose_name_plural = _("Rooms")
@@ -503,23 +470,6 @@ class Room(Resource):
)
super().save(*args, **kwargs)
@property
def is_deleted(self):
"""Whether the room has been soft deleted."""
return self.deleted_at is not None
def soft_delete(self):
"""Soft delete the room.
The room is hidden from the default manager making it impossible to
list, join or update.
"""
if self.deleted_at:
raise RuntimeError("This room is already deleted.")
self.deleted_at = timezone.now()
self.save(update_fields=["deleted_at"])
def clean_fields(self, exclude=None):
"""
Automatically generate the slug from the name and make sure it does not look like a UUID.
@@ -555,7 +505,7 @@ class Room(Resource):
for _ in range(settings.ROOM_TELEPHONY_PIN_MAX_RETRIES):
pin_code = str(secrets.randbelow(max_value)).zfill(length)
if not Room.all_objects.filter(pin_code=pin_code).exists():
if not Room.objects.filter(pin_code=pin_code).exists():
return pin_code
# Log a warning as a temporary measure until backend observability is implemented.
+10 -33
View File
@@ -271,24 +271,20 @@ class LiveKitEventsService:
)
raise ActionFailedError("Failed to process room started event") from e
try:
room = models.Room.all_objects.get(id=room_id)
except models.Room.DoesNotExist as err:
raise ActionFailedError(f"Room with ID {room_id} does not exist") from err
# The block below is intended to fix the issue where long-lived livekit
# tokens allow users who already entered a room to re-create it,
# even if it was closed.
if room.is_deleted:
self._close_deleted_room(room_id)
return
# Update through the queryset to skip the full_clean run by save()
models.Room.all_objects.filter(pk=room.pk).update(
room_updated_count = models.Room.objects.filter(pk=room_id).update(
last_started_at=timezone.now()
)
if not room_updated_count:
raise ActionFailedError(f"Room with ID {room_id} does not exist")
if settings.ROOM_TELEPHONY_ENABLED or settings.ROOMKIT_ENABLED:
try:
room = models.Room.objects.get(pk=room_id)
except models.Room.DoesNotExist as err:
raise ActionFailedError(
f"Room with ID {room_id} does not exist"
) from err
try:
self.sip_management.ensure_dispatch_rule(room)
except SIPException as e:
@@ -296,25 +292,6 @@ class LiveKitEventsService:
f"Failed to create sip dispatch rule for room {room_id}"
) from e
@staticmethod
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.
"""
logger.warning(
"LiveKit room %s started for a deleted room, closing it", room_id
)
try:
RoomManagement.delete_room(str(room_id))
except RoomNotFoundException:
logger.info("LiveKit room %s is already closed", room_id)
except RoomManagementException as e:
raise ActionFailedError(f"Failed to close deleted room {room_id}") from e
def _handle_room_finished(self, data):
"""Handle 'room_finished' event."""
@@ -2,13 +2,10 @@
# pylint: disable=no-name-in-module
import contextlib
import json
from logging import getLogger
from typing import Dict, Optional
from django.conf import settings
from asgiref.sync import async_to_sync
from livekit.api import (
DeleteRoomRequest,
@@ -18,9 +15,6 @@ from livekit.api import (
)
from core import utils
from core.models import Room
from .sip_management import SIPException, SIPManagement
logger = getLogger(__name__)
@@ -121,38 +115,6 @@ class RoomManagement:
finally:
await lkapi.aclose()
@classmethod
def soft_delete(cls, room: Room):
"""Soft delete a room, remove its SIP routing and close its LiveKit room."""
room.soft_delete()
try:
cls._delete_dispatch_rule(room)
with contextlib.suppress(RoomNotFoundException):
cls.delete_room(str(room.id))
except Exception:
Room.all_objects.filter(pk=room.pk, deleted_at=room.deleted_at).update(
deleted_at=None
)
room.deleted_at = None
raise
@staticmethod
def _delete_dispatch_rule(room: Room):
"""Delete a room's SIP dispatch rule, so its PIN no longer routes calls.
This cannot be left to the room_finished webhook: a roomkit join creates
the rule before any LiveKit room exists, so no room may ever finish.
"""
if settings.ROOM_TELEPHONY_ENABLED or settings.ROOMKIT_ENABLED:
try:
SIPManagement().delete_dispatch_rule(room.id)
except SIPException as e:
raise RoomManagementException("Could not delete dispatch rule") from e
@classmethod
def sync_room_metadata(cls, room):
"""Push a room's configuration and access level to its LiveKit room metadata.
+4 -15
View File
@@ -124,11 +124,7 @@ class SIPManagement:
@async_to_sync
async def delete_dispatch_rule(self, room_id):
"""Delete all SIP inbound dispatch rules associated with a specific room.
A rule deleted meanwhile (e.g. by both a room deletion and its
room_finished webhook) is not an error.
"""
"""Delete all SIP inbound dispatch rules associated with a specific room."""
rules_ids = await self._list_dispatch_rules_ids(room_id)
@@ -142,16 +138,9 @@ class SIPManagement:
lkapi = utils.create_livekit_client()
try:
for rule_id in rules_ids:
try:
await lkapi.sip.delete_sip_dispatch_rule(
delete=DeleteSIPDispatchRuleRequest(
sip_dispatch_rule_id=rule_id
)
)
except TwirpError as e:
if e.code != TwirpErrorCode.NOT_FOUND:
raise
logger.info("Dispatch rule %s was already deleted", rule_id)
await lkapi.sip.delete_sip_dispatch_rule(
delete=DeleteSIPDispatchRuleRequest(sip_dispatch_rule_id=rule_id)
)
return True
@@ -9,7 +9,6 @@ from django.core.management import call_command
from django.utils import timezone
import pytest
from rest_framework.test import APIClient
from core import factories, models
@@ -20,25 +19,14 @@ COMMAND_MODULE = "core.management.commands.purge_inactive_rooms"
BEFORE_PERIOD = timedelta(days=366)
WITHIN_PERIOD = timedelta(days=364)
BEFORE_RETENTION = timedelta(days=31)
WITHIN_RETENTION = timedelta(days=29)
@pytest.fixture(name="purge_enabled", autouse=True)
def fixture_purge_enabled(settings):
"""Enable the purge of the rooms inactive for a year."""
settings.ROOM_INACTIVITY_DELETION_DAYS = 365
settings.ROOM_DELETED_RETENTION_DAYS = None
settings.RECORDING_EXPIRATION_DAYS = 30
@pytest.fixture(name="retention_only")
def fixture_retention_only(settings):
"""Only purge the rooms soft deleted more than 30 days ago."""
settings.ROOM_INACTIVITY_DELETION_DAYS = None
settings.ROOM_DELETED_RETENTION_DAYS = 30
def create_at(date, factory, **kwargs):
"""Build an object with the factory as if it was created at the given date."""
with mock.patch("django.utils.timezone.now", return_value=date):
@@ -53,12 +41,12 @@ def call_purge(*args):
def room_exists(room):
"""Tell whether the room is still in database, soft deleted or not."""
return models.Room.all_objects.filter(pk=room.pk).exists()
"""Tell whether the room is still in database."""
return models.Room.objects.filter(pk=room.pk).exists()
def test_purge_inactive_rooms_disabled(settings):
"""Should delete nothing when neither period is configured."""
"""Should delete nothing when no inactivity period is configured."""
settings.ROOM_INACTIVITY_DELETION_DAYS = None
room = create_at(timezone.now() - BEFORE_PERIOD, factories.RoomFactory)
@@ -80,7 +68,7 @@ def test_purge_inactive_rooms_without_recording_expiration(settings):
status=models.RecordingStatusChoices.SAVED,
)
assert call_purge() == "Purged 1 room(s).\n"
assert call_purge() == "Purged 1 inactive room(s).\n"
assert not room_exists(room)
assert room_exists(room_with_recording)
@@ -109,7 +97,7 @@ def test_purge_inactive_rooms_started_before_period(caplog):
with caplog.at_level(logging.INFO, logger=COMMAND_MODULE):
output = call_purge()
assert output == "Purged 1 room(s).\n"
assert output == "Purged 1 inactive room(s).\n"
assert not room_exists(room)
assert f"Purging inactive room {room.pk} ({room.slug})" in caplog.text
@@ -132,7 +120,7 @@ def test_purge_inactive_rooms_started_within_period():
last_started_at=now - WITHIN_PERIOD,
)
assert call_purge() == "No room to purge.\n"
assert call_purge() == "No inactive room to purge.\n"
assert room_exists(room)
@@ -141,7 +129,7 @@ def test_purge_inactive_rooms_never_started_created_within_period():
"""Should keep a room that was never started but created within the period."""
room = create_at(timezone.now() - WITHIN_PERIOD, factories.RoomFactory)
assert call_purge() == "No room to purge.\n"
assert call_purge() == "No inactive room to purge.\n"
assert room_exists(room)
@@ -233,7 +221,7 @@ def test_purge_inactive_rooms_dry_run():
factories.RoomFactory(name="Recent room")
assert call_purge("--dry-run") == (
"[dry-run] 2 room(s) would be purged:\n- Alpha room\n- Beta room\n"
"[dry-run] 2 inactive room(s) would be purged:\n- Alpha room\n- Beta room\n"
)
assert all(room_exists(room) for room in rooms)
@@ -247,134 +235,5 @@ def test_purge_inactive_rooms_several_chunks():
with mock.patch(f"{COMMAND_MODULE}.CHUNK_SIZE", 2):
output = call_purge()
assert output == "Purged 5 room(s).\n"
assert output == "Purged 5 inactive room(s).\n"
assert not any(room_exists(room) for room in rooms)
def test_purge_inactive_rooms_soft_deleted(caplog):
"""Should delete an inactive room even if it was soft deleted recently."""
now = timezone.now()
room = create_at(
now - BEFORE_PERIOD,
factories.RoomFactory,
deleted_at=now - timedelta(days=1),
)
with caplog.at_level(logging.INFO, logger=COMMAND_MODULE):
output = call_purge()
assert output == "Purged 1 room(s).\n"
assert not room_exists(room)
assert f"Purging deleted room {room.pk} ({room.slug})" in caplog.text
@pytest.mark.usefixtures("retention_only")
def test_purge_deleted_rooms_before_retention(caplog):
"""Should delete a room soft deleted before the retention period."""
room = factories.RoomFactory(deleted_at=timezone.now() - BEFORE_RETENTION)
with caplog.at_level(logging.INFO, logger=COMMAND_MODULE):
output = call_purge()
assert output == "Purged 1 room(s).\n"
assert not room_exists(room)
assert f"Purging deleted room {room.pk} ({room.slug})" in caplog.text
@pytest.mark.usefixtures("retention_only")
def test_purge_deleted_rooms_within_retention():
"""Should keep a room soft deleted within the retention period."""
room = factories.RoomFactory(deleted_at=timezone.now() - WITHIN_RETENTION)
assert call_purge() == "No room to purge.\n"
assert room_exists(room)
@pytest.mark.usefixtures("retention_only")
def test_purge_deleted_rooms_retention_only_keeps_inactive_rooms():
"""Should keep inactive rooms that are not deleted when only retention is set."""
room = create_at(timezone.now() - BEFORE_PERIOD, factories.RoomFactory)
assert call_purge() == "No room to purge.\n"
assert room_exists(room)
def test_purge_deleted_rooms_within_retention_but_inactive(settings):
"""Should delete an inactive room even if it was deleted within the retention."""
settings.ROOM_DELETED_RETENTION_DAYS = 30
now = timezone.now()
room = create_at(
now - BEFORE_PERIOD,
factories.RoomFactory,
deleted_at=now - WITHIN_RETENTION,
)
call_purge()
assert not room_exists(room)
@pytest.mark.usefixtures("retention_only")
def test_purge_deleted_rooms_recording_not_expired():
"""Should keep a deleted room holding a saved recording that has not expired."""
room = factories.RoomFactory(deleted_at=timezone.now() - BEFORE_RETENTION)
factories.RecordingFactory(room=room, status=models.RecordingStatusChoices.SAVED)
assert call_purge() == "No room to purge.\n"
assert room_exists(room)
@pytest.mark.usefixtures("retention_only")
def test_purge_deleted_rooms_recording_expired():
"""Should delete a deleted room along with its expired recordings."""
now = timezone.now()
room = create_at(
now - timedelta(days=40),
factories.RoomFactory,
deleted_at=now - BEFORE_RETENTION,
)
recording = create_at(
now - timedelta(days=40),
factories.RecordingFactory,
room=room,
status=models.RecordingStatusChoices.SAVED,
)
call_purge()
assert not room_exists(room)
assert not models.Recording.objects.filter(pk=recording.pk).exists()
def test_purge_rooms_dry_run_flags_deleted_rooms(settings):
"""Should flag the soft-deleted rooms listed on a dry run."""
settings.ROOM_DELETED_RETENTION_DAYS = 30
now = timezone.now()
rooms = [
create_at(now - BEFORE_PERIOD, factories.RoomFactory, name="Alpha room"),
factories.RoomFactory(name="Beta room", deleted_at=now - BEFORE_RETENTION),
]
factories.RoomFactory(name="Gamma room", deleted_at=now - WITHIN_RETENTION)
assert call_purge("--dry-run") == (
"[dry-run] 2 room(s) would be purged:\n- Alpha room\n- Beta room (deleted)\n"
)
assert all(room_exists(room) for room in rooms)
@pytest.mark.usefixtures("retention_only")
def test_purge_deleted_rooms_frees_slug():
"""Should let a new room take the slug of a purged deleted room."""
factories.RoomFactory(name="my room", deleted_at=timezone.now() - BEFORE_RETENTION)
client = APIClient()
client.force_login(factories.UserFactory())
call_purge()
response = client.post("/api/v1.0/rooms/", {"name": "My Room!"})
assert response.status_code == 201
assert models.Room.objects.get().slug == "my-room"
@@ -117,29 +117,6 @@ def test_api_rooms_create_authenticated_existing_slug():
assert response.json() == {"slug": ["Room with this Slug already exists."]}
def test_api_rooms_create_authenticated_slug_held_by_soft_deleted_room():
"""
A deleted room keeps its slug: creating a room with the same name should
fail validation rather than hit the database constraint.
"""
RoomFactory(name="my room").soft_delete()
user = UserFactory()
client = APIClient()
client.force_login(user)
response = client.post(
"/api/v1.0/rooms/",
{
"name": "My Room!",
},
)
assert response.status_code == 400
assert response.json() == {"slug": ["Room with this Slug already exists."]}
assert Room.all_objects.count() == 1
def test_api_rooms_create_authenticated_user_default_access_level():
"""
The user's default room access level should be applied to the new room
@@ -2,16 +2,11 @@
Test rooms API endpoints in the Meet core app: delete.
"""
from unittest import mock
import pytest
from rest_framework.test import APIClient
from ...analytics import AnalyticsEvent
from ...factories import RoomFactory, UserFactory
from ...models import Room, RoomAccessLevel
from ...services.room_management import RoomManagement, RoomNotFoundException
from ...services.sip_management import SIPManagement
from ...models import Room
pytestmark = pytest.mark.django_db
@@ -88,52 +83,12 @@ def test_api_rooms_delete_administrators():
assert Room.objects.count() == 1
@mock.patch("core.api.viewsets.analytics.capture")
@mock.patch.object(SIPManagement, "delete_dispatch_rule")
@mock.patch.object(RoomManagement, "delete_room")
def test_api_rooms_delete_owners(mock_delete_room, _, mock_capture):
def test_api_rooms_delete_owners():
"""
Authenticated users should be able to delete a room for which they are directly
owner. The room is soft deleted, its LiveKit room is closed and a ROOM_DELETED
analytics event is emitted.
owner.
"""
user = UserFactory()
room = RoomFactory(users=[(user, "owner")], access_level=RoomAccessLevel.TRUSTED)
client = APIClient()
client.force_login(user)
response = client.delete(
f"/api/v1.0/rooms/{room.id}/",
)
assert response.status_code == 204
mock_delete_room.assert_called_once_with(str(room.id))
assert Room.objects.exists() is False
assert Room.all_objects.get(id=room.id).deleted_at is not None
mock_capture.assert_called_once_with(
user,
AnalyticsEvent.ROOM_DELETED,
{"room_id": str(room.pk), "access_level": RoomAccessLevel.TRUSTED},
)
@mock.patch.object(SIPManagement, "delete_dispatch_rule")
@mock.patch.object(
RoomManagement,
"delete_room",
side_effect=RoomNotFoundException("Room does not exist"),
)
def test_api_rooms_delete_owners_room_not_live(
mock_delete_room, mock_delete_dispatch_rule, settings
):
"""
Deleting a room that is not live in LiveKit should still soft delete it, and
delete its SIP dispatch rule, as no room_finished webhook will.
"""
settings.ROOM_TELEPHONY_ENABLED = True
user = UserFactory()
room = RoomFactory(users=[(user, "owner")])
client = APIClient()
@@ -144,47 +99,4 @@ def test_api_rooms_delete_owners_room_not_live(
)
assert response.status_code == 204
mock_delete_room.assert_called_once_with(str(room.id))
mock_delete_dispatch_rule.assert_called_once_with(room.id)
assert Room.objects.exists() is False
assert Room.all_objects.get(id=room.id).deleted_at is not None
@mock.patch.object(RoomManagement, "delete_room")
def test_api_rooms_delete_soft_deleted(mock_delete_room):
"""Deleting a room that is already soft deleted should return a 410."""
user = UserFactory()
room = RoomFactory(users=[(user, "owner")])
room.soft_delete()
client = APIClient()
client.force_login(user)
response = client.delete(
f"/api/v1.0/rooms/{room.id}/",
)
assert response.status_code == 410
assert response.json() == {"detail": "This room has been deleted."}
mock_delete_room.assert_not_called()
@mock.patch.object(RoomManagement, "delete_room")
def test_api_rooms_delete_soft_deleted_not_owner(mock_delete_room):
"""
Deleting a soft-deleted room as a non-owner should return a 403,
not revealing that the room has been deleted.
"""
user = UserFactory()
room = RoomFactory(users=[(user, "administrator")])
room.soft_delete()
client = APIClient()
client.force_login(user)
response = client.delete(
f"/api/v1.0/rooms/{room.id}/",
)
assert response.status_code == 403
mock_delete_room.assert_not_called()
@@ -2,8 +2,7 @@
Test rooms API endpoints in the Meet core app: participants management.
"""
# pylint: disable=redefined-outer-name,unused-argument,protected-access
# pylint: disable=no-name-in-module,too-many-lines
# pylint: disable=redefined-outer-name,unused-argument,protected-access,no-name-in-module,too-many-lines
import random
from unittest import mock
@@ -193,28 +193,6 @@ def test_api_rooms_retrieve_anonymous_unregistered_not_allowed():
assert response.json() == {"detail": "No Room matches the given query."}
@pytest.mark.parametrize("allow_unregistered_rooms", [True, False])
@pytest.mark.parametrize("lookup", ["id", "slug"])
@mock.patch("core.utils.generate_token", return_value="foo")
def test_api_rooms_retrieve_soft_deleted(
mock_token, lookup, allow_unregistered_rooms, settings
):
"""
Retrieving a soft-deleted room should return a 410, and never fall back
to an unregistered room with the same slug.
"""
settings.ALLOW_UNREGISTERED_ROOMS = allow_unregistered_rooms
room = RoomFactory(access_level=RoomAccessLevel.PUBLIC)
room.soft_delete()
client = APIClient()
response = client.get(f"/api/v1.0/rooms/{getattr(room, lookup)!s}/")
assert response.status_code == 410
assert response.json() == {"detail": "This room has been deleted."}
mock_token.assert_not_called()
@mock.patch("core.utils.generate_token", return_value="foo")
@override_settings(
LIVEKIT_CONFIGURATION={
@@ -1,7 +1,7 @@
"""
Test LiveKitEvents service.
"""
# pylint: disable=W0621,W0613, W0212, E0611, C0302
# pylint: disable=W0621,W0613, W0212, E0611
import logging
import uuid
@@ -27,10 +27,7 @@ from core.services.livekit_events import (
to_recording_event,
)
from core.services.lobby import LobbyService
from core.services.room_management import (
RoomManagementException,
RoomNotFoundException,
)
from core.services.room_management import RoomManagementException
from core.services.sip_management import (
SIPException,
SIPManagement,
@@ -799,61 +796,6 @@ def test_handle_room_started_raises_error_for_nonexistent_room(service):
service._handle_room_started(mock_data)
@mock.patch.object(SIPManagement, "ensure_dispatch_rule")
@mock.patch("core.services.room_management.RoomManagement.delete_room")
def test_handle_room_started_closes_deleted_room(
mock_delete_room, mock_ensure_dispatch_rule, service, settings
):
"""Should close a LiveKit room recreated for a soft-deleted room."""
settings.ROOM_TELEPHONY_ENABLED = True
room = RoomFactory()
room.soft_delete()
mock_data = mock.MagicMock()
mock_data.room.name = str(room.id)
service._handle_room_started(mock_data)
mock_delete_room.assert_called_once_with(str(room.id))
mock_ensure_dispatch_rule.assert_not_called()
@mock.patch(
"core.services.room_management.RoomManagement.delete_room",
side_effect=RoomNotFoundException("Room does not exist"),
)
def test_handle_room_started_ignores_already_closed_deleted_room(
mock_delete_room, service
):
"""Should proceed silently when the deleted room is already closed in LiveKit."""
room = RoomFactory()
room.soft_delete()
mock_data = mock.MagicMock()
mock_data.room.name = str(room.id)
service._handle_room_started(mock_data)
mock_delete_room.assert_called_once_with(str(room.id))
@mock.patch(
"core.services.room_management.RoomManagement.delete_room",
side_effect=RoomManagementException("Could not delete room"),
)
def test_handle_room_started_raises_error_when_closing_deleted_room_fails(
mock_delete_room, service
):
"""Should raise ActionFailedError when the deleted room cannot be closed."""
room = RoomFactory()
room.soft_delete()
mock_data = mock.MagicMock()
mock_data.room.name = str(room.id)
expected_error = f"Failed to close deleted room {room.id}"
with pytest.raises(ActionFailedError, match=expected_error):
service._handle_room_started(mock_data)
@mock.patch.object(
api.WebhookReceiver, "receive", side_effect=Exception("Invalid payload")
)
@@ -2,19 +2,16 @@
from unittest import mock
from django.db import connection
import pytest
from livekit.api import TwirpError
from core.factories import RoomFactory
from core.models import Room, RoomAccessLevel
from core.models import RoomAccessLevel
from core.services.room_management import (
RoomManagement,
RoomManagementException,
RoomNotFoundException,
)
from core.services.sip_management import SIPException, SIPManagement
@mock.patch("core.services.room_management.utils.create_livekit_client")
@@ -65,148 +62,6 @@ def test_delete_room_raises_management_exception(mock_create_livekit_client):
mock_api.aclose.assert_awaited_once()
@pytest.mark.django_db(transaction=True)
@mock.patch.object(SIPManagement, "delete_dispatch_rule")
@mock.patch.object(RoomManagement, "delete_room")
def test_soft_delete_commits_before_closing_livekit_room(mock_delete_room, _):
"""The deletion is committed before the LiveKit room is closed, so the
room_started webhook of a participant reconnecting right away sees it."""
room = RoomFactory()
def assert_deletion_committed(room_name):
assert connection.in_atomic_block is False
assert Room.all_objects.get(id=room_name).is_deleted
mock_delete_room.side_effect = assert_deletion_committed
RoomManagement.soft_delete(room)
mock_delete_room.assert_called_once_with(str(room.id))
@pytest.mark.django_db
@pytest.mark.parametrize(
"error",
[
RoomManagementException("Could not delete room"),
ConnectionError("LiveKit is unreachable"),
],
)
@mock.patch.object(SIPManagement, "delete_dispatch_rule")
@mock.patch.object(RoomManagement, "delete_room")
def test_soft_delete_failure_rolls_back_and_can_be_retried(mock_delete_room, _, error):
"""A failed soft delete leaves the room untouched, in database and in memory,
so it can be retried."""
room = RoomFactory()
mock_delete_room.side_effect = error
with pytest.raises(type(error)):
RoomManagement.soft_delete(room)
assert room.deleted_at is None
assert Room.objects.filter(id=room.id).exists()
mock_delete_room.side_effect = None
RoomManagement.soft_delete(room)
assert mock_delete_room.call_count == 2
assert room.deleted_at is not None
assert Room.all_objects.get(id=room.id).deleted_at is not None
assert Room.objects.filter(id=room.id).exists() is False
@pytest.mark.django_db
@pytest.mark.parametrize("sip_setting", ["ROOM_TELEPHONY_ENABLED", "ROOMKIT_ENABLED"])
@mock.patch.object(SIPManagement, "delete_dispatch_rule")
@mock.patch.object(
RoomManagement,
"delete_room",
side_effect=RoomNotFoundException("Room does not exist"),
)
def test_soft_delete_room_not_live_deletes_dispatch_rule(
mock_delete_room, mock_delete_dispatch_rule, sip_setting, settings
):
"""A roomkit join creates the dispatch rule before any LiveKit room exists,
so no room_finished webhook deletes it: the soft delete must, or the
retained PIN would still route SIP calls to the deleted room."""
settings.ROOM_TELEPHONY_ENABLED = False
settings.ROOMKIT_ENABLED = False
setattr(settings, sip_setting, True)
room = RoomFactory()
RoomManagement.soft_delete(room)
mock_delete_room.assert_called_once_with(str(room.id))
mock_delete_dispatch_rule.assert_called_once_with(room.id)
assert Room.all_objects.get(id=room.id).is_deleted
@pytest.mark.django_db
def test_soft_delete_live_room_deletes_dispatch_rule_before_closing_it(settings):
"""The dispatch rule of a live room is deleted before the LiveKit room is
closed, so a dispatch rule failure rolls the deletion back without having
disconnected the participants."""
settings.ROOM_TELEPHONY_ENABLED = True
room = RoomFactory()
calls = mock.Mock()
with (
mock.patch.object(RoomManagement, "delete_room", calls.delete_room),
mock.patch.object(
SIPManagement, "delete_dispatch_rule", calls.delete_dispatch_rule
),
):
RoomManagement.soft_delete(room)
assert calls.mock_calls == [
mock.call.delete_dispatch_rule(room.id),
mock.call.delete_room(str(room.id)),
]
@pytest.mark.django_db
@mock.patch.object(SIPManagement, "delete_dispatch_rule")
@mock.patch.object(RoomManagement, "delete_room")
def test_soft_delete_sip_disabled_skips_dispatch_rule(
mock_delete_room, mock_delete_dispatch_rule, settings
):
"""Without telephony nor roomkit, no dispatch rule is looked up."""
settings.ROOM_TELEPHONY_ENABLED = False
settings.ROOMKIT_ENABLED = False
room = RoomFactory()
RoomManagement.soft_delete(room)
mock_delete_room.assert_called_once_with(str(room.id))
mock_delete_dispatch_rule.assert_not_called()
assert Room.all_objects.get(id=room.id).is_deleted
@pytest.mark.django_db
@mock.patch.object(
SIPManagement,
"delete_dispatch_rule",
side_effect=SIPException("Could not delete dispatch rules"),
)
@mock.patch.object(RoomManagement, "delete_room")
def test_soft_delete_dispatch_rule_failure_rolls_back(
mock_delete_room, mock_delete_dispatch_rule, settings
):
"""A dispatch rule that can't be deleted fails the soft delete like a LiveKit
room that can't be closed: it is rolled back so it can be retried, and the
LiveKit room is left open."""
settings.ROOMKIT_ENABLED = True
room = RoomFactory()
with pytest.raises(RoomManagementException):
RoomManagement.soft_delete(room)
mock_delete_room.assert_not_called()
mock_delete_dispatch_rule.assert_called_once_with(room.id)
assert room.deleted_at is None
assert Room.objects.filter(id=room.id).exists()
@mock.patch.object(RoomManagement, "update_metadata")
def test_sync_room_metadata_pushes_configuration_and_access_level(mock_update_metadata):
"""The room's configuration and access level are forwarded to LiveKit."""
@@ -257,31 +257,6 @@ def test_delete_dispatch_rule_multiple_rules(mock_client_factory, mock_list_rule
mock_api.aclose.assert_called_once()
@mock.patch("core.services.sip_management.SIPManagement._list_dispatch_rules_ids")
@mock.patch("core.utils.create_livekit_client")
def test_delete_dispatch_rule_already_deleted(mock_client_factory, mock_list_rules):
"""A rule deleted between listing and deletion (e.g. by both a room deletion and
its room_finished webhook) should not fail, nor stop the other deletions."""
sip_management = SIPManagement()
room = RoomFactory(access_level=RoomAccessLevel.RESTRICTED, pin_code="1234")
mock_list_rules.return_value = ["rule-1", "rule-2"]
mock_api = create_mock_livekit_client()
mock_api.sip.delete_sip_dispatch_rule = mock.AsyncMock(
side_effect=[
TwirpError(msg="sip dispatch rule not found", code="not_found", status=404),
None,
]
)
mock_client_factory.return_value = mock_api
result = sip_management.delete_dispatch_rule(room.id)
assert result is True
assert mock_api.sip.delete_sip_dispatch_rule.call_count == 2
mock_api.aclose.assert_called_once()
@mock.patch("core.services.sip_management.SIPManagement._list_dispatch_rules_ids")
@mock.patch("core.utils.create_livekit_client")
def test_delete_dispatch_rule_partial_failure(mock_client_factory, mock_list_rules):
@@ -2,8 +2,6 @@
Test resource accesses API endpoints in the Meet core app.
"""
# pylint: disable=too-many-lines
import random
from unittest import mock
from uuid import uuid4
@@ -958,99 +956,3 @@ def test_api_room_user_access_delete_owners_last_owner():
assert response.status_code == 403
assert ResourceAccess.objects.count() == 1
# Soft-deleted rooms
def test_api_room_user_accesses_create_soft_deleted_room():
"""
Owners of a soft-deleted room should not be allowed to add accesses to it.
"""
user = UserFactory()
room = RoomFactory(users=[(user, "owner")])
room.soft_delete()
client = APIClient()
client.force_login(user)
response = client.post(
"/api/v1.0/resource-accesses/",
{
"user": str(UserFactory().id),
"resource": str(room.id),
"role": "member",
},
)
assert response.status_code == 410
assert response.json() == {"detail": "This room has been deleted."}
assert ResourceAccess.objects.count() == 1
def test_api_room_user_accesses_create_soft_deleted_room_not_administrator():
"""
Users without privileges on a soft-deleted room should get a 403,
not revealing that the room has been deleted.
"""
user = UserFactory()
room = RoomFactory(users=[(user, "member")])
room.soft_delete()
client = APIClient()
client.force_login(user)
response = client.post(
"/api/v1.0/resource-accesses/",
{
"user": str(UserFactory().id),
"resource": str(room.id),
"role": "member",
},
)
assert response.status_code == 403
assert ResourceAccess.objects.count() == 1
def test_api_room_user_accesses_update_soft_deleted_room():
"""
Owners of a soft-deleted room should not be allowed to update its accesses.
"""
user = UserFactory()
room = RoomFactory(users=[(user, "owner")])
access = UserResourceAccessFactory(resource=room, role="member")
room.soft_delete()
client = APIClient()
client.force_login(user)
response = client.patch(
f"/api/v1.0/resource-accesses/{access.id!s}/",
{"role": "administrator"},
format="json",
)
assert response.status_code == 410
access.refresh_from_db()
assert access.role == "member"
def test_api_room_user_access_delete_soft_deleted_room():
"""
Owners of a soft-deleted room should not be allowed to remove its accesses.
"""
user = UserFactory()
room = RoomFactory(users=[(user, "owner")])
access = UserResourceAccessFactory(resource=room, role="member")
room.soft_delete()
client = APIClient()
client.force_login(user)
response = client.delete(
f"/api/v1.0/resource-accesses/{access.id!s}/",
)
assert response.status_code == 410
assert ResourceAccess.objects.filter(id=access.id).exists() is True
@@ -26,12 +26,7 @@ from core.models import (
RoomAccessLevel,
User,
)
from core.services.room_management import (
RoomManagement,
RoomManagementException,
RoomNotFoundException,
)
from core.services.sip_management import SIPManagement
from core.services.room_management import RoomManagement
pytestmark = pytest.mark.django_db
@@ -568,53 +563,6 @@ def test_api_rooms_retrieve_not_found():
assert "no room matches the given query." in str(response.data).lower()
def test_api_rooms_retrieve_invalid_id():
"""Retrieving a room with a malformed id should return a 404."""
user = UserFactory()
token = generate_test_token(user, [ApplicationScope.ROOMS_RETRIEVE])
client = APIClient()
client.credentials(HTTP_AUTHORIZATION=f"Bearer {token}")
response = client.get("/external-api/v1.0/rooms/not-a-uuid/")
assert response.status_code == 404
def test_api_rooms_retrieve_soft_deleted():
"""Retrieving a soft-deleted room should return a 410."""
user = UserFactory()
room = RoomFactory(users=[(user, RoleChoices.OWNER)])
room.soft_delete()
token = generate_test_token(user, [ApplicationScope.ROOMS_RETRIEVE])
client = APIClient()
client.credentials(HTTP_AUTHORIZATION=f"Bearer {token}")
response = client.get(f"/external-api/v1.0/rooms/{room.id}/")
assert response.status_code == 410
assert response.json() == {"detail": "This room has been deleted."}
def test_api_rooms_retrieve_soft_deleted_not_member():
"""Retrieving a soft-deleted room without any role on it should return a 403,
not revealing that the room has been deleted."""
user = UserFactory()
room = RoomFactory()
room.soft_delete()
token = generate_test_token(user, [ApplicationScope.ROOMS_RETRIEVE])
client = APIClient()
client.credentials(HTTP_AUTHORIZATION=f"Bearer {token}")
response = client.get(f"/external-api/v1.0/rooms/{room.id}/")
assert response.status_code == 403
def test_api_rooms_create_requires_authentication():
"""Creating rooms without authentication should return 401."""
@@ -1444,212 +1392,6 @@ def test_api_rooms_update_tracks_analytics(mock_update_metadata, mock_capture):
mock_update_metadata.assert_called_once()
@mock.patch.object(RoomManagement, "delete_room")
def test_api_rooms_delete_requires_authentication(mock_delete_room):
"""Deleting a room without authentication should return 401."""
room = RoomFactory(users=[(UserFactory(), RoleChoices.OWNER)])
client = APIClient()
response = client.delete(f"/external-api/v1.0/rooms/{room.id}/")
assert response.status_code == 401
assert Room.objects.filter(id=room.id).exists() is True
mock_delete_room.assert_not_called()
@mock.patch.object(RoomManagement, "delete_room")
def test_api_rooms_delete_requires_scope(mock_delete_room):
"""Deleting a room requires the ROOMS_DELETE scope."""
user = UserFactory()
room = RoomFactory(users=[(user, RoleChoices.OWNER)])
# Token without ROOMS_DELETE scope
token = generate_test_token(
user, [ApplicationScope.ROOMS_RETRIEVE, ApplicationScope.ROOMS_UPDATE]
)
client = APIClient()
client.credentials(HTTP_AUTHORIZATION=f"Bearer {token}")
response = client.delete(f"/external-api/v1.0/rooms/{room.id}/")
assert response.status_code == 403
assert (
"insufficient permissions. required scope: rooms:delete"
in str(response.data).lower()
)
assert Room.objects.filter(id=room.id).exists() is True
mock_delete_room.assert_not_called()
@pytest.mark.parametrize("role", [RoleChoices.ADMIN, RoleChoices.MEMBER, None])
@mock.patch.object(RoomManagement, "delete_room")
def test_api_rooms_delete_without_ownership(mock_delete_room, role):
"""Only owners should be able to delete a room, administrators included."""
user = UserFactory()
users = [(user, role)] if role else []
room = RoomFactory(users=users)
token = generate_test_token(user, [ApplicationScope.ROOMS_DELETE])
client = APIClient()
client.credentials(HTTP_AUTHORIZATION=f"Bearer {token}")
response = client.delete(f"/external-api/v1.0/rooms/{room.id}/")
assert response.status_code == 403
assert Room.objects.filter(id=room.id).exists() is True
mock_delete_room.assert_not_called()
@mock.patch.object(RoomManagement, "delete_room")
def test_api_rooms_delete_unknown_room(mock_delete_room):
"""Deleting a room that does not exist should return 404."""
user = UserFactory()
token = generate_test_token(user, [ApplicationScope.ROOMS_DELETE])
client = APIClient()
client.credentials(HTTP_AUTHORIZATION=f"Bearer {token}")
response = client.delete(f"/external-api/v1.0/rooms/{uuid.uuid4()}/")
assert response.status_code == 404
mock_delete_room.assert_not_called()
@mock.patch("core.external_api.viewsets.analytics.capture")
@mock.patch.object(SIPManagement, "delete_dispatch_rule")
@mock.patch.object(RoomManagement, "delete_room")
def test_api_rooms_delete_success(mock_delete_room, _, mock_capture):
"""Owners should be able to delete a room: it is soft deleted, its LiveKit
room is closed and a ROOM_DELETED analytics event is emitted."""
user = UserFactory()
room = RoomFactory(
users=[(user, RoleChoices.OWNER)], access_level=RoomAccessLevel.TRUSTED
)
token = generate_test_token(user, [ApplicationScope.ROOMS_DELETE])
application = Application.objects.get()
client = APIClient()
client.credentials(HTTP_AUTHORIZATION=f"Bearer {token}")
response = client.delete(f"/external-api/v1.0/rooms/{room.id}/")
assert response.status_code == 204
mock_delete_room.assert_called_once_with(str(room.id))
assert Room.objects.filter(id=room.id).exists() is False
assert Room.all_objects.get(id=room.id).deleted_at is not None
mock_capture.assert_called_once()
captured_user, event, properties = mock_capture.call_args[0]
assert captured_user == user
assert event == AnalyticsEvent.ROOM_DELETED
assert properties == {
"room_id": str(room.pk),
"access_level": RoomAccessLevel.TRUSTED,
"client_id": str(application.client_id),
"external_api": True,
"auth_method": "ApplicationJWTAuthentication",
"$set": {"email": user.email},
}
@mock.patch("core.external_api.viewsets.analytics.capture")
@mock.patch.object(SIPManagement, "delete_dispatch_rule")
@mock.patch.object(
RoomManagement,
"delete_room",
side_effect=RoomManagementException("Could not delete room"),
)
def test_api_rooms_delete_livekit_failure(mock_delete_room, _, mock_capture):
"""When the LiveKit room can't be closed, the deletion should be rolled back
and no analytics event emitted."""
user = UserFactory()
room = RoomFactory(users=[(user, RoleChoices.OWNER)])
token = generate_test_token(user, [ApplicationScope.ROOMS_DELETE])
client = APIClient()
client.credentials(HTTP_AUTHORIZATION=f"Bearer {token}")
response = client.delete(f"/external-api/v1.0/rooms/{room.id}/")
assert response.status_code == 500
assert response.json() == {"detail": "Could not delete the room, please try again."}
mock_delete_room.assert_called_once_with(str(room.id))
assert Room.objects.get(id=room.id).deleted_at is None
mock_capture.assert_not_called()
@mock.patch.object(SIPManagement, "delete_dispatch_rule")
@mock.patch.object(
RoomManagement,
"delete_room",
side_effect=RoomNotFoundException("Room does not exist"),
)
def test_api_rooms_delete_room_not_live(
mock_delete_room, mock_delete_dispatch_rule, settings
):
"""Deleting a room that is not live in LiveKit should still soft delete it,
and delete its SIP dispatch rule, as no room_finished webhook will."""
settings.ROOMKIT_ENABLED = True
user = UserFactory()
room = RoomFactory(users=[(user, RoleChoices.OWNER)])
token = generate_test_token(user, [ApplicationScope.ROOMS_DELETE])
client = APIClient()
client.credentials(HTTP_AUTHORIZATION=f"Bearer {token}")
response = client.delete(f"/external-api/v1.0/rooms/{room.id}/")
assert response.status_code == 204
mock_delete_room.assert_called_once_with(str(room.id))
mock_delete_dispatch_rule.assert_called_once_with(room.id)
assert Room.objects.filter(id=room.id).exists() is False
assert Room.all_objects.get(id=room.id).deleted_at is not None
@mock.patch.object(RoomManagement, "delete_room")
def test_api_rooms_delete_soft_deleted(mock_delete_room):
"""Deleting a room that is already soft deleted should return a 410."""
user = UserFactory()
room = RoomFactory(users=[(user, RoleChoices.OWNER)])
room.soft_delete()
token = generate_test_token(user, [ApplicationScope.ROOMS_DELETE])
client = APIClient()
client.credentials(HTTP_AUTHORIZATION=f"Bearer {token}")
response = client.delete(f"/external-api/v1.0/rooms/{room.id}/")
assert response.status_code == 410
mock_delete_room.assert_not_called()
@mock.patch.object(RoomManagement, "delete_room")
def test_api_rooms_delete_soft_deleted_not_owner(mock_delete_room):
"""Deleting a soft-deleted room as a non-owner should return a 403,
not revealing that the room has been deleted."""
user = UserFactory()
room = RoomFactory(users=[(user, RoleChoices.ADMIN)])
room.soft_delete()
token = generate_test_token(user, [ApplicationScope.ROOMS_DELETE])
client = APIClient()
client.credentials(HTTP_AUTHORIZATION=f"Bearer {token}")
response = client.delete(f"/external-api/v1.0/rooms/{room.id}/")
assert response.status_code == 403
mock_delete_room.assert_not_called()
def test_api_rooms_response_no_url(settings):
"""Response should not include url field when APPLICATION_BASE_URL is None."""
settings.APPLICATION_BASE_URL = None
+1 -2
View File
@@ -333,8 +333,7 @@ def detect_mimetype(file_buffer: bytes, filename: str | None = None) -> str:
str: The detected MIME type
Notes:
Originally from
https://github.com/suitenumerique/drive/blob/564822d31f071c6dfacd112ef4b7146c73077cd9/src/backend/core/api/utils.py#L166
Originally from https://github.com/suitenumerique/drive/blob/564822d31f071c6dfacd112ef4b7146c73077cd9/src/backend/core/api/utils.py#L166 # pylint:disable=line-too-long
"""
# Initialize magic detector
mime_detector = magic.Magic(mime=True)
+8 -16
View File
@@ -778,9 +778,6 @@ class Base(Configuration):
ROOM_INACTIVITY_DELETION_DAYS = values.PositiveIntegerValue(
None, environ_name="ROOM_INACTIVITY_DELETION_DAYS", environ_prefix=None
)
ROOM_DELETED_RETENTION_DAYS = values.PositiveIntegerValue(
None, environ_name="ROOM_DELETED_RETENTION_DAYS", environ_prefix=None
)
# if provided, treat as suspicious (possible privilege escalation attempt).
PARTICIPANT_FORBIDDEN_PERMISSION_FIELDS = values.ListValue(
["hidden", "recorder", "agent"],
@@ -1478,26 +1475,21 @@ class Base(Configuration):
stacklevel=2,
)
for setting_name, rooms, period in (
("ROOM_INACTIVITY_DELETION_DAYS", "Inactive rooms", "inactivity period"),
("ROOM_DELETED_RETENTION_DAYS", "Deleted rooms", "retention period"),
):
purge_days = getattr(cls, setting_name)
if not purge_days:
continue
if cls.ROOM_INACTIVITY_DELETION_DAYS:
if not cls.RECORDING_EXPIRATION_DAYS:
warnings.warn(
f"{setting_name} is set but RECORDING_EXPIRATION_DAYS is not. "
f"Recordings never expire, so {rooms.lower()} holding a saved "
"recording will never be purged.",
"ROOM_INACTIVITY_DELETION_DAYS is set but "
"RECORDING_EXPIRATION_DAYS is not. Recordings never expire, so "
"inactive rooms holding a saved recording will never be purged.",
UserWarning,
stacklevel=2,
)
elif cls.RECORDING_EXPIRATION_DAYS >= purge_days:
elif cls.RECORDING_EXPIRATION_DAYS >= cls.ROOM_INACTIVITY_DELETION_DAYS:
warnings.warn(
"RECORDING_EXPIRATION_DAYS is greater than or equal to "
f"{setting_name}. {rooms} holding a saved recording will be "
f"kept past the {period}, until their recordings expire.",
"ROOM_INACTIVITY_DELETION_DAYS. Inactive rooms holding a saved "
"recording will be kept past the inactivity period, until their "
"recordings expire.",
UserWarning,
stacklevel=2,
)
+1 -1
View File
@@ -82,7 +82,7 @@ dev = [
"ipython==9.16.1",
"pyfakefs==6.2.0",
"pylint-django==2.8.0",
"pylint==4.1.3",
"pylint<4.0.0",
"pytest-cov==7.1.0",
"pytest-django==4.14.0",
"pytest==9.1.1",
+7 -7
View File
@@ -136,11 +136,11 @@ wheels = [
[[package]]
name = "astroid"
version = "4.3.4"
version = "3.3.11"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/2d/87/5732fa68bf100a095cfcbd108f919220d995db99e1a7502b8119a869fd62/astroid-4.3.4.tar.gz", hash = "sha256:d515a105722b72098bbe82d430d65e635f742b6cbac3bdfaf8b7c188b87c5e39", size = 444627, upload-time = "2026-10-08T09:36:44.122Z" }
sdist = { url = "https://files.pythonhosted.org/packages/18/74/dfb75f9ccd592bbedb175d4a32fc643cf569d7c218508bfbd6ea7ef9c091/astroid-3.3.11.tar.gz", hash = "sha256:1e5a5011af2920c7c67a53f65d536d65bfa7116feeaf2354d8b94f29573bb0ce", size = 400439, upload-time = "2025-07-13T18:04:23.177Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/16/d4/f23c0ac6e6de33ba5686cb21c672c95e0c2d3d4c9351f16d3b5fed818652/astroid-4.3.4-py3-none-any.whl", hash = "sha256:2bcd0d02648a443a4b818c952c3550091989daefac3c12d3b83b2289482e0818", size = 288310, upload-time = "2026-10-08T09:36:42.284Z" },
{ url = "https://files.pythonhosted.org/packages/af/0f/3b8fdc946b4d9cc8cc1e8af42c4e409468c84441b933d037e101b3d72d86/astroid-3.3.11-py3-none-any.whl", hash = "sha256:54c760ae8322ece1abd213057c4b5bba7c49818853fc901ef09719a60dbf9dec", size = 275612, upload-time = "2025-07-13T18:04:21.07Z" },
]
[[package]]
@@ -1416,7 +1416,7 @@ dev = [
{ name = "ipdb", specifier = "==0.13.13" },
{ name = "ipython", specifier = "==9.16.1" },
{ name = "pyfakefs", specifier = "==6.2.0" },
{ name = "pylint", specifier = "==4.1.3" },
{ name = "pylint", specifier = "<4.0.0" },
{ name = "pylint-django", specifier = "==2.8.0" },
{ name = "pytest", specifier = "==9.1.1" },
{ name = "pytest-cov", specifier = "==7.1.0" },
@@ -2032,7 +2032,7 @@ wheels = [
[[package]]
name = "pylint"
version = "4.1.3"
version = "3.3.9"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "astroid" },
@@ -2043,9 +2043,9 @@ dependencies = [
{ name = "platformdirs" },
{ name = "tomlkit" },
]
sdist = { url = "https://files.pythonhosted.org/packages/38/c9/0bde4152a05a7686b431ce216fe3f3698b0c0d94c20bfa256dd935b608f6/pylint-4.1.3.tar.gz", hash = "sha256:9928603068edfa0d1a3c167f174b099d4b97c3db75d32d0fcdd029770b4713a9", size = 1756180, upload-time = "2026-10-11T07:49:10.69Z" }
sdist = { url = "https://files.pythonhosted.org/packages/04/9d/81c84a312d1fa8133b0db0c76148542a98349298a01747ab122f9314b04e/pylint-3.3.9.tar.gz", hash = "sha256:d312737d7b25ccf6b01cc4ac629b5dcd14a0fcf3ec392735ac70f137a9d5f83a", size = 1525946, upload-time = "2025-10-05T18:41:43.786Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/3f/ba/62b18e2e157d05f976bd490b349b55d8850c2a454a5c313c91af9d2e0baf/pylint-4.1.3-py3-none-any.whl", hash = "sha256:a85357cae24f33ad8d86c8f3daaa92c600ae4012b54a57299cee76000e9364cf", size = 588959, upload-time = "2026-10-11T07:49:08.272Z" },
{ url = "https://files.pythonhosted.org/packages/1a/a7/69460c4a6af7575449e615144aa2205b89408dc2969b87bc3df2f262ad0b/pylint-3.3.9-py3-none-any.whl", hash = "sha256:01f9b0462c7730f94786c283f3e52a1fbdf0494bbe0971a78d7277ef46a751e7", size = 523465, upload-time = "2025-10-05T18:41:41.766Z" },
]
[[package]]
@@ -3,6 +3,9 @@ import { getScrollBarWidth } from '@livekit/components-core'
import * as React from 'react'
import { TrackLoop, useVisualStableUpdate } from '@livekit/components-react'
import { useSize } from '@/features/rooms/livekit/hooks/useResizeObserver'
import { useSpeakerPromotionTrigger } from '../hooks/useSpeakerPromotionTrigger'
import { useTopSpeaker } from '../hooks/useTopSpeaker'
import { splitCarouselTiles } from '../utils/splitCarouselTiles'
const MIN_HEIGHT = 130
const MIN_WIDTH = 140
@@ -66,7 +69,20 @@ export function CarouselLayout({
setPrevTiles(tilesThatFit)
}
const sortedTiles = useVisualStableUpdate(tracks, maxVisibleTiles)
const topSpeakerId = useTopSpeaker(tracks)
const { head, rest, restSlots } = splitCarouselTiles(
tracks,
topSpeakerId,
maxVisibleTiles
)
// useVisualStableUpdate needs a page of at least one tile.
const stableRest = useVisualStableUpdate(rest, Math.max(restSlots, 1))
const sortedTiles = [...head, ...stableRest]
// When the head fills the carousel, no rest speaker can be brought on
// screen, so the trigger ignores them instead of re-rendering for nothing.
const onScreen = sortedTiles.slice(0, maxVisibleTiles)
useSpeakerPromotionTrigger(onScreen, restSlots > 0 ? tracks : onScreen)
React.useLayoutEffect(() => {
if (asideEl.current) {
@@ -46,7 +46,7 @@ export function GridLayout({ tracks, ...props }: GridLayoutProps) {
const { layout } = useGridLayout(gridEl, tracks.length)
const pagination = usePagination(layout.maxTiles, tracks)
useSpeakerPromotionTrigger(pagination.tracks)
useSpeakerPromotionTrigger(pagination.tracks, tracks)
useSwipe(gridEl, {
onLeftSwipe: pagination.nextPage,
@@ -8,35 +8,42 @@ import { useEffect, useReducer, useRef } from 'react'
* Tripwire for speaker promotion.
*
* Listens to `RoomEvent.ActiveSpeakersChanged` imperatively and forces ONE
* re-render of the host component only when an active speaker has none of
* their tiles are within the visible span (`maxVisibleTiles`). That render
* re-runs `useVisualStableUpdate`, which reads live `participant.isSpeaking`
* state and performs the actual swap.
* re-render of the host when a speaker has a tile in `allTiles` but none in
* `visibleTiles`. That render re-runs `useVisualStableUpdate`, which reads
* live `participant.isSpeaking` state and performs the actual swap.
*
* Speakers already visible are ignored. Everything else costs zero React work.
* Speakers already visible cost nothing, nor do speakers the layout doesn't
* show at all (e.g. the pinned participant, rendered by the focus view).
*
* Requires the parent to NOT re-render on speaker events itself, i.e.
* `useTracks(..., { updateOnlyOn: [] })` upstream.
*/
export function useSpeakerPromotionTrigger(
sortedTiles: TrackReferenceOrPlaceholder[]
/** Tiles inside the span the layout guarantees to speakers. */
visibleTiles: TrackReferenceOrPlaceholder[],
/** Every tile the layout shows, visible or not. */
allTiles: TrackReferenceOrPlaceholder[]
) {
const room = useRoomContext()
const [, forceRender] = useReducer((n: number) => n + 1, 0)
// Refs so the listener reads current values without re-subscribing
// and without itself being a render dependency.
const tilesRef = useRef(sortedTiles)
tilesRef.current = sortedTiles
// Read by the listener at event time, so it never re-subscribes.
const tilesRef = useRef({ visibleTiles, allTiles })
tilesRef.current = { visibleTiles, allTiles }
useEffect(() => {
const onActiveSpeakersChanged = (speakers: Participant[]) => {
const tiles = tilesRef.current
const hiddenSpeakerExists = speakers.some(
(speaker) =>
!tiles.some((t) => t.participant.identity === speaker.identity)
)
if (hiddenSpeakerExists) {
const { visibleTiles, allTiles } = tilesRef.current
const hasTileIn =
(tiles: TrackReferenceOrPlaceholder[]) => (identity: string) =>
tiles.some((t) => t.participant.identity === identity)
const isShown = hasTileIn(allTiles)
const isVisible = hasTileIn(visibleTiles)
const isHidden = (identity: string) =>
isShown(identity) && !isVisible(identity)
if (speakers.some(({ identity }) => isHidden(identity))) {
forceRender()
}
}
@@ -0,0 +1,40 @@
import type { TrackReferenceOrPlaceholder } from '@livekit/components-core'
import { useRoomContext } from '@livekit/components-react'
import { Track } from 'livekit-client'
import { useEffect, useRef, useState } from 'react'
import { watchTopSpeaker } from '../utils/watchTopSpeaker'
/**
* Identity of the participant who should hold the top speaker slot, among
* those with a camera tile in `tracks`: the slot only shows cameras, so a
* participant whose camera is pinned away can't hold it through their screen
* share. See `watchTopSpeaker` for the rules.
*
* Re-renders the host only when the holder changes. Expects
* `useTracks(..., { updateOnlyOn: [] })` upstream.
*/
export function useTopSpeaker(tracks: TrackReferenceOrPlaceholder[]) {
const room = useRoomContext()
const [topSpeakerId, setTopSpeakerId] = useState<string>()
// Read by the listener at event time; subscribing once keeps the hold
// state alive across renders.
const tracksRef = useRef(tracks)
tracksRef.current = tracks
useEffect(
() =>
watchTopSpeaker(room, {
isEligible: (identity) =>
tracksRef.current.some(
(t) =>
t.participant.identity === identity &&
t.source === Track.Source.Camera
),
onChange: setTopSpeakerId,
}),
[room]
)
return topSpeakerId
}
@@ -0,0 +1,39 @@
import type { TrackReferenceOrPlaceholder } from '@livekit/components-core'
import { Track } from 'livekit-client'
/**
* Splits carousel tiles into a fixed head and a rest that is free to reorder.
*
* Head: the local camera, then the top speaker's camera. When only one tile
* fits, the speaker goes first so they are the one on screen. The rest goes
* through `useVisualStableUpdate`.
*
* `restSlots` is how many on-screen slots are left for the rest. It is 0 or
* negative when the head fills the carousel.
*
* The speaker slot is reserved even while it is empty: `useVisualStableUpdate`
* treats any change of page size as a relayout and re-sorts everything, so it
* must not move when the first speaker gets promoted.
*/
export function splitCarouselTiles(
tracks: TrackReferenceOrPlaceholder[],
topSpeakerId: string | undefined,
maxVisibleTiles: number
) {
const cameraOf = (match: (t: TrackReferenceOrPlaceholder) => boolean) =>
tracks.find((t) => t.source === Track.Source.Camera && match(t))
const local = cameraOf((t) => t.participant.isLocal)
const speaker = topSpeakerId
? cameraOf((t) => t.participant.identity === topSpeakerId)
: undefined
const order = maxVisibleTiles < 2 ? [speaker, local] : [local, speaker]
const head = order.filter((t) => t !== undefined)
const rest = tracks.filter((t) => !head.includes(t))
const reservedSlots = (local ? 1 : 0) + 1
const restSlots = maxVisibleTiles - reservedSlots
return { head, rest, restSlots }
}
@@ -0,0 +1,63 @@
import { RoomEvent } from 'livekit-client'
import type { Room } from 'livekit-client'
/** Minimum time a speaker keeps the top slot before someone else can take it. */
export const TOP_SPEAKER_HOLD_MS = 2000
type SpeakerSource = Pick<Room, 'on' | 'off' | 'activeSpeakers'>
/**
* Calls `onChange` with the participant who should hold the top speaker slot.
*
* The candidate is the loudest remote speaker for whom `isEligible` is true
* (e.g. who has a tile in the layout). The slot is sticky: silence keeps the
* current holder. A new speaker only takes over once the holder has had it for
* `holdMs`, and only if they are still the loudest at that point; someone who
* stops talking before then never steals it. A holder who is no longer
* eligible (left, got pinned) is replaced right away.
*
* `onChange` only fires on an actual change. Returns an unsubscribe function.
*/
export function watchTopSpeaker(
room: SpeakerSource,
{
isEligible,
onChange,
holdMs = TOP_SPEAKER_HOLD_MS,
}: {
isEligible: (identity: string) => boolean
onChange: (identity: string) => void
holdMs?: number
}
) {
let holder: string | undefined
let holdUntil = 0
let retry: ReturnType<typeof setTimeout> | undefined
const evaluate = () => {
clearTimeout(retry)
// `activeSpeakers` is sorted loudest first and is always current, which
// the deferred retry needs; the event payload would be stale by then.
const candidate = room.activeSpeakers.find(
(p) => !p.isLocal && isEligible(p.identity)
)?.identity
if (!candidate || candidate === holder) return
const wait = holder && isEligible(holder) ? holdUntil - Date.now() : 0
if (wait > 0) {
retry = setTimeout(evaluate, wait)
return
}
holder = candidate
holdUntil = Date.now() + holdMs
onChange(candidate)
}
room.on(RoomEvent.ActiveSpeakersChanged, evaluate)
return () => {
room.off(RoomEvent.ActiveSpeakersChanged, evaluate)
clearTimeout(retry)
}
}
@@ -13,8 +13,6 @@ export enum ApiLobbyStatus {
DENIED = 'denied',
TIMEOUT = 'timeout',
ACCEPTED = 'accepted',
// Client-side only: the room was deleted while waiting
DELETED = 'deleted',
}
export interface ApiRequestEntry {
@@ -86,7 +86,6 @@ export const Conference = ({
const {
status: fetchStatus,
isError: isFetchError,
error: fetchError,
data,
} = useQuery({
queryKey: fetchKey,
@@ -100,8 +99,6 @@ export const Conference = ({
if (error.statusCode == '404') {
createRoom({ slug: roomId, username })
}
// A deleted room can't be recreated, surface the error instead
if (error.statusCode == '410') throw error
}),
retry: false,
})
@@ -202,15 +199,6 @@ export const Conference = ({
}, [apiConfig?.livekit])
const { t } = useTranslation('rooms')
if (fetchError?.statusCode == 410) {
return (
<ErrorScreen
title={t('error.deletedRoom.heading')}
body={t('error.deletedRoom.body')}
/>
)
}
if (isCreateError) {
// this error screen should be replaced by a proper waiting room for anonymous user.
return (
@@ -295,7 +283,6 @@ export const Conference = ({
return
case DisconnectReason.DUPLICATE_IDENTITY:
case DisconnectReason.PARTICIPANT_REMOVED:
case DisconnectReason.ROOM_DELETED:
navigateTo(
'feedback',
{},
@@ -74,9 +74,7 @@ export const Lobby = ({
const { openLoginHint } = useLoginHint()
const handleSubmit = async () => {
const { data, error } = await refetchRoom()
if (error?.statusCode == 410) return
const { data } = await refetchRoom()
if (!data?.livekit) {
// Display a message to inform the user that by logging in, they won't have to wait for room entry approval.
@@ -90,22 +88,7 @@ export const Lobby = ({
enterRoom()
}
const isRoomDeleted = isError && error?.statusCode == 410
const lobbyStatus = isRoomDeleted ? ApiLobbyStatus.DELETED : status
switch (lobbyStatus) {
case ApiLobbyStatus.DELETED:
return (
<VStack alignItems="center" textAlign="center">
<H lvl={1} margin={false} centered>
{t('deleted.title')}
</H>
<Text as="p" variant="note">
{t('deleted.body')}
</Text>
</VStack>
)
switch (status) {
case ApiLobbyStatus.TIMEOUT:
return (
<VStack alignItems="center" textAlign="center">
@@ -1,7 +1,6 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { keys } from '@/api/queryKeys'
import { ApiError } from '@/api/ApiError'
import {
requestEntry,
ApiLobbyStatus,
@@ -41,33 +40,24 @@ export const useLobby = ({
const { data: waitingData } = useQuery({
queryKey: [keys.requestEntry, roomId],
queryFn: async () => {
try {
const response = await requestEntry({
roomId,
username,
})
const response = await requestEntry({
roomId,
username,
})
if (response.id) {
setLobbyParticipantId(roomId, response.id)
}
if (response.status === ApiLobbyStatus.ACCEPTED) {
clearWaitingTimeout()
setStatus(ApiLobbyStatus.ACCEPTED)
onAccepted(response)
} else if (response.status === ApiLobbyStatus.DENIED) {
clearWaitingTimeout()
setStatus(ApiLobbyStatus.DENIED)
}
return response
} catch (error) {
// The room was deleted while waiting, stop polling
if (error instanceof ApiError && error.statusCode === 410) {
clearWaitingTimeout()
setStatus(ApiLobbyStatus.DELETED)
return { status: ApiLobbyStatus.DELETED }
}
throw error
if (response.id) {
setLobbyParticipantId(roomId, response.id)
}
if (response.status === ApiLobbyStatus.ACCEPTED) {
clearWaitingTimeout()
setStatus(ApiLobbyStatus.ACCEPTED)
onAccepted(response)
} else if (response.status === ApiLobbyStatus.DENIED) {
clearWaitingTimeout()
setStatus(ApiLobbyStatus.DENIED)
}
return response
},
refetchInterval: POLL_INTERVAL_MS,
refetchOnWindowFocus: false,
@@ -31,7 +31,6 @@ const buttonClass = css({
enum DisconnectReasonKey {
DuplicateIdentity = 'duplicateIdentity',
ParticipantRemoved = 'participantRemoved',
RoomDeleted = 'roomDeleted',
}
const FeedbackRoute = () => {
@@ -47,8 +46,6 @@ const FeedbackRoute = () => {
return DisconnectReasonKey.DuplicateIdentity
case DisconnectReason.PARTICIPANT_REMOVED:
return DisconnectReasonKey.ParticipantRemoved
case DisconnectReason.ROOM_DELETED:
return DisconnectReasonKey.RoomDeleted
}
}, [])
@@ -59,10 +56,7 @@ const FeedbackRoute = () => {
}
}, [])
// Rejoining is not possible once removed or once the room is deleted
const showBackButton =
reasonKey !== DisconnectReasonKey.ParticipantRemoved &&
reasonKey !== DisconnectReasonKey.RoomDeleted
const showBackButton = reasonKey !== DisconnectReasonKey.ParticipantRemoved
return (
<Screen layout="centered" footer={false}>
+1 -10
View File
@@ -3,8 +3,7 @@
"heading": {
"normal": "Du hast das Meeting verlassen",
"duplicateIdentity": "Du bist dem Meeting von einem anderen Gerät aus beigetreten",
"participantRemoved": "Du wurdest vom Host aus dem Meeting entfernt",
"roomDeleted": "Dieses Meeting wurde gelöscht"
"participantRemoved": "Du wurdest vom Host aus dem Meeting entfernt"
},
"home": "Zur Startseite zurückkehren",
"back": "Dem Meeting erneut beitreten"
@@ -95,10 +94,6 @@
"timeoutInvite": {
"title": "Du kannst diesem Meeting nicht beitreten",
"body": "Niemand hat auf deine Anfrage reagiert"
},
"deleted": {
"title": "Du kannst diesem Meeting nicht beitreten",
"body": "Dieses Meeting wurde gelöscht."
}
},
"leaveRoomPrompt": "Hiermit verlässt du das Meeting.",
@@ -220,10 +215,6 @@
"heading": "Authentifizierung erforderlich",
"body": "Dieser Raum wurde noch nicht erstellt. Bitte authentifiziere dich, um ihn zu erstellen, oder warte, bis eine authentifizierte Person dies tut."
},
"deletedRoom": {
"heading": "Meeting gelöscht",
"body": "Dieses Meeting wurde gelöscht und kann nicht mehr betreten werden."
},
"screenShare": {
"title": "Bildschirmfreigabe nicht möglich",
"ariaLabel": "Bildschirmfreigabe nicht möglich",
+1 -10
View File
@@ -3,8 +3,7 @@
"heading": {
"normal": "You have left the meeting",
"duplicateIdentity": "You have joined the meeting from another device",
"participantRemoved": "You have been removed from the meeting by a host",
"roomDeleted": "This meeting has been deleted"
"participantRemoved": "You have been removed from the meeting by a host"
},
"home": "Return to home",
"back": "Rejoin the meeting"
@@ -95,10 +94,6 @@
"timeoutInvite": {
"title": "You cannot join this call",
"body": "No one responded to your request"
},
"deleted": {
"title": "You cannot join this call",
"body": "This meeting has been deleted."
}
},
"leaveRoomPrompt": "This will make you leave the meeting.",
@@ -220,10 +215,6 @@
"heading": "Authentication Required",
"body": "This room has not been created yet. Please authenticate to create it or wait for an authenticated user to do so."
},
"deletedRoom": {
"heading": "Meeting deleted",
"body": "This meeting has been deleted and can no longer be joined."
},
"screenShare": {
"title": "Unable to share your screen",
"ariaLabel": "Unable to share your screen",
+1 -10
View File
@@ -3,8 +3,7 @@
"heading": {
"normal": "Has salido de la reunión",
"duplicateIdentity": "Te has unido a la reunión desde otro dispositivo",
"participantRemoved": "Un administrador te ha expulsado de la llamada",
"roomDeleted": "Esta reunión ha sido eliminada"
"participantRemoved": "Un administrador te ha expulsado de la llamada"
},
"home": "Volver al inicio",
"back": "Volver a la reunión"
@@ -95,10 +94,6 @@
"timeoutInvite": {
"title": "No puedes participar en esta llamada",
"body": "Nadie ha respondido a tu solicitud de participación en la llamada"
},
"deleted": {
"title": "No puedes participar en esta llamada",
"body": "Esta reunión ha sido eliminada."
}
},
"leaveRoomPrompt": "Volver al inicio hará que salgas de la reunión.",
@@ -220,10 +215,6 @@
"heading": "Autenticación necesaria",
"body": "Esta reunión todavía no se ha creado. Autentícate para crearla o espera a que lo haga un usuario autenticado."
},
"deletedRoom": {
"heading": "Reunión eliminada",
"body": "Esta reunión ha sido eliminada y ya no es posible unirse a ella."
},
"screenShare": {
"title": "No se puede compartir tu pantalla",
"ariaLabel": "No se puede compartir tu pantalla",
+1 -10
View File
@@ -3,8 +3,7 @@
"heading": {
"normal": "Vous avez quitté la réunion",
"duplicateIdentity": "Vous avez rejoint la réunion depuis un autre appareil",
"participantRemoved": "Vous avez été exclu de l'appel par un administrateur",
"roomDeleted": "Cette réunion a été supprimée"
"participantRemoved": "Vous avez été exclu de l'appel par un administrateur"
},
"home": "Retourner à l'accueil",
"back": "Réintégrer la réunion"
@@ -95,10 +94,6 @@
"timeoutInvite": {
"title": "Vous ne pouvez pas participer à cet appel",
"body": "Personne n'a répondu à votre demande de participation à l'appel"
},
"deleted": {
"title": "Vous ne pouvez pas participer à cet appel",
"body": "Cette réunion a été supprimée."
}
},
"leaveRoomPrompt": "Revenir à l'accueil vous fera quitter la réunion.",
@@ -220,10 +215,6 @@
"heading": "Authentification requise",
"body": "Cette réunion n'a pas encore été créée. Veuillez vous authentifier pour la créer ou attendre qu'un utilisateur authentifié le fasse."
},
"deletedRoom": {
"heading": "Réunion supprimée",
"body": "Cette réunion a été supprimée et n'est plus accessible."
},
"screenShare": {
"title": "Impossible de partager votre écran",
"ariaLabel": "Impossible de partager votre écran",
+1 -10
View File
@@ -3,8 +3,7 @@
"heading": {
"normal": "Je hebt de vergadering verlaten",
"duplicateIdentity": "U heeft de vergadering via een ander apparaat geopend",
"participantRemoved": "U bent door een beheerder uit het gesprek verwijderd",
"roomDeleted": "Deze vergadering is verwijderd"
"participantRemoved": "U bent door een beheerder uit het gesprek verwijderd"
},
"home": "Keer terug naar het hoofdscherm",
"back": "Sluit weer bij de vergadering aan"
@@ -95,10 +94,6 @@
"timeoutInvite": {
"title": "U kunt niet deelnemen aan dit gesprek",
"body": "Niemand heeft gereageerd op uw verzoek om deel te nemen aan het gesprek"
},
"deleted": {
"title": "U kunt niet deelnemen aan dit gesprek",
"body": "Deze vergadering is verwijderd."
}
},
"leaveRoomPrompt": "Dat zal u de vergadering doen verlaten.",
@@ -220,10 +215,6 @@
"heading": "Verificatie vereist",
"body": "Deze ruimte is nog niet gemaakt. Logt u alstublieft in om hem aan te maken, of wacht tot een ingelogde gebruiker dat doet."
},
"deletedRoom": {
"heading": "Vergadering verwijderd",
"body": "Deze vergadering is verwijderd en u kunt er niet meer aan deelnemen."
},
"screenShare": {
"title": "Kan uw scherm niet delen",
"ariaLabel": "Kan uw scherm niet delen",