Compare commits
109 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6544c895dc | |||
| 44d3c738d7 | |||
| 888c66a218 | |||
| 86641bd160 | |||
| 3d91af23cc | |||
| 2d0d30ce01 | |||
| 98ae9af84a | |||
| 3dda12ada6 | |||
| 8b2750c413 | |||
| c16c27fa50 | |||
| b3ef57e1b6 | |||
| b554a6a542 | |||
| 574fd6dc89 | |||
| 8d77332a0a | |||
| 0e2c805b41 | |||
| 9782eb8c7c | |||
| f6bc57ba91 | |||
| 4d5aec9a49 | |||
| 74b296aa37 | |||
| 88fadd1d61 | |||
| cac58f49d3 | |||
| 12c27eedac | |||
| 6a7ec95493 | |||
| e41656a760 | |||
| eb90c0f28c | |||
| f3c4b0ac40 | |||
| 038e6368e4 | |||
| 028f20375f | |||
| ccc23ff46a | |||
| e3b7a1f77b | |||
| 69a8eea1ce | |||
| 20493edd07 | |||
| 79f7fcab6e | |||
| ce3a6dab12 | |||
| 1b57dd0ecf | |||
| c6318910c2 | |||
| 03b3630611 | |||
| 5b8c8d493a | |||
| b12fb6bf48 | |||
| a8f64f5a36 | |||
| 6ab5b3300a | |||
| 6189e6454d | |||
| a8b2c56f4b | |||
| b472220151 | |||
| 223cee3828 | |||
| 101be503bf | |||
| 47e2d85471 | |||
| 16321b3cb0 | |||
| 144cb56cda | |||
| e6a15e36b4 | |||
| 3541af5992 | |||
| 68f0ea3639 | |||
| 925eb92c60 | |||
| d965ee7060 | |||
| aef85bb1ab | |||
| 8f59b08088 | |||
| 366998b3d6 | |||
| c8ad0ab24f | |||
| d2bbcb0f51 | |||
| 40457bd68a | |||
| c21c5f604b | |||
| 66350b8fb5 | |||
| 378cc3a651 | |||
| 28f43fb2c0 | |||
| 37eea16a50 | |||
| fe8ed43aae | |||
| 671aa68804 | |||
| 6449aaf7ea | |||
| f8fff3dbdf | |||
| 1715ec10dd | |||
| 8c7aed4b00 | |||
| 217b19e42a | |||
| bd26a0abc1 | |||
| abb708aa49 | |||
| 5d35161ae3 | |||
| 0b6f58bf9c | |||
| 79519fef26 | |||
| d7b1fbaf28 | |||
| 26bc67d1b4 | |||
| b783a8bac6 | |||
| e7dc54d6c5 | |||
| 9a07fba991 | |||
| ca3b1f0297 | |||
| 01390b12fb | |||
| df1eca7c34 | |||
| b529e9c848 | |||
| 23a2d3bcac | |||
| 55749a9565 | |||
| 8115a39538 | |||
| 2416ca1127 | |||
| 1971f594cf | |||
| fb0ee9e8f6 | |||
| b261f2ee5b | |||
| aa54075e6b | |||
| 271b598cee | |||
| fc232759fb | |||
| a992aa8898 | |||
| 1b8b91a44d | |||
| 63c6f5a8a1 | |||
| 1970a4d6b1 | |||
| d406f31bd8 | |||
| 4a011024dd | |||
| 59b23ad1b9 | |||
| 93be2881d2 | |||
| daa125edf3 | |||
| c93e770704 | |||
| 1f57adc4da | |||
| 952e6970f0 | |||
| af0746eac1 |
@@ -89,7 +89,7 @@ jobs:
|
||||
- name: Lint code with ruff
|
||||
run: ~/.local/bin/ruff check .
|
||||
- name: Lint code with pylint
|
||||
run: ~/.local/bin/pylint .
|
||||
run: ~/.local/bin/pylint meet demo core
|
||||
|
||||
test-back:
|
||||
runs-on: ubuntu-latest
|
||||
@@ -160,6 +160,21 @@ jobs:
|
||||
- name: Run tests
|
||||
run: ~/.local/bin/pytest -n 2
|
||||
|
||||
lint-front:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Install dependencies
|
||||
run: cd src/frontend/ && npm ci
|
||||
|
||||
- name: Check linting
|
||||
run: cd src/frontend/ && npm run lint
|
||||
|
||||
- name: Check format
|
||||
run: cd src/frontend/ && npm run check
|
||||
|
||||
i18n-crowdin:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
|
||||
@@ -48,7 +48,7 @@ WAIT_DB = @$(COMPOSE_RUN) dockerize -wait tcp://$(DB_HOST):$(DB_PORT
|
||||
|
||||
# -- Backend
|
||||
MANAGE = $(COMPOSE_RUN_APP) python manage.py
|
||||
MAIL_YARN = $(COMPOSE_RUN) -w /app/src/mail node yarn # FIXME : use npm
|
||||
MAIL_NPM = $(COMPOSE_RUN) -w /app/src/mail node npm
|
||||
|
||||
# -- Frontend
|
||||
PATH_FRONT = ./src/frontend
|
||||
@@ -141,7 +141,7 @@ lint-ruff-check: ## lint back-end python sources with ruff
|
||||
|
||||
lint-pylint: ## lint back-end python sources with pylint only on changed files from main
|
||||
@echo 'lint:pylint started…'
|
||||
bin/pylint --diff-only=origin/main
|
||||
@$(COMPOSE_RUN_APP) pylint meet demo core
|
||||
.PHONY: lint-pylint
|
||||
|
||||
test: ## run project tests
|
||||
@@ -259,19 +259,19 @@ i18n-generate-and-upload: \
|
||||
# -- Mail generator
|
||||
|
||||
mails-build: ## Convert mjml files to html and text
|
||||
@$(MAIL_YARN) build
|
||||
@$(MAIL_NPM) run build
|
||||
.PHONY: mails-build
|
||||
|
||||
mails-build-html-to-plain-text: ## Convert html files to text
|
||||
@$(MAIL_YARN) build-html-to-plain-text
|
||||
@$(MAIL_NPM) run build-html-to-plain-text
|
||||
.PHONY: mails-build-html-to-plain-text
|
||||
|
||||
mails-build-mjml-to-html: ## Convert mjml files to html and text
|
||||
@$(MAIL_YARN) build-mjml-to-html
|
||||
@$(MAIL_NPM) run build-mjml-to-html
|
||||
.PHONY: mails-build-mjml-to-html
|
||||
|
||||
mails-install: ## install the mail generator
|
||||
@$(MAIL_YARN) install
|
||||
@$(MAIL_NPM) install
|
||||
.PHONY: mails-install
|
||||
|
||||
|
||||
|
||||
@@ -5,7 +5,6 @@ set -eo pipefail
|
||||
REPO_DIR="$(cd "$( dirname "${BASH_SOURCE[0]}" )/.." && pwd)"
|
||||
UNSET_USER=0
|
||||
|
||||
TERRAFORM_DIRECTORY="./env.d/terraform"
|
||||
COMPOSE_FILE="${REPO_DIR}/docker-compose.yml"
|
||||
COMPOSE_PROJECT="meet"
|
||||
|
||||
@@ -92,66 +91,3 @@ function _dc_exec() {
|
||||
function _django_manage() {
|
||||
_dc_run "app-dev" python manage.py "$@"
|
||||
}
|
||||
|
||||
# _set_openstack_project: select an OpenStack project from the openrc files defined in the
|
||||
# terraform directory.
|
||||
#
|
||||
# usage: _set_openstack_project
|
||||
#
|
||||
# If necessary the script will prompt the user to choose a project from those available
|
||||
function _set_openstack_project() {
|
||||
|
||||
declare prompt
|
||||
declare -a projects
|
||||
declare -i default=1
|
||||
declare -i choice=0
|
||||
declare -i n_projects
|
||||
|
||||
# List projects by looking in the "./env.d/terraform" directory
|
||||
# and store them in an array
|
||||
read -r -a projects <<< "$(
|
||||
find "${TERRAFORM_DIRECTORY}" -maxdepth 1 -mindepth 1 -type d |
|
||||
sed 's|'"${TERRAFORM_DIRECTORY}\/"'||' |
|
||||
xargs
|
||||
)"
|
||||
nb_projects=${#projects[@]}
|
||||
|
||||
if [[ ${nb_projects} -le 0 ]]; then
|
||||
echo "There are no OpenStack projects defined..." >&2
|
||||
echo "To add one, create a subdirectory in \"${TERRAFORM_DIRECTORY}\" with the name" \
|
||||
"of your project and copy your \"openrc.sh\" file into it." >&2
|
||||
exit 10
|
||||
fi
|
||||
|
||||
if [[ ${nb_projects} -gt 1 ]]; then
|
||||
prompt="Select an OpenStack project to target:\\n"
|
||||
for (( i=0; i<nb_projects; i++ )); do
|
||||
prompt+="[$((i+1))] ${projects[$i]}"
|
||||
if [[ $((i+1)) -eq ${default} ]]; then
|
||||
prompt+=" (default)"
|
||||
fi
|
||||
prompt+="\\n"
|
||||
done
|
||||
prompt+="If your OpenStack project is not listed, add it to the \"env.d/terraform\" directory.\\n"
|
||||
prompt+="Your choice: "
|
||||
read -r -p "$(echo -e "${prompt}")" choice
|
||||
|
||||
if [[ ${choice} -gt nb_projects ]]; then
|
||||
(>&2 echo "Invalid choice ${choice} (should be <= ${nb_projects})")
|
||||
exit 11
|
||||
fi
|
||||
|
||||
if [[ ${choice} -le 0 ]]; then
|
||||
choice=${default}
|
||||
fi
|
||||
fi
|
||||
|
||||
project=${projects[$((choice-1))]}
|
||||
# Check that the openrc.sh file exists for this project
|
||||
if [ ! -f "${TERRAFORM_DIRECTORY}/${project}/openrc.sh" ]; then
|
||||
(>&2 echo "Missing \"openrc.sh\" file in \"${TERRAFORM_DIRECTORY}/${project}\". Check documentation.")
|
||||
exit 12
|
||||
fi
|
||||
|
||||
echo "${project}"
|
||||
}
|
||||
|
||||
-38
@@ -1,38 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
# shellcheck source=bin/_config.sh
|
||||
source "$(dirname "${BASH_SOURCE[0]}")/_config.sh"
|
||||
|
||||
declare diff_from
|
||||
declare -a paths
|
||||
declare -a args
|
||||
|
||||
# Parse options
|
||||
for arg in "$@"
|
||||
do
|
||||
case $arg in
|
||||
--diff-only=*)
|
||||
diff_from="${arg#*=}"
|
||||
shift
|
||||
;;
|
||||
-*)
|
||||
args+=("$arg")
|
||||
shift
|
||||
;;
|
||||
*)
|
||||
paths+=("$arg")
|
||||
shift
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
if [[ -n "${diff_from}" ]]; then
|
||||
# Run pylint only on modified files located in src/backend
|
||||
# (excluding deleted files and migration files)
|
||||
# shellcheck disable=SC2207
|
||||
paths=($(git diff "${diff_from}" --name-only --diff-filter=d -- src/backend ':!**/migrations/*.py' | grep -E '^src/backend/.*\.py$'))
|
||||
fi
|
||||
|
||||
# Fix docker vs local path when project sources are mounted as a volume
|
||||
read -ra paths <<< "$(echo "${paths[@]}" | sed "s|src/backend/||g")"
|
||||
_dc_run app-dev pylint "${paths[@]}" "${args[@]}"
|
||||
@@ -1,25 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
set -eo pipefail
|
||||
|
||||
source "$(dirname "${BASH_SOURCE[0]}")/_config.sh"
|
||||
|
||||
project=$(_set_openstack_project)
|
||||
echo "Using \"${project}\" project..."
|
||||
|
||||
source "${TERRAFORM_DIRECTORY}/${project}/openrc.sh"
|
||||
|
||||
# Run Terraform commands in the Hashicorp docker container via docker compose
|
||||
# shellcheck disable=SC2068
|
||||
DOCKER_USER="$(id -u):$(id -g)" \
|
||||
PROJECT="${project}" \
|
||||
docker compose run --rm \
|
||||
-e OS_AUTH_URL \
|
||||
-e OS_IDENTITY_API_VERSION \
|
||||
-e OS_USER_DOMAIN_NAME \
|
||||
-e OS_PROJECT_DOMAIN_NAME \
|
||||
-e OS_TENANT_ID \
|
||||
-e OS_TENANT_NAME \
|
||||
-e OS_USERNAME \
|
||||
-e OS_PASSWORD \
|
||||
-e OS_REGION_NAME \
|
||||
terraform-state "$@"
|
||||
@@ -1,26 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
set -eo pipefail
|
||||
|
||||
source "$(dirname "${BASH_SOURCE[0]}")/_config.sh"
|
||||
|
||||
project=$(_set_openstack_project)
|
||||
echo "Using \"${project}\" project..."
|
||||
|
||||
source "${TERRAFORM_DIRECTORY}/${project}/openrc.sh"
|
||||
|
||||
# Run Terraform commands in the Hashicorp docker container via docker compose
|
||||
# shellcheck disable=SC2068
|
||||
DOCKER_USER="$(id -u):$(id -g)" \
|
||||
PROJECT="${project}" \
|
||||
docker compose run --rm \
|
||||
-e OS_AUTH_URL \
|
||||
-e OS_IDENTITY_API_VERSION \
|
||||
-e OS_USER_DOMAIN_NAME \
|
||||
-e OS_PROJECT_DOMAIN_NAME \
|
||||
-e OS_TENANT_ID \
|
||||
-e OS_TENANT_NAME \
|
||||
-e OS_USERNAME \
|
||||
-e OS_PASSWORD \
|
||||
-e OS_REGION_NAME \
|
||||
-e TF_VAR_user_name \
|
||||
terraform "$@"
|
||||
+19
-11
@@ -3,20 +3,28 @@
|
||||
Whenever we are cooking a new release (e.g. `4.18.1`) we should follow a standard procedure described below:
|
||||
|
||||
1. Create a new branch named: `release/4.18.1`.
|
||||
2. Bump the release number for backend project, frontend projects, and Helm files:
|
||||
2. Bump the release number for backend project, frontend projects, and Helm files:
|
||||
|
||||
- for backend, update the version number by hand in `pyproject.toml`,
|
||||
- for each frontend projects (`src/frontend`, `src/mail`), run `npm version 4.18.1` in their directory. This will update both their `package.json` and `package-lock.json` for you,
|
||||
- for Helm, update Docker image tag in files located at `src/helm/env.d` for both `preprod` and `production` environments:
|
||||
- for backend, update the version number by hand in `pyproject.toml`,
|
||||
- for each frontend projects (`src/frontend`, `src/mail`), run `npm version 4.18.1` in their directory. This will update both their `package.json` and `package-lock.json` for you,
|
||||
- for Helm, update Docker image tag in files located at `src/helm/env.d` for both `preprod` and `production` environments:
|
||||
|
||||
```yaml
|
||||
image:
|
||||
repository: lasuite/meet-backend
|
||||
pullPolicy: Always
|
||||
tag: "v4.18.1" # Replace with your new version number, without forgetting the "v" prefix
|
||||
```
|
||||
```yaml
|
||||
image:
|
||||
repository: lasuite/meet-backend
|
||||
pullPolicy: Always
|
||||
tag: "v4.18.1" # Replace with your new version number, without forgetting the "v" prefix
|
||||
|
||||
...
|
||||
|
||||
frontend:
|
||||
image:
|
||||
repository: lasuite/meet-frontend
|
||||
pullPolicy: Always
|
||||
tag: "v4.18.1" # Replace with your new version number, without forgetting the "v" prefix
|
||||
```
|
||||
|
||||
The new images don't exist _yet_: they will be created automatically later in the process.
|
||||
The new images don't exist _yet_: they will be created automatically later in the process.
|
||||
|
||||
3. ~~Update the project's `Changelog` following the [keepachangelog](https://keepachangelog.com/en/0.3.0/) recommendations~~ _we don't keep a changelog yet for now as the project is still in its infancy. Soon™!_
|
||||
4. Commit your changes with the following format: the 🔖 release emoji, the type of release (patch/minor/patch) and the release version:
|
||||
|
||||
@@ -41,3 +41,4 @@ OIDC_AUTH_REQUEST_EXTRA_PARAMS={"acr_values": "eidas1"}
|
||||
LIVEKIT_API_SECRET=secret
|
||||
LIVEKIT_API_KEY=devkey
|
||||
LIVEKIT_API_URL=http://localhost:7880
|
||||
ALLOW_UNREGISTERED_ROOMS=False
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
find . -name "*.enc.*" -exec sops updatekeys -y {} \;
|
||||
+1
-1
Submodule secrets updated: 9da011f5c2...f5fbc16e6e
@@ -1,4 +1,5 @@
|
||||
"""Admin classes and registrations for core app."""
|
||||
|
||||
from django.contrib import admin
|
||||
from django.contrib.auth import admin as auth_admin
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
"""
|
||||
Meet analytics class.
|
||||
"""
|
||||
|
||||
import uuid
|
||||
|
||||
from django.conf import settings
|
||||
|
||||
from june import analytics as jAnalytics
|
||||
|
||||
|
||||
class Analytics:
|
||||
"""Analytics integration
|
||||
|
||||
This class wraps the June analytics code to avoid coupling our code directly
|
||||
with this third-party library. By doing so, we create a generic interface
|
||||
for analytics that can be easily modified or replaced in the future.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
key = getattr(settings, "ANALYTICS_KEY", None)
|
||||
|
||||
if key is not None:
|
||||
jAnalytics.write_key = key
|
||||
|
||||
self._enabled = key is not None
|
||||
|
||||
def _is_anonymous_user(self, user):
|
||||
"""Check if the user is anonymous."""
|
||||
return user is None or user.is_anonymous
|
||||
|
||||
def identify(self, user, **kwargs):
|
||||
"""Identify a user"""
|
||||
|
||||
if self._is_anonymous_user(user) or not self._enabled:
|
||||
return
|
||||
|
||||
traits = kwargs.pop("traits", {})
|
||||
traits.update({"email": user.email_anonymized})
|
||||
|
||||
jAnalytics.identify(user_id=user.sub, traits=traits, **kwargs)
|
||||
|
||||
def track(self, user, **kwargs):
|
||||
"""Track an event"""
|
||||
|
||||
if not self._enabled:
|
||||
return
|
||||
|
||||
event_data = {}
|
||||
if self._is_anonymous_user(user):
|
||||
event_data["anonymous_id"] = str(uuid.uuid4())
|
||||
else:
|
||||
event_data["user_id"] = user.sub
|
||||
|
||||
jAnalytics.track(**event_data, **kwargs)
|
||||
|
||||
|
||||
analytics = Analytics()
|
||||
@@ -1,4 +1,5 @@
|
||||
"""Meet core API endpoints"""
|
||||
|
||||
from django.conf import settings
|
||||
from django.core.exceptions import ValidationError
|
||||
|
||||
@@ -22,6 +23,8 @@ def exception_handler(exc, context):
|
||||
detail = exc.message
|
||||
elif hasattr(exc, "messages"):
|
||||
detail = exc.messages
|
||||
else:
|
||||
detail = ""
|
||||
|
||||
exc = drf_exceptions.ValidationError(detail=detail)
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""Permission handlers for the Meet core app."""
|
||||
|
||||
from rest_framework import permissions
|
||||
|
||||
from ..models import RoleChoices
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""Client serializers for the Meet core app."""
|
||||
|
||||
from django.conf import settings
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
@@ -122,7 +123,7 @@ class RoomSerializer(serializers.ModelSerializer):
|
||||
if role is not None or instance.is_public:
|
||||
slug = f"{instance.id!s}".replace("-", "")
|
||||
|
||||
username = request.GET.get("username", None)
|
||||
username = request.query_params.get("username", None)
|
||||
|
||||
output["livekit"] = {
|
||||
"url": settings.LIVEKIT_CONFIGURATION["url"],
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""API endpoints"""
|
||||
|
||||
import uuid
|
||||
|
||||
from django.conf import settings
|
||||
@@ -19,6 +20,7 @@ from rest_framework import (
|
||||
|
||||
from core import models, utils
|
||||
|
||||
from ..analytics import analytics
|
||||
from . import permissions, serializers
|
||||
|
||||
# pylint: disable=too-many-ancestors
|
||||
@@ -184,6 +186,13 @@ class RoomViewSet(
|
||||
"""
|
||||
try:
|
||||
instance = self.get_object()
|
||||
|
||||
analytics.track(
|
||||
user=self.request.user,
|
||||
event="Get Room",
|
||||
properties={"slug": instance.slug},
|
||||
)
|
||||
|
||||
except Http404:
|
||||
if not settings.ALLOW_UNREGISTERED_ROOMS:
|
||||
raise
|
||||
@@ -232,6 +241,14 @@ class RoomViewSet(
|
||||
role=models.RoleChoices.OWNER,
|
||||
)
|
||||
|
||||
analytics.track(
|
||||
user=self.request.user,
|
||||
event="Create Room",
|
||||
properties={
|
||||
"slug": room.slug,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
class ResourceAccessListModelMixin:
|
||||
"""List mixin for resource access API."""
|
||||
|
||||
@@ -10,6 +10,8 @@ from mozilla_django_oidc.auth import (
|
||||
|
||||
from core.models import User
|
||||
|
||||
from ..analytics import analytics
|
||||
|
||||
|
||||
class OIDCAuthenticationBackend(MozillaOIDCAuthenticationBackend):
|
||||
"""Custom OpenID Connect (OIDC) Authentication Backend.
|
||||
@@ -79,6 +81,7 @@ class OIDCAuthenticationBackend(MozillaOIDCAuthenticationBackend):
|
||||
else:
|
||||
user = None
|
||||
|
||||
analytics.identify(user=user)
|
||||
return user
|
||||
|
||||
def create_user(self, claims):
|
||||
|
||||
@@ -22,6 +22,8 @@ from mozilla_django_oidc.views import (
|
||||
OIDCLogoutView as MozillaOIDCOIDCLogoutView,
|
||||
)
|
||||
|
||||
from ..analytics import analytics
|
||||
|
||||
|
||||
class OIDCLogoutView(MozillaOIDCOIDCLogoutView):
|
||||
"""Custom logout view for handling OpenID Connect (OIDC) logout flow.
|
||||
@@ -98,6 +100,10 @@ class OIDCLogoutView(MozillaOIDCOIDCLogoutView):
|
||||
|
||||
logout_url = self.redirect_url
|
||||
|
||||
analytics.track(
|
||||
user=request.user,
|
||||
event="Signed Out",
|
||||
)
|
||||
if request.user.is_authenticated:
|
||||
logout_url = self.construct_oidc_logout_url(request)
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
Core application enums declaration
|
||||
"""
|
||||
|
||||
from django.conf import global_settings, settings
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
"""
|
||||
Core application factories
|
||||
"""
|
||||
|
||||
from django.conf import settings
|
||||
from django.contrib.auth.hashers import make_password
|
||||
from django.utils.text import slugify
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
# Generated by Django 5.0.7 on 2024-08-07 14:38
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('core', '0002_create_pg_trgm_extension'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='room',
|
||||
name='configuration',
|
||||
field=models.JSONField(blank=True, default=dict, help_text='Values for Visio parameters to configure the room.', verbose_name='Visio room configuration'),
|
||||
)
|
||||
]
|
||||
@@ -0,0 +1,18 @@
|
||||
# Generated by Django 5.0.7 on 2024-08-07 14:39
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('core', '0003_alter_room_configuration'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='user',
|
||||
name='language',
|
||||
field=models.CharField(choices="(('en-us', 'English'), ('fr-fr', 'French'))", default='en-us', help_text='The language in which the user wants to see the interface.', max_length=10, verbose_name='language'),
|
||||
),
|
||||
]
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
Declare and configure the models for the Meet core application
|
||||
"""
|
||||
|
||||
import uuid
|
||||
from logging import getLogger
|
||||
|
||||
@@ -162,6 +163,13 @@ class User(AbstractBaseUser, BaseModel, auth_models.PermissionsMixin):
|
||||
"""
|
||||
return []
|
||||
|
||||
@property
|
||||
def email_anonymized(self):
|
||||
"""Anonymize the email address by replacing the local part with asterisks."""
|
||||
if not self.email:
|
||||
return ""
|
||||
return f"***@{self.email.split('@')[1]}"
|
||||
|
||||
|
||||
class Resource(BaseModel):
|
||||
"""Model to define access control"""
|
||||
@@ -288,7 +296,7 @@ class Room(Resource):
|
||||
|
||||
configuration = models.JSONField(
|
||||
blank=True,
|
||||
default={},
|
||||
default=dict,
|
||||
verbose_name=_("Visio room configuration"),
|
||||
help_text=_("Values for Visio parameters to configure the room."),
|
||||
)
|
||||
|
||||
@@ -92,9 +92,12 @@ def test_models_oidc_user_getter_invalid_token(django_assert_num_queries, monkey
|
||||
|
||||
monkeypatch.setattr(OIDCAuthenticationBackend, "get_userinfo", get_userinfo_mocked)
|
||||
|
||||
with django_assert_num_queries(0), pytest.raises(
|
||||
SuspiciousOperation,
|
||||
match="User info contained no recognizable user identification",
|
||||
with (
|
||||
django_assert_num_queries(0),
|
||||
pytest.raises(
|
||||
SuspiciousOperation,
|
||||
match="User info contained no recognizable user identification",
|
||||
),
|
||||
):
|
||||
klass.get_or_create_user(access_token="test-token", id_token=None, payload=None)
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""Fixtures for tests in the Meet core application"""
|
||||
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
Test rooms API endpoints in the Meet core app: create.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from rest_framework.test import APIClient
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
Test rooms API endpoints in the Meet core app: delete.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from rest_framework.test import APIClient
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
Test rooms API endpoints in the Meet core app: list.
|
||||
"""
|
||||
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
Test rooms API endpoints in the Meet core app: retrieve.
|
||||
"""
|
||||
|
||||
import random
|
||||
from unittest import mock
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
Test rooms API endpoints in the Meet core app: update.
|
||||
"""
|
||||
|
||||
import random
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
Test suite for generated openapi schema.
|
||||
"""
|
||||
|
||||
import json
|
||||
from io import StringIO
|
||||
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
"""
|
||||
Test for the Analytics class.
|
||||
"""
|
||||
|
||||
# pylint: disable=W0212
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
from django.contrib.auth.models import AnonymousUser
|
||||
from django.test.utils import override_settings
|
||||
|
||||
import pytest
|
||||
|
||||
from core.analytics import Analytics
|
||||
from core.factories import UserFactory
|
||||
|
||||
pytestmark = pytest.mark.django_db
|
||||
|
||||
|
||||
@pytest.fixture(name="mock_june_analytics")
|
||||
def _mock_june_analytics():
|
||||
with patch("core.analytics.jAnalytics") as mock:
|
||||
yield mock
|
||||
|
||||
|
||||
@override_settings(ANALYTICS_KEY="test_key")
|
||||
def test_analytics_init_enabled(mock_june_analytics):
|
||||
"""Should enable analytics and set the write key correctly when ANALYTICS_KEY is set."""
|
||||
analytics = Analytics()
|
||||
assert analytics._enabled is True
|
||||
assert mock_june_analytics.write_key == "test_key"
|
||||
|
||||
|
||||
@override_settings(ANALYTICS_KEY=None)
|
||||
def test_analytics_init_disabled():
|
||||
"""Should disable analytics when ANALYTICS_KEY is not set."""
|
||||
analytics = Analytics()
|
||||
assert analytics._enabled is False
|
||||
|
||||
|
||||
@override_settings(ANALYTICS_KEY="test_key")
|
||||
def test_analytics_identify_user(mock_june_analytics):
|
||||
"""Should identify a user with the correct traits when analytics is enabled."""
|
||||
user = UserFactory(sub="12345", email="user@example.com")
|
||||
analytics = Analytics()
|
||||
analytics.identify(user)
|
||||
mock_june_analytics.identify.assert_called_once_with(
|
||||
user_id="12345", traits={"email": "***@example.com"}
|
||||
)
|
||||
|
||||
|
||||
@override_settings(ANALYTICS_KEY="test_key")
|
||||
def test_analytics_identify_user_with_traits(mock_june_analytics):
|
||||
"""Should identify a user with additional traits when analytics is enabled."""
|
||||
user = UserFactory(sub="12345", email="user@example.com")
|
||||
analytics = Analytics()
|
||||
analytics.identify(user, traits={"email": "user@example.com", "foo": "foo"})
|
||||
mock_june_analytics.identify.assert_called_once_with(
|
||||
user_id="12345", traits={"email": "***@example.com", "foo": "foo"}
|
||||
)
|
||||
|
||||
|
||||
@override_settings(ANALYTICS_KEY=None)
|
||||
def test_analytics_identify_not_enabled(mock_june_analytics):
|
||||
"""Should not call identify when analytics is not enabled."""
|
||||
user = UserFactory(sub="12345", email="user@example.com")
|
||||
analytics = Analytics()
|
||||
analytics.identify(user)
|
||||
mock_june_analytics.identify.assert_not_called()
|
||||
|
||||
|
||||
@override_settings(ANALYTICS_KEY="test_key")
|
||||
def test_analytics_identify_no_user(mock_june_analytics):
|
||||
"""Should not call identify when the user is None."""
|
||||
analytics = Analytics()
|
||||
analytics.identify(None)
|
||||
mock_june_analytics.identify.assert_not_called()
|
||||
|
||||
|
||||
@override_settings(ANALYTICS_KEY="test_key")
|
||||
def test_analytics_identify_anonymous_user(mock_june_analytics):
|
||||
"""Should not call identify when the user is anonymous."""
|
||||
user = AnonymousUser()
|
||||
analytics = Analytics()
|
||||
analytics.identify(user)
|
||||
mock_june_analytics.identify.assert_not_called()
|
||||
|
||||
|
||||
@override_settings(ANALYTICS_KEY="test_key")
|
||||
def test_analytics_track_event(mock_june_analytics):
|
||||
"""Should track an event with the correct user and event details when analytics is enabled."""
|
||||
user = UserFactory(sub="12345")
|
||||
analytics = Analytics()
|
||||
analytics.track(user, event="test_event", foo="foo")
|
||||
mock_june_analytics.track.assert_called_once_with(
|
||||
user_id="12345", event="test_event", foo="foo"
|
||||
)
|
||||
|
||||
|
||||
@override_settings(ANALYTICS_KEY=None)
|
||||
def test_analytics_track_event_not_enabled(mock_june_analytics):
|
||||
"""Should not call track when analytics is not enabled."""
|
||||
user = UserFactory(sub="12345")
|
||||
analytics = Analytics()
|
||||
analytics.track(user, event="test_event", foo="foo")
|
||||
|
||||
mock_june_analytics.track.assert_not_called()
|
||||
|
||||
|
||||
@override_settings(ANALYTICS_KEY="test_key")
|
||||
@patch("uuid.uuid4", return_value="test_uuid4")
|
||||
def test_analytics_track_event_no_user(mock_uuid4, mock_june_analytics):
|
||||
"""Should track an event with a random anonymous user ID when the user is None."""
|
||||
analytics = Analytics()
|
||||
analytics.track(None, event="test_event", foo="foo")
|
||||
mock_june_analytics.track.assert_called_once_with(
|
||||
anonymous_id="test_uuid4", event="test_event", foo="foo"
|
||||
)
|
||||
mock_uuid4.assert_called_once()
|
||||
|
||||
|
||||
@override_settings(ANALYTICS_KEY="test_key")
|
||||
@patch("uuid.uuid4", return_value="test_uuid4")
|
||||
def test_analytics_track_event_anonymous_user(mock_uuid4, mock_june_analytics):
|
||||
"""Should track an event with a random anonymous user ID when the user is anonymous."""
|
||||
user = AnonymousUser()
|
||||
analytics = Analytics()
|
||||
analytics.track(user, event="test_event", foo="foo")
|
||||
mock_june_analytics.track.assert_called_once_with(
|
||||
anonymous_id="test_uuid4", event="test_event", foo="foo"
|
||||
)
|
||||
mock_uuid4.assert_called_once()
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
Test resource accesses API endpoints in the Meet core app.
|
||||
"""
|
||||
|
||||
import random
|
||||
from unittest import mock
|
||||
from uuid import uuid4
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
Test users API endpoints in the Meet core app.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from rest_framework.test import APIClient
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
Unit tests for the ResourceAccess model with user
|
||||
"""
|
||||
|
||||
from django.core.exceptions import ValidationError
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
Unit tests for the Room model
|
||||
"""
|
||||
|
||||
from django.contrib.auth.models import AnonymousUser
|
||||
from django.core.exceptions import ValidationError
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
Unit tests for the User model
|
||||
"""
|
||||
|
||||
from unittest import mock
|
||||
|
||||
from django.core.exceptions import ValidationError
|
||||
@@ -43,3 +44,12 @@ def test_models_users_send_mail_main_missing():
|
||||
user.email_user("my subject", "my message")
|
||||
|
||||
assert str(excinfo.value) == "User has no email address."
|
||||
|
||||
|
||||
def test_models_users_email_anonymized():
|
||||
"""The user's email should be anonymized if it exists."""
|
||||
user = factories.UserFactory(email="john.doe@world.com")
|
||||
assert user.email_anonymized == "***@world.com"
|
||||
|
||||
user = factories.UserFactory(email=None)
|
||||
assert user.email_anonymized == ""
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""URL configuration for the core app."""
|
||||
|
||||
from django.conf import settings
|
||||
from django.urls import include, path
|
||||
|
||||
|
||||
+37
-10
@@ -1,6 +1,11 @@
|
||||
"""
|
||||
Utils functions used in the core app
|
||||
"""
|
||||
|
||||
# ruff: noqa:S311
|
||||
|
||||
import json
|
||||
import random
|
||||
from typing import Optional
|
||||
from uuid import uuid4
|
||||
|
||||
@@ -9,8 +14,26 @@ from django.conf import settings
|
||||
from livekit.api import AccessToken, VideoGrants
|
||||
|
||||
|
||||
def generate_color(identity: str) -> str:
|
||||
"""Generates a consistent HSL color based on a given identity string.
|
||||
|
||||
The function seeds the random generator with the identity's hash,
|
||||
ensuring consistent color output. The HSL format allows fine-tuned control
|
||||
over saturation and lightness, empirically adjusted to produce visually
|
||||
appealing and distinct colors. HSL is preferred over hex to constrain the color
|
||||
range and ensure predictability.
|
||||
"""
|
||||
|
||||
random.seed(hash(identity))
|
||||
hue = random.randint(0, 360)
|
||||
saturation = random.randint(50, 75)
|
||||
lightness = random.randint(25, 60)
|
||||
|
||||
return f"hsl({hue}, {saturation}%, {lightness}%)"
|
||||
|
||||
|
||||
def generate_token(room: str, user, username: Optional[str] = None) -> str:
|
||||
"""Generate a Livekit access token for a user in a specific room.
|
||||
"""Generate a LiveKit access token for a user in a specific room.
|
||||
|
||||
Args:
|
||||
room (str): The name of the room.
|
||||
@@ -21,10 +44,10 @@ def generate_token(room: str, user, username: Optional[str] = None) -> str:
|
||||
Returns:
|
||||
str: The LiveKit JWT access token.
|
||||
"""
|
||||
|
||||
video_grants = VideoGrants(
|
||||
room=room,
|
||||
room_join=True,
|
||||
can_update_own_metadata=True,
|
||||
can_publish_sources=[
|
||||
"camera",
|
||||
"microphone",
|
||||
@@ -33,18 +56,22 @@ def generate_token(room: str, user, username: Optional[str] = None) -> str:
|
||||
],
|
||||
)
|
||||
|
||||
token = AccessToken(
|
||||
api_key=settings.LIVEKIT_CONFIGURATION["api_key"],
|
||||
api_secret=settings.LIVEKIT_CONFIGURATION["api_secret"],
|
||||
).with_grants(video_grants)
|
||||
|
||||
if user.is_anonymous:
|
||||
token.with_identity(str(uuid4()))
|
||||
identity = str(uuid4())
|
||||
default_username = "Anonymous"
|
||||
else:
|
||||
token.with_identity(user.sub)
|
||||
identity = str(user.sub)
|
||||
default_username = str(user)
|
||||
|
||||
token.with_name(username or default_username)
|
||||
token = (
|
||||
AccessToken(
|
||||
api_key=settings.LIVEKIT_CONFIGURATION["api_key"],
|
||||
api_secret=settings.LIVEKIT_CONFIGURATION["api_secret"],
|
||||
)
|
||||
.with_grants(video_grants)
|
||||
.with_identity(identity)
|
||||
.with_name(username or default_username)
|
||||
.with_metadata(json.dumps({"color": generate_color(identity)}))
|
||||
)
|
||||
|
||||
return token.to_jwt()
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""Management user to create a superuser."""
|
||||
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.core.management.base import BaseCommand
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
"""
|
||||
meet's sandbox management script.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""Meet celery configuration file."""
|
||||
|
||||
import os
|
||||
|
||||
from celery import Celery
|
||||
|
||||
@@ -9,8 +9,10 @@ https://docs.djangoproject.com/en/3.1/topics/settings/
|
||||
For the full list of settings and their values, see
|
||||
https://docs.djangoproject.com/en/3.1/ref/settings/
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
from socket import gethostbyname, gethostname
|
||||
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
@@ -70,6 +72,7 @@ class Base(Configuration):
|
||||
# Security
|
||||
ALLOWED_HOSTS = values.ListValue([])
|
||||
SECRET_KEY = values.Value(None)
|
||||
SILENCED_SYSTEM_CHECKS = values.ListValue([])
|
||||
|
||||
# Application definition
|
||||
ROOT_URLCONF = "meet.urls"
|
||||
@@ -272,6 +275,7 @@ class Base(Configuration):
|
||||
# Easy thumbnails
|
||||
THUMBNAIL_EXTENSION = "webp"
|
||||
THUMBNAIL_TRANSPARENCY_EXTENSION = "webp"
|
||||
THUMBNAIL_DEFAULT_STORAGE_ALIAS = "default"
|
||||
THUMBNAIL_ALIASES = {}
|
||||
|
||||
# Celery
|
||||
@@ -364,6 +368,9 @@ class Base(Configuration):
|
||||
ALLOW_UNREGISTERED_ROOMS = values.BooleanValue(
|
||||
True, environ_name="ALLOW_UNREGISTERED_ROOMS", environ_prefix=None
|
||||
)
|
||||
ANALYTICS_KEY = values.Value(
|
||||
None, environ_name="ANALYTICS_KEY", environ_prefix=None
|
||||
)
|
||||
|
||||
# pylint: disable=invalid-name
|
||||
@property
|
||||
@@ -484,6 +491,8 @@ class Test(Base):
|
||||
|
||||
CELERY_TASK_ALWAYS_EAGER = values.BooleanValue(True)
|
||||
|
||||
ANALYTICS_KEY = None
|
||||
|
||||
def __init__(self):
|
||||
# pylint: disable=invalid-name
|
||||
self.INSTALLED_APPS += ["drf_spectacular_sidecar"]
|
||||
@@ -507,7 +516,11 @@ class Production(Base):
|
||||
"""
|
||||
|
||||
# Security
|
||||
ALLOWED_HOSTS = values.ListValue(None)
|
||||
ALLOWED_HOSTS = [
|
||||
*values.ListValue([], environ_name="ALLOWED_HOSTS"),
|
||||
gethostbyname(gethostname()),
|
||||
]
|
||||
|
||||
CSRF_TRUSTED_ORIGINS = values.ListValue([])
|
||||
SECURE_BROWSER_XSS_FILTER = True
|
||||
SECURE_CONTENT_TYPE_NOSNIFF = True
|
||||
@@ -544,6 +557,26 @@ class Production(Base):
|
||||
},
|
||||
}
|
||||
|
||||
LOGGING = {
|
||||
"version": 1,
|
||||
"formatters": {
|
||||
"json": {"()": "dockerflow.logging.JsonLogFormatter", "logger_name": "meet"}
|
||||
},
|
||||
"handlers": {
|
||||
"console": {
|
||||
"level": "DEBUG",
|
||||
"class": "logging.StreamHandler",
|
||||
"formatter": "json",
|
||||
},
|
||||
},
|
||||
"loggers": {
|
||||
"request.summary": {
|
||||
"handlers": ["console"],
|
||||
"level": "DEBUG",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
class Feature(Production):
|
||||
"""
|
||||
|
||||
+40
-39
@@ -7,7 +7,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "meet"
|
||||
version = "0.1.2"
|
||||
version = "0.1.4"
|
||||
authors = [{ "name" = "DINUM", "email" = "dev@mail.numerique.gouv.fr" }]
|
||||
classifiers = [
|
||||
"Development Status :: 5 - Production/Stable",
|
||||
@@ -25,38 +25,39 @@ license = { file = "LICENSE" }
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
dependencies = [
|
||||
"boto3==1.33.6",
|
||||
"boto3==1.35.5",
|
||||
"Brotli==1.1.0",
|
||||
"celery[redis]==5.3.6",
|
||||
"django-configurations==2.5",
|
||||
"django-cors-headers==4.3.1",
|
||||
"django-countries==7.5.1",
|
||||
"celery[redis]==5.4.0",
|
||||
"django-configurations==2.5.1",
|
||||
"django-cors-headers==4.4.0",
|
||||
"django-countries==7.6.1",
|
||||
"django-parler==2.3",
|
||||
"redis==5.0.3",
|
||||
"redis==5.0.8",
|
||||
"django-redis==5.4.0",
|
||||
"django-storages[s3]==1.14.2",
|
||||
"django-storages[s3]==1.14.4",
|
||||
"django-timezone-field>=5.1",
|
||||
"django==5.0.7",
|
||||
"django==5.1",
|
||||
"djangorestframework==3.15.2",
|
||||
"drf_spectacular==0.26.5",
|
||||
"dockerflow==2022.8.0",
|
||||
"easy_thumbnails==2.8.5",
|
||||
"factory_boy==3.3.0",
|
||||
"freezegun==1.5.0",
|
||||
"gunicorn==22.0.0",
|
||||
"jsonschema==4.20.0",
|
||||
"markdown==3.5.1",
|
||||
"drf_spectacular==0.27.2",
|
||||
"dockerflow==2024.4.2",
|
||||
"easy_thumbnails==2.9",
|
||||
"factory_boy==3.3.1",
|
||||
"freezegun==1.5.1",
|
||||
"gunicorn==23.0.0",
|
||||
"jsonschema==4.23.0",
|
||||
"june-analytics-python==2.3.0",
|
||||
"markdown==3.7",
|
||||
"nested-multipart-parser==1.5.0",
|
||||
"psycopg[binary]==3.1.14",
|
||||
"PyJWT==2.8.0",
|
||||
"python-frontmatter==1.0.1",
|
||||
"requests==2.32.2",
|
||||
"sentry-sdk==2.8.0",
|
||||
"psycopg[binary]==3.2.1",
|
||||
"PyJWT==2.9.0",
|
||||
"python-frontmatter==1.1.0",
|
||||
"requests==2.32.3",
|
||||
"sentry-sdk==2.13.0",
|
||||
"url-normalize==1.4.3",
|
||||
"WeasyPrint>=60.2",
|
||||
"whitenoise==6.6.0",
|
||||
"mozilla-django-oidc==4.0.0",
|
||||
"livekit-api==0.5.1",
|
||||
"whitenoise==6.7.0",
|
||||
"mozilla-django-oidc==4.0.1",
|
||||
"livekit-api==0.7.0",
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
@@ -68,20 +69,20 @@ dependencies = [
|
||||
[project.optional-dependencies]
|
||||
dev = [
|
||||
"django-extensions==3.2.3",
|
||||
"drf-spectacular-sidecar==2023.12.1",
|
||||
"drf-spectacular-sidecar==2024.7.1",
|
||||
"ipdb==0.13.13",
|
||||
"ipython==8.18.1",
|
||||
"pyfakefs==5.3.2",
|
||||
"ipython==8.26.0",
|
||||
"pyfakefs==5.6.0",
|
||||
"pylint-django==2.5.5",
|
||||
"pylint==3.0.3",
|
||||
"pytest-cov==4.1.0",
|
||||
"pytest-django==4.7.0",
|
||||
"pytest==7.4.3",
|
||||
"pytest-icdiff==0.8",
|
||||
"pytest-xdist==3.5.0",
|
||||
"responses==0.24.1",
|
||||
"ruff==0.1.6",
|
||||
"types-requests==2.31.0.10",
|
||||
"pylint==3.2.6",
|
||||
"pytest-cov==5.0.0",
|
||||
"pytest-django==4.8.0",
|
||||
"pytest==8.3.2",
|
||||
"pytest-icdiff==0.9",
|
||||
"pytest-xdist==3.6.1",
|
||||
"responses==0.25.3",
|
||||
"ruff==0.6.2",
|
||||
"types-requests==2.32.0.20240712",
|
||||
]
|
||||
|
||||
[tool.setuptools]
|
||||
@@ -100,7 +101,6 @@ exclude = [
|
||||
"__pycache__",
|
||||
"*/migrations/*",
|
||||
]
|
||||
ignore= ["DJ001", "PLR2004"]
|
||||
line-length = 88
|
||||
|
||||
|
||||
@@ -121,12 +121,13 @@ select = [
|
||||
"SLF", # flake8-self
|
||||
"T20", # flake8-print
|
||||
]
|
||||
ignore= ["DJ001", "PLR2004"]
|
||||
|
||||
[tool.ruff.lint.isort]
|
||||
section-order = ["future","standard-library","django","third-party","meet","first-party","local-folder"]
|
||||
sections = { meet=["core"], django=["django"] }
|
||||
|
||||
[tool.ruff.per-file-ignores]
|
||||
[tool.ruff.lint.per-file-ignores]
|
||||
"**/tests/*" = ["S", "SLF"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
"""Setup file for the meet module. All configuration stands in the setup.cfg file."""
|
||||
# coding: utf-8
|
||||
|
||||
from setuptools import setup
|
||||
|
||||
setup()
|
||||
@@ -7,6 +7,7 @@ module.exports = {
|
||||
'plugin:react-hooks/recommended',
|
||||
'plugin:@tanstack/eslint-plugin-query/recommended',
|
||||
'plugin:jsx-a11y/recommended',
|
||||
'prettier'
|
||||
],
|
||||
ignorePatterns: ['dist', '.eslintrc.cjs', 'styled-system'],
|
||||
parser: '@typescript-eslint/parser',
|
||||
|
||||
Generated
+84
-8
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "meet",
|
||||
"version": "0.1.2",
|
||||
"version": "0.1.4",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "meet",
|
||||
"version": "0.1.2",
|
||||
"version": "0.1.4",
|
||||
"dependencies": {
|
||||
"@livekit/components-react": "2.3.3",
|
||||
"@livekit/components-styles": "1.0.12",
|
||||
@@ -23,6 +23,7 @@
|
||||
"react-aria-components": "1.2.1",
|
||||
"react-dom": "18.2.0",
|
||||
"react-i18next": "14.1.3",
|
||||
"valtio": "1.13.2",
|
||||
"wouter": "3.3.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -36,10 +37,12 @@
|
||||
"@typescript-eslint/parser": "7.13.1",
|
||||
"@vitejs/plugin-react": "4.3.1",
|
||||
"eslint": "8.57.0",
|
||||
"eslint-config-prettier": "9.1.0",
|
||||
"eslint-plugin-jsx-a11y": "6.9.0",
|
||||
"eslint-plugin-react-hooks": "4.6.2",
|
||||
"eslint-plugin-react-refresh": "0.4.7",
|
||||
"postcss": "8.4.39",
|
||||
"prettier": "3.3.3",
|
||||
"typescript": "5.5.2",
|
||||
"vite": "5.3.1",
|
||||
"vite-tsconfig-paths": "4.3.2"
|
||||
@@ -1587,6 +1590,21 @@
|
||||
"node": "^10 || ^12 || >=14"
|
||||
}
|
||||
},
|
||||
"node_modules/@pandacss/node/node_modules/prettier": {
|
||||
"version": "3.2.5",
|
||||
"resolved": "https://registry.npmjs.org/prettier/-/prettier-3.2.5.tgz",
|
||||
"integrity": "sha512-3/GWa9aOC0YeD7LUfvOG2NiDyhOWRvt1k+rcKhOuYnMY24iiCphgneUfJDyFXd6rZCAnuLBv6UeAULtrhT/F4A==",
|
||||
"dev": true,
|
||||
"bin": {
|
||||
"prettier": "bin/prettier.cjs"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/prettier/prettier?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/@pandacss/parser": {
|
||||
"version": "0.41.0",
|
||||
"resolved": "https://registry.npmjs.org/@pandacss/parser/-/parser-0.41.0.tgz",
|
||||
@@ -3643,13 +3661,13 @@
|
||||
"version": "15.7.12",
|
||||
"resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.12.tgz",
|
||||
"integrity": "sha512-5zvhXYtRNRluoE/jAp4GVsSduVUzNWKkOZrCDBWYtE7biZywwdC2AcEzg+cSMLFRfVgeAFqpfNabiPjxFddV1Q==",
|
||||
"dev": true
|
||||
"devOptional": true
|
||||
},
|
||||
"node_modules/@types/react": {
|
||||
"version": "18.3.3",
|
||||
"resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.3.tgz",
|
||||
"integrity": "sha512-hti/R0pS0q1/xx+TsI73XIqk26eBsISZ2R0wUijXIngRK9R/e7Xw/cXVxQK7R5JjW+SV4zGcn5hXjudkN/pLIw==",
|
||||
"dev": true,
|
||||
"devOptional": true,
|
||||
"dependencies": {
|
||||
"@types/prop-types": "*",
|
||||
"csstype": "^3.0.2"
|
||||
@@ -5134,7 +5152,7 @@
|
||||
"version": "3.1.3",
|
||||
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz",
|
||||
"integrity": "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==",
|
||||
"dev": true
|
||||
"devOptional": true
|
||||
},
|
||||
"node_modules/damerau-levenshtein": {
|
||||
"version": "1.0.8",
|
||||
@@ -5282,6 +5300,14 @@
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/derive-valtio": {
|
||||
"version": "0.1.0",
|
||||
"resolved": "https://registry.npmjs.org/derive-valtio/-/derive-valtio-0.1.0.tgz",
|
||||
"integrity": "sha512-OCg2UsLbXK7GmmpzMXhYkdO64vhJ1ROUUGaTFyHjVwEdMEcTTRj7W1TxLbSBxdY8QLBPCcp66MTyaSy0RpO17A==",
|
||||
"peerDependencies": {
|
||||
"valtio": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/detect-libc": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-1.0.3.tgz",
|
||||
@@ -5691,6 +5717,18 @@
|
||||
"url": "https://opencollective.com/eslint"
|
||||
}
|
||||
},
|
||||
"node_modules/eslint-config-prettier": {
|
||||
"version": "9.1.0",
|
||||
"resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-9.1.0.tgz",
|
||||
"integrity": "sha512-NSWl5BFQWEPi1j4TjVNItzYV7dZXZ+wP6I6ZhrBGpChQhZRUaElihE9uRRkcbRnNb76UMKDF3r+WTmNcGPKsqw==",
|
||||
"dev": true,
|
||||
"bin": {
|
||||
"eslint-config-prettier": "bin/cli.js"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"eslint": ">=7.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/eslint-plugin-jsx-a11y": {
|
||||
"version": "6.9.0",
|
||||
"resolved": "https://registry.npmjs.org/eslint-plugin-jsx-a11y/-/eslint-plugin-jsx-a11y-6.9.0.tgz",
|
||||
@@ -8910,9 +8948,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/prettier": {
|
||||
"version": "3.2.5",
|
||||
"resolved": "https://registry.npmjs.org/prettier/-/prettier-3.2.5.tgz",
|
||||
"integrity": "sha512-3/GWa9aOC0YeD7LUfvOG2NiDyhOWRvt1k+rcKhOuYnMY24iiCphgneUfJDyFXd6rZCAnuLBv6UeAULtrhT/F4A==",
|
||||
"version": "3.3.3",
|
||||
"resolved": "https://registry.npmjs.org/prettier/-/prettier-3.3.3.tgz",
|
||||
"integrity": "sha512-i2tDNA0O5IrMO757lfrdQZCc2jPNDVntV0m/+4whiDfWaTKfMNgR7Qz0NAeGz/nRqF4m5/6CLzbP4/liHt12Ew==",
|
||||
"dev": true,
|
||||
"bin": {
|
||||
"prettier": "bin/prettier.cjs"
|
||||
@@ -8937,6 +8975,11 @@
|
||||
"node": "10.* || >= 12.*"
|
||||
}
|
||||
},
|
||||
"node_modules/proxy-compare": {
|
||||
"version": "2.6.0",
|
||||
"resolved": "https://registry.npmjs.org/proxy-compare/-/proxy-compare-2.6.0.tgz",
|
||||
"integrity": "sha512-8xuCeM3l8yqdmbPoYeLbrAXCBWu19XEYc5/F28f5qOaoAIMyfmBUkl5axiK+x9olUvRlcekvnm98AP9RDngOIw=="
|
||||
},
|
||||
"node_modules/punycode": {
|
||||
"version": "2.3.1",
|
||||
"resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
|
||||
@@ -10101,6 +10144,39 @@
|
||||
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
|
||||
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="
|
||||
},
|
||||
"node_modules/valtio": {
|
||||
"version": "1.13.2",
|
||||
"resolved": "https://registry.npmjs.org/valtio/-/valtio-1.13.2.tgz",
|
||||
"integrity": "sha512-Qik0o+DSy741TmkqmRfjq+0xpZBXi/Y6+fXZLn0xNF1z/waFMbE3rkivv5Zcf9RrMUp6zswf2J7sbh2KBlba5A==",
|
||||
"dependencies": {
|
||||
"derive-valtio": "0.1.0",
|
||||
"proxy-compare": "2.6.0",
|
||||
"use-sync-external-store": "1.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12.20.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@types/react": ">=16.8",
|
||||
"react": ">=16.8"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@types/react": {
|
||||
"optional": true
|
||||
},
|
||||
"react": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/valtio/node_modules/use-sync-external-store": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.2.0.tgz",
|
||||
"integrity": "sha512-eEgnFxGQ1Ife9bzYs6VLi8/4X6CObHMw9Qr9tPY43iKwsPw8xE8+EFsf/2cFZ5S3esXgpWgtSCtLNS41F+sKPA==",
|
||||
"peerDependencies": {
|
||||
"react": "^16.8.0 || ^17.0.0 || ^18.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/value-or-function": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/value-or-function/-/value-or-function-4.0.0.tgz",
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
{
|
||||
"name": "meet",
|
||||
"private": true,
|
||||
"version": "0.1.2",
|
||||
"version": "0.1.4",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "panda codegen && vite",
|
||||
"build": "panda codegen && tsc -b && vite build",
|
||||
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
|
||||
"preview": "vite preview",
|
||||
"i18n:extract": "npx i18next -c i18next-parser.config.json"
|
||||
"i18n:extract": "npx i18next -c i18next-parser.config.json",
|
||||
"format": "prettier --write ./src",
|
||||
"check": "prettier --check ./src"
|
||||
},
|
||||
"dependencies": {
|
||||
"@livekit/components-react": "2.3.3",
|
||||
@@ -26,6 +28,7 @@
|
||||
"react-aria-components": "1.2.1",
|
||||
"react-dom": "18.2.0",
|
||||
"react-i18next": "14.1.3",
|
||||
"valtio": "1.13.2",
|
||||
"wouter": "3.3.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -39,10 +42,12 @@
|
||||
"@typescript-eslint/parser": "7.13.1",
|
||||
"@vitejs/plugin-react": "4.3.1",
|
||||
"eslint": "8.57.0",
|
||||
"eslint-config-prettier": "9.1.0",
|
||||
"eslint-plugin-jsx-a11y": "6.9.0",
|
||||
"eslint-plugin-react-hooks": "4.6.2",
|
||||
"eslint-plugin-react-refresh": "0.4.7",
|
||||
"postcss": "8.4.39",
|
||||
"prettier": "3.3.3",
|
||||
"typescript": "5.5.2",
|
||||
"vite": "5.3.1",
|
||||
"vite-tsconfig-paths": "4.3.2"
|
||||
|
||||
@@ -58,6 +58,11 @@ const config: Config = {
|
||||
},
|
||||
},
|
||||
fade: { from: { opacity: 0 }, to: { opacity: 1 } },
|
||||
pulse: {
|
||||
'0%': { boxShadow: '0 0 0 0 rgba(255, 255, 255, 0.7)' },
|
||||
'75%': { boxShadow: '0 0 0 30px rgba(255, 255, 255, 0)' },
|
||||
'100%': { boxShadow: '0 0 0 0 rgba(255, 255, 255, 0)' },
|
||||
},
|
||||
},
|
||||
tokens: defineTokens({
|
||||
/* we take a few things from the panda preset but for now we clear out some stuff.
|
||||
@@ -199,6 +204,7 @@ const config: Config = {
|
||||
text: { value: '{colors.white}' },
|
||||
subtle: { value: '{colors.red.100}' },
|
||||
'subtle-text': { value: '{colors.red.700}' },
|
||||
...pandaPreset.theme.tokens.colors.red,
|
||||
},
|
||||
success: {
|
||||
DEFAULT: { value: '{colors.green.700}' },
|
||||
|
||||
Binary file not shown.
+21
-14
@@ -2,32 +2,39 @@ import '@livekit/components-styles'
|
||||
import '@/styles/index.css'
|
||||
import { Suspense } from 'react'
|
||||
import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { QueryClientProvider } from '@tanstack/react-query'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useLang } from 'hoofd'
|
||||
import { Switch, Route } from 'wouter'
|
||||
import { NotFoundScreen } from './layout/NotFoundScreen'
|
||||
import { RenderIfUserFetched } from './features/auth'
|
||||
import { I18nProvider } from 'react-aria-components'
|
||||
import { Layout } from './layout/Layout'
|
||||
import { NotFoundScreen } from './components/NotFoundScreen'
|
||||
import { routes } from './routes'
|
||||
import './i18n/init'
|
||||
|
||||
const queryClient = new QueryClient()
|
||||
import { silenceLiveKitLogs } from '@/utils/livekit.ts'
|
||||
import { queryClient } from '@/api/queryClient'
|
||||
|
||||
function App() {
|
||||
const { i18n } = useTranslation()
|
||||
useLang(i18n.language)
|
||||
|
||||
const isProduction = import.meta.env.PROD
|
||||
silenceLiveKitLogs(isProduction)
|
||||
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<Suspense fallback={null}>
|
||||
<RenderIfUserFetched>
|
||||
<Switch>
|
||||
{Object.entries(routes).map(([, route], i) => (
|
||||
<Route key={i} path={route.path} component={route.Component} />
|
||||
))}
|
||||
<Route component={NotFoundScreen} />
|
||||
</Switch>
|
||||
</RenderIfUserFetched>
|
||||
<ReactQueryDevtools initialIsOpen={false} />
|
||||
<I18nProvider locale={i18n.language}>
|
||||
<Layout>
|
||||
<Switch>
|
||||
{Object.entries(routes).map(([, route], i) => (
|
||||
<Route key={i} path={route.path} component={route.Component} />
|
||||
))}
|
||||
<Route component={NotFoundScreen} />
|
||||
</Switch>
|
||||
</Layout>
|
||||
<ReactQueryDevtools initialIsOpen={false} />
|
||||
</I18nProvider>
|
||||
</Suspense>
|
||||
</QueryClientProvider>
|
||||
)
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
import { QueryClient } from '@tanstack/react-query'
|
||||
|
||||
export const queryClient = new QueryClient()
|
||||
@@ -0,0 +1,53 @@
|
||||
import { cva, RecipeVariantProps } from '@/styled-system/css'
|
||||
import React from 'react'
|
||||
|
||||
const avatar = cva({
|
||||
base: {
|
||||
backgroundColor: 'transparent',
|
||||
color: 'white',
|
||||
display: 'flex',
|
||||
borderRadius: '50%',
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
userSelect: 'none',
|
||||
cursor: 'default',
|
||||
flexGrow: 0,
|
||||
flexShrink: 0,
|
||||
},
|
||||
variants: {
|
||||
context: {
|
||||
list: {
|
||||
width: '32px',
|
||||
height: '32px',
|
||||
fontSize: '0.8rem',
|
||||
},
|
||||
placeholder: {
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
},
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
context: 'list',
|
||||
},
|
||||
})
|
||||
|
||||
export type AvatarProps = React.HTMLAttributes<HTMLDivElement> & {
|
||||
name?: string
|
||||
bgColor?: string
|
||||
} & RecipeVariantProps<typeof avatar>
|
||||
|
||||
export const Avatar = ({ name, bgColor, context, ...props }: AvatarProps) => {
|
||||
const initial = name?.trim()?.charAt(0) || ''
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
backgroundColor: bgColor,
|
||||
}}
|
||||
className={avatar({ context })}
|
||||
{...props}
|
||||
>
|
||||
{initial}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { Link } from '@/primitives'
|
||||
import { AProps } from '@/primitives/A'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
export const BackToHome = ({ size }: { size?: AProps['size'] }) => {
|
||||
const { t } = useTranslation()
|
||||
return (
|
||||
<p>
|
||||
<Link to="/" size={size}>
|
||||
{t('backToHome')}
|
||||
</Link>
|
||||
</p>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { useState, useEffect, type ReactNode } from 'react'
|
||||
|
||||
export const DelayedRender = ({
|
||||
children,
|
||||
delay = 500,
|
||||
}: {
|
||||
delay?: number
|
||||
children: ReactNode
|
||||
}) => {
|
||||
const [show, setShow] = useState(false)
|
||||
useEffect(() => {
|
||||
if (delay === 0) {
|
||||
setShow(true)
|
||||
return
|
||||
}
|
||||
const timeout = setTimeout(() => setShow(true), delay)
|
||||
return () => clearTimeout(timeout)
|
||||
}, [delay])
|
||||
if (delay !== 0 && !show) {
|
||||
return null
|
||||
}
|
||||
|
||||
return children
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { CenteredContent } from '@/layout/CenteredContent'
|
||||
import { Screen } from '@/layout/Screen'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { Center } from '@/styled-system/jsx'
|
||||
import { Text } from '@/primitives'
|
||||
|
||||
export const ErrorScreen = ({
|
||||
title,
|
||||
body,
|
||||
}: {
|
||||
title?: string
|
||||
body?: string
|
||||
}) => {
|
||||
const { t } = useTranslation()
|
||||
return (
|
||||
<Screen layout="centered">
|
||||
<CenteredContent title={title || t('error.heading')} withBackButton>
|
||||
{!!body && (
|
||||
<Center>
|
||||
<Text as="p" variant="h3" centered>
|
||||
{body}
|
||||
</Text>
|
||||
</Center>
|
||||
)}
|
||||
</CenteredContent>
|
||||
</Screen>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { Screen, type ScreenProps } from '@/layout/Screen'
|
||||
import { DelayedRender } from './DelayedRender'
|
||||
import { CenteredContent } from '@/layout/CenteredContent'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { Center } from '@/styled-system/jsx'
|
||||
|
||||
export const LoadingScreen = ({
|
||||
delay = 500,
|
||||
header = undefined,
|
||||
layout = 'centered',
|
||||
}: {
|
||||
delay?: number
|
||||
} & Omit<ScreenProps, 'children'>) => {
|
||||
const { t } = useTranslation()
|
||||
|
||||
return (
|
||||
<DelayedRender delay={delay}>
|
||||
<Screen layout={layout} header={header}>
|
||||
<CenteredContent>
|
||||
<Center>
|
||||
<p>{t('loading')}</p>
|
||||
</Center>
|
||||
</CenteredContent>
|
||||
</Screen>
|
||||
</DelayedRender>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { CenteredContent } from '@/layout/CenteredContent'
|
||||
import { Screen } from '@/layout/Screen'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
export const NotFoundScreen = () => {
|
||||
const { t } = useTranslation()
|
||||
return (
|
||||
<Screen layout="centered">
|
||||
<CenteredContent title={t('notFound.heading')} withBackButton />
|
||||
</Screen>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { ErrorScreen } from '@/components/ErrorScreen'
|
||||
import { LoadingScreen } from '@/components/LoadingScreen'
|
||||
|
||||
/**
|
||||
* Render an error or loading Screen while a given `status` is not a success,
|
||||
* otherwise directly render children.
|
||||
*
|
||||
* `status` matches react query statuses.
|
||||
*
|
||||
* Children usually contain a Screen at some point in the render tree.
|
||||
*/
|
||||
export const QueryAware = ({
|
||||
status,
|
||||
children,
|
||||
}: {
|
||||
status: 'error' | 'idle' | 'pending' | 'success'
|
||||
children: React.ReactNode
|
||||
}) => {
|
||||
if (status === 'error') {
|
||||
return <ErrorScreen />
|
||||
}
|
||||
|
||||
if (status === 'pending') {
|
||||
return <LoadingScreen header={undefined} />
|
||||
}
|
||||
|
||||
return children
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { Button } from '@/primitives'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useMediaDeviceSelect } from '@livekit/components-react'
|
||||
|
||||
export const SoundTester = () => {
|
||||
const { t } = useTranslation('settings')
|
||||
const [isPlaying, setIsPlaying] = useState(false)
|
||||
const audioRef = useRef<HTMLAudioElement>(null)
|
||||
|
||||
const { activeDeviceId } = useMediaDeviceSelect({ kind: 'audiooutput' })
|
||||
|
||||
useEffect(() => {
|
||||
const updateActiveId = async (deviceId: string) => {
|
||||
try {
|
||||
await audioRef?.current?.setSinkId(deviceId)
|
||||
} catch (error) {
|
||||
console.error(`Error setting sinkId: ${error}`)
|
||||
}
|
||||
}
|
||||
updateActiveId(activeDeviceId)
|
||||
}, [activeDeviceId])
|
||||
|
||||
// prevent pausing the sound
|
||||
navigator.mediaSession.setActionHandler('pause', function () {})
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
onPress={() => {
|
||||
audioRef?.current?.play()
|
||||
setIsPlaying(true)
|
||||
}}
|
||||
size="sm"
|
||||
isDisabled={isPlaying}
|
||||
>
|
||||
{isPlaying ? t('audio.speakers.ongoingTest') : t('audio.speakers.test')}
|
||||
</Button>
|
||||
{/* eslint-disable jsx-a11y/media-has-caption */}
|
||||
<audio
|
||||
ref={audioRef}
|
||||
src="sounds/uprise.mp3"
|
||||
onEnded={() => setIsPlaying(false)}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -12,6 +12,7 @@ export const useUser = () => {
|
||||
const query = useQuery({
|
||||
queryKey: [keys.user],
|
||||
queryFn: fetchUser,
|
||||
staleTime: 1000 * 60 * 60, // 1 hour
|
||||
})
|
||||
|
||||
const isLoggedIn =
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
import { type ReactNode } from 'react'
|
||||
import { useUser } from '@/features/auth'
|
||||
import { LoadingScreen } from '@/layout/LoadingScreen'
|
||||
|
||||
/**
|
||||
* wrapper that renders children only when user info has been actually fetched
|
||||
*
|
||||
* this is helpful to prevent flash of logged-out content for a few milliseconds when user is actually logged in
|
||||
*/
|
||||
export const RenderIfUserFetched = ({ children }: { children: ReactNode }) => {
|
||||
const { isLoggedIn } = useUser()
|
||||
return isLoggedIn !== undefined ? (
|
||||
children
|
||||
) : (
|
||||
<LoadingScreen renderTimeout={1000} />
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { useUser } from '@/features/auth'
|
||||
import { LoadingScreen } from '@/components/LoadingScreen'
|
||||
|
||||
/**
|
||||
* Renders a loading Screen while user info has not been fetched yet,
|
||||
* otherwise directly render children.
|
||||
*
|
||||
* Children usually contain a Screen at some point in the render tree.
|
||||
*
|
||||
* This is helpful to prevent flash of logged-out content for a few milliseconds when user is actually logged in
|
||||
*/
|
||||
export const UserAware = ({ children }: { children: React.ReactNode }) => {
|
||||
const { isLoggedIn } = useUser()
|
||||
|
||||
return isLoggedIn !== undefined ? (
|
||||
children
|
||||
) : (
|
||||
<LoadingScreen header={false} delay={1000} />
|
||||
)
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
export { useUser } from './api/useUser'
|
||||
export { authUrl } from './utils/authUrl'
|
||||
export { logoutUrl } from './utils/logoutUrl'
|
||||
export { RenderIfUserFetched } from './components/RenderIfUserFetched'
|
||||
export { UserAware } from './components/UserAware'
|
||||
|
||||
@@ -4,5 +4,7 @@ export const authUrl = ({
|
||||
silent = false,
|
||||
returnTo = window.location.href,
|
||||
} = {}) => {
|
||||
return apiUrl(`/authenticate?silent=${encodeURIComponent(silent)}&returnTo=${encodeURIComponent(returnTo)}`)
|
||||
return apiUrl(
|
||||
`/authenticate?silent=${encodeURIComponent(silent)}&returnTo=${encodeURIComponent(returnTo)}`
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,20 +1,20 @@
|
||||
import { authUrl } from "@/features/auth";
|
||||
import { authUrl } from '@/features/auth'
|
||||
|
||||
const SILENT_LOGIN_RETRY_KEY = 'silent-login-retry'
|
||||
|
||||
const isRetryAllowed = () => {
|
||||
const lastRetryDate = localStorage.getItem(SILENT_LOGIN_RETRY_KEY);
|
||||
const lastRetryDate = localStorage.getItem(SILENT_LOGIN_RETRY_KEY)
|
||||
if (!lastRetryDate) {
|
||||
return true;
|
||||
return true
|
||||
}
|
||||
const now = new Date();
|
||||
const now = new Date()
|
||||
return now.getTime() > Number(lastRetryDate)
|
||||
}
|
||||
|
||||
const setNextRetryTime = (retryIntervalInSeconds: number) => {
|
||||
const now = new Date()
|
||||
const nextRetryTime = now.getTime() + (retryIntervalInSeconds * 1000);
|
||||
localStorage.setItem(SILENT_LOGIN_RETRY_KEY, String(nextRetryTime));
|
||||
const nextRetryTime = now.getTime() + retryIntervalInSeconds * 1000
|
||||
localStorage.setItem(SILENT_LOGIN_RETRY_KEY, String(nextRetryTime))
|
||||
}
|
||||
|
||||
const initiateSilentLogin = () => {
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { getRouteUrl } from '@/navigation/getRouteUrl'
|
||||
import { Div, Button, Dialog, Input, type DialogProps, P } from '@/primitives'
|
||||
import { HStack } from '@/styled-system/jsx'
|
||||
|
||||
// fixme - duplication with the InviteDialog
|
||||
export const LaterMeetingDialog = ({
|
||||
roomId,
|
||||
...dialogProps
|
||||
}: { roomId: string } & Omit<DialogProps, 'title'>) => {
|
||||
const { t } = useTranslation('home')
|
||||
const roomUrl = getRouteUrl('room', roomId)
|
||||
const copyLabel = t('laterMeetingDialog.copy')
|
||||
const copiedLabel = t('laterMeetingDialog.copied')
|
||||
const [copyLinkLabel, setCopyLinkLabel] = useState(copyLabel)
|
||||
useEffect(() => {
|
||||
if (copyLinkLabel == copiedLabel) {
|
||||
const timeout = setTimeout(() => {
|
||||
setCopyLinkLabel(copyLabel)
|
||||
}, 5000)
|
||||
return () => {
|
||||
clearTimeout(timeout)
|
||||
}
|
||||
}
|
||||
}, [copyLinkLabel, copyLabel, copiedLabel])
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
isOpen={!!roomId}
|
||||
{...dialogProps}
|
||||
title={t('laterMeetingDialog.heading')}
|
||||
>
|
||||
<P>{t('laterMeetingDialog.description')}</P>
|
||||
<HStack alignItems="stretch" gap="gutter">
|
||||
<Div flex="1">
|
||||
<Input
|
||||
type="text"
|
||||
aria-label={t('laterMeetingDialog.inputLabel')}
|
||||
value={roomUrl}
|
||||
readOnly
|
||||
onClick={(e) => {
|
||||
e.currentTarget.select()
|
||||
}}
|
||||
/>
|
||||
</Div>
|
||||
<Div minWidth="8rem">
|
||||
<Button
|
||||
variant="primary"
|
||||
size="sm"
|
||||
fullWidth
|
||||
onPress={() => {
|
||||
navigator.clipboard.writeText(roomUrl)
|
||||
setCopyLinkLabel(copiedLabel)
|
||||
}}
|
||||
>
|
||||
{copyLinkLabel}
|
||||
</Button>
|
||||
</Div>
|
||||
</HStack>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -1,20 +1,38 @@
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { DialogTrigger } from 'react-aria-components'
|
||||
import { Button, Div, Text, VerticallyOffCenter } from '@/primitives'
|
||||
import { Button, Menu, Text } from '@/primitives'
|
||||
import { HStack } from '@/styled-system/jsx'
|
||||
import { navigateTo } from '@/navigation/navigateTo'
|
||||
import { generateRoomId } from '@/features/rooms'
|
||||
import { authUrl, useUser } from '@/features/auth'
|
||||
import { Screen } from '@/layout/Screen'
|
||||
import { Centered } from '@/layout/Centered'
|
||||
import { generateRoomId } from '@/features/rooms'
|
||||
import { authUrl, useUser, UserAware } from '@/features/auth'
|
||||
import { JoinMeetingDialog } from '../components/JoinMeetingDialog'
|
||||
import { useCreateRoom } from '@/features/rooms'
|
||||
import { usePersistentUserChoices } from '@livekit/components-react'
|
||||
import { menuItemRecipe } from '@/primitives/menuItemRecipe'
|
||||
import { RiAddLine, RiLink } from '@remixicon/react'
|
||||
import { MenuItem, Menu as RACMenu } from 'react-aria-components'
|
||||
import { LaterMeetingDialog } from '@/features/home/components/LaterMeetingDialog'
|
||||
import { useState } from 'react'
|
||||
|
||||
export const Home = () => {
|
||||
const { t } = useTranslation('home')
|
||||
const { isLoggedIn } = useUser()
|
||||
|
||||
const {
|
||||
userChoices: { username },
|
||||
} = usePersistentUserChoices()
|
||||
|
||||
const { mutateAsync: createRoom } = useCreateRoom()
|
||||
const [laterRoomId, setLaterRoomId] = useState<null | string>(null)
|
||||
|
||||
console.log(laterRoomId)
|
||||
|
||||
return (
|
||||
<Screen>
|
||||
<VerticallyOffCenter>
|
||||
<Div margin="auto" width="fit-content">
|
||||
<UserAware>
|
||||
<Screen>
|
||||
<Centered width="fit-content">
|
||||
<Text as="h1" variant="display">
|
||||
{t('heading')}
|
||||
</Text>
|
||||
@@ -27,21 +45,43 @@ export const Home = () => {
|
||||
</Text>
|
||||
)}
|
||||
<HStack gap="gutter">
|
||||
<Button
|
||||
variant="primary"
|
||||
onPress={
|
||||
isLoggedIn
|
||||
? () =>
|
||||
navigateTo('room', generateRoomId(), {
|
||||
state: { create: true },
|
||||
})
|
||||
: undefined
|
||||
}
|
||||
href={isLoggedIn ? undefined : authUrl()}
|
||||
>
|
||||
{isLoggedIn ? t('createMeeting') : t('login', { ns: 'global' })}
|
||||
</Button>
|
||||
|
||||
{isLoggedIn ? (
|
||||
<Menu>
|
||||
<Button variant="primary">{t('createMeeting')}</Button>
|
||||
<RACMenu>
|
||||
<MenuItem
|
||||
className={menuItemRecipe({ icon: true })}
|
||||
onAction={async () => {
|
||||
const slug = generateRoomId()
|
||||
createRoom({ slug, username }).then((data) =>
|
||||
navigateTo('room', data.slug, {
|
||||
state: { create: true, initialRoomData: data },
|
||||
})
|
||||
)
|
||||
}}
|
||||
>
|
||||
<RiAddLine size={18} />
|
||||
{t('createMenu.instantOption')}
|
||||
</MenuItem>
|
||||
<MenuItem
|
||||
className={menuItemRecipe({ icon: true })}
|
||||
onAction={() => {
|
||||
const slug = generateRoomId()
|
||||
createRoom({ slug, username }).then((data) =>
|
||||
setLaterRoomId(data.slug)
|
||||
)
|
||||
}}
|
||||
>
|
||||
<RiLink size={18} />
|
||||
{t('createMenu.laterOption')}
|
||||
</MenuItem>
|
||||
</RACMenu>
|
||||
</Menu>
|
||||
) : (
|
||||
<Button variant="primary" href={authUrl()}>
|
||||
{t('login', { ns: 'global' })}
|
||||
</Button>
|
||||
)}
|
||||
<DialogTrigger>
|
||||
<Button variant="primary" outline>
|
||||
{t('joinMeeting')}
|
||||
@@ -49,8 +89,12 @@ export const Home = () => {
|
||||
<JoinMeetingDialog />
|
||||
</DialogTrigger>
|
||||
</HStack>
|
||||
</Div>
|
||||
</VerticallyOffCenter>
|
||||
</Screen>
|
||||
</Centered>
|
||||
<LaterMeetingDialog
|
||||
roomId={laterRoomId || ''}
|
||||
onOpenChange={() => setLaterRoomId(null)}
|
||||
/>
|
||||
</Screen>
|
||||
</UserAware>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -8,4 +8,7 @@ export type ApiRoom = {
|
||||
room: string
|
||||
token: string
|
||||
}
|
||||
configuration?: {
|
||||
[key: string]: string | number | boolean
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { useMutation, UseMutationOptions } from '@tanstack/react-query'
|
||||
import { fetchApi } from '@/api/fetchApi'
|
||||
import { ApiError } from '@/api/ApiError'
|
||||
import { ApiRoom } from './ApiRoom'
|
||||
|
||||
export interface CreateRoomParams {
|
||||
slug: string
|
||||
username?: string
|
||||
}
|
||||
|
||||
const createRoom = ({
|
||||
slug,
|
||||
username = '',
|
||||
}: CreateRoomParams): Promise<ApiRoom> => {
|
||||
return fetchApi(`rooms/?username=${encodeURIComponent(username)}`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
name: slug,
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
export function useCreateRoom(
|
||||
options?: UseMutationOptions<ApiRoom, ApiError, CreateRoomParams>
|
||||
) {
|
||||
return useMutation<ApiRoom, ApiError, CreateRoomParams>({
|
||||
mutationFn: createRoom,
|
||||
onSuccess: options?.onSuccess,
|
||||
})
|
||||
}
|
||||
@@ -1,33 +1,67 @@
|
||||
import { useMemo, useState } from 'react'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import {
|
||||
formatChatMessageLinks,
|
||||
LiveKitRoom,
|
||||
VideoConference,
|
||||
type LocalUserChoices,
|
||||
} from '@livekit/components-react'
|
||||
import { Room, RoomOptions } from 'livekit-client'
|
||||
import { keys } from '@/api/queryKeys'
|
||||
import { queryClient } from '@/api/queryClient'
|
||||
import { navigateTo } from '@/navigation/navigateTo'
|
||||
import { QueryAware } from '@/layout/QueryAware'
|
||||
import { Screen } from '@/layout/Screen'
|
||||
import { QueryAware } from '@/components/QueryAware'
|
||||
import { ErrorScreen } from '@/components/ErrorScreen'
|
||||
import { fetchRoom } from '../api/fetchRoom'
|
||||
import { ApiRoom } from '../api/ApiRoom'
|
||||
import { useCreateRoom } from '../api/createRoom'
|
||||
import { InviteDialog } from './InviteDialog'
|
||||
|
||||
import { VideoConference } from '../livekit/prefabs/VideoConference'
|
||||
|
||||
export const Conference = ({
|
||||
roomId,
|
||||
userConfig,
|
||||
initialRoomData,
|
||||
mode = 'join',
|
||||
}: {
|
||||
roomId: string
|
||||
userConfig: LocalUserChoices
|
||||
mode?: 'join' | 'create'
|
||||
initialRoomData?: ApiRoom
|
||||
}) => {
|
||||
const { status, data } = useQuery({
|
||||
queryKey: [keys.room, roomId, userConfig.username],
|
||||
const fetchKey = [keys.room, roomId, userConfig.username]
|
||||
|
||||
const {
|
||||
mutateAsync: createRoom,
|
||||
status: createStatus,
|
||||
isError: isCreateError,
|
||||
} = useCreateRoom({
|
||||
onSuccess: (data) => {
|
||||
queryClient.setQueryData(fetchKey, data)
|
||||
},
|
||||
})
|
||||
|
||||
const {
|
||||
status: fetchStatus,
|
||||
isError: isFetchError,
|
||||
data,
|
||||
} = useQuery({
|
||||
queryKey: fetchKey,
|
||||
staleTime: 6 * 60 * 60 * 1000, // By default, LiveKit access tokens expire 6 hours after generation
|
||||
enabled: !initialRoomData,
|
||||
initialData: initialRoomData,
|
||||
queryFn: () =>
|
||||
fetchRoom({
|
||||
roomId: roomId as string,
|
||||
username: userConfig.username,
|
||||
}).catch((error) => {
|
||||
if (error.statusCode == '404') {
|
||||
createRoom({ slug: roomId, username: userConfig.username })
|
||||
}
|
||||
}),
|
||||
retry: false,
|
||||
})
|
||||
|
||||
const roomOptions = useMemo((): RoomOptions => {
|
||||
@@ -46,29 +80,58 @@ export const Conference = ({
|
||||
|
||||
const [showInviteDialog, setShowInviteDialog] = useState(mode === 'create')
|
||||
|
||||
/**
|
||||
* checks for actual click on the leave button instead of
|
||||
* relying on LiveKitRoom onDisconnected because onDisconnected
|
||||
* triggers even on page reload, it's not a user "onLeave" event really.
|
||||
* Here we want to react to the user actually deciding to leave.
|
||||
*/
|
||||
useEffect(() => {
|
||||
const checkOnLeaveClick = (event: MouseEvent) => {
|
||||
const target = event.target as HTMLElement
|
||||
if (target.classList.contains('lk-disconnect-button')) {
|
||||
navigateTo('feedback')
|
||||
}
|
||||
}
|
||||
document.body.addEventListener('click', checkOnLeaveClick)
|
||||
return () => {
|
||||
document.body.removeEventListener('click', checkOnLeaveClick)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const { t } = useTranslation('rooms')
|
||||
if (isCreateError) {
|
||||
// this error screen should be replaced by a proper waiting room for anonymous user.
|
||||
return (
|
||||
<ErrorScreen
|
||||
title={t('error.createRoom.heading')}
|
||||
body={t('error.createRoom.body')}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<QueryAware status={status}>
|
||||
<LiveKitRoom
|
||||
room={room}
|
||||
serverUrl={data?.livekit?.url}
|
||||
token={data?.livekit?.token}
|
||||
connect={true}
|
||||
audio={userConfig.audioEnabled}
|
||||
video={userConfig.videoEnabled}
|
||||
onDisconnected={() => {
|
||||
navigateTo('feedback')
|
||||
}}
|
||||
>
|
||||
<VideoConference />
|
||||
{showInviteDialog && (
|
||||
<InviteDialog
|
||||
isOpen={showInviteDialog}
|
||||
onOpenChange={setShowInviteDialog}
|
||||
roomId={roomId}
|
||||
onClose={() => setShowInviteDialog(false)}
|
||||
/>
|
||||
)}
|
||||
</LiveKitRoom>
|
||||
<QueryAware status={isFetchError ? createStatus : fetchStatus}>
|
||||
<Screen header={false}>
|
||||
<LiveKitRoom
|
||||
room={room}
|
||||
serverUrl={data?.livekit?.url}
|
||||
token={data?.livekit?.token}
|
||||
connect={true}
|
||||
audio={userConfig.audioEnabled}
|
||||
video={userConfig.videoEnabled}
|
||||
>
|
||||
<VideoConference chatMessageFormatter={formatChatMessageLinks} />
|
||||
{showInviteDialog && (
|
||||
<InviteDialog
|
||||
isOpen={showInviteDialog}
|
||||
onOpenChange={setShowInviteDialog}
|
||||
roomId={roomId}
|
||||
onClose={() => setShowInviteDialog(false)}
|
||||
/>
|
||||
)}
|
||||
</LiveKitRoom>
|
||||
</Screen>
|
||||
</QueryAware>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { Box } from '@/layout/Box'
|
||||
import { PreJoin, type LocalUserChoices } from '@livekit/components-react'
|
||||
import { Screen } from '@/layout/Screen'
|
||||
import { CenteredContent } from '@/layout/CenteredContent'
|
||||
|
||||
export const Join = ({
|
||||
onSubmit,
|
||||
@@ -10,15 +11,17 @@ export const Join = ({
|
||||
const { t } = useTranslation('rooms')
|
||||
|
||||
return (
|
||||
<Box title={t('join.heading')} withBackButton>
|
||||
<PreJoin
|
||||
persistUserChoices
|
||||
onSubmit={onSubmit}
|
||||
micLabel={t('join.micLabel')}
|
||||
camLabel={t('join.camlabel')}
|
||||
joinLabel={t('join.joinLabel')}
|
||||
userLabel={t('join.userLabel')}
|
||||
/>
|
||||
</Box>
|
||||
<Screen layout="centered">
|
||||
<CenteredContent title={t('join.heading')}>
|
||||
<PreJoin
|
||||
persistUserChoices
|
||||
onSubmit={onSubmit}
|
||||
micLabel={t('join.micLabel')}
|
||||
camLabel={t('join.camlabel')}
|
||||
joinLabel={t('join.joinLabel')}
|
||||
userLabel={t('join.userLabel')}
|
||||
/>
|
||||
</CenteredContent>
|
||||
</Screen>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2,3 +2,4 @@ export { Room as RoomRoute } from './routes/Room'
|
||||
export { FeedbackRoute } from './routes/Feedback'
|
||||
export { roomIdPattern, isRoomValid } from './utils/isRoomValid'
|
||||
export { generateRoomId } from './utils/generateRoomId'
|
||||
export { useCreateRoom } from './api/createRoom'
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
import { ParticipantTile } from './ParticipantTile'
|
||||
import { FocusLayoutProps } from '@livekit/components-react'
|
||||
|
||||
export function FocusLayout({ trackRef, ...htmlProps }: FocusLayoutProps) {
|
||||
return <ParticipantTile trackRef={trackRef} {...htmlProps} />
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { Participant } from 'livekit-client'
|
||||
import { styled } from '@/styled-system/jsx'
|
||||
import { Avatar } from '@/components/Avatar'
|
||||
import { useIsSpeaking } from '@livekit/components-react'
|
||||
import { getParticipantColor } from '@/features/rooms/utils/getParticipantColor'
|
||||
import { useSize } from '@/features/rooms/livekit/hooks/useResizeObserver'
|
||||
import { useMemo, useRef } from 'react'
|
||||
|
||||
const StyledParticipantPlaceHolder = styled('div', {
|
||||
base: {
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
backgroundColor: '#3d4043', // fixme - copied from gmeet
|
||||
display: 'flex',
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
},
|
||||
})
|
||||
|
||||
type ParticipantPlaceholderProps = {
|
||||
participant: Participant
|
||||
}
|
||||
|
||||
export const ParticipantPlaceholder = ({
|
||||
participant,
|
||||
}: ParticipantPlaceholderProps) => {
|
||||
const isSpeaking = useIsSpeaking(participant)
|
||||
const participantColor = getParticipantColor(participant)
|
||||
|
||||
const placeholderEl = useRef<HTMLDivElement>(null)
|
||||
const { width, height } = useSize(placeholderEl)
|
||||
|
||||
const minDimension = Math.min(width, height)
|
||||
const avatarSize = useMemo(
|
||||
() => Math.min(Math.round(minDimension * 0.9), 160),
|
||||
[minDimension]
|
||||
)
|
||||
|
||||
const initialSize = useMemo(() => Math.round(avatarSize * 0.3), [avatarSize])
|
||||
|
||||
return (
|
||||
<StyledParticipantPlaceHolder ref={placeholderEl}>
|
||||
<div
|
||||
style={{
|
||||
borderRadius: '50%',
|
||||
animation: isSpeaking ? 'pulse 1s infinite' : undefined,
|
||||
height: 'auto',
|
||||
aspectRatio: '1/1',
|
||||
width: '80%',
|
||||
maxWidth: `${avatarSize}px`,
|
||||
fontSize: `${initialSize}px`,
|
||||
}}
|
||||
>
|
||||
{/*fixme - participant doesn't update on ParticipantNameChanged event */}
|
||||
<Avatar
|
||||
name={participant.name}
|
||||
bgColor={participantColor}
|
||||
context="placeholder"
|
||||
/>
|
||||
</div>
|
||||
</StyledParticipantPlaceHolder>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import {
|
||||
AudioTrack,
|
||||
ConnectionQualityIndicator,
|
||||
FocusToggle,
|
||||
LockLockedIcon,
|
||||
ParticipantName,
|
||||
ParticipantTileProps,
|
||||
ScreenShareIcon,
|
||||
TrackMutedIndicator,
|
||||
useEnsureTrackRef,
|
||||
useFeatureContext,
|
||||
useIsEncrypted,
|
||||
useMaybeLayoutContext,
|
||||
useMaybeTrackRefContext,
|
||||
useParticipantTile,
|
||||
VideoTrack,
|
||||
TrackRefContext,
|
||||
ParticipantContextIfNeeded,
|
||||
} from '@livekit/components-react'
|
||||
import React from 'react'
|
||||
import {
|
||||
isTrackReference,
|
||||
isTrackReferencePinned,
|
||||
TrackReferenceOrPlaceholder,
|
||||
} from '@livekit/components-core'
|
||||
import { Track } from 'livekit-client'
|
||||
import { ParticipantPlaceholder } from '@/features/rooms/livekit/components/ParticipantPlaceholder'
|
||||
|
||||
export function TrackRefContextIfNeeded(
|
||||
props: React.PropsWithChildren<{
|
||||
trackRef?: TrackReferenceOrPlaceholder
|
||||
}>
|
||||
) {
|
||||
const hasContext = !!useMaybeTrackRefContext()
|
||||
return props.trackRef && !hasContext ? (
|
||||
<TrackRefContext.Provider value={props.trackRef}>
|
||||
{props.children}
|
||||
</TrackRefContext.Provider>
|
||||
) : (
|
||||
<>{props.children}</>
|
||||
)
|
||||
}
|
||||
|
||||
export const ParticipantTile: (
|
||||
props: ParticipantTileProps & React.RefAttributes<HTMLDivElement>
|
||||
) => React.ReactNode = /* @__PURE__ */ React.forwardRef<
|
||||
HTMLDivElement,
|
||||
ParticipantTileProps
|
||||
>(function ParticipantTile(
|
||||
{
|
||||
trackRef,
|
||||
children,
|
||||
onParticipantClick,
|
||||
disableSpeakingIndicator,
|
||||
...htmlProps
|
||||
}: ParticipantTileProps,
|
||||
ref
|
||||
) {
|
||||
const trackReference = useEnsureTrackRef(trackRef)
|
||||
|
||||
const { elementProps } = useParticipantTile<HTMLDivElement>({
|
||||
htmlProps,
|
||||
disableSpeakingIndicator,
|
||||
onParticipantClick,
|
||||
trackRef: trackReference,
|
||||
})
|
||||
const isEncrypted = useIsEncrypted(trackReference.participant)
|
||||
const layoutContext = useMaybeLayoutContext()
|
||||
|
||||
const autoManageSubscription = useFeatureContext()?.autoSubscription
|
||||
|
||||
const handleSubscribe = React.useCallback(
|
||||
(subscribed: boolean) => {
|
||||
if (
|
||||
trackReference.source &&
|
||||
!subscribed &&
|
||||
layoutContext &&
|
||||
layoutContext.pin.dispatch &&
|
||||
isTrackReferencePinned(trackReference, layoutContext.pin.state)
|
||||
) {
|
||||
layoutContext.pin.dispatch({ msg: 'clear_pin' })
|
||||
}
|
||||
},
|
||||
[trackReference, layoutContext]
|
||||
)
|
||||
|
||||
return (
|
||||
<div ref={ref} style={{ position: 'relative' }} {...elementProps}>
|
||||
<TrackRefContextIfNeeded trackRef={trackReference}>
|
||||
<ParticipantContextIfNeeded participant={trackReference.participant}>
|
||||
{children ?? (
|
||||
<>
|
||||
{isTrackReference(trackReference) &&
|
||||
(trackReference.publication?.kind === 'video' ||
|
||||
trackReference.source === Track.Source.Camera ||
|
||||
trackReference.source === Track.Source.ScreenShare) ? (
|
||||
<VideoTrack
|
||||
trackRef={trackReference}
|
||||
onSubscriptionStatusChanged={handleSubscribe}
|
||||
manageSubscription={autoManageSubscription}
|
||||
/>
|
||||
) : (
|
||||
isTrackReference(trackReference) && (
|
||||
<AudioTrack
|
||||
trackRef={trackReference}
|
||||
onSubscriptionStatusChanged={handleSubscribe}
|
||||
/>
|
||||
)
|
||||
)}
|
||||
<div className="lk-participant-placeholder">
|
||||
<ParticipantPlaceholder
|
||||
participant={trackReference.participant}
|
||||
/>
|
||||
</div>
|
||||
<div className="lk-participant-metadata">
|
||||
<div className="lk-participant-metadata-item">
|
||||
{trackReference.source === Track.Source.Camera ? (
|
||||
<>
|
||||
{isEncrypted && (
|
||||
<LockLockedIcon style={{ marginRight: '0.25rem' }} />
|
||||
)}
|
||||
<TrackMutedIndicator
|
||||
trackRef={{
|
||||
participant: trackReference.participant,
|
||||
source: Track.Source.Microphone,
|
||||
}}
|
||||
show={'muted'}
|
||||
></TrackMutedIndicator>
|
||||
<ParticipantName />
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<ScreenShareIcon style={{ marginRight: '0.25rem' }} />
|
||||
<ParticipantName>'s screen</ParticipantName>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<ConnectionQualityIndicator className="lk-participant-metadata-item" />
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<FocusToggle trackRef={trackReference} />
|
||||
</ParticipantContextIfNeeded>
|
||||
</TrackRefContextIfNeeded>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,55 @@
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { RiChat1Line } from '@remixicon/react'
|
||||
import { ToggleButton } from '@/primitives'
|
||||
import { css } from '@/styled-system/css'
|
||||
import { useLayoutContext } from '@livekit/components-react'
|
||||
import { useSnapshot } from 'valtio'
|
||||
import { participantsStore } from '@/stores/participants'
|
||||
|
||||
export const ChatToggle = () => {
|
||||
const { t } = useTranslation('rooms')
|
||||
|
||||
const { dispatch, state } = useLayoutContext().widget
|
||||
const tooltipLabel = state?.showChat ? 'open' : 'closed'
|
||||
|
||||
const participantsSnap = useSnapshot(participantsStore)
|
||||
const showParticipants = participantsSnap.showParticipants
|
||||
|
||||
return (
|
||||
<div
|
||||
className={css({
|
||||
position: 'relative',
|
||||
display: 'inline-block',
|
||||
})}
|
||||
>
|
||||
<ToggleButton
|
||||
square
|
||||
legacyStyle
|
||||
aria-label={t(`controls.chat.${tooltipLabel}`)}
|
||||
tooltip={t(`controls.chat.${tooltipLabel}`)}
|
||||
isSelected={state?.showChat}
|
||||
onPress={() => {
|
||||
if (showParticipants) participantsStore.showParticipants = false
|
||||
if (dispatch) dispatch({ msg: 'toggle_chat' })
|
||||
}}
|
||||
>
|
||||
<RiChat1Line />
|
||||
</ToggleButton>
|
||||
{!!state?.unreadMessages && (
|
||||
<div
|
||||
className={css({
|
||||
position: 'absolute',
|
||||
top: '-.25rem',
|
||||
right: '-.25rem',
|
||||
width: '1rem',
|
||||
height: '1rem',
|
||||
backgroundColor: 'red',
|
||||
borderRadius: '50%',
|
||||
zIndex: 1,
|
||||
border: '2px solid #d1d5db',
|
||||
})}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { RiMore2Line } from '@remixicon/react'
|
||||
import { Button, Menu } from '@/primitives'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { OptionsMenuItems } from '@/features/rooms/livekit/components/controls/Options/OptionsMenuItems'
|
||||
import { SettingsDialogExtended } from '@/features/settings/components/SettingsDialogExtended'
|
||||
|
||||
export type DialogState = 'username' | 'settings' | null
|
||||
|
||||
export const OptionsButton = () => {
|
||||
const { t } = useTranslation('rooms')
|
||||
const [dialogOpen, setDialogOpen] = useState<DialogState>(null)
|
||||
return (
|
||||
<>
|
||||
<Menu>
|
||||
<Button
|
||||
square
|
||||
legacyStyle
|
||||
aria-label={t('options.buttonLabel')}
|
||||
tooltip={t('options.buttonLabel')}
|
||||
>
|
||||
<RiMore2Line />
|
||||
</Button>
|
||||
<OptionsMenuItems onOpenDialog={setDialogOpen} />
|
||||
</Menu>
|
||||
<SettingsDialogExtended
|
||||
isOpen={dialogOpen === 'settings'}
|
||||
onOpenChange={(v) => !v && setDialogOpen(null)}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
import { menuItemRecipe } from '@/primitives/menuItemRecipe'
|
||||
import {
|
||||
RiFeedbackLine,
|
||||
RiQuestionLine,
|
||||
RiSettings3Line,
|
||||
} from '@remixicon/react'
|
||||
import { MenuItem, Menu as RACMenu } from 'react-aria-components'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { Dispatch, SetStateAction } from 'react'
|
||||
import { DialogState } from '@/features/rooms/livekit/components/controls/Options/OptionsButton'
|
||||
|
||||
// @todo try refactoring it to use MenuList component
|
||||
export const OptionsMenuItems = ({
|
||||
onOpenDialog,
|
||||
}: {
|
||||
onOpenDialog: Dispatch<SetStateAction<DialogState>>
|
||||
}) => {
|
||||
const { t } = useTranslation('rooms')
|
||||
|
||||
return (
|
||||
<RACMenu
|
||||
style={{
|
||||
minWidth: '150px',
|
||||
width: '300px',
|
||||
}}
|
||||
>
|
||||
<MenuItem
|
||||
href="https://tchap.gouv.fr/#/room/!aGImQayAgBLjSBycpm:agent.dinum.tchap.gouv.fr?via=agent.dinum.tchap.gouv.fr"
|
||||
target="_blank"
|
||||
className={menuItemRecipe({ icon: true })}
|
||||
>
|
||||
<RiQuestionLine size={18} />
|
||||
{t('options.items.support')}
|
||||
</MenuItem>
|
||||
<MenuItem
|
||||
href="https://grist.incubateur.net/o/docs/forms/1YrfNP1QSSy8p2gCxMFnSf/4"
|
||||
target="_blank"
|
||||
className={menuItemRecipe({ icon: true })}
|
||||
>
|
||||
<RiFeedbackLine size={18} />
|
||||
{t('options.items.feedbacks')}
|
||||
</MenuItem>
|
||||
<MenuItem
|
||||
className={menuItemRecipe({ icon: true })}
|
||||
onAction={() => onOpenDialog('settings')}
|
||||
>
|
||||
<RiSettings3Line size={18} />
|
||||
{t('options.items.settings')}
|
||||
</MenuItem>
|
||||
</RACMenu>
|
||||
)
|
||||
}
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
import { css } from '@/styled-system/css'
|
||||
import { useParticipants } from '@livekit/components-react'
|
||||
|
||||
import { Heading } from 'react-aria-components'
|
||||
import { Box, Button, Div } from '@/primitives'
|
||||
import { HStack, VStack } from '@/styled-system/jsx'
|
||||
import { Text, text } from '@/primitives/Text'
|
||||
import { RiCloseLine } from '@remixicon/react'
|
||||
import { capitalize } from '@/utils/capitalize'
|
||||
import { participantsStore } from '@/stores/participants'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { allParticipantRoomEvents } from '@/features/rooms/livekit/constants/events'
|
||||
import { Avatar } from '@/components/Avatar'
|
||||
import { getParticipantColor } from '@/features/rooms/utils/getParticipantColor'
|
||||
|
||||
// TODO: Optimize rendering performance, especially for longer participant lists, even though they are generally short.
|
||||
export const ParticipantsList = () => {
|
||||
const { t } = useTranslation('rooms')
|
||||
|
||||
// Preferred using the 'useParticipants' hook rather than the separate remote and local hooks,
|
||||
// because the 'useLocalParticipant' hook does not update the participant's information when their
|
||||
// metadata/name changes. The LiveKit team has marked this as a TODO item in the code.
|
||||
const participants = useParticipants({
|
||||
updateOnlyOn: allParticipantRoomEvents,
|
||||
})
|
||||
|
||||
const formattedParticipants = participants.map((participant) => ({
|
||||
name: participant.name || participant.identity,
|
||||
id: participant.identity,
|
||||
color: getParticipantColor(participant),
|
||||
}))
|
||||
|
||||
const sortedRemoteParticipants = formattedParticipants
|
||||
.slice(1)
|
||||
.sort((a, b) => a.name.localeCompare(b.name))
|
||||
|
||||
const allParticipants = [
|
||||
formattedParticipants[0], // first participant returned by the hook, is always the local one
|
||||
...sortedRemoteParticipants,
|
||||
]
|
||||
|
||||
// TODO - extract inline styling in a centralized styling file, and avoid magic numbers
|
||||
return (
|
||||
<Box
|
||||
size="sm"
|
||||
minWidth="300px"
|
||||
className={css({
|
||||
overflow: 'hidden',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
margin: '1.5rem 1.5rem 1.5rem 0',
|
||||
})}
|
||||
>
|
||||
<Heading slot="title" level={3} className={text({ variant: 'h2' })}>
|
||||
<span>{t('participants.heading')}</span>{' '}
|
||||
<span
|
||||
className={css({
|
||||
marginLeft: '0.75rem',
|
||||
fontWeight: 'normal',
|
||||
fontSize: '1rem',
|
||||
})}
|
||||
>
|
||||
{participants?.length}
|
||||
</span>
|
||||
</Heading>
|
||||
<Div position="absolute" top="5" right="5">
|
||||
<Button
|
||||
invisible
|
||||
size="xs"
|
||||
onPress={() => (participantsStore.showParticipants = false)}
|
||||
aria-label={t('participants.closeButton')}
|
||||
tooltip={t('participants.closeButton')}
|
||||
>
|
||||
<RiCloseLine />
|
||||
</Button>
|
||||
</Div>
|
||||
{participants?.length > 0 && (
|
||||
<VStack
|
||||
role="list"
|
||||
className={css({
|
||||
alignItems: 'start',
|
||||
gap: 'none',
|
||||
overflowY: 'scroll',
|
||||
overflowX: 'hidden',
|
||||
minHeight: 0,
|
||||
flexGrow: 1,
|
||||
display: 'flex',
|
||||
})}
|
||||
>
|
||||
{allParticipants.map((participant, index) => (
|
||||
<HStack
|
||||
role="listitem"
|
||||
key={participant.id}
|
||||
id={participant.id}
|
||||
className={css({
|
||||
padding: '0.25rem 0',
|
||||
})}
|
||||
>
|
||||
<Avatar name={participant.name} bgColor={participant.color} />
|
||||
<Text
|
||||
variant={'sm'}
|
||||
className={css({
|
||||
userSelect: 'none',
|
||||
cursor: 'default',
|
||||
display: 'flex',
|
||||
})}
|
||||
>
|
||||
<span
|
||||
className={css({
|
||||
whiteSpace: 'nowrap',
|
||||
overflow: 'hidden',
|
||||
textOverflow: 'ellipsis',
|
||||
maxWidth: '120px',
|
||||
display: 'block',
|
||||
})}
|
||||
>
|
||||
{capitalize(participant.name)}
|
||||
</span>
|
||||
{index === 0 && (
|
||||
<span
|
||||
className={css({
|
||||
marginLeft: '.25rem',
|
||||
whiteSpace: 'nowrap',
|
||||
})}
|
||||
>
|
||||
({t('participants.you')})
|
||||
</span>
|
||||
)}
|
||||
</Text>
|
||||
</HStack>
|
||||
))}
|
||||
</VStack>
|
||||
)}
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { RiGroupLine, RiInfinityLine } from '@remixicon/react'
|
||||
import { ToggleButton } from '@/primitives'
|
||||
import { css } from '@/styled-system/css'
|
||||
import { useLayoutContext, useParticipants } from '@livekit/components-react'
|
||||
import { useSnapshot } from 'valtio'
|
||||
import { participantsStore } from '@/stores/participants'
|
||||
|
||||
export const ParticipantsToggle = () => {
|
||||
const { t } = useTranslation('rooms')
|
||||
|
||||
const { dispatch, state } = useLayoutContext().widget
|
||||
|
||||
/**
|
||||
* Context could not be used due to inconsistent refresh behavior.
|
||||
* The 'numParticipant' property on the room only updates when the room's metadata changes,
|
||||
* resulting in a delay compared to the participant list's actual refresh rate.
|
||||
*/
|
||||
const participants = useParticipants()
|
||||
const numParticipants = participants?.length
|
||||
|
||||
const participantsSnap = useSnapshot(participantsStore)
|
||||
const showParticipants = participantsSnap.showParticipants
|
||||
|
||||
const tooltipLabel = showParticipants ? 'open' : 'closed'
|
||||
|
||||
return (
|
||||
<div
|
||||
className={css({
|
||||
position: 'relative',
|
||||
display: 'inline-block',
|
||||
})}
|
||||
>
|
||||
<ToggleButton
|
||||
square
|
||||
legacyStyle
|
||||
aria-label={t(`controls.participants.${tooltipLabel}`)}
|
||||
tooltip={t(`controls.participants.${tooltipLabel}`)}
|
||||
isSelected={showParticipants}
|
||||
onPress={() => {
|
||||
if (dispatch && state?.showChat) dispatch({ msg: 'toggle_chat' })
|
||||
participantsStore.showParticipants = !showParticipants
|
||||
}}
|
||||
>
|
||||
<RiGroupLine />
|
||||
</ToggleButton>
|
||||
<div
|
||||
className={css({
|
||||
position: 'absolute',
|
||||
top: '-.25rem',
|
||||
right: '-.25rem',
|
||||
width: '1.25rem',
|
||||
height: '1.25rem',
|
||||
backgroundColor: 'gray',
|
||||
borderRadius: '50%',
|
||||
color: 'white',
|
||||
fontSize: '0.75rem',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
textAlign: 'center',
|
||||
zIndex: 1,
|
||||
userSelect: 'none',
|
||||
})}
|
||||
>
|
||||
{numParticipants < 100 ? (
|
||||
numParticipants || 1
|
||||
) : (
|
||||
<RiInfinityLine size={10} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import {
|
||||
useRoomContext,
|
||||
useStartAudio,
|
||||
useStartVideo,
|
||||
} from '@livekit/components-react'
|
||||
import React from 'react'
|
||||
|
||||
/** @public */
|
||||
export interface AllowMediaPlaybackProps
|
||||
extends React.ButtonHTMLAttributes<HTMLButtonElement> {
|
||||
label?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* The `StartMediaButton` component is only visible when the browser blocks media playback. This is due to some browser implemented autoplay policies.
|
||||
* To start media playback, the user must perform a user-initiated event such as clicking this button.
|
||||
* As soon as media playback starts, the button hides itself again.
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* <LiveKitRoom>
|
||||
* <StartMediaButton label="Click to allow media playback" />
|
||||
* </LiveKitRoom>
|
||||
* ```
|
||||
*
|
||||
* @see Autoplay policy on MDN web docs: {@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API/Best_practices#autoplay_policy}
|
||||
* @public
|
||||
*/
|
||||
export const StartMediaButton: (
|
||||
props: AllowMediaPlaybackProps & React.RefAttributes<HTMLButtonElement>
|
||||
) => React.ReactNode = /* @__PURE__ */ React.forwardRef<
|
||||
HTMLButtonElement,
|
||||
AllowMediaPlaybackProps
|
||||
>(function StartMediaButton({ label, ...props }: AllowMediaPlaybackProps, ref) {
|
||||
const room = useRoomContext()
|
||||
const { mergedProps: audioProps, canPlayAudio } = useStartAudio({
|
||||
room,
|
||||
props,
|
||||
})
|
||||
const { mergedProps, canPlayVideo } = useStartVideo({
|
||||
room,
|
||||
props: audioProps,
|
||||
})
|
||||
const { style, ...restProps } = mergedProps
|
||||
style.display = canPlayAudio && canPlayVideo ? 'none' : 'block'
|
||||
|
||||
return (
|
||||
<button ref={ref} style={style} {...restProps}>
|
||||
{label ?? `Start ${!canPlayAudio ? 'Audio' : 'Video'}`}
|
||||
</button>
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,33 @@
|
||||
import { RoomEvent } from 'livekit-client'
|
||||
|
||||
// Issue: 'allRemoteParticipantRoomEvents' is not exposed or importable. One event is missing
|
||||
// to trigger the real-time update of participants when they change their name.
|
||||
// This code is duplicated from LiveKit.
|
||||
export const allRemoteParticipantRoomEvents = [
|
||||
RoomEvent.ConnectionStateChanged,
|
||||
RoomEvent.RoomMetadataChanged,
|
||||
|
||||
RoomEvent.ActiveSpeakersChanged,
|
||||
RoomEvent.ConnectionQualityChanged,
|
||||
|
||||
RoomEvent.ParticipantConnected,
|
||||
RoomEvent.ParticipantDisconnected,
|
||||
RoomEvent.ParticipantPermissionsChanged,
|
||||
RoomEvent.ParticipantMetadataChanged,
|
||||
RoomEvent.ParticipantNameChanged, // This element is missing in LiveKit and causes problems
|
||||
|
||||
RoomEvent.TrackMuted,
|
||||
RoomEvent.TrackUnmuted,
|
||||
RoomEvent.TrackPublished,
|
||||
RoomEvent.TrackUnpublished,
|
||||
RoomEvent.TrackStreamStateChanged,
|
||||
RoomEvent.TrackSubscriptionFailed,
|
||||
RoomEvent.TrackSubscriptionPermissionChanged,
|
||||
RoomEvent.TrackSubscriptionStatusChanged,
|
||||
]
|
||||
|
||||
export const allParticipantRoomEvents = [
|
||||
...allRemoteParticipantRoomEvents,
|
||||
RoomEvent.LocalTrackPublished,
|
||||
RoomEvent.LocalTrackUnpublished,
|
||||
]
|
||||
@@ -0,0 +1,46 @@
|
||||
import * as React from 'react'
|
||||
/**
|
||||
* Implementation used from https://github.com/juliencrn/usehooks-ts
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
export function useMediaQuery(query: string): boolean {
|
||||
const getMatches = (query: string): boolean => {
|
||||
// Prevents SSR issues
|
||||
if (typeof window !== 'undefined') {
|
||||
return window.matchMedia(query).matches
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
const [matches, setMatches] = React.useState<boolean>(getMatches(query))
|
||||
|
||||
function handleChange() {
|
||||
setMatches(getMatches(query))
|
||||
}
|
||||
|
||||
React.useEffect(() => {
|
||||
const matchMedia = window.matchMedia(query)
|
||||
|
||||
// Triggered at the first client-side load and if query changes
|
||||
handleChange()
|
||||
|
||||
// Listen matchMedia
|
||||
if (matchMedia.addListener) {
|
||||
matchMedia.addListener(handleChange)
|
||||
} else {
|
||||
matchMedia.addEventListener('change', handleChange)
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (matchMedia.removeListener) {
|
||||
matchMedia.removeListener(handleChange)
|
||||
} else {
|
||||
matchMedia.removeEventListener('change', handleChange)
|
||||
}
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [query])
|
||||
|
||||
return matches
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
/* eslint-disable react-hooks/exhaustive-deps */
|
||||
import * as React from 'react'
|
||||
|
||||
const useLatest = <T>(current: T) => {
|
||||
const storedValue = React.useRef(current)
|
||||
React.useEffect(() => {
|
||||
storedValue.current = current
|
||||
})
|
||||
return storedValue
|
||||
}
|
||||
|
||||
/**
|
||||
* A React hook that fires a callback whenever ResizeObserver detects a change to its size
|
||||
* code extracted from https://github.com/jaredLunde/react-hook/blob/master/packages/resize-observer/src/index.tsx in order to not include the polyfill for resize-observer
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
export function useResizeObserver<T extends HTMLElement>(
|
||||
target: React.RefObject<T>,
|
||||
callback: UseResizeObserverCallback
|
||||
) {
|
||||
const resizeObserver = getResizeObserver()
|
||||
const storedCallback = useLatest(callback)
|
||||
|
||||
React.useLayoutEffect(() => {
|
||||
let didUnsubscribe = false
|
||||
|
||||
const targetEl = target.current
|
||||
if (!targetEl) return
|
||||
|
||||
function cb(entry: ResizeObserverEntry, observer: ResizeObserver) {
|
||||
if (didUnsubscribe) return
|
||||
storedCallback.current(entry, observer)
|
||||
}
|
||||
|
||||
resizeObserver?.subscribe(targetEl as HTMLElement, cb)
|
||||
|
||||
return () => {
|
||||
didUnsubscribe = true
|
||||
resizeObserver?.unsubscribe(targetEl as HTMLElement, cb)
|
||||
}
|
||||
}, [target.current, resizeObserver, storedCallback])
|
||||
|
||||
return resizeObserver?.observer
|
||||
}
|
||||
|
||||
function createResizeObserver() {
|
||||
let ticking = false
|
||||
let allEntries: ResizeObserverEntry[] = []
|
||||
|
||||
const callbacks: Map<unknown, Array<UseResizeObserverCallback>> = new Map()
|
||||
|
||||
if (typeof window === 'undefined') {
|
||||
return
|
||||
}
|
||||
|
||||
const observer = new ResizeObserver(
|
||||
(entries: ResizeObserverEntry[], obs: ResizeObserver) => {
|
||||
allEntries = allEntries.concat(entries)
|
||||
if (!ticking) {
|
||||
window.requestAnimationFrame(() => {
|
||||
const triggered = new Set<Element>()
|
||||
for (let i = 0; i < allEntries.length; i++) {
|
||||
if (triggered.has(allEntries[i].target)) continue
|
||||
triggered.add(allEntries[i].target)
|
||||
const cbs = callbacks.get(allEntries[i].target)
|
||||
cbs?.forEach((cb) => cb(allEntries[i], obs))
|
||||
}
|
||||
allEntries = []
|
||||
ticking = false
|
||||
})
|
||||
}
|
||||
ticking = true
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
observer,
|
||||
subscribe(target: HTMLElement, callback: UseResizeObserverCallback) {
|
||||
observer.observe(target)
|
||||
const cbs = callbacks.get(target) ?? []
|
||||
cbs.push(callback)
|
||||
callbacks.set(target, cbs)
|
||||
},
|
||||
unsubscribe(target: HTMLElement, callback: UseResizeObserverCallback) {
|
||||
const cbs = callbacks.get(target) ?? []
|
||||
if (cbs.length === 1) {
|
||||
observer.unobserve(target)
|
||||
callbacks.delete(target)
|
||||
return
|
||||
}
|
||||
const cbIndex = cbs.indexOf(callback)
|
||||
if (cbIndex !== -1) cbs.splice(cbIndex, 1)
|
||||
callbacks.set(target, cbs)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
let _resizeObserver: ReturnType<typeof createResizeObserver>
|
||||
|
||||
const getResizeObserver = () =>
|
||||
!_resizeObserver
|
||||
? (_resizeObserver = createResizeObserver())
|
||||
: _resizeObserver
|
||||
|
||||
export type UseResizeObserverCallback = (
|
||||
entry: ResizeObserverEntry,
|
||||
observer: ResizeObserver
|
||||
) => unknown
|
||||
|
||||
export const useSize = (target: React.RefObject<HTMLDivElement>) => {
|
||||
const [size, setSize] = React.useState({ width: 0, height: 0 })
|
||||
React.useLayoutEffect(() => {
|
||||
if (target.current) {
|
||||
const { width, height } = target.current.getBoundingClientRect()
|
||||
setSize({ width, height })
|
||||
}
|
||||
}, [target.current])
|
||||
|
||||
const resizeCallback = React.useCallback(
|
||||
(entry: ResizeObserverEntry) => setSize(entry.contentRect),
|
||||
[]
|
||||
)
|
||||
// Where the magic happens
|
||||
useResizeObserver(target, resizeCallback)
|
||||
return size
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
import { Track } from 'livekit-client'
|
||||
import * as React from 'react'
|
||||
|
||||
import { supportsScreenSharing } from '@livekit/components-core'
|
||||
|
||||
import {
|
||||
DisconnectButton,
|
||||
LeaveIcon,
|
||||
MediaDeviceMenu,
|
||||
TrackToggle,
|
||||
useMaybeLayoutContext,
|
||||
usePersistentUserChoices,
|
||||
} from '@livekit/components-react'
|
||||
|
||||
import { mergeProps } from '@/utils/mergeProps.ts'
|
||||
import { StartMediaButton } from '../components/controls/StartMediaButton'
|
||||
import { useMediaQuery } from '../hooks/useMediaQuery'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { OptionsButton } from '../components/controls/Options/OptionsButton'
|
||||
import { ParticipantsToggle } from '@/features/rooms/livekit/components/controls/Participants/ParticipantsToggle'
|
||||
import { ChatToggle } from '@/features/rooms/livekit/components/controls/ChatToggle'
|
||||
|
||||
/** @public */
|
||||
export type ControlBarControls = {
|
||||
microphone?: boolean
|
||||
camera?: boolean
|
||||
chat?: boolean
|
||||
screenShare?: boolean
|
||||
leave?: boolean
|
||||
settings?: boolean
|
||||
}
|
||||
|
||||
/** @public */
|
||||
export interface ControlBarProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
onDeviceError?: (error: { source: Track.Source; error: Error }) => void
|
||||
variation?: 'minimal' | 'verbose' | 'textOnly'
|
||||
controls?: ControlBarControls
|
||||
/**
|
||||
* If `true`, the user's device choices will be persisted.
|
||||
* This will enables the user to have the same device choices when they rejoin the room.
|
||||
* @defaultValue true
|
||||
* @alpha
|
||||
*/
|
||||
saveUserChoices?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* The `ControlBar` prefab gives the user the basic user interface to control their
|
||||
* media devices (camera, microphone and screen share), open the `Chat` and leave the room.
|
||||
*
|
||||
* @remarks
|
||||
* This component is build with other LiveKit components like `TrackToggle`,
|
||||
* `DeviceSelectorButton`, `DisconnectButton` and `StartAudio`.
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* <LiveKitRoom>
|
||||
* <ControlBar />
|
||||
* </LiveKitRoom>
|
||||
* ```
|
||||
* @public
|
||||
*/
|
||||
export function ControlBar({
|
||||
variation,
|
||||
saveUserChoices = true,
|
||||
onDeviceError,
|
||||
...props
|
||||
}: ControlBarProps) {
|
||||
const { t } = useTranslation('rooms')
|
||||
const [isChatOpen, setIsChatOpen] = React.useState(false)
|
||||
const layoutContext = useMaybeLayoutContext()
|
||||
React.useEffect(() => {
|
||||
if (layoutContext?.widget.state?.showChat !== undefined) {
|
||||
setIsChatOpen(layoutContext?.widget.state?.showChat)
|
||||
}
|
||||
}, [layoutContext?.widget.state?.showChat])
|
||||
|
||||
const isTooLittleSpace = useMediaQuery(
|
||||
`(max-width: ${isChatOpen ? 1000 : 760}px)`
|
||||
)
|
||||
|
||||
const defaultVariation = isTooLittleSpace ? 'minimal' : 'verbose'
|
||||
variation ??= defaultVariation
|
||||
|
||||
const showIcon = React.useMemo(
|
||||
() => variation === 'minimal' || variation === 'verbose',
|
||||
[variation]
|
||||
)
|
||||
const showText = React.useMemo(
|
||||
() => variation === 'textOnly' || variation === 'verbose',
|
||||
[variation]
|
||||
)
|
||||
|
||||
const browserSupportsScreenSharing = supportsScreenSharing()
|
||||
|
||||
const [isScreenShareEnabled, setIsScreenShareEnabled] = React.useState(false)
|
||||
|
||||
const onScreenShareChange = React.useCallback(
|
||||
(enabled: boolean) => {
|
||||
setIsScreenShareEnabled(enabled)
|
||||
},
|
||||
[setIsScreenShareEnabled]
|
||||
)
|
||||
|
||||
const htmlProps = mergeProps({ className: 'lk-control-bar' }, props)
|
||||
|
||||
const {
|
||||
saveAudioInputEnabled,
|
||||
saveVideoInputEnabled,
|
||||
saveAudioInputDeviceId,
|
||||
saveVideoInputDeviceId,
|
||||
} = usePersistentUserChoices({ preventSave: !saveUserChoices })
|
||||
|
||||
const microphoneOnChange = React.useCallback(
|
||||
(enabled: boolean, isUserInitiated: boolean) =>
|
||||
isUserInitiated ? saveAudioInputEnabled(enabled) : null,
|
||||
[saveAudioInputEnabled]
|
||||
)
|
||||
|
||||
const cameraOnChange = React.useCallback(
|
||||
(enabled: boolean, isUserInitiated: boolean) =>
|
||||
isUserInitiated ? saveVideoInputEnabled(enabled) : null,
|
||||
[saveVideoInputEnabled]
|
||||
)
|
||||
|
||||
return (
|
||||
<div {...htmlProps}>
|
||||
<div className="lk-button-group">
|
||||
<TrackToggle
|
||||
source={Track.Source.Microphone}
|
||||
showIcon={showIcon}
|
||||
onChange={microphoneOnChange}
|
||||
onDeviceError={(error) =>
|
||||
onDeviceError?.({ source: Track.Source.Microphone, error })
|
||||
}
|
||||
>
|
||||
{showText && t('controls.microphone')}
|
||||
</TrackToggle>
|
||||
<div className="lk-button-group-menu">
|
||||
<MediaDeviceMenu
|
||||
kind="audioinput"
|
||||
onActiveDeviceChange={(_kind, deviceId) =>
|
||||
saveAudioInputDeviceId(deviceId ?? '')
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="lk-button-group">
|
||||
<TrackToggle
|
||||
source={Track.Source.Camera}
|
||||
showIcon={showIcon}
|
||||
onChange={cameraOnChange}
|
||||
onDeviceError={(error) =>
|
||||
onDeviceError?.({ source: Track.Source.Camera, error })
|
||||
}
|
||||
>
|
||||
{showText && t('controls.camera')}
|
||||
</TrackToggle>
|
||||
<div className="lk-button-group-menu">
|
||||
<MediaDeviceMenu
|
||||
kind="videoinput"
|
||||
onActiveDeviceChange={(_kind, deviceId) =>
|
||||
saveVideoInputDeviceId(deviceId ?? '')
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{browserSupportsScreenSharing && (
|
||||
<TrackToggle
|
||||
source={Track.Source.ScreenShare}
|
||||
captureOptions={{ audio: true, selfBrowserSurface: 'include' }}
|
||||
showIcon={showIcon}
|
||||
onChange={onScreenShareChange}
|
||||
onDeviceError={(error) =>
|
||||
onDeviceError?.({ source: Track.Source.ScreenShare, error })
|
||||
}
|
||||
>
|
||||
{showText &&
|
||||
t(
|
||||
isScreenShareEnabled
|
||||
? 'controls.stopScreenShare'
|
||||
: 'controls.shareScreen'
|
||||
)}
|
||||
</TrackToggle>
|
||||
)}
|
||||
<ChatToggle />
|
||||
<ParticipantsToggle />
|
||||
<OptionsButton />
|
||||
<DisconnectButton>
|
||||
{showIcon && <LeaveIcon />}
|
||||
{showText && t('controls.leave')}
|
||||
</DisconnectButton>
|
||||
<StartMediaButton />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
import type {
|
||||
MessageDecoder,
|
||||
MessageEncoder,
|
||||
TrackReferenceOrPlaceholder,
|
||||
WidgetState,
|
||||
} from '@livekit/components-core'
|
||||
import {
|
||||
isEqualTrackRef,
|
||||
isTrackReference,
|
||||
isWeb,
|
||||
log,
|
||||
} from '@livekit/components-core'
|
||||
import { RoomEvent, Track } from 'livekit-client'
|
||||
import * as React from 'react'
|
||||
|
||||
import {
|
||||
CarouselLayout,
|
||||
ConnectionStateToast,
|
||||
FocusLayoutContainer,
|
||||
GridLayout,
|
||||
LayoutContextProvider,
|
||||
RoomAudioRenderer,
|
||||
MessageFormatter,
|
||||
usePinnedTracks,
|
||||
useTracks,
|
||||
useCreateLayoutContext,
|
||||
Chat,
|
||||
} from '@livekit/components-react'
|
||||
|
||||
import { ControlBar } from './ControlBar'
|
||||
import { styled } from '@/styled-system/jsx'
|
||||
import { cva } from '@/styled-system/css'
|
||||
import { ParticipantsList } from '@/features/rooms/livekit/components/controls/Participants/ParticipantsList'
|
||||
import { useSnapshot } from 'valtio'
|
||||
import { participantsStore } from '@/stores/participants'
|
||||
import { FocusLayout } from '../components/FocusLayout'
|
||||
import { ParticipantTile } from '../components/ParticipantTile'
|
||||
|
||||
const LayoutWrapper = styled(
|
||||
'div',
|
||||
cva({
|
||||
base: {
|
||||
position: 'relative',
|
||||
display: 'flex',
|
||||
width: '100%',
|
||||
height: 'calc(100% - var(--lk-control-bar-height))',
|
||||
},
|
||||
})
|
||||
)
|
||||
|
||||
/**
|
||||
* @public
|
||||
*/
|
||||
export interface VideoConferenceProps
|
||||
extends React.HTMLAttributes<HTMLDivElement> {
|
||||
chatMessageFormatter?: MessageFormatter
|
||||
chatMessageEncoder?: MessageEncoder
|
||||
chatMessageDecoder?: MessageDecoder
|
||||
/** @alpha */
|
||||
SettingsComponent?: React.ComponentType
|
||||
}
|
||||
|
||||
/**
|
||||
* The `VideoConference` ready-made component is your drop-in solution for a classic video conferencing application.
|
||||
* It provides functionality such as focusing on one participant, grid view with pagination to handle large numbers
|
||||
* of participants, basic non-persistent chat, screen sharing, and more.
|
||||
*
|
||||
* @remarks
|
||||
* The component is implemented with other LiveKit components like `FocusContextProvider`,
|
||||
* `GridLayout`, `ControlBar`, `FocusLayoutContainer` and `FocusLayout`.
|
||||
* You can use this components as a starting point for your own custom video conferencing application.
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* <LiveKitRoom>
|
||||
* <VideoConference />
|
||||
* <LiveKitRoom>
|
||||
* ```
|
||||
* @public
|
||||
*/
|
||||
export function VideoConference({
|
||||
chatMessageFormatter,
|
||||
chatMessageDecoder,
|
||||
chatMessageEncoder,
|
||||
...props
|
||||
}: VideoConferenceProps) {
|
||||
const [widgetState, setWidgetState] = React.useState<WidgetState>({
|
||||
showChat: false,
|
||||
unreadMessages: 0,
|
||||
showSettings: false,
|
||||
})
|
||||
const lastAutoFocusedScreenShareTrack =
|
||||
React.useRef<TrackReferenceOrPlaceholder | null>(null)
|
||||
|
||||
const tracks = useTracks(
|
||||
[
|
||||
{ source: Track.Source.Camera, withPlaceholder: true },
|
||||
{ source: Track.Source.ScreenShare, withPlaceholder: false },
|
||||
],
|
||||
{ updateOnlyOn: [RoomEvent.ActiveSpeakersChanged], onlySubscribed: false }
|
||||
)
|
||||
|
||||
const widgetUpdate = (state: WidgetState) => {
|
||||
log.debug('updating widget state', state)
|
||||
setWidgetState(state)
|
||||
}
|
||||
|
||||
const layoutContext = useCreateLayoutContext()
|
||||
|
||||
const screenShareTracks = tracks
|
||||
.filter(isTrackReference)
|
||||
.filter((track) => track.publication.source === Track.Source.ScreenShare)
|
||||
|
||||
const focusTrack = usePinnedTracks(layoutContext)?.[0]
|
||||
const carouselTracks = tracks.filter(
|
||||
(track) => !isEqualTrackRef(track, focusTrack)
|
||||
)
|
||||
|
||||
/* eslint-disable react-hooks/exhaustive-deps */
|
||||
// Code duplicated from LiveKit; this warning will be addressed in the refactoring.
|
||||
React.useEffect(() => {
|
||||
// If screen share tracks are published, and no pin is set explicitly, auto set the screen share.
|
||||
if (
|
||||
screenShareTracks.some((track) => track.publication.isSubscribed) &&
|
||||
lastAutoFocusedScreenShareTrack.current === null
|
||||
) {
|
||||
log.debug('Auto set screen share focus:', {
|
||||
newScreenShareTrack: screenShareTracks[0],
|
||||
})
|
||||
layoutContext.pin.dispatch?.({
|
||||
msg: 'set_pin',
|
||||
trackReference: screenShareTracks[0],
|
||||
})
|
||||
lastAutoFocusedScreenShareTrack.current = screenShareTracks[0]
|
||||
} else if (
|
||||
lastAutoFocusedScreenShareTrack.current &&
|
||||
!screenShareTracks.some(
|
||||
(track) =>
|
||||
track.publication.trackSid ===
|
||||
lastAutoFocusedScreenShareTrack.current?.publication?.trackSid
|
||||
)
|
||||
) {
|
||||
log.debug('Auto clearing screen share focus.')
|
||||
layoutContext.pin.dispatch?.({ msg: 'clear_pin' })
|
||||
lastAutoFocusedScreenShareTrack.current = null
|
||||
}
|
||||
if (focusTrack && !isTrackReference(focusTrack)) {
|
||||
const updatedFocusTrack = tracks.find(
|
||||
(tr) =>
|
||||
tr.participant.identity === focusTrack.participant.identity &&
|
||||
tr.source === focusTrack.source
|
||||
)
|
||||
if (
|
||||
updatedFocusTrack !== focusTrack &&
|
||||
isTrackReference(updatedFocusTrack)
|
||||
) {
|
||||
layoutContext.pin.dispatch?.({
|
||||
msg: 'set_pin',
|
||||
trackReference: updatedFocusTrack,
|
||||
})
|
||||
}
|
||||
}
|
||||
}, [
|
||||
screenShareTracks
|
||||
.map(
|
||||
(ref) => `${ref.publication.trackSid}_${ref.publication.isSubscribed}`
|
||||
)
|
||||
.join(),
|
||||
focusTrack?.publication?.trackSid,
|
||||
tracks,
|
||||
])
|
||||
/* eslint-enable react-hooks/exhaustive-deps */
|
||||
|
||||
const participantsSnap = useSnapshot(participantsStore)
|
||||
const showParticipants = participantsSnap.showParticipants
|
||||
|
||||
return (
|
||||
<div className="lk-video-conference" {...props}>
|
||||
{isWeb() && (
|
||||
<LayoutContextProvider
|
||||
value={layoutContext}
|
||||
// onPinChange={handleFocusStateChange}
|
||||
onWidgetChange={widgetUpdate}
|
||||
>
|
||||
<div className="lk-video-conference-inner">
|
||||
<LayoutWrapper>
|
||||
{!focusTrack ? (
|
||||
<div
|
||||
className="lk-grid-layout-wrapper"
|
||||
style={{ height: 'auto' }}
|
||||
>
|
||||
<GridLayout tracks={tracks}>
|
||||
<ParticipantTile />
|
||||
</GridLayout>
|
||||
</div>
|
||||
) : (
|
||||
<div className="lk-focus-layout-wrapper">
|
||||
<FocusLayoutContainer>
|
||||
<CarouselLayout tracks={carouselTracks}>
|
||||
<ParticipantTile />
|
||||
</CarouselLayout>
|
||||
{focusTrack && <FocusLayout trackRef={focusTrack} />}
|
||||
</FocusLayoutContainer>
|
||||
</div>
|
||||
)}
|
||||
<Chat
|
||||
style={{ display: widgetState.showChat ? 'grid' : 'none' }}
|
||||
messageFormatter={chatMessageFormatter}
|
||||
messageEncoder={chatMessageEncoder}
|
||||
messageDecoder={chatMessageDecoder}
|
||||
/>
|
||||
{showParticipants && <ParticipantsList />}
|
||||
</LayoutWrapper>
|
||||
<ControlBar />
|
||||
</div>
|
||||
</LayoutContextProvider>
|
||||
)}
|
||||
<RoomAudioRenderer />
|
||||
<ConnectionStateToast />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,19 +1,17 @@
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { BoxScreen } from '@/layout/BoxScreen'
|
||||
import { Div, Link, P } from '@/primitives'
|
||||
import { Text } from '@/primitives'
|
||||
import { Screen } from '@/layout/Screen'
|
||||
import { CenteredContent } from '@/layout/CenteredContent'
|
||||
|
||||
export const FeedbackRoute = () => {
|
||||
const { t } = useTranslation('rooms')
|
||||
return (
|
||||
<BoxScreen title={t('feedback.heading')}>
|
||||
<Div textAlign="left">
|
||||
<P>{t('feedback.body')}</P>
|
||||
</Div>
|
||||
<Div marginTop={1}>
|
||||
<P>
|
||||
<Link to="/">{t('backToHome', { ns: 'global' })}</Link>
|
||||
</P>
|
||||
</Div>
|
||||
</BoxScreen>
|
||||
<Screen layout="centered">
|
||||
<CenteredContent title={t('feedback.heading')} withBackButton>
|
||||
<Text as="p" variant="h3" centered>
|
||||
{t('feedback.body')}
|
||||
</Text>
|
||||
</CenteredContent>
|
||||
</Screen>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,45 +1,60 @@
|
||||
import { useState } from 'react'
|
||||
import { useEffect, useState } from 'react'
|
||||
import {
|
||||
usePersistentUserChoices,
|
||||
type LocalUserChoices,
|
||||
} from '@livekit/components-react'
|
||||
import { useParams } from 'wouter'
|
||||
import { Screen } from '@/layout/Screen'
|
||||
import { ErrorScreen } from '@/layout/ErrorScreen'
|
||||
import { useUser } from '@/features/auth'
|
||||
import { ErrorScreen } from '@/components/ErrorScreen'
|
||||
import { useUser, UserAware } from '@/features/auth'
|
||||
import { Conference } from '../components/Conference'
|
||||
import { Join } from '../components/Join'
|
||||
|
||||
export const Room = () => {
|
||||
const { user, isLoggedIn } = useUser()
|
||||
const { isLoggedIn } = useUser()
|
||||
const { userChoices: existingUserChoices } = usePersistentUserChoices()
|
||||
const [userConfig, setUserConfig] = useState<LocalUserChoices | null>(null)
|
||||
|
||||
const { roomId } = useParams()
|
||||
const initialRoomData = history.state?.initialRoomData
|
||||
const mode = isLoggedIn && history.state?.create ? 'create' : 'join'
|
||||
const skipJoinScreen = isLoggedIn && mode === 'create'
|
||||
|
||||
const clearRouterState = () => {
|
||||
if (window?.history?.state) {
|
||||
window.history.replaceState({}, '')
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
window.addEventListener('beforeunload', clearRouterState)
|
||||
return () => {
|
||||
window.removeEventListener('beforeunload', clearRouterState)
|
||||
}
|
||||
}, [])
|
||||
|
||||
if (!roomId) {
|
||||
return <ErrorScreen />
|
||||
}
|
||||
|
||||
if (!userConfig && !skipJoinScreen) {
|
||||
return (
|
||||
<Screen>
|
||||
<UserAware>
|
||||
<Join onSubmit={setUserConfig} />
|
||||
</Screen>
|
||||
</UserAware>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Conference
|
||||
roomId={roomId}
|
||||
mode={mode}
|
||||
userConfig={{
|
||||
...existingUserChoices,
|
||||
...(skipJoinScreen ? { username: user?.email as string } : {}),
|
||||
...userConfig,
|
||||
}}
|
||||
/>
|
||||
<UserAware>
|
||||
<Conference
|
||||
initialRoomData={initialRoomData}
|
||||
roomId={roomId}
|
||||
mode={mode}
|
||||
userConfig={{
|
||||
...existingUserChoices,
|
||||
...userConfig,
|
||||
}}
|
||||
/>
|
||||
</UserAware>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import { Participant } from 'livekit-client'
|
||||
|
||||
export const getParticipantColor = (
|
||||
participant: Participant
|
||||
): undefined | string => {
|
||||
const { metadata } = participant
|
||||
if (!metadata) {
|
||||
return
|
||||
}
|
||||
return JSON.parse(metadata)['color']
|
||||
}
|
||||
@@ -1,12 +1,38 @@
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { Trans, useTranslation } from 'react-i18next'
|
||||
import { useLanguageLabels } from '@/i18n/useLanguageLabels'
|
||||
import { Dialog, Field, H } from '@/primitives'
|
||||
import { A, Badge, Dialog, type DialogProps, Field, H, P } from '@/primitives'
|
||||
import { authUrl, logoutUrl, useUser } from '@/features/auth'
|
||||
|
||||
export const SettingsDialog = () => {
|
||||
export type SettingsDialogProps = Pick<DialogProps, 'isOpen' | 'onOpenChange'>
|
||||
|
||||
export const SettingsDialog = (props: SettingsDialogProps) => {
|
||||
const { t, i18n } = useTranslation('settings')
|
||||
const { user, isLoggedIn } = useUser()
|
||||
const { languagesList, currentLanguage } = useLanguageLabels()
|
||||
return (
|
||||
<Dialog title={t('dialog.heading')}>
|
||||
<Dialog title={t('dialog.heading')} {...props}>
|
||||
<H lvl={2}>{t('account.heading')}</H>
|
||||
{isLoggedIn ? (
|
||||
<>
|
||||
<P>
|
||||
<Trans
|
||||
i18nKey="settings:account.currentlyLoggedAs"
|
||||
values={{ user: user?.email }}
|
||||
components={[<Badge />]}
|
||||
/>
|
||||
</P>
|
||||
<P>
|
||||
<A href={logoutUrl()}>{t('logout', { ns: 'global' })}</A>
|
||||
</P>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<P>{t('account.youAreNotLoggedIn')}</P>
|
||||
<P>
|
||||
<A href={authUrl()}>{t('login', { ns: 'global' })}</A>
|
||||
</P>
|
||||
</>
|
||||
)}
|
||||
<H lvl={2}>{t('language.heading')}</H>
|
||||
<Field
|
||||
type="select"
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import { Dialog, type DialogProps } from '@/primitives'
|
||||
import { Tab, Tabs, TabList } from '@/primitives/Tabs.tsx'
|
||||
import { css } from '@/styled-system/css'
|
||||
import { text } from '@/primitives/Text.tsx'
|
||||
import { Heading } from 'react-aria-components'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import {
|
||||
RiAccountCircleLine,
|
||||
RiSettings3Line,
|
||||
RiSpeakerLine,
|
||||
} from '@remixicon/react'
|
||||
import { AccountTab } from './tabs/AccountTab'
|
||||
import { GeneralTab } from '@/features/settings/components/tabs/GeneralTab.tsx'
|
||||
import { AudioTab } from '@/features/settings/components/tabs/AudioTab.tsx'
|
||||
|
||||
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',
|
||||
paddingRight: '1.5rem',
|
||||
flex: '0 0 16rem', // fixme size copied from meet settings modal
|
||||
})
|
||||
|
||||
const tabPanelContainerStyle = css({
|
||||
display: 'flex',
|
||||
flexGrow: '1',
|
||||
marginTop: '3.5rem',
|
||||
})
|
||||
|
||||
export type SettingsDialogExtended = Pick<
|
||||
DialogProps,
|
||||
'isOpen' | 'onOpenChange'
|
||||
>
|
||||
|
||||
export const SettingsDialogExtended = (props: SettingsDialogExtended) => {
|
||||
// display only icon on small screen
|
||||
const { t } = useTranslation('settings')
|
||||
return (
|
||||
<Dialog {...props} role="dialog" type="flex">
|
||||
<Tabs orientation="vertical" className={tabsStyle}>
|
||||
<div className={tabListContainerStyle}>
|
||||
<Heading slot="title" level={1} className={text({ variant: 'h1' })}>
|
||||
{t('dialog.heading')}
|
||||
</Heading>
|
||||
<TabList border={false} aria-label="Chat log orientation example">
|
||||
<Tab icon highlight id="1">
|
||||
<RiAccountCircleLine />
|
||||
{t('tabs.account')}
|
||||
</Tab>
|
||||
<Tab icon highlight id="2">
|
||||
<RiSpeakerLine />
|
||||
{t('tabs.audio')}
|
||||
</Tab>
|
||||
<Tab icon highlight id="3">
|
||||
<RiSettings3Line />
|
||||
{t('tabs.general')}
|
||||
</Tab>
|
||||
</TabList>
|
||||
</div>
|
||||
<div className={tabPanelContainerStyle}>
|
||||
<AccountTab id="1" onOpenChange={props.onOpenChange} />
|
||||
<AudioTab id="2" />
|
||||
<GeneralTab id="3" />
|
||||
</div>
|
||||
</Tabs>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import { A, Badge, Button, DialogProps, Field, H, P } from '@/primitives'
|
||||
import { Trans, useTranslation } from 'react-i18next'
|
||||
import {
|
||||
usePersistentUserChoices,
|
||||
useRoomContext,
|
||||
} from '@livekit/components-react'
|
||||
import { authUrl, logoutUrl, useUser } from '@/features/auth'
|
||||
import { css } from '@/styled-system/css'
|
||||
import { TabPanel, TabPanelProps } from '@/primitives/Tabs'
|
||||
import { HStack } from '@/styled-system/jsx'
|
||||
import { useState } from 'react'
|
||||
|
||||
export type AccountTabProps = Pick<DialogProps, 'onOpenChange'> &
|
||||
Pick<TabPanelProps, 'id'>
|
||||
|
||||
export const AccountTab = ({ id, onOpenChange }: AccountTabProps) => {
|
||||
const { t } = useTranslation('settings')
|
||||
const { saveUsername } = usePersistentUserChoices()
|
||||
const room = useRoomContext()
|
||||
const { user, isLoggedIn } = useUser()
|
||||
const [name, setName] = useState(room?.localParticipant.name || '')
|
||||
|
||||
const handleOnSubmit = () => {
|
||||
if (room) room.localParticipant.setName(name)
|
||||
saveUsername(name)
|
||||
if (onOpenChange) onOpenChange(false)
|
||||
}
|
||||
const handleOnCancel = () => {
|
||||
if (onOpenChange) onOpenChange(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<TabPanel padding={'md'} flex id={id}>
|
||||
<H lvl={2}>{t('account.heading')}</H>
|
||||
<Field
|
||||
type="text"
|
||||
label={t('account.nameLabel')}
|
||||
value={name}
|
||||
onChange={setName}
|
||||
validate={(value) => {
|
||||
return !value ? <p>{'Votre Nom ne peut pas être vide'}</p> : null
|
||||
}}
|
||||
/>
|
||||
<H lvl={2}>{t('account.authentication')}</H>
|
||||
{isLoggedIn ? (
|
||||
<>
|
||||
<P>
|
||||
<Trans
|
||||
i18nKey="settings:account.currentlyLoggedAs"
|
||||
values={{ user: user?.email }}
|
||||
components={[<Badge />]}
|
||||
/>
|
||||
</P>
|
||||
<P>
|
||||
<A href={logoutUrl()}>{t('logout', { ns: 'global' })}</A>
|
||||
</P>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<P>{t('account.youAreNotLoggedIn')}</P>
|
||||
<P>
|
||||
<A href={authUrl()}>{t('login', { ns: 'global' })}</A>
|
||||
</P>
|
||||
</>
|
||||
)}
|
||||
<HStack
|
||||
className={css({
|
||||
marginTop: 'auto',
|
||||
marginLeft: 'auto',
|
||||
})}
|
||||
>
|
||||
<Button onPress={handleOnCancel}>
|
||||
{t('cancel', { ns: 'global' })}
|
||||
</Button>
|
||||
<Button variant={'primary'} onPress={handleOnSubmit}>
|
||||
{t('submit', { ns: 'global' })}
|
||||
</Button>
|
||||
</HStack>
|
||||
</TabPanel>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import { DialogProps, Field, H } from '@/primitives'
|
||||
|
||||
import { TabPanel, TabPanelProps } from '@/primitives/Tabs'
|
||||
import { useMediaDeviceSelect } from '@livekit/components-react'
|
||||
import { isSafari } from '@/utils/livekit'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { SoundTester } from '@/components/SoundTester.tsx'
|
||||
|
||||
export type AudioTabProps = Pick<DialogProps, 'onOpenChange'> &
|
||||
Pick<TabPanelProps, 'id'>
|
||||
|
||||
type DeviceItems = Array<{ value: string; label: string }>
|
||||
|
||||
export const AudioTab = ({ id }: AudioTabProps) => {
|
||||
const { t } = useTranslation('settings')
|
||||
|
||||
const {
|
||||
devices: devicesOut,
|
||||
activeDeviceId: activeDeviceIdOut,
|
||||
setActiveMediaDevice: setActiveMediaDeviceOut,
|
||||
} = useMediaDeviceSelect({ kind: 'audiooutput' })
|
||||
|
||||
const {
|
||||
devices: devicesIn,
|
||||
activeDeviceId: activeDeviceIdIn,
|
||||
setActiveMediaDevice: setActiveMediaDeviceIn,
|
||||
} = useMediaDeviceSelect({ kind: 'audioinput' })
|
||||
|
||||
const itemsOut: DeviceItems = devicesOut.map((d) => ({
|
||||
value: d.deviceId,
|
||||
label: d.label,
|
||||
}))
|
||||
|
||||
const itemsIn: DeviceItems = devicesIn.map((d) => ({
|
||||
value: d.deviceId,
|
||||
label: d.label,
|
||||
}))
|
||||
|
||||
// The Permissions API is not fully supported in Firefox and Safari, and attempting to use it for microphone permissions
|
||||
// may raise an error. As a workaround, we infer microphone permission status by checking if the list of audio input
|
||||
// devices (devicesIn) is non-empty. If the list has one or more devices, we assume the user has granted microphone access.
|
||||
const isMicEnabled = devicesIn?.length > 0
|
||||
|
||||
const disabledProps = isMicEnabled
|
||||
? {}
|
||||
: {
|
||||
placeholder: t('audio.permissionsRequired'),
|
||||
isDisabled: true,
|
||||
defaultSelectedKey: undefined,
|
||||
}
|
||||
|
||||
// No API to directly query the default audio device; this function heuristically finds it.
|
||||
// Returns the item with value 'default' if present; otherwise, returns the first item in the list.
|
||||
const getDefaultSelectedKey = (items: DeviceItems) => {
|
||||
if (!items || items.length === 0) return
|
||||
const defaultItem =
|
||||
items.find((item) => item.value === 'default') || items[0]
|
||||
return defaultItem.value
|
||||
}
|
||||
|
||||
return (
|
||||
<TabPanel padding={'md'} flex id={id}>
|
||||
<H lvl={2}>{t('audio.microphone.heading')}</H>
|
||||
<Field
|
||||
type="select"
|
||||
label={t('audio.microphone.label')}
|
||||
items={itemsIn}
|
||||
defaultSelectedKey={activeDeviceIdIn || getDefaultSelectedKey(itemsIn)}
|
||||
onSelectionChange={(key) => setActiveMediaDeviceIn(key as string)}
|
||||
{...disabledProps}
|
||||
/>
|
||||
{/* Safari has a known limitation where its implementation of 'enumerateDevices' does not include audio output devices.
|
||||
To prevent errors or an empty selection list, we only render the speakers selection field on non-Safari browsers. */}
|
||||
{!isSafari() && (
|
||||
<>
|
||||
<H lvl={2}>{t('audio.speakers.heading')}</H>
|
||||
<Field
|
||||
type="select"
|
||||
label={t('audio.speakers.label')}
|
||||
items={itemsOut}
|
||||
defaultSelectedKey={
|
||||
activeDeviceIdOut || getDefaultSelectedKey(itemsOut)
|
||||
}
|
||||
onSelectionChange={async (key) =>
|
||||
setActiveMediaDeviceOut(key as string)
|
||||
}
|
||||
{...disabledProps}
|
||||
/>
|
||||
<SoundTester />
|
||||
</>
|
||||
)}
|
||||
</TabPanel>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { Field, H } from '@/primitives'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useLanguageLabels } from '@/i18n/useLanguageLabels'
|
||||
import { TabPanel, TabPanelProps } from '@/primitives/Tabs'
|
||||
|
||||
export type GeneralTabProps = Pick<TabPanelProps, 'id'>
|
||||
|
||||
export const GeneralTab = ({ id }: GeneralTabProps) => {
|
||||
const { t, i18n } = useTranslation('settings')
|
||||
const { languagesList, currentLanguage } = useLanguageLabels()
|
||||
|
||||
return (
|
||||
<TabPanel padding={'md'} flex id={id}>
|
||||
<H lvl={2}>{t('language.heading')}</H>
|
||||
<Field
|
||||
type="select"
|
||||
label={t('language.label')}
|
||||
items={languagesList}
|
||||
defaultSelectedKey={currentLanguage.key}
|
||||
onSelectionChange={(lang) => {
|
||||
i18n.changeLanguage(lang as string)
|
||||
}}
|
||||
/>
|
||||
</TabPanel>
|
||||
)
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user