Compare commits

..

51 Commits

Author SHA1 Message Date
leo d8ab229813 wip 2026-08-04 19:49:51 +02:00
lebaudantoine 7bd5ab7a13 (frontend) expose media state to external gateways
Add a hidden div in the DOM that reflects the current state of the
microphone and camera, so that external SIP media gateways (e.g. the
Renater one) can observe it and keep an accurate view of the media
state.

Also emit a custom event from the page whenever the microphone or
camera state changes, so external consumers can subscribe to updates
instead of polling the DOM.
2026-08-04 19:04:16 +02:00
lebaudantoine ac8eae7295 (backend) apply user preferences on unconfigured room creation
Update the API so that, when a user creates a new meeting without
passing an explicit configuration, the user's persisted preferences
are applied as defaults.

This allows a user to, for example, enable the waiting room by
default on every meeting they create.
2026-08-04 19:04:16 +02:00
lebaudantoine 15b1ab7e0a (frontend) let users set default configuration for generated links
Extend the existing out-of-room settings so users can configure a
default room configuration that is applied to every link they
generate from the app.
2026-08-04 19:04:16 +02:00
lebaudantoine 2e509eff28 (backend) persist user preferences for room defaults on the User model
Add attributes on the User model to persist per-user preferences for
the default link access level and the default room configuration.

The frontend will let users update these preferences and then reuse
them when generating a link through the webapp.

Persisting them on the backend (rather than in application memory
only) ensures the preferences survive across sessions and devices.
2026-08-04 19:04:16 +02:00
lebaudantoine ca56ae87c2 (backend) expose the default room access level in settings
Expose the default access level for rooms in the backend settings
response, so the frontend can initialize the global room preferences
UI with the current default value.
2026-08-04 19:04:15 +02:00
lebaudantoine 2c5a766d02 🔥(ci) remove unused Anthropic security step
Drop the Anthropic security step from the project CI, as it is no
longer used and only added noise to the pipeline.
2026-08-04 19:04:15 +02:00
davd-gzl a67467b193 🩹(all) clear the SonarCloud reliability finding and the lint debt
The SonarCloud gate fails on main, so every commit lands red, and
gh run list hides it: it lists only Actions workflows, and the
failure is an app check run.

Reliability rests on one bug, in test_file_service.py, which wrapped
an assertion in an except Exception re-raised through pytest.fail.
Removing it takes the rating from D to A.

Two pieces of debt ride along. The SDK callback id now comes from
crypto.getRandomValues, since it guards an endpoint with no auth. And
core/tasks gets the __init__.py that lets pylint see it, with the
debt that exposes, which is why #1533 fails lint-back.
2026-08-04 19:04:15 +02:00
Florent Chehab 24d5a5a035 🧑‍💻(backend) use solo pool celery worker in dev
Change to reduce memory usage in dev.
2026-08-04 19:04:15 +02:00
lebaudantoine 9e500a59ea 🧑‍💻(backend) add commented the roomkit env variables
Useful for an easier devex when working on the feature.
2026-08-04 19:04:15 +02:00
lebaudantoine 8a0d4b1ad6 ♻️(backend) refactor tests to rely on decorators
Slightly refactor the existing tests to use decorators for common
setup and configuration.
2026-08-04 19:04:15 +02:00
lebaudantoine d0726ba631 🐛(backend) ensure SIP dispatch rule instead of creating it
The roomkit can now create a SIP dispatch rule before the LiveKit
webhook that used to trigger this creation is fired. In practice,
when the roomkit connects to the room, it also triggers the
webhook, leading to a duplicated dispatch rule.

Switch from "create dispatch rule" to "ensure dispatch rule exists"
semantics, so subsequent calls are idempotent and no duplicate rule
is created.
2026-08-04 19:04:14 +02:00
lebaudantoine e65036fe90 🚚(backend) rename TelephonyService to SIPManagement
Rename the telephony service to a more descriptive name,
SIPManagementService, which clearly states what the service is used
for.

It is no longer used only by the telephony feature; the roomkit
feature also relies on it now.
2026-08-04 19:04:14 +02:00
lebaudantoine 8b198726e9 (backend) add roomkit viewset to start a room without WebRTC join
Introduce a new viewset that lets the roomkit start a room even when
no WebRTC participant has joined yet.

This is a first entry point that will be extended over time with
more actions a roomkit needs to be able to trigger.

Known limitations:

* The responsibility around SIP rules is currently split between
  the telephony feature and the roomkit one. This may need a
  refactor later on to consolidate ownership in a single place.
* The default throttle might be too low for production usage and
  will likely need to be revisited.
2026-08-04 19:04:14 +02:00
lebaudantoine fc4774199b 🔧(devx) stop declaring LiveKit as an app-dev dependency
LiveKit was declared as an app-dev dependency, which caused it
(along with its egress) to be started whenever we ran unrelated
commands such as tests, migrate or makemigrations.

Drop that dependency and start LiveKit explicitly only when it is
actually needed, i.e. when calling run-backend.
2026-08-04 19:04:14 +02:00
lebaudantoine 9a3e54e6ec 🐛(backend) disable recording events in the default env file
The tests were failing when the Django settings did not disable
recording events, which was the case by default.

We do not rely on these events anymore by default, so set the
corresponding environment variable to false in the env file to make
the tests pass out of the box.
2026-08-04 19:04:14 +02:00
snyk-bot a0d4d82e18 fix: upgrade i18next from 26.3.4 to 26.3.6
Snyk has created this PR to upgrade i18next from 26.3.4 to 26.3.6.

See this package in npm:
i18next

See this project in Snyk:
https://app.eu.snyk.io/org/lasuite-dinum-default/project/af693e79-8c43-4c09-ab65-60580515c9e8?utm_source=github&utm_medium=referral&page=upgrade-pr
2026-08-04 19:04:14 +02:00
renovate[bot] 8ed49c880b ⬆️(dependencies) update django to v5.2.16 2026-08-04 19:04:13 +02:00
leo be369bc04b ♻️(devex) optimize Makefile linting workflow
The linting workflow was unnecessarily building Docker dependencies and
creating containers multiple times. Optimize the Makefile to fix both
issues, for faster and lighter linting.
2026-08-04 19:04:13 +02:00
lebaudantoine be98c5210e 💄(frontend) adjust centering of Avatar initials
Fine-tune the vertical alignment of the initials in the Avatar so
they sit properly centered inside the circle.
2026-08-04 19:04:13 +02:00
lebaudantoine e400d05a7c 🚸(frontend) show two initials in the Avatar when possible
Display two initials in the Avatar whenever the participant's name
allows it, instead of a single letter.

A single initial makes it too hard to distinguish participants when
their cameras are off, especially in larger
2026-08-04 19:04:13 +02:00
lebaudantoine 9af42568bf 💄(frontend) improve participant name rendering in the list
Rework how the participant name is displayed in the participant
list to show as much of the name as possible before truncating.

When the name has to be truncated, add a tooltip so users can hover
to see the full name.

Requested by users.
2026-08-04 19:04:13 +02:00
lebaudantoine 7eba983c15 (frontend) introduce an "unauthenticated" participant badge
Add a visual badge on participants who are not authenticated, so it
is immediately clear who could be an anonymous participant. This is
a small but explicit security signal in the participant list.

Beyond that, the badge also plays a functional role: since only
authenticated participants can be promoted or demoted, the badge
helps users see at a glance who is eligible for a role change.
2026-08-04 19:04:12 +02:00
lebaudantoine b7210e62bb (frontend) notify user when their meeting role changes
Show a notification to the user whenever their role in the meeting
changes, so they immediately see when they have been promoted or
demoted.
2026-08-04 19:04:12 +02:00
lebaudantoine 653326347b 🐛(frontend) fall back to user.full_name on request-entry
Since the username refactoring, the username in the store could be
undefined when the join input was pre-filled from user.full_name,
because no keystroke was needed to populate the store.

This led to a 400 error on the request-entry endpoint whenever the
user joined without editing the pre-filled name.

Fall back to user.full_name when the store username is missing, so
the endpoint always receives a value.

Acknowledged as a somewhat wobbly fix, but ships as-is until the
underlying flow is reworked.
2026-08-04 19:04:12 +02:00
lebaudantoine 187e289548 (frontend) close admin side panel when the user is demoted
Listen to role changes in the admin panel and close the side panel
if the current user is demoted while it is open. Without this,
unprivileged users could still see the admin side panel until they
closed it manually.

I checked the other features that could be affected by hot role
changes; this was the only one still exposing admin-only UI after a
demotion. Everything else already handles live permission updates
correctly.
2026-08-04 19:04:12 +02:00
lebaudantoine 496a192ced (frontend) allow promoting authenticated participants
Introduce a new feature that lets a user promote one of the
authenticated participants of the meeting to a role with additional
privileges.

Known limitations:

* Only authenticated participants can be promoted, but there is no
  visual indicator yet distinguishing authenticated from anonymous
  participants. This will be added in a follow-up commit.
* The resource_access data fetched in the initial API call becomes
  stale after a promotion. It is not currently used in the product,
  so this is not visible, but it should either be refreshed later
  or removed from the initial fetch.
* Demoting a promoted user turns them into a member, which is still
  a privileged role. This is a deliberate choice until we introduce
  finer-grained tuning of participant roles.
2026-08-04 19:04:12 +02:00
lebaudantoine 715c18d276 ♻️(frontend) extract closeSidePanel action at the store level
Extract the logic that closes the side panel into a utility function
declared at the store module level, as recommended by Valtio.

This avoids re-creating the function on every render and prevents
extra re-renders in components that use it.
2026-08-04 19:04:12 +02:00
lebaudantoine dd3f23b1bf 🐛(backend) allow any string as sub in the API serializer
The API serializer was too restrictive on the `sub` field, expecting
a UUID. This worked in our development and production setups because
our Keycloak is configured to emit UUID subs, but it broke for other
providers.

Per the OIDC spec and the DB model, `sub` can be any string. Align
the serializer with this and accept arbitrary string values.

Fixes #1525.
2026-08-04 19:04:11 +02:00
lebaudantoine 066cd5f704 💄(frontend) render Avatar initials in uppercase
Uppercase the initials rendered in the Avatar so their vertical
centering stays consistent.

With lowercase letters, the initials were slightly shifted toward
the bottom of the Avatar, which broke the alignment.
2026-08-04 19:04:11 +02:00
lebaudantoine 19dfa26ee4 🔥(frontend) remove leftover console.count call
Drop a stray console.count call that was accidentally committed in a
previous PR and had been left in the codebase.
2026-08-04 19:04:11 +02:00
lebaudantoine 82aafa2030 ♻️(frontend) derive is_administrable from participant metadata
The is_administrable flag was previously read from the room API
response through the room serializer, giving the frontend static
information about the user's rights.

Refactor the frontend so it derives this flag from the participant
role carried in the participant metadata instead.

Two benefits:

* The flag now updates live along with the participant
  attributes/metadata, so role changes are reflected immediately.
* It removes the duplication between the API response and the
  metadata, which both used to determine the user's capabilities.
2026-08-04 19:04:11 +02:00
lebaudantoine bfb02b2242 (frontend) add client for the update participant role endpoint
Add the frontend client that calls the update participant role
endpoint. Straightforward API call, no special handling.
2026-08-04 19:04:11 +02:00
lebaudantoine ec9cd84cf8 (backend) expose is_authenticated in the LiveKit token
Include the is_authenticated flag on the user in the LiveKit token
and participant metadata.

The frontend needs this information (used in the next commit) to
know whether it can offer to promote a user with access to the room
admin.
2026-08-04 19:04:10 +02:00
lebaudantoine 65172447ca ♻️(backend) pass the participant role in the LiveKit token
The backend previously passed an abstract is_admin_or_owner boolean
flag in the LiveKit token. That kept the frontend minimalistic and
saved it from having to handle role comparisons.

As we introduce more features that need to distinguish between the
room owner and admins, refactor the token to carry the role
directly. The frontend can then derive the relevant flags from a
richer piece of information.
2026-08-04 19:04:10 +02:00
lebaudantoine 71d76abc0f (backend) add endpoint to update a participant role during a meeting
Add an endpoint that allows updating a user's role while in a
meeting. The goal is to let users promote other connected
participants to admin or moderator, so the burden of administrating
a meeting can be shared.
2026-08-04 19:04:10 +02:00
lebaudantoine 47f3da4153 ️(backend) add permission class checking the user is in the call
Introduce a new permission class that verifies the caller making a
request is both authenticated and actually present in the call.

It will be used to gate actions that require the user to be live in
the room, for example:

* allowing someone in from the waiting room
* promoting another participant to a different role

More generally, this covers every action where, for security
reasons, we need to make sure the user is truly present in the call
and that someone is not reusing their cookie as an API key.
2026-08-04 19:04:10 +02:00
Arnaud Robin ab0b2d67c3 📝(legal) update terms of service
Update terms of service content after legal review
2026-08-04 19:04:10 +02:00
leo a911226d07 🐛(backend) preserve recording metadata when updating room access
Updating room access rewrote the entire metadata payload, removing information
about active recordings. This caused the frontend to lose track of ongoing
recordings and could trigger 409 errors when attempting to start a new
recording.

Consolidate the duplicated metadata update logic into
`RoomManagement.update_metadata()` and preserve merge behavior instead of
overwriting the full metadata object.
2026-08-04 19:04:10 +02:00
snyk-bot adaffb0343 ⬆️(frontend) upgrade i18next from 26.3.2 to 26.3.4
Snyk has created this PR to upgrade i18next from 26.3.2 to 26.3.4.

See this package in npm:
i18next

See this project in Snyk:
https://app.eu.snyk.io/org/lasuite-dinum-default/project/af693e79-8c43-4c09-ab65-60580515c9e8?utm_source=github&utm_medium=referral&page=upgrade-pr
2026-08-04 19:04:09 +02:00
Camille Moulin ee5710e61c 📝(metadata): Add publiccode.yml file
Recommended for Public Administration Open Source software projects.
See https://yml.publiccode.tools/

Signed-off-by: Camille Moulin <camille.moulin@numerique.gouv.fr>
2026-08-04 19:04:09 +02:00
lebaudantoine 6dd914fe66 📝(frontend) add changelog entry for PR #1510
Document in the CHANGELOG the set of changes shipped in PR #1510,
which groups the recent chat, layout and participant tile render
optimizations.
2026-08-04 19:04:09 +02:00
lebaudantoine a52ea119ac 🐛(frontend) reset chat state when the ChatProvider mounts
Reset the chat state on the first render of the ChatProvider, to
make sure no chat messages from a previous room leak into the new
one.

This covers SPA navigations where the user switches from one room
to another without a full page reload.
2026-08-04 19:04:09 +02:00
lebaudantoine fc4ee70265 🐛(frontend) fix pinnedTrackRef always evaluating to true
pinnedTrackRef was always truthy when evaluated in this
code path.
2026-08-04 19:04:09 +02:00
lebaudantoine 81f23aeb88 ️(frontend) tripwire promotion of off-screen active speakers
Introduce a tripwire component that listens to
RoomEvent.ActiveSpeakersChanged imperatively and forces a single
re-render of its host only when an active speaker has none of their
tiles within the visible span (maxVisibleTiles). That re-render
re-runs useVisualStableUpdate, which reads live isSpeaking state
and performs the actual tile swap.

Speakers already visible are ignored, so this costs zero React work
in the common case.

This lets us drop the ActiveSpeakersChanged subscription from
useTracks in the StageLayout upstream (updateOnlyOn: []), which was
re-rendering the whole stage on every speaker change.
2026-08-04 19:04:09 +02:00
lebaudantoine a5651249c5 ️(frontend) memoize the EffectsButton
Memoize the EffectsButton so it does not re-render on unrelated
parent updates when its props have not changed.
2026-08-04 19:04:08 +02:00
lebaudantoine 167839ebd0 ️(frontend) reduce re-renders of the ParticipantTile focus overlay
Optimize the idle mouse handling and the FocusOverlay component so
they no longer trigger frequent re-renders of the ParticipantTile
focus.

State related to hover and focus is now scoped closer to where it
is used, keeping updates local instead of propagating up the tile.
2026-08-04 19:04:08 +02:00
lebaudantoine 18ec920ebe 🚚(frontend) extract ParticipantTile sub-components into their own files
Split the sub-components currently declared inside ParticipantTile
into dedicated files.

This makes the ParticipantTile file easier to read and lets each
sub-component be imported and reasoned about on its own.
2026-08-04 19:04:08 +02:00
lebaudantoine 8a24502295 ♻️(frontend) harmonize participant name handling in ParticipantTile
Align how the participant name is retrieved and rendered inside the
ParticipantTile, so the different code paths use a single consistent
approach instead of a mix of ad hoc logic.
2026-08-04 19:04:08 +02:00
lebaudantoine c3f212bf54 ️(frontend) synchronize room metadata in a leaf component
Wrap the hook in a leaf component.
2026-08-04 19:03:18 +02:00
lebaudantoine a0274a2d54 ️(frontend) memoize the Placeholder component
Turn the Placeholder into a pure leaf component and memoize it, so
it does not re-render on unrelated parent updates when its props
have not changed.
2026-08-04 19:02:40 +02:00
45 changed files with 3920 additions and 188 deletions
-29
View File
@@ -1,29 +0,0 @@
# /!\
# Security Note: This action is not hardened against prompt injection attacks and should only be used
# to review trusted PRs. Configure your repository with "Require approval for all external contributors"
# to ensure workflows only run after a maintainer has reviewed the PR.
name: Security Review
permissions:
pull-requests: write # Needed for leaving PR comments
contents: read
on:
pull_request:
branches:
- 'main'
jobs:
security:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
with:
ref: ${{ github.event.pull_request.head.sha || github.sha }}
fetch-depth: 2
- uses: anthropics/claude-code-security-review@0c6a49f1fa56a1d472575da86a94dbc1edb78eda
with:
comment-pr: true
exclude-directories: docs,gitlint,LICENSES,bin
claude-api-key: ${{ secrets.CLAUDE_API_KEY }}
+5 -1
View File
@@ -15,6 +15,9 @@ and this project adheres to
- ✨(frontend) allow promoting authenticated participants
- ✨(frontend) introduce an "unauthenticated" participant badge
- ✨(backend) add roomkit viewset to start a room without WebRTC join
- ✨(frontend) let users set default configuration for generated links
- ✨(frontend) expose media state to external gateways
- ✨(backend) push recordings to the owner's Drive (POC)
### Changed
@@ -29,7 +32,7 @@ and this project adheres to
- 💄(frontend) improve participant name rendering in the list
- 🚚(backend) rename TelephonyService to SIPManagement
## Fixed
### Fixed
- 🐛(transcription) fix silent bug in speaker assignment
- 🐛(summary) extend tasks auto retry logic
@@ -38,6 +41,7 @@ and this project adheres to
- 🐛(backend) allow any string as sub in the API serializer
- 🐛(frontend) fall back to user.full_name on request-entry
- 🚸(frontend) show two initials in the Avatar when possible
- 🩹(all) clear the SonarCloud reliability finding and the lint debt
## [1.24.0] - 2026-07-21
+10
View File
@@ -81,6 +81,7 @@ create-env-files: \
env.d/development/common \
env.d/development/crowdin \
env.d/development/postgresql \
env.d/development/kc_postgresql \
env.d/development/summary \
env.d/development/kube-secret \
env.d/development/multi_user_transcriber \
@@ -92,6 +93,7 @@ bootstrap: \
data/media \
data/static \
create-env-files \
create-docker-network \
build \
migrate \
demo \
@@ -125,11 +127,16 @@ down: ## stop and remove containers, networks, images, and volumes
@$(COMPOSE) down
.PHONY: down
create-docker-network: ## create the shared lasuite-network if it doesn't exist
@docker network create lasuite-network || true
.PHONY: create-docker-network
logs: ## display app-dev logs (follow mode)
@$(COMPOSE) logs -f app-dev
.PHONY: logs
run-backend: ## start only the backend application and all needed services
@$(MAKE) create-docker-network
@$(COMPOSE) up --force-recreate -d celery-dev --remove-orphans
@$(COMPOSE) up --force-recreate -d nginx
@$(COMPOSE) up -d livekit
@@ -287,6 +294,9 @@ env.d/development/common:
env.d/development/postgresql:
cp -n env.d/development/postgresql.dist env.d/development/postgresql
env.d/development/kc_postgresql:
cp -n env.d/development/kc_postgresql.dist env.d/development/kc_postgresql
env.d/development/summary:
cp -n env.d/development/summary.dist env.d/development/summary
+48 -10
View File
@@ -14,6 +14,9 @@ services:
image: sj26/mailcatcher:latest
ports:
- "1081:1080"
networks:
- default
- lasuite
minio:
user: ${DOCKER_USER:-1000}
@@ -33,6 +36,10 @@ services:
command: minio server --console-address :9001 /data
volumes:
- ./data/media:/data
networks:
default:
aliases:
- meet-minio
createbuckets:
image: minio/mc
@@ -92,6 +99,7 @@ services:
networks:
- resource-server
- default
- lasuite
celery-dev:
user: ${DOCKER_USER:-1000}
@@ -108,6 +116,9 @@ services:
- /app/.venv
depends_on:
- app-dev
networks:
- default
- lasuite
app:
build:
@@ -147,7 +158,7 @@ services:
volumes:
- ./docker/files/etc/nginx/conf.d:/etc/nginx/conf.d:ro
depends_on:
- dex
- keycloak
- app-dev
networks:
- resource-server
@@ -187,16 +198,40 @@ services:
volumes:
- ".:/app"
# OIDC provider for the development stack. Dex uses in-memory storage, so it
# needs no database and no volume: restarting it rotates the signing keys and
# drops every active session, which is fine locally.
dex:
image: dexidp/dex:v2.45.1
command: ["dex", "serve", "/etc/dex/config.yaml"]
kc_postgresql:
image: postgres:14.3
ports:
- "5433:5432"
env_file:
- env.d/development/kc_postgresql
keycloak:
image: quay.io/keycloak/keycloak:26.3.2
volumes:
- ./docker/auth/dex.yaml:/etc/dex/config.yaml:ro
expose:
- "5556"
- ./docker/auth/realm.json:/opt/keycloak/data/import/realm.json
command:
- start-dev
- --features=preview
- --import-realm
- --proxy-headers=xforwarded
- --hostname=http://localhost:8083
- --hostname-strict=false
environment:
KC_BOOTSTRAP_ADMIN_USERNAME: admin
KC_BOOTSTRAP_ADMIN_PASSWORD: admin
KC_DB: postgres
KC_DB_URL_HOST: kc_postgresql
KC_DB_URL_DATABASE: keycloak
KC_DB_PASSWORD: pass
KC_DB_USERNAME: meet
KC_DB_SCHEMA: public
ports:
- "8080:8080"
depends_on:
- kc_postgresql
networks:
- default
- lasuite
livekit:
image: livekit/livekit-server
@@ -313,3 +348,6 @@ services:
networks:
default:
resource-server:
lasuite:
name: lasuite-network
external: true
-93
View File
@@ -1,93 +0,0 @@
# Dex configuration for the local development stack.
#
# This file replaces the former Keycloak "meet" realm (docker/auth/realm.json).
# The client and the users below are a one-to-one port of that realm.
#
# Storage is in-memory on purpose: no database container, no volume, ~30 MB of
# RAM instead of the Keycloak + PostgreSQL pair. The trade-off is that
# restarting the `dex` service rotates the signing keys and drops every active
# session, so you have to log in again.
# Must match OIDC_OP_URL in env.d/development/common. Dex serves all of its
# endpoints under the path component of the issuer, i.e. /dex/auth, /dex/token,
# /dex/keys, /dex/userinfo and /dex/.well-known/openid-configuration.
issuer: http://localhost:8083/dex
storage:
type: memory
web:
http: 0.0.0.0:5556
allowedOrigins:
- http://localhost:3000
- http://localhost:8071
logger:
level: info
format: text
oauth2:
# Logging in implies authorization: no consent screen, as with the realm.
skipApprovalScreen: true
expiry:
idTokens: 24h
signingKeys: 6h
staticClients:
- id: meet
name: Meet
secret: ThisIsAnExampleKeyForDevPurposeOnly
# Dex does not support wildcards: every callback URL must be listed
# explicitly. The path is the one exposed by mozilla-django-oidc through
# lasuite.oidc_login, mounted under api/<version>/ by core.urls.
redirectURIs:
- http://localhost:3000/api/v1.0/callback/
- http://localhost:3200/api/v1.0/callback/
- http://localhost:8070/api/v1.0/callback/
- http://localhost:8071/api/v1.0/callback/
- http://localhost:8088/api/v1.0/callback/
enablePasswordDB: true
# Dex's local password database authenticates on the *email address*, not on
# the username, so the login is now "meet@meet.world" (password unchanged).
#
# Hashes are bcrypt with cost 10, the minimum dex accepts. To add a user:
# htpasswd -bnBC 10 "" <password> | tr -d ':\n'
staticPasswords:
- email: meet@meet.world
hash: "$2b$10$qVCVTnaF67S/7a.pQM4djOgpj61FxD/yz6LoiQdtX0TKISelAfZxC"
username: meet
name: John Doe
preferredUsername: John
userID: 4ad6106f-a64f-43eb-ad0e-380d2cad9a9d
groups:
- user
- email: user@chromium.e2e
hash: "$2b$10$4Rs3Jd/Q23RM09g7c1Z/yeGmEjoAYlMKXDBkkjERaRDlz0Doiwl2q"
username: user-e2e-chromium
name: E2E Chromium
preferredUsername: E2E
userID: 1cd83dfc-153f-4987-b8a6-a2ac72d39122
groups:
- user
- email: user@webkit.e2e
hash: "$2b$10$D50UlVVMA7qWlB.Pw8P02eMJpo8qfwWuGiA63IeTqq/3mAE7RyH3m"
username: user-e2e-webkit
name: E2E Webkit
preferredUsername: E2E
userID: 9b9bd390-a6e5-42f8-a06d-9a11ede7bb8c
groups:
- user
- email: user@firefox.e2e
hash: "$2b$10$0D8WW7.KXMkzSY2b9JhwYeIM3WkTPQCwGd36/G3TZ/HHh4ObCVRga"
username: user-e2e-firefox
name: E2E Firefox
preferredUsername: E2E
userID: ec3e8750-7629-42f1-a0c3-6e23968a2fba
groups:
- user
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -40,7 +40,7 @@ server {
}
location / {
proxy_pass http://dex:5556;
proxy_pass http://keycloak:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+4 -5
View File
@@ -1,13 +1,12 @@
version: '3'
# You can add any necessary service here that will join the same docker network
# sharing the OIDC provider. Services added to the 'meet_resource-server'
# network will be able to communicate with dex (through nginx) and the backend
# on that network.
# sharing keycloak. Services added to the 'meet_resource-server' network will be
# able to communicate with keycloak and the backend on that network.
services:
# busybox service is only used for testing purposes. It provides curl to test
# connectivity to the backend and the OIDC provider. Replace this with your
# relevant application services that need to communicate with them.
# connectivity to the backend and keycloak services. Replace this with your
# relevant application services that need to communicate with keycloak.
busybox:
image: alpine:latest
privileged: true
+1 -5
View File
@@ -71,12 +71,8 @@ $ make bootstrap FLUSH_ARGS='--no-input'
2. Access the project:
- The frontend is available at [http://localhost:3000](http://localhost:3000) with the default credentials:
- email: meet@meet.world
- username: meet
- password: meet
Authentication is handled by [dex](https://dexidp.io/), configured in
`docker/auth/dex.yaml`. It logs you in by email address, and its storage is
in-memory: restarting the `dex` container logs everyone out.
- The Django backend is available at [http://localhost:8071](http://localhost:8071)
---
+55
View File
@@ -126,6 +126,61 @@ RECORDING_STORAGE_EVENT_TOKEN = <token>
> Questions? Open an issue on [GitHub](https://github.com/suitenumerique/meet/issues/new?assignees=&labels=bug&template=Bug_report.md) or join our [Matrix community](https://matrix.to/#/#meet-official:matrix.org).
## Push recordings to Drive
Once a recording is over, it can be pushed (streamed) to the user's [Drive](https://github.com/suitenumerique/drive), in addition to staying in the object storage.
Drive is called as a resource server, following its
[resource server documentation](https://github.com/suitenumerique/drive/blob/main/docs/resource_server.md):
### Special requirements
- Drive configured as an OIDC resource server, accepting Meet's audience
(`OIDC_RS_ALLOWED_AUDIENCES` must contain Meet's client id), with the `items`
endpoint allowing the `list`, `children` and `upload_ended` actions.
- `OIDC_STORE_ACCESS_TOKEN` enabled on Meet, along with
`OIDC_STORE_REFRESH_TOKEN_KEY`, the Fernet key encrypting the stored token.
> [!CAUTION]
> This is a proof of concept: the access token is captured when the recording
> starts and assumed to still be valid when the recording ends. Long recordings
> may therefore fail to be pushed. Exchanging it for a long-lived, narrowly
> scoped token is the intended follow-up.
### Configuration options
| Option | Type | Default | Description |
| ----------------------------------------------------- | ----------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| **RECORDING_PUSH_TO_DRIVE_ENABLED** | Boolean | `False` | Enable pushing recordings to the owner's Drive. |
| **DRIVE_API_BASE_URL** | String | `None` | Base URL of Drive's external API, e.g. `https://fichiers.numerique.gouv.fr/external_api/v1.0`. |
| **RECORDING_PUSH_TO_DRIVE_SIGNED_URL_EXPIRY_SECONDS** | Integer | `3600` | Lifetime of the signed URL the worker downloads the recording from. |
| **OIDC_STORE_ACCESS_TOKEN** | Boolean | `False` | Keep the user's access token in the session, required to call Drive on their behalf. |
| **OIDC_STORE_REFRESH_TOKEN_KEY** | Secret/File | `None` | Fernet key encrypting OIDC tokens at rest. Generate one with `Fernet.generate_key()`. |
| **DRIVE_UPLOAD_STORAGE_NETLOC** | String | `None` | Development only: `host:port` to reach Drive's object storage at, when the domain Drive signs its upload URLs with only resolves from a browser. |
### Local development
Meet and Drive run as two separate compose projects, joined by the external
`lasuite-network` (`make create-docker-network`). Meet's backend containers reach
Drive's nginx at `drive-nginx:8083` and its object storage at `drive-minio:9000`.
On the Drive side:
```bash
OIDC_RESOURCE_SERVER_ENABLED=True
OIDC_RS_CLIENT_ID=drive
OIDC_RS_CLIENT_SECRET=ThisIsAnExampleKeyForDevPurposeOnly
OIDC_RS_AUDIENCE_CLAIM=client_id
OIDC_RS_ALLOWED_AUDIENCES=meet
```
`DRIVE_UPLOAD_STORAGE_NETLOC` is needed because Drive signs its upload URLs
with `localhost:9100`, which does not resolve from Meet's containers. The
presigned signature covers the `Host` header, so the backend keeps announcing the
signed host and only swaps the address it connects to.
## LiveKit Egress
La Suite Meet uses LiveKit Egress to record room sessions. For reference, see the [LiveKit Egress repository](https://github.com/livekit/egress) and the [official documentation](https://docs.livekit.io/home/egress/overview/).
+19 -20
View File
@@ -24,42 +24,35 @@ MEET_BASE_URL="http://localhost:8072"
# Media
STORAGES_STATICFILES_BACKEND=django.contrib.staticfiles.storage.StaticFilesStorage
AWS_S3_DOMAIN_REPLACE=http://localhost:9000
AWS_S3_ENDPOINT_URL=http://minio:9000
AWS_S3_ENDPOINT_URL=http://meet-minio:9000
AWS_S3_ACCESS_KEY_ID=meet
AWS_S3_SECRET_ACCESS_KEY=password
MEDIA_BASE_URL=http://localhost:3000
FILE_UPLOAD_ENABLED=True
# OIDC
# Provider is dex (docker/auth/dex.yaml), served behind nginx on port 8083.
# Endpoints reached by the browser use localhost, the ones called server-side
# by the backend use the nginx service name.
OIDC_OP_JWKS_ENDPOINT=http://nginx:8083/dex/keys
OIDC_OP_AUTHORIZATION_ENDPOINT=http://localhost:8083/dex/auth
OIDC_OP_TOKEN_ENDPOINT=http://nginx:8083/dex/token
OIDC_OP_USER_ENDPOINT=http://nginx:8083/dex/userinfo
OIDC_OP_INTROSPECTION_ENDPOINT=http://nginx:8083/dex/token/introspect
OIDC_OP_URL=http://localhost:8083/dex
OIDC_OP_JWKS_ENDPOINT=http://nginx:8083/realms/meet/protocol/openid-connect/certs
OIDC_OP_AUTHORIZATION_ENDPOINT=http://localhost:8083/realms/meet/protocol/openid-connect/auth
OIDC_OP_TOKEN_ENDPOINT=http://nginx:8083/realms/meet/protocol/openid-connect/token
OIDC_OP_USER_ENDPOINT=http://nginx:8083/realms/meet/protocol/openid-connect/userinfo
OIDC_OP_INTROSPECTION_ENDPOINT=http://nginx:8083/realms/meet/protocol/openid-connect/token/introspect
OIDC_OP_URL=http://localhost:8083/realms/meet
OIDC_RP_CLIENT_ID=meet
OIDC_RP_CLIENT_SECRET=ThisIsAnExampleKeyForDevPurposeOnly
OIDC_RP_SIGN_ALGO=RS256
# "profile" is required: dex only emits the name claims under that scope.
OIDC_RP_SCOPES="openid email profile"
# Dex exposes the display name through the standard "name" and
# "preferred_username" claims and never emits given_name/family_name.
OIDC_USERINFO_FULLNAME_FIELDS=name
OIDC_USERINFO_SHORTNAME_FIELD=preferred_username
OIDC_RP_SCOPES="openid email"
LOGIN_REDIRECT_URL=http://localhost:3000
LOGIN_REDIRECT_URL_FAILURE=http://localhost:3000
LOGOUT_REDIRECT_URL=http://localhost:3000
OIDC_REDIRECT_ALLOWED_HOSTS=localhost:8083,localhost:3000
# Dex has no notion of ACR, the eIDAS level requested from ProConnect in
# production is meaningless here and would just be ignored.
OIDC_AUTH_REQUEST_EXTRA_PARAMS={}
OIDC_AUTH_REQUEST_EXTRA_PARAMS={"acr_values": "eidas1"}
# The key below encrypts OIDC tokens at rest.
OIDC_STORE_ACCESS_TOKEN=True
OIDC_STORE_REFRESH_TOKEN_KEY=
OIDC_RS_CLIENT_ID=meet
OIDC_RS_CLIENT_SECRET=ThisIsAnExampleKeyForDevPurposeOnly
@@ -81,6 +74,12 @@ SUMMARY_SERVICE_API_TOKEN=password
SUMMARY_SERVICE_WEBHOOK_API_TOKEN=webhook-password
RECORDING_DOWNLOAD_BASE_URL=http://localhost:3000/recording
# Push recordings to Drive
# DRIVE_UPLOAD_STORAGE_NETLOC is a development-only workaround.
RECORDING_PUSH_TO_DRIVE_ENABLED=True
DRIVE_API_BASE_URL=http://drive-app-dev:8000/external_api/v1.0
DRIVE_UPLOAD_STORAGE_NETLOC=drive-minio:9000
# Recording encoding (LiveKit Egress advanced options).
# When RECORDING_ENCODING_ENABLED is False (default), LiveKit uses its built-in
# H264_720P_30 preset (1280x720, 30fps, 3000 kbps). Enable and tune to reduce
+11
View File
@@ -0,0 +1,11 @@
# Postgresql db container configuration
POSTGRES_DB=keycloak
POSTGRES_USER=meet
POSTGRES_PASSWORD=pass
# App database configuration
DB_HOST=kc_postgresql
DB_NAME=keycloak
DB_USER=meet
DB_PASSWORD=pass
DB_PORT=5433
+1 -1
View File
@@ -2,7 +2,7 @@ LIVEKIT_URL=ws://livekit:7880
LIVEKIT_API_KEY=devkey
LIVEKIT_API_SECRET=secret
AWS_S3_ENDPOINT_URL=minio:9000
AWS_S3_ENDPOINT_URL=meet-minio:9000
AWS_S3_ACCESS_KEY_ID=meet
AWS_S3_SECRET_ACCESS_KEY=password
AWS_STORAGE_BUCKET_NAME=meet-media-storage
+1 -1
View File
@@ -2,7 +2,7 @@ APP_NAME="meet-app-summary-dev"
APP_API_TOKEN="password"
AWS_STORAGE_BUCKET_NAME="meet-media-storage"
AWS_S3_ENDPOINT_URL="minio:9000"
AWS_S3_ENDPOINT_URL="meet-minio:9000"
AWS_S3_SECURE_ACCESS=false
AWS_S3_ACCESS_KEY_ID="meet"
+3
View File
@@ -61,6 +61,9 @@ def get_frontend_configuration(request):
],
},
"telephony": build_telephony_config(),
"resource": {
"default_access_level": settings.RESOURCE_DEFAULT_ACCESS_LEVEL,
},
"subtitle": {"enabled": settings.ROOM_SUBTITLE_ENABLED},
"livekit": {
"url": settings.LIVEKIT_CONFIGURATION["url"],
+20 -1
View File
@@ -31,9 +31,28 @@ class UserSerializer(serializers.ModelSerializer):
class Meta:
model = models.User
fields = ["id", "email", "full_name", "short_name", "timezone", "language"]
fields = [
"id",
"email",
"full_name",
"short_name",
"timezone",
"language",
"default_room_access_level",
"default_room_configuration",
]
read_only_fields = ["id", "email", "full_name", "short_name"]
def validate_default_room_configuration(self, value):
"""Validate the default room configuration against the RoomConfiguration schema."""
if value is None or value == {}:
return value
try:
RoomConfiguration.model_validate(value)
except PydanticValidationError as e:
raise serializers.ValidationError(e.errors()) from e
return value
class UserLightSerializer(serializers.ModelSerializer):
"""Serialize users with limited fields."""
+53 -2
View File
@@ -308,8 +308,27 @@ class RoomViewSet(
return drf_response.Response(serializer.data)
def perform_create(self, serializer):
"""Set the current user as owner of the newly created room."""
room = serializer.save()
"""Set the current user as owner of the newly created room.
Apply the user's default room preferences (access level and configuration)
unless the request explicitly provides its own values.
"""
user = self.request.user
save_kwargs = {}
if (
"access_level" not in serializer.validated_data
and user.default_room_access_level not in (None, "")
):
save_kwargs["access_level"] = user.default_room_access_level
user_default_configuration = user.default_room_configuration
if not serializer.validated_data.get(
"configuration"
) and user_default_configuration not in (None, {}):
save_kwargs["configuration"] = user.default_room_configuration
room = serializer.save(**save_kwargs)
models.ResourceAccess.objects.create(
resource=room,
user=self.request.user,
@@ -364,6 +383,37 @@ class RoomViewSet(
room.id,
)
@staticmethod
def _store_drive_credentials(request, recording):
"""Keep the OIDC access token needed to push the recording to Drive later.
Pushing happens long after this request, when the egress is over and the
user may be gone, so the token has to be stored.
POC limitation: we assume the token is still valid by then. The target
design is a token exchange performed here, to get a long-lived
token narrowly scoped to that upload.
"""
if not settings.RECORDING_PUSH_TO_DRIVE_ENABLED:
return
if recording.mode != models.RecordingModeChoices.SCREEN_RECORDING:
# Only videos are pushed to Drive, no need for a token otherwise.
return
access_token = request.session.get("oidc_access_token")
if not access_token:
logger.warning(
"No OIDC access token in session, recording %s will not be pushed "
"to Drive. Is OIDC_STORE_ACCESS_TOKEN enabled?",
recording.id,
)
return
recording.set_owner_access_token(access_token)
@decorators.action(
detail=True,
methods=["post"],
@@ -399,6 +449,7 @@ class RoomViewSet(
role=models.RoleChoices.OWNER,
recording=recording,
)
self._store_drive_credentials(request, recording)
except (DjangoValidationError, IntegrityError):
# DjangoValidationError covers the Python-level check (full_clean);
@@ -0,0 +1,23 @@
# Generated by Django 5.2.14 on 2026-08-03 13:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0021_recording_external_process_id_alter_recording_status'),
]
operations = [
migrations.AddField(
model_name='user',
name='default_room_access_level',
field=models.CharField(blank=True, choices=[('public', 'Public Access'), ('trusted', 'Trusted Access'), ('restricted', 'Restricted Access')], help_text='Access level applied by default to new rooms created by this user. When empty, the instance default is used.', max_length=50, null=True, verbose_name='default room access level'),
),
migrations.AddField(
model_name='user',
name='default_room_configuration',
field=models.JSONField(blank=True, default=dict, help_text='Configurations applied by default to new rooms created by this user.', verbose_name='default room configuration'),
),
]
+63
View File
@@ -189,6 +189,25 @@ class User(AbstractBaseUser, BaseModel, auth_models.PermissionsMixin):
default=settings.TIME_ZONE,
help_text=_("The timezone in which the user wants to see times."),
)
default_room_access_level = models.CharField(
max_length=50,
choices=RoomAccessLevel.choices,
blank=True,
null=True,
verbose_name=_("default room access level"),
help_text=_(
"Access level applied by default to new rooms created by this user. "
"When empty, the instance default is used."
),
)
default_room_configuration = models.JSONField(
blank=True,
default=dict,
verbose_name=_("default room configuration"),
help_text=_(
"Configurations applied by default to new rooms created by this user."
),
)
is_device = models.BooleanField(
_("device"),
default=False,
@@ -620,6 +639,17 @@ class Recording(BaseModel):
verbose_name=_("External Process ID"),
help_text=_("ID of the external process associated with the recording."),
)
owner_access_token = models.TextField(
null=True,
blank=True,
editable=False,
verbose_name=_("Owner access token"),
help_text=_(
"Encrypted OIDC access token of the user who started the recording, "
"used to push the recording to their Drive on their behalf. "
"Dropped as soon as the push has been attempted."
),
)
class Meta:
db_table = "meet_recording"
@@ -722,6 +752,39 @@ class Recording(BaseModel):
return self.expired_at < timezone.now()
def set_owner_access_token(self, access_token: str) -> None:
"""Store the OIDC access token of the user who started the recording.
It is stored encrypted, and only long enough for the worker to push the
recording to that user's Drive once the recording is over.
"""
self.owner_access_token = utils.encrypt_secret(access_token)
self.save(update_fields=["owner_access_token", "updated_at"])
def get_owner_access_token(self) -> Optional[str]:
"""Return the stored OIDC access token, or None if there is none left."""
if not self.owner_access_token:
return None
try:
return utils.decrypt_secret(self.owner_access_token)
except utils.SecretDecryptionError:
logger.exception(
"Could not decrypt the access token of recording %s", self.id
)
return None
def clear_owner_access_token(self) -> None:
"""Drop the stored access token, it is a user credential."""
if self.owner_access_token is None:
return
self.owner_access_token = None
self.save(update_fields=["owner_access_token", "updated_at"])
class RecordingAccess(BaseAccess):
"""Relation model to give access to a recording for a user or a team with a role."""
@@ -19,6 +19,7 @@ from livekit import api as livekit_api
from core import models, utils
from core.analytics import UserFeatureFlag, is_user_feature_flag_enabled
from core.tasks.push_recording import push_recording
from core.utils import generate_download_s3_url
logger = logging.getLogger(__name__)
@@ -45,7 +46,15 @@ class NotificationService:
"""Service for processing recordings and notifying external services."""
def notify_external_services(self, recording):
"""Process a recording based on its mode."""
"""Process a recording, then push the video to the owner's Drive."""
try:
return self._notify_by_mode(recording)
finally:
self._push_recording_to_drive(recording)
def _notify_by_mode(self, recording):
"""Route a recording to the services its mode calls for."""
if recording.mode == models.RecordingModeChoices.TRANSCRIPT:
return self._notify_summary_service(recording)
@@ -222,6 +231,31 @@ class NotificationService:
f"Unknown summary service version: {settings.SUMMARY_SERVICE_VERSION}"
)
@staticmethod
def _push_recording_to_drive(recording: models.Recording):
"""Hand the recording over to the task pushing it to the owner's Drive."""
if not settings.RECORDING_PUSH_TO_DRIVE_ENABLED:
return
if recording.mode != models.RecordingModeChoices.SCREEN_RECORDING:
recording.clear_owner_access_token()
return
if not recording.owner_access_token:
logger.warning(
"No access token stored for recording %s, skipping the Drive push",
recording.id,
)
return
try:
push_recording.delay(str(recording.id))
except Exception: # pylint: disable=broad-except
logger.exception(
"Could not schedule the Drive push of recording %s", recording.id
)
@staticmethod
def _notify_summary_service_v1(recording: models.Recording):
"""Notify summary service about a new recording."""
@@ -107,4 +107,4 @@ class RecordingEventsService:
if notification_succeeded
else models.RecordingStatusChoices.SAVED
)
recording.save()
recording.save(update_fields=["status", "updated_at"])
+181
View File
@@ -0,0 +1,181 @@
"""Client for La Suite Drive's external API (OIDC resource server).
Drive exposes `/external_api/v1.0/*` to applications holding an user's OIDC
access token.
"""
import logging
from urllib.parse import urlparse, urlunparse
from django.conf import settings
import requests
logger = logging.getLogger(__name__)
# (connect, read) timeouts, in seconds. The upload one covers a
# whole recording being relayed to Drive's object storage.
API_TIMEOUT = (10, 30)
UPLOAD_TIMEOUT = (10, 1800)
class DriveError(Exception):
"""Raised when Drive's external API cannot fulfill a request."""
class SizedStream:
"""Read-only byte stream of a known size, suitable as a `requests` body.
`requests` falls back to a chunked transfer encoding when it cannot guess the
body size upfront, which presigned S3 uploads reject. Advertising the size
through `__len__` makes it send a plain `Content-Length` instead, while the
underlying stream is still consumed chunk by chunk.
"""
def __init__(self, stream, length: int):
"""Wrap `stream`, whose full content is `length` bytes long."""
self._stream = stream
self._length = length
def __len__(self) -> int:
"""Return the total size of the stream, in bytes."""
return self._length
def __iter__(self):
"""Iterate over the stream, required for `requests` to stream the body."""
return iter(self._stream)
def read(self, amt=None) -> bytes:
"""Read up to `amt` bytes from the stream."""
return self._stream.read(amt)
class DriveClient:
"""Access Drive's external API on behalf of a user.
The client is bound to a single user access token: every call is performed
as that user, and Drive applies its own permissions accordingly.
"""
def __init__(self, access_token: str, *, base_url: str | None = None):
"""Prepare a session authenticated with the user's OIDC access token."""
self._base_url = (base_url or settings.DRIVE_API_BASE_URL or "").rstrip("/")
if not self._base_url:
raise DriveError(
"Drive API is not configured, set DRIVE_API_BASE_URL to enable it."
)
if not access_token:
raise DriveError("An access token is required to call Drive.")
self._session = requests.Session()
self._session.headers.update(
{
"Authorization": f"Bearer {access_token}",
"Content-Type": "application/json",
}
)
def __enter__(self):
"""Allow use as a context manager, closing the session on exit."""
return self
def __exit__(self, *args):
"""Close the underlying HTTP session."""
self.close()
def close(self):
"""Release the underlying HTTP session."""
self._session.close()
def _request(self, method, path, **kwargs):
"""Perform an authenticated call to the external API and return its body."""
url = f"{self._base_url}{path}"
kwargs.setdefault("timeout", API_TIMEOUT)
try:
response = self._session.request(method, url, **kwargs)
response.raise_for_status()
except requests.RequestException as exc:
raise DriveError(f"Drive call failed: {method} {url}") from exc
if not response.content:
return None
try:
return response.json()
except ValueError as exc:
raise DriveError(f"Drive returned a non-JSON body for {url}") from exc
def create_file(self, *, filename: str) -> dict:
"""Create a file item at the root of the user's Drive and return it.
The returned item carries a `policy`: the presigned URL the content has
to be uploaded to.
"""
item = self._request(
"POST",
"/items/",
json={"type": "file", "filename": filename},
)
if not item or not item.get("policy"):
raise DriveError(
f"Drive did not return an upload policy for file '{filename}'."
)
return item
@staticmethod
def _resolve_upload_target(policy_url: str) -> tuple[str, str | None]:
"""Return the address to connect to, and the `Host` header to send.
Drive signs its upload URLs with the object storage domain meant for
browsers, which may not resolve from dev split docker compose setup.
The signature covers the `Host` header, so we swap the address we connect
to but keep announcing the original host.
"""
override = settings.DRIVE_UPLOAD_STORAGE_NETLOC
if not override:
return policy_url, None
parsed = urlparse(policy_url)
return urlunparse(parsed._replace(netloc=override)), parsed.netloc
def upload_content(self, *, policy_url: str, stream, content_length, content_type):
"""Push `stream` to the presigned URL, without buffering it as a whole."""
url, host_header = self._resolve_upload_target(policy_url)
headers = {
"Content-Type": content_type,
"Content-Length": str(content_length),
"x-amz-acl": "private",
}
if host_header:
headers["Host"] = host_header
try:
# A bare `requests.put`, not the authenticated session: the presigned
# URL carries its own credentials
response = requests.put(
url,
data=SizedStream(stream, content_length),
headers=headers,
timeout=UPLOAD_TIMEOUT,
)
response.raise_for_status()
except requests.RequestException as exc:
raise DriveError("Upload to Drive's object storage failed.") from exc
def complete_upload(self, item_id: str) -> None:
"""Inform Drive that the upload is over, making the file available."""
self._request("POST", f"/items/{item_id}/upload-ended/", json={})
+11
View File
@@ -0,0 +1,11 @@
"""Asynchronous tasks of the core application.
Importing the task modules here is what makes Celery's `autodiscover_tasks`
register them: it only imports the `core.tasks` package itself, never its
submodules.
"""
from core.tasks.file import process_file_deletion
from core.tasks.push_recording import push_recording
__all__ = ["process_file_deletion", "push_recording"]
+8
View File
@@ -1,4 +1,12 @@
"""
Celery task decorator that degrades to a synchronous call when Celery is off.
"""
# The Celery app is imported lazily so that importing this module does not pull
# in Celery when CELERY_ENABLED is false.
# ruff: noqa: PLC0415
# pylint: disable=import-outside-toplevel
from django.conf import settings
+110
View File
@@ -0,0 +1,110 @@
"""Task pushing a finished recording to its owner's Drive."""
import logging
from django.conf import settings
import requests
from core import models, utils
from core.services.drive import API_TIMEOUT, DriveClient, DriveError
from core.tasks._task import task
logger = logging.getLogger(__name__)
# (connect, read) timeouts for the download, in seconds. The read one has to
# accommodate a whole recording being relayed.
DOWNLOAD_TIMEOUT = (API_TIMEOUT[0], 1800)
def _build_filename(recording: models.Recording) -> str:
"""Return a filename for the Drive item."""
return (
f"{recording.room.slug}-"
f"{recording.created_at:%Y-%m-%d-%H-%M}."
f"{recording.extension}"
)
@task
def push_recording(recording_id: str) -> bool:
"""Push a recording to the Drive of the user who started it.
The recording is streamed from object storage to Drive's presigned
URL. It is NOT fully downloaded to the worker's disk or memory.
The access token stored when the recording started is consumed here and
dropped afterwards whatever the outcome.
Mostly taken from: https://github.com/suitenumerique/drive/blob/main/docs/resource_server.md
"""
try:
recording = models.Recording.objects.select_related("room").get(pk=recording_id)
except models.Recording.DoesNotExist:
logger.error(
"Recording %s does not exist, cannot push it to Drive", recording_id
)
return False
access_token = recording.get_owner_access_token()
if not access_token:
logger.error(
"No access token stored for recording %s, cannot push it to Drive. "
"Was OIDC_STORE_ACCESS_TOKEN enabled when the recording started?",
recording_id,
)
return False
download_url = utils.generate_download_s3_url(
recording.key,
expires_in=settings.RECORDING_PUSH_TO_DRIVE_SIGNED_URL_EXPIRY_SECONDS,
override_domain=False,
)
filename = _build_filename(recording)
try:
with DriveClient(access_token) as drive:
item = drive.create_file(filename=filename)
# The bytes are relayed chunk by chunk: the recording is never held
# in memory as a whole.
with requests.get(
download_url, stream=True, timeout=DOWNLOAD_TIMEOUT
) as download:
download.raise_for_status()
content_length = download.headers.get("Content-Length")
if content_length is None:
raise DriveError(
"Object storage did not return the recording size, "
"cannot stream it to Drive."
)
drive.upload_content(
policy_url=item["policy"],
stream=download.raw,
content_length=int(content_length),
content_type=download.headers.get(
"Content-Type", "application/octet-stream"
),
)
drive.complete_upload(item["id"])
except (DriveError, requests.RequestException):
logger.exception("Failed to push recording %s to Drive", recording_id)
return False
finally:
recording.clear_owner_access_token()
logger.info(
"Recording %s pushed to Drive as '%s' (item %s)",
recording_id,
filename,
item["id"],
)
return True
@@ -117,7 +117,7 @@ def test_api_files_create_file_authenticated_success():
policy_parsed = urlparse(policy)
assert policy_parsed.scheme == "http"
assert policy_parsed.netloc in ["minio:9000", "localhost:9000"]
assert policy_parsed.netloc in ["meet-minio:9000", "minio:9000", "localhost:9000"]
assert policy_parsed.path == f"/meet-media-storage/tmp/files/{file.id!s}.png"
query_params = parse_qs(policy_parsed.query)
@@ -3,13 +3,14 @@ Test rooms API endpoints in the Meet core app: create.
"""
# pylint: disable=redefined-outer-name,unused-argument
from django.conf import settings
from django.core.cache import cache
import pytest
from rest_framework.test import APIClient
from ...factories import RoomFactory, UserFactory
from ...models import Room
from ...models import Room, RoomAccessLevel
pytestmark = pytest.mark.django_db
@@ -109,3 +110,205 @@ def test_api_rooms_create_authenticated_existing_slug():
assert response.status_code == 400
assert response.json() == {"slug": ["Room with this Slug already exists."]}
def test_api_rooms_create_authenticated_user_default_access_level():
"""
The user's default room access level should be applied to the new room
when the request does not provide one.
"""
user = UserFactory(default_room_access_level=RoomAccessLevel.RESTRICTED)
client = APIClient()
client.force_login(user)
response = client.post(
"/api/v1.0/rooms/",
{
"name": "my room",
},
)
assert response.status_code == 201
room = Room.objects.get()
assert room.access_level == RoomAccessLevel.RESTRICTED
def test_api_rooms_create_authenticated_explicit_access_level_overrides_default():
"""
An access level explicitly provided in the request should take precedence
over the user's default room access level.
"""
user = UserFactory(default_room_access_level=RoomAccessLevel.RESTRICTED)
client = APIClient()
client.force_login(user)
response = client.post(
"/api/v1.0/rooms/",
{
"name": "my room",
"access_level": RoomAccessLevel.TRUSTED,
},
)
assert response.status_code == 201
room = Room.objects.get()
assert room.access_level == RoomAccessLevel.TRUSTED
def test_api_rooms_create_authenticated_no_user_default_access_level():
"""
When the user has no default room access level, the instance default
should be applied to the new room.
"""
user = UserFactory(default_room_access_level=None)
client = APIClient()
client.force_login(user)
response = client.post(
"/api/v1.0/rooms/",
{
"name": "my room",
},
)
assert response.status_code == 201
room = Room.objects.get()
assert room.access_level == settings.RESOURCE_DEFAULT_ACCESS_LEVEL
def test_api_rooms_create_authenticated_user_default_configuration():
"""
The user's default room configuration should be applied to the new room
when the request does not provide one.
"""
user = UserFactory(default_room_configuration={"everyone_can_mute": False})
client = APIClient()
client.force_login(user)
response = client.post(
"/api/v1.0/rooms/",
{
"name": "my room",
},
)
assert response.status_code == 201
room = Room.objects.get()
assert room.configuration == {"everyone_can_mute": False}
def test_api_rooms_create_authenticated_explicit_configuration_overrides_default():
"""
A configuration explicitly provided in the request should take precedence
over the user's default room configuration.
"""
user = UserFactory(default_room_configuration={"everyone_can_mute": False})
client = APIClient()
client.force_login(user)
response = client.post(
"/api/v1.0/rooms/",
{
"name": "my room",
"configuration": {"can_publish_sources": ["camera", "microphone"]},
},
format="json",
)
assert response.status_code == 201
room = Room.objects.get()
assert room.configuration == {"can_publish_sources": ["camera", "microphone"]}
def test_api_rooms_create_authenticated_empty_configuration_falls_back_to_default():
"""
An empty configuration in the request should not be considered an explicit
value: the user's default room configuration should still be applied.
"""
user = UserFactory(default_room_configuration={"everyone_can_mute": True})
client = APIClient()
client.force_login(user)
response = client.post(
"/api/v1.0/rooms/",
{
"name": "my room",
"configuration": {},
},
format="json",
)
assert response.status_code == 201
room = Room.objects.get()
assert room.configuration == {"everyone_can_mute": True}
def test_api_rooms_create_authenticated_empty_user_default_configuration():
"""
When the user's default room configuration is empty, the new room should
keep its default empty configuration.
"""
user = UserFactory(default_room_configuration={})
client = APIClient()
client.force_login(user)
response = client.post(
"/api/v1.0/rooms/",
{
"name": "my room",
},
)
assert response.status_code == 201
room = Room.objects.get()
assert room.configuration == {}
def test_api_rooms_create_authenticated_request_precedence_over_user_empty():
"""
When the user's default room configuration is empty, the request should take precedence.
"""
user = UserFactory(default_room_configuration={})
client = APIClient()
client.force_login(user)
response = client.post(
"/api/v1.0/rooms/",
{"name": "my room", "configuration": {"everyone_can_mute": True}},
format="json",
)
assert response.status_code == 201
room = Room.objects.get()
assert room.configuration == {"everyone_can_mute": True}
def test_api_rooms_create_authenticated_blank_user_default_access_level():
"""
A blank default room access level (stored as an empty string) should be
treated as unset: the instance default should be applied to the new room
instead of persisting an invalid empty access level.
"""
user = UserFactory(default_room_access_level="")
client = APIClient()
client.force_login(user)
response = client.post(
"/api/v1.0/rooms/",
{
"name": "my room",
},
)
assert response.status_code == 201
room = Room.objects.get()
assert room.access_level == settings.RESOURCE_DEFAULT_ACCESS_LEVEL
@@ -453,6 +453,8 @@ def test_api_rooms_retrieve_administrators(
{
"id": str(other_user_access.id),
"user": {
"default_room_access_level": None,
"default_room_configuration": {},
"id": str(other_user_access.user.id),
"email": other_user_access.user.email,
"full_name": other_user_access.user.full_name,
@@ -466,6 +468,8 @@ def test_api_rooms_retrieve_administrators(
{
"id": str(user_access.id),
"user": {
"default_room_access_level": None,
"default_room_configuration": {},
"id": str(user_access.user.id),
"email": user_access.user.email,
"full_name": user_access.user.full_name,
+2
View File
@@ -119,6 +119,8 @@ def test_api_users_retrieve_me_authenticated(settings):
assert response.status_code == 200
assert response.json() == {
"default_room_access_level": None,
"default_room_configuration": {},
"id": str(user.id),
"email": user.email,
"full_name": user.full_name,
@@ -0,0 +1,111 @@
"""
Test the default room preferences exposed on the users API.
"""
import pytest
from rest_framework.test import APIClient
from core import factories
pytestmark = pytest.mark.django_db
def test_api_users_me_includes_default_room_preferences():
"""The "me" endpoint should expose the user's default room preferences."""
user = factories.UserFactory(
default_room_access_level="restricted",
default_room_configuration={"everyone_can_mute": False},
)
client = APIClient()
client.force_login(user)
response = client.get("/api/v1.0/users/me/")
assert response.status_code == 200
content = response.json()
assert content["default_room_access_level"] == "restricted"
assert content["default_room_configuration"] == {"everyone_can_mute": False}
def test_api_users_update_default_room_preferences():
"""Users should be able to update their own default room preferences."""
user = factories.UserFactory()
client = APIClient()
client.force_login(user)
response = client.patch(
f"/api/v1.0/users/{user.id!s}/",
{
"default_room_access_level": "trusted",
"default_room_configuration": {
"can_publish_sources": ["microphone", "camera"],
"everyone_can_mute": False,
},
},
format="json",
)
assert response.status_code == 200
user.refresh_from_db()
assert user.default_room_access_level == "trusted"
assert user.default_room_configuration == {
"can_publish_sources": ["microphone", "camera"],
"everyone_can_mute": False,
}
def test_api_users_update_default_room_access_level_invalid():
"""An invalid access level should be rejected."""
user = factories.UserFactory()
client = APIClient()
client.force_login(user)
response = client.patch(
f"/api/v1.0/users/{user.id!s}/",
{"default_room_access_level": "invalid"},
format="json",
)
assert response.status_code == 400
user.refresh_from_db()
assert user.default_room_access_level is None
def test_api_users_update_default_room_configuration_invalid():
"""An invalid room configuration should be rejected."""
user = factories.UserFactory()
client = APIClient()
client.force_login(user)
response = client.patch(
f"/api/v1.0/users/{user.id!s}/",
{"default_room_configuration": {"unknown_field": True}},
format="json",
)
assert response.status_code == 400
user.refresh_from_db()
assert user.default_room_configuration == {}
def test_api_users_update_other_user_default_room_preferences_forbidden():
"""Users should not be able to update someone else's preferences."""
user = factories.UserFactory()
other_user = factories.UserFactory()
client = APIClient()
client.force_login(user)
response = client.patch(
f"/api/v1.0/users/{other_user.id!s}/",
{"default_room_access_level": "restricted"},
format="json",
)
assert response.status_code == 403
other_user.refresh_from_db()
assert other_user.default_room_access_level is None
+38
View File
@@ -17,6 +17,7 @@ from typing import List, Optional
from uuid import uuid4
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.files.storage import default_storage
import aiohttp
@@ -25,6 +26,7 @@ import botocore
import magic
import phonenumbers
from asgiref.sync import async_to_sync
from cryptography.fernet import Fernet, InvalidToken
from livekit.api import ( # pylint: disable=E0611
AccessToken,
ListRoomsRequest,
@@ -417,6 +419,42 @@ def generate_upload_policy(file):
return policy
class SecretDecryptionError(Exception):
"""Raised when a stored secret cannot be decrypted."""
@lru_cache(maxsize=1)
def get_cipher_suite():
"""Return the Fernet key used to encrypt secrets at rest.
The same key as django-lasuite's OIDC token storage.
"""
key = settings.OIDC_STORE_REFRESH_TOKEN_KEY
if not key:
raise ImproperlyConfigured("OIDC_STORE_REFRESH_TOKEN_KEY setting is required.")
return Fernet(key)
def encrypt_secret(value: str) -> str:
"""Encrypt a secret meant to be stored at rest."""
return get_cipher_suite().encrypt(value.encode()).decode()
def decrypt_secret(value: str) -> str:
"""Decrypt a secret stored by `encrypt_secret`."""
try:
return get_cipher_suite().decrypt(value.encode()).decode()
except InvalidToken as exc:
raise SecretDecryptionError(
"The stored secret could not be decrypted."
) from exc
def generate_download_s3_url(
key: str, *, expires_in: int, override_domain: bool = True
):
+37
View File
@@ -573,6 +573,20 @@ class Base(Configuration):
OIDC_STORE_ID_TOKEN = values.BooleanValue(
default=True, environ_name="OIDC_STORE_ID_TOKEN", environ_prefix=None
)
# Required to call other La Suite applications on behalf of the user, e.g.
# to push a recording to their Drive.
OIDC_STORE_ACCESS_TOKEN = values.BooleanValue(
default=False, environ_name="OIDC_STORE_ACCESS_TOKEN", environ_prefix=None
)
OIDC_STORE_REFRESH_TOKEN = values.BooleanValue(
default=False, environ_name="OIDC_STORE_REFRESH_TOKEN", environ_prefix=None
)
# Fernet key used to encrypt OIDC tokens at rest, both the refresh token
# django-lasuite stores in the session and the access token stored on a
# recording. Generate one with `Fernet.generate_key()`.
OIDC_STORE_REFRESH_TOKEN_KEY = SecretFileValue(
None, environ_name="OIDC_STORE_REFRESH_TOKEN_KEY", environ_prefix=None
)
ALLOW_LOGOUT_GET_METHOD = values.BooleanValue(
default=True, environ_name="ALLOW_LOGOUT_GET_METHOD", environ_prefix=None
)
@@ -725,6 +739,29 @@ class Base(Configuration):
None, environ_name="RECORDING_MAX_DURATION", environ_prefix=None
)
# Push recordings to Drive
# Once a recording is over, it is pushed to the user's
# started it, using their OIDC access token. It requires OIDC_STORE_ACCESS_TOKEN,
# and Drive to be configured as an OIDC resource server accepting Meet's audience.
RECORDING_PUSH_TO_DRIVE_ENABLED = values.BooleanValue(
False, environ_name="RECORDING_PUSH_TO_DRIVE_ENABLED", environ_prefix=None
)
# Base URL of Drive's external API, e.g. https://fichiers.numerique.gouv.fr/external_api/v1.0
DRIVE_API_BASE_URL = values.Value(
None, environ_name="DRIVE_API_BASE_URL", environ_prefix=None
)
# Lifetime of the signed URL the worker downloads the recording from.
RECORDING_PUSH_TO_DRIVE_SIGNED_URL_EXPIRY_SECONDS = values.PositiveIntegerValue(
60 * 60,
environ_name="RECORDING_PUSH_TO_DRIVE_SIGNED_URL_EXPIRY_SECONDS",
environ_prefix=None,
)
# Development only: host:port to reach Drive's object storage at, when the
# domain Drive signs its upload URLs with is only resolvable from a browser.
DRIVE_UPLOAD_STORAGE_NETLOC = values.Value(
None, environ_name="DRIVE_UPLOAD_STORAGE_NETLOC", environ_prefix=None
)
# Recording encoding options for LiveKit Egress (video composite egress only).
# These settings affect screen recordings handled by VideoCompositeEgressService;
# they are silently ignored by AudioCompositeEgressService (audio-only transcript
+4
View File
@@ -2,6 +2,7 @@ import { fetchApi } from './fetchApi'
import { keys } from './queryKeys'
import { useQuery } from '@tanstack/react-query'
import { RecordingMode } from '@/features/recording'
import type { ApiAccessLevel } from '@/features/rooms/api/ApiRoom'
import type { Track } from 'livekit-client'
type Source = Track.Source
@@ -49,6 +50,9 @@ export interface ApiConfig {
international_phone_number?: string
default_country?: string
}
resource?: {
default_access_level?: ApiAccessLevel
}
manifest_link?: string
livekit: {
url: string
@@ -1,4 +1,8 @@
import { BackendLanguage } from '@/utils/languages'
import type {
ApiAccessLevel,
RoomConfiguration,
} from '@/features/rooms/api/ApiRoom'
export type ApiUser = {
id: string
@@ -7,4 +11,6 @@ export type ApiUser = {
last_name: string
language: BackendLanguage
timezone: string
default_room_access_level?: ApiAccessLevel | null
default_room_configuration?: RoomConfiguration | null
}
@@ -0,0 +1,36 @@
import { useMutation, type UseMutationOptions } from '@tanstack/react-query'
import { fetchApi } from '@/api/fetchApi'
import type { ApiError } from '@/api/ApiError'
import { type ApiUser } from './ApiUser'
export type PatchUserParams = {
userId: string
user: Partial<
Pick<
ApiUser,
| 'timezone'
| 'language'
| 'default_room_access_level'
| 'default_room_configuration'
>
>
}
export const patchUser = ({ userId, user }: PatchUserParams) => {
return fetchApi<ApiUser>(`/users/${userId}/`, {
method: 'PATCH',
body: JSON.stringify(user),
})
}
export const patchUserMutationKey = ['patchUser']
export function usePatchUser(
options?: UseMutationOptions<ApiUser, ApiError, PatchUserParams>
) {
return useMutation<ApiUser, ApiError, PatchUserParams>({
mutationKey: patchUserMutationKey,
mutationFn: patchUser,
...options,
})
}
@@ -0,0 +1,42 @@
import { useLocalParticipant } from '@livekit/components-react'
import { useEffect } from 'react'
export const MEDIA_STATE_ELEMENT_ID = 'media-state'
export const MEDIA_STATE_CHANGED_EVENT = 'media-state-changed'
export type MediaStateChangedDetail = {
microphoneEnabled: boolean
cameraEnabled: boolean
}
/**
* Exposes the local participant's media state in the DOM so external tools
* (e.g. bots automating the frontend) can reliably read the microphone and
* camera state, and watch for changes with a MutationObserver:
*
* const el = document.getElementById('media-state')
* new MutationObserver(...).observe(el, { attributes: true })
*/
export const MediaStateObserver = () => {
const { isMicrophoneEnabled, isCameraEnabled } = useLocalParticipant()
useEffect(() => {
window.dispatchEvent(
new CustomEvent<MediaStateChangedDetail>(MEDIA_STATE_CHANGED_EVENT, {
detail: {
microphoneEnabled: isMicrophoneEnabled,
cameraEnabled: isCameraEnabled,
},
})
)
}, [isMicrophoneEnabled, isCameraEnabled])
return (
<div
id={MEDIA_STATE_ELEMENT_ID}
style={{ display: 'none' }}
data-microphone-enabled={isMicrophoneEnabled ? 'true' : 'false'}
data-camera-enabled={isCameraEnabled ? 'true' : 'false'}
/>
)
}
@@ -11,6 +11,7 @@ import { SidePanel } from '../components/SidePanel'
import { RecordingProvider } from '@/features/recording'
import { ScreenShareErrorModal } from '../components/ScreenShareErrorModal'
import { ConnectionObserver } from '../components/ConnectionObserver'
import { MediaStateObserver } from '../components/MediaStateObserver'
import { RoomMetadataSynchronizer } from '../components/RoomMetadataSynchronizer'
import { useRoomPageTitle } from '../hooks/useRoomPageTitle'
import { useNoiseReduction } from '../hooks/useNoiseReduction'
@@ -63,6 +64,7 @@ export function VideoConference({ ...props }: VideoConferenceProps) {
<>
<RoomMetadataSynchronizer />
<ConnectionObserver />
<MediaStateObserver />
<ChatProvider />
<VideoResolutionSubscription />
<div
@@ -2,9 +2,12 @@ export class CallbackIdHandler {
private readonly storageKey = 'popup_callback_id'
private generateId(): string {
return (
Math.random().toString(36).substring(2, 15) +
Math.random().toString(36).substring(2, 15)
// The id is the only thing guarding /rooms/creation-callback/, which is
// unauthenticated, so it comes from the CSPRNG rather than Math.random.
const bytes = new Uint8Array(16)
crypto.getRandomValues(bytes)
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join(
''
)
}
@@ -1,22 +1,79 @@
import { Trans, useTranslation } from 'react-i18next'
import { useRef } from 'react'
import { Heading } from 'react-aria-components'
import { RiSettings3Line, RiDoorOpenLine } from '@remixicon/react'
import { useLanguageLabels } from '@/i18n/useLanguageLabels'
import { A, Badge, Dialog, type DialogProps, Field, H, P } from '@/primitives'
import { Tab, TabList, TabPanel, Tabs } from '@/primitives/Tabs'
import { text } from '@/primitives/Text.tsx'
import { css } from '@/styled-system/css'
import { useUser } from '@/features/auth/api/useUser'
import { LoginButton } from '@/components/LoginButton'
import { logout } from '@/features/auth/utils/logout'
import { useMediaQuery } from '@/features/rooms/livekit/hooks/useMediaQuery'
import { RoomsTab } from './tabs/RoomsTab'
export type SettingsDialogProps = Pick<DialogProps, 'isOpen' | 'onOpenChange'>
enum SettingsDialogTabKey {
GENERAL = 'general',
ROOMS = 'rooms',
}
const tabsStyle = css({
maxHeight: '40.625rem', // fixme size copied from meet settings modal
width: '50rem', // fixme size copied from meet settings modal
marginY: '-1rem', // fixme hacky solution to cancel modal padding
maxWidth: '100%',
overflow: 'hidden',
height: 'calc(100vh - 2rem)',
})
const tabListContainerStyle = css({
display: 'flex',
flexDirection: 'column',
borderRight: '1px solid lightGray', // fixme poor color management
paddingY: '1rem',
paddingLeft: '0.2rem',
paddingRight: '1.5rem',
})
const tabPanelContainerStyle = css({
display: 'flex',
flexGrow: '1',
marginTop: '3.5rem',
minWidth: 0,
})
const tabPanelStyle = css({
flexGrow: '1',
minWidth: 0,
overflowY: 'auto',
paddingRight: '1.5rem',
paddingBottom: '1rem',
})
export const SettingsDialog = (props: SettingsDialogProps) => {
const { t, i18n } = useTranslation('settings')
const { user, isLoggedIn } = useUser()
const { languagesList, currentLanguage } = useLanguageLabels()
const dialogEl = useRef<HTMLDivElement>(null)
const isWideScreen = useMediaQuery('(min-width: 800px)') // fixme - hardcoded 50rem in pixel
const userDisplay =
user?.full_name && user?.email
? `${user.full_name} (${user.email})`
: user?.email
return (
<Dialog title={t('dialog.heading')} {...props}>
const generalContent = (
<div
className={css({
display: 'flex',
flexDirection: 'column',
minWidth: '360px',
})}
>
<H lvl={2}>{t('account.heading')}</H>
{isLoggedIn ? (
<>
@@ -47,6 +104,56 @@ export const SettingsDialog = (props: SettingsDialogProps) => {
i18n.changeLanguage(lang as string)
}}
/>
</div>
)
// Without tabs there is no rail to host the heading, so keep the plain dialog.
if (!isLoggedIn) {
return (
<Dialog title={t('dialog.heading')} {...props} role="dialog" type="flex">
{generalContent}
</Dialog>
)
}
return (
<Dialog innerRef={dialogEl} {...props} role="dialog" type="flex">
<Tabs
orientation="vertical"
className={tabsStyle}
defaultSelectedKey={SettingsDialogTabKey.GENERAL}
>
<div
className={tabListContainerStyle}
style={{
flex: isWideScreen ? '0 0 16rem' : undefined,
paddingTop: !isWideScreen ? '64px' : undefined,
paddingRight: !isWideScreen ? '1rem' : undefined,
}}
>
{isWideScreen && (
<Heading slot="title" level={1} className={text({ variant: 'h1' })}>
{t('dialog.heading')}
</Heading>
)}
<TabList border={false}>
<Tab icon highlight id={SettingsDialogTabKey.GENERAL}>
<RiSettings3Line />
{isWideScreen && t(`tabs.${SettingsDialogTabKey.GENERAL}`)}
</Tab>
<Tab icon highlight id={SettingsDialogTabKey.ROOMS}>
<RiDoorOpenLine />
{isWideScreen && t(`tabs.${SettingsDialogTabKey.ROOMS}`)}
</Tab>
</TabList>
</div>
<div className={tabPanelContainerStyle}>
<TabPanel id={SettingsDialogTabKey.GENERAL} className={tabPanelStyle}>
{generalContent}
</TabPanel>
<RoomsTab id={SettingsDialogTabKey.ROOMS} />
</div>
</Tabs>
</Dialog>
)
}
@@ -0,0 +1,226 @@
import { useTranslation } from 'react-i18next'
import { useUser } from '@/features/auth/api/useUser'
import { useConfig } from '@/api/useConfig'
import {
usePatchUser,
patchUserMutationKey,
} from '@/features/auth/api/patchUser'
import { type ApiUser } from '@/features/auth/api/ApiUser'
import { ApiAccessLevel, RoomConfiguration } from '@/features/rooms/api/ApiRoom'
import { useMemo } from 'react'
import { queryClient } from '@/api/queryClient'
import { keys } from '@/api/queryKeys'
import { Track } from 'livekit-client'
import Source = Track.Source
import { isSubsetOf } from '@/features/rooms/utils/isSubsetOf'
import { updatePublishSources } from '@/features/rooms/livekit/hooks/usePublishSourcesManager'
import { Field, H, Text } from '@/primitives'
import { TabPanel } from '@/primitives/Tabs'
import { css } from '@/styled-system/css'
import { Separator as RACSeparator } from 'react-aria-components'
type RoomsTabProps = {
id: string
}
export const RoomsTab = ({ id }: RoomsTabProps) => {
const { t } = useTranslation('settings', { keyPrefix: 'roomDefaults' })
const { t: tAdmin } = useTranslation('rooms', {
keyPrefix: 'admin',
useSuspense: false,
})
const { user } = useUser()
const { data: configData } = useConfig()
// Optimistic updates: patch the cache immediately so the UI updates
// instantly and concurrent saves always build on the latest local state.
// Since each PATCH replaces the full JSON config, this avoids overwriting
// earlier changes with a stale snapshot.
//
// No per-request rollback: later requests already include earlier changes.
// Once the last in-flight save completes, re-fetch the server state once to
// restore the UI if all saves failed.
const { mutate: patchUser } = usePatchUser({
onMutate: async ({ user: partialUser }) => {
await queryClient.cancelQueries({ queryKey: [keys.user] })
queryClient.setQueryData<ApiUser | false>([keys.user], (previous) =>
previous ? { ...previous, ...partialUser } : previous
)
},
onSettled: () => {
if (queryClient.isMutating({ mutationKey: patchUserMutationKey }) === 1) {
queryClient.invalidateQueries({ queryKey: [keys.user] })
}
},
})
const configuration: RoomConfiguration = useMemo(
() => user?.default_room_configuration ?? {},
[user?.default_room_configuration]
)
const currentSources: Source[] = useMemo(() => {
const defaultSources = configData?.livekit?.default_sources ?? []
if (!Array.isArray(configuration?.can_publish_sources)) {
return defaultSources
}
return configuration.can_publish_sources
}, [configData, configuration])
const accessLevel =
user?.default_room_access_level ??
configData?.resource?.default_access_level ??
ApiAccessLevel.PUBLIC
// Every change saves immediately; the optimistic onMutate above keeps the
// cached user (and therefore `configuration`) in sync right away.
const saveConfiguration = (newConfiguration: RoomConfiguration) => {
if (!user) return
patchUser({
userId: user.id,
user: { default_room_configuration: newConfiguration },
})
}
const updateSource = (sources: Source[], enabled: boolean) =>
saveConfiguration({
...configuration,
can_publish_sources: updatePublishSources(
currentSources,
sources,
enabled
),
})
const isMicrophoneEnabled = isSubsetOf([Source.Microphone], currentSources)
const isCameraEnabled = isSubsetOf([Source.Camera], currentSources)
const isScreenShareEnabled = isSubsetOf(
[Source.ScreenShare, Source.ScreenShareAudio],
currentSources
)
const isMutingEnabled = configuration?.everyone_can_mute ?? true
const saveAccessLevel = (newAccessLevel: ApiAccessLevel) => {
if (!user) return
patchUser({
userId: user.id,
user: { default_room_access_level: newAccessLevel },
})
}
return (
<TabPanel padding={'md'} flex id={id}>
<H lvl={2}>{t('heading')}</H>
<Text variant="note" margin={'md'}>
{t('description')}
</Text>
<RACSeparator
className={css({
border: 'none',
height: '1px',
width: '100%',
flexShrink: 0,
background: 'greyscale.250',
})}
/>
<H
lvl={3}
variant={'h2'}
className={css({
fontWeight: 500,
})}
margin="sm"
>
{tAdmin('moderation.title')}
</H>
<Text
variant="note"
wrap="balance"
className={css({
textStyle: 'sm',
})}
margin={'md'}
>
{tAdmin('moderation.description')}
</Text>
<Field
type="switch"
label={tAdmin('moderation.microphone.label')}
isSelected={isMicrophoneEnabled}
onChange={(enabled) => updateSource([Source.Microphone], enabled)}
/>
<Field
type="switch"
label={tAdmin('moderation.camera.label')}
isSelected={isCameraEnabled}
onChange={(enabled) => updateSource([Source.Camera], enabled)}
/>
<Field
type="switch"
label={tAdmin('moderation.screenshare.label')}
isSelected={isScreenShareEnabled}
onChange={(enabled) =>
updateSource([Source.ScreenShare, Source.ScreenShareAudio], enabled)
}
/>
<Field
type="switch"
label={tAdmin('moderation.mute.label')}
isSelected={isMutingEnabled}
onChange={(enabled) =>
saveConfiguration({ ...configuration, everyone_can_mute: enabled })
}
/>
<RACSeparator
className={css({
border: 'none',
height: '1px',
width: '100%',
flexShrink: 0,
marginY: '1rem',
background: 'greyscale.250',
})}
/>
<H
lvl={3}
variant={'h2'}
className={css({
fontWeight: 500,
})}
margin="sm"
>
{tAdmin('access.title')}
</H>
<Field
type="radioGroup"
label={tAdmin('access.type')}
value={accessLevel}
labelProps={{
className: css({
fontSize: '1rem',
paddingBottom: '1rem',
}),
}}
onChange={(value) => saveAccessLevel(value as ApiAccessLevel)}
items={[
{
value: ApiAccessLevel.PUBLIC,
label: tAdmin('access.levels.public.label'),
description: tAdmin('access.levels.public.description'),
},
{
value: ApiAccessLevel.TRUSTED,
label: tAdmin('access.levels.trusted.label'),
description: tAdmin('access.levels.trusted.description'),
},
{
value: ApiAccessLevel.RESTRICTED,
label: tAdmin('access.levels.restricted.label'),
description: tAdmin('access.levels.restricted.description'),
},
]}
/>
</TabPanel>
)
}
+6 -1
View File
@@ -179,6 +179,11 @@
"notifications": "Benachrichtigungen",
"accessibility": "Barrierefreiheit",
"transcription": "Transkription",
"shortcuts": "Tastenkürzel"
"shortcuts": "Tastenkürzel",
"rooms": "Räume"
},
"roomDefaults": {
"heading": "Standardeinstellungen für Räume",
"description": "Wählen Sie die Einstellungen, die standardmäßig auf neue von Ihnen erstellte Räume angewendet werden. Sie können sie für jedes Meeting weiterhin in den Moderationseinstellungen ändern."
}
}
+6 -1
View File
@@ -179,6 +179,11 @@
"notifications": "Notifications",
"accessibility": "Accessibility",
"transcription": "Transcription",
"shortcuts": "Shortcuts"
"shortcuts": "Shortcuts",
"rooms": "Rooms"
},
"roomDefaults": {
"heading": "Default room settings",
"description": "Choose the settings applied by default to the new rooms you create. You can still change them for each meeting from the host settings."
}
}
+6 -1
View File
@@ -179,6 +179,11 @@
"notifications": "Notifications",
"accessibility": "Accessibilité",
"transcription": "Transcription",
"shortcuts": "Raccourcis"
"shortcuts": "Raccourcis",
"rooms": "Réunions"
},
"roomDefaults": {
"heading": "Paramètres par défaut des réunions",
"description": "Choisissez les paramètres appliqués par défaut aux nouvelles réunions que vous créez. Vous pourrez toujours les modifier pour chaque réunion depuis les paramètres dadministration."
}
}
+6 -1
View File
@@ -179,6 +179,11 @@
"notifications": "Meldingen",
"accessibility": "Toegankelijkheid",
"transcription": "Transcriptie",
"shortcuts": "Sneltoetsen"
"shortcuts": "Sneltoetsen",
"rooms": "Vergaderingen"
},
"roomDefaults": {
"heading": "Standaardinstellingen voor vergaderingen",
"description": "Kies de instellingen die standaard worden toegepast op nieuwe vergaderingen die u aanmaakt. U kunt ze voor elke vergadering nog steeds wijzigen via de hostinstellingen."
}
}
+2 -6
View File
@@ -143,13 +143,9 @@ def test_media_info_ignores_empty_stream_entry(monkeypatch: pytest.MonkeyPatch)
def test_extract_audio_from_video():
"""Test that extract_audio_from_video can extract audio from a video file."""
path = None
path = extract_audio_from_media(MEDIA_INFO_SAMPLE_VISIO)
# A bit of cleanup logic since this is not a generator
try:
path = extract_audio_from_media(MEDIA_INFO_SAMPLE_VISIO)
assert path.name.endswith(".m4a")
except Exception as e:
pytest.fail(f"Failed to extract audio from video: {e}")
finally:
if path and path.exists():
path.unlink()
path.unlink(missing_ok=True)