From f4a301c1168bdde0ba23c4a0975c710818b9b928 Mon Sep 17 00:00:00 2001 From: lukasIO Date: Fri, 20 Jan 2023 15:41:00 +0100 Subject: [PATCH] Change env var names, add support for region query (#10) --- .env.example | 5 ++-- lib/Debug.tsx | 10 ++++---- lib/client-utils.ts | 21 +++++++++++++++++ lib/{clients.ts => server-utils.ts} | 8 +++---- lib/types.ts | 1 - pages/api/token.ts | 7 +----- pages/api/url.ts | 17 ++++++++++++++ pages/rooms/[name].tsx | 36 +++++++++++++++++++---------- 8 files changed, 75 insertions(+), 30 deletions(-) create mode 100644 lib/client-utils.ts rename lib/{clients.ts => server-utils.ts} (74%) create mode 100644 pages/api/url.ts diff --git a/.env.example b/.env.example index 7b20efa..1d92e0e 100644 --- a/.env.example +++ b/.env.example @@ -5,7 +5,8 @@ LIVEKIT_API_KEY=devkey LIVEKIT_API_SECRET=secret +# URL pointing to the LiveKit server. +LIVEKIT_URL=wss://my-livekit-project.livekit.cloud ## PUBLIC -NEXT_PUBLIC_LK_TOKEN_ENDPOINT=/api/token -NEXT_PUBLIC_LK_SERVER_URL=wss://my-livekit-project.livekit.cloud +NEXT_PUBLIC_LK_TOKEN_ENDPOINT=/api/token \ No newline at end of file diff --git a/lib/Debug.tsx b/lib/Debug.tsx index 3666e2b..6362398 100644 --- a/lib/Debug.tsx +++ b/lib/Debug.tsx @@ -1,9 +1,9 @@ import * as React from 'react'; import { useRoomContext } from '@livekit/components-react'; -import { setLogLevel } from 'livekit-client'; +import { setLogLevel, LogLevel } from 'livekit-client'; -export const useDebugMode = () => { - setLogLevel('debug'); +export const useDebugMode = ({ logLevel }: { logLevel?: LogLevel }) => { + setLogLevel(logLevel ?? 'debug'); const room = useRoomContext(); React.useEffect(() => { // @ts-expect-error @@ -16,7 +16,7 @@ export const useDebugMode = () => { }); }; -export const DebugMode = () => { - useDebugMode(); +export const DebugMode = ({ logLevel }: { logLevel?: LogLevel }) => { + useDebugMode({ logLevel }); return <>; }; diff --git a/lib/client-utils.ts b/lib/client-utils.ts new file mode 100644 index 0000000..a2401c8 --- /dev/null +++ b/lib/client-utils.ts @@ -0,0 +1,21 @@ +import { useEffect, useState } from 'react'; + +export function useServerUrl(region?: string) { + const [serverUrl, setServerUrl] = useState(); + useEffect(() => { + let endpoint = `/api/url`; + if (region) { + endpoint += `?region=${region}`; + } + fetch(endpoint).then(async (res) => { + if (res.ok) { + const body = await res.json(); + console.log(body); + setServerUrl(body.url); + } else { + throw Error('Error fetching server url, check server logs'); + } + }); + }); + return serverUrl; +} diff --git a/lib/clients.ts b/lib/server-utils.ts similarity index 74% rename from lib/clients.ts rename to lib/server-utils.ts index 4d6c9a5..1ea1c31 100644 --- a/lib/clients.ts +++ b/lib/server-utils.ts @@ -5,10 +5,10 @@ export function getRoomClient(): RoomServiceClient { return new RoomServiceClient(getLiveKitURL()); } -export function getLiveKitURL(region?: string): string { - let targetKey = 'NEXT_PUBLIC_LK_SERVER_URL'; - if (region) { - targetKey = `NEXT_PUBLIC_LK_SERVER_URL${region}`.toUpperCase(); +export function getLiveKitURL(region?: string | string[]): string { + let targetKey = 'LIVEKIT_URL'; + if (region && !Array.isArray(region)) { + targetKey = `LIVEKIT_URL_${region}`.toUpperCase(); } const url = process.env[targetKey]; if (!url) { diff --git a/lib/types.ts b/lib/types.ts index 6975c7d..122a847 100644 --- a/lib/types.ts +++ b/lib/types.ts @@ -12,6 +12,5 @@ export interface SessionProps { export interface TokenResult { identity: string; - url: string; accessToken: string; } diff --git a/pages/api/token.ts b/pages/api/token.ts index 8aef402..c4353b5 100644 --- a/pages/api/token.ts +++ b/pages/api/token.ts @@ -2,7 +2,6 @@ import { NextApiRequest, NextApiResponse } from 'next'; import { AccessToken } from 'livekit-server-sdk'; import type { AccessTokenOptions, VideoGrant } from 'livekit-server-sdk'; -import { getLiveKitURL } from '../../lib/clients'; import { TokenResult } from '../../lib/types'; const apiKey = process.env.LIVEKIT_API_KEY; @@ -19,7 +18,7 @@ const roomPattern = /\w{4}\-\w{4}/; export default async function handleToken(req: NextApiRequest, res: NextApiResponse) { try { - const { roomName, identity, name, metadata, region } = req.query; + const { roomName, identity, name, metadata } = req.query; if (typeof identity !== 'string' || typeof roomName !== 'string') { res.status(403).end(); @@ -32,9 +31,6 @@ export default async function handleToken(req: NextApiRequest, res: NextApiRespo if (Array.isArray(metadata)) { throw Error('provide max one metadata string'); } - if (Array.isArray(region)) { - throw Error('provide max one region string'); - } // enforce room name to be xxxx-xxxx // this is simple & naive way to prevent user from guessing room names @@ -61,7 +57,6 @@ export default async function handleToken(req: NextApiRequest, res: NextApiRespo const result: TokenResult = { identity, accessToken: token, - url: getLiveKitURL(region), }; res.status(200).json(result); diff --git a/pages/api/url.ts b/pages/api/url.ts new file mode 100644 index 0000000..1fdadd2 --- /dev/null +++ b/pages/api/url.ts @@ -0,0 +1,17 @@ +import { NextApiRequest, NextApiResponse } from 'next'; +import { getLiveKitURL } from '../../lib/server-utils'; + +export default async function handleServerUrl(req: NextApiRequest, res: NextApiResponse) { + try { + const { region } = req.query; + + if (Array.isArray(region)) { + throw Error('provide max one region string'); + } + const url = getLiveKitURL(region); + res.status(200).json({ url }); + } catch (e) { + res.statusMessage = (e as Error).message; + res.status(500).end(); + } +} diff --git a/pages/rooms/[name].tsx b/pages/rooms/[name].tsx index 0e49bea..cd66c18 100644 --- a/pages/rooms/[name].tsx +++ b/pages/rooms/[name].tsx @@ -5,13 +5,15 @@ import { useToken, VideoConference, } from '@livekit/components-react'; -import { RoomOptions } from 'livekit-client'; +import { LogLevel, RoomOptions } from 'livekit-client'; import type { NextPage } from 'next'; import Head from 'next/head'; import { useRouter } from 'next/router'; import { useMemo, useState } from 'react'; +import { getLiveKitURL } from '../../lib/server-utils'; import { DebugMode } from '../../lib/Debug'; +import { useServerUrl } from '../../lib/client-utils'; const Home: NextPage = () => { const router = useRouter(); @@ -58,6 +60,7 @@ export default Home; type ActiveRoomProps = { userChoices: LocalUserChoices; roomName: string; + region?: string; onLeave?: () => void; }; const ActiveRoom = ({ roomName, userChoices, onLeave }: ActiveRoomProps) => { @@ -70,6 +73,11 @@ const ActiveRoom = ({ roomName, userChoices, onLeave }: ActiveRoomProps) => { }, }); + const router = useRouter(); + const { region } = router.query; + + const liveKitUrl = useServerUrl(region as string | undefined); + const roomOptions = useMemo((): RoomOptions => { return { videoCaptureDefaults: { @@ -84,16 +92,20 @@ const ActiveRoom = ({ roomName, userChoices, onLeave }: ActiveRoomProps) => { }, [userChoices]); return ( - - - - + <> + {liveKitUrl && ( + + + + + )} + ); };