2024-06-25 18:55:52 +02:00
|
|
|
"""
|
|
|
|
|
Utils functions used in the core app
|
|
|
|
|
"""
|
2024-07-17 17:36:25 +02:00
|
|
|
from typing import Optional
|
2024-06-25 18:55:52 +02:00
|
|
|
from uuid import uuid4
|
|
|
|
|
|
|
|
|
|
from django.conf import settings
|
|
|
|
|
|
|
|
|
|
from livekit.api import AccessToken, VideoGrants
|
|
|
|
|
|
|
|
|
|
|
2024-07-17 17:36:25 +02:00
|
|
|
def generate_token(room: str, user, username: Optional[str] = None) -> str:
|
2024-06-25 18:55:52 +02:00
|
|
|
"""Generate a Livekit access token for a user in a specific room.
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
room (str): The name of the room.
|
|
|
|
|
user (User): The user which request the access token.
|
2024-07-17 17:36:25 +02:00
|
|
|
username (Optional[str]): The username to be displayed in the room.
|
|
|
|
|
If none, a default value will be used.
|
2024-06-25 18:55:52 +02:00
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
|
str: The LiveKit JWT access token.
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
video_grants = VideoGrants(
|
|
|
|
|
room=room,
|
|
|
|
|
room_join=True,
|
|
|
|
|
can_publish_sources=[
|
|
|
|
|
"camera",
|
|
|
|
|
"microphone",
|
|
|
|
|
"screen_share",
|
|
|
|
|
"screen_share_audio",
|
|
|
|
|
],
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
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()))
|
2024-07-17 17:36:25 +02:00
|
|
|
default_username = "Anonymous"
|
2024-06-25 18:55:52 +02:00
|
|
|
else:
|
2024-07-17 17:36:25 +02:00
|
|
|
token.with_identity(user.sub)
|
|
|
|
|
default_username = str(user)
|
|
|
|
|
|
|
|
|
|
token.with_name(username or default_username)
|
2024-06-25 18:55:52 +02:00
|
|
|
|
|
|
|
|
return token.to_jwt()
|