Skip to content

Commit

Permalink
move endpoint in api folder
Browse files Browse the repository at this point in the history
  • Loading branch information
Ocupe committed Sep 16, 2024
1 parent c8ea468 commit c75b3a0
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 2 deletions.
68 changes: 68 additions & 0 deletions frontend/app/api/connection-details/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import {
AccessToken,
AccessTokenOptions,
VideoGrant,
} from "livekit-server-sdk";
import { NextResponse } from "next/server";

const API_KEY = process.env.LIVEKIT_API_KEY;
const API_SECRET = process.env.LIVEKIT_API_SECRET;
const LIVEKIT_URL = process.env.LIVEKIT_URL;

export type ConnectionDetails = {
serverUrl: string;
roomName: string;
participantName: string;
participantToken: string;
};

export async function GET() {
try {
// Generate participant token
const participantIdentity = `voice_assistant_user_${Math.round(
Math.random() * 10_000
)}`;
const participantToken = await createParticipantToken(
{
identity: participantIdentity,
},
"roomName"
);

if (LIVEKIT_URL === undefined) {
throw new Error("LIVEKIT_URL is not defined");
}

// Return connection details
const data: ConnectionDetails = {
serverUrl: LIVEKIT_URL,
roomName: "voice_assistant_room",
participantToken: participantToken,
participantName: participantIdentity,
};
return NextResponse.json(data);
} catch (error) {
if (error instanceof Error) {
console.error(error);

return new NextResponse(error.message, { status: 500 });
}
}
}

function createParticipantToken(
userInfo: AccessTokenOptions,
roomName: string
) {
const at = new AccessToken(API_KEY, API_SECRET, userInfo);
at.ttl = "5m";
const grant: VideoGrant = {
room: roomName,
roomJoin: true,
canPublish: true,
canPublishData: true,
canSubscribe: true,
};
at.addGrant(grant);
return at.toJwt();
}
5 changes: 3 additions & 2 deletions frontend/app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
} from "@livekit/components-react";
import { useCallback, useState } from "react";
import { MediaDeviceFailure } from "livekit-client";
import type { ConnectionDetails } from "./connection-details/route";
import type { ConnectionDetails } from "./api/connection-details/route";

export default function Page() {
const [connectionDetails, updateConnectionDetails] = useState<
Expand All @@ -20,7 +20,8 @@ export default function Page() {

const onConnectButtonClicked = useCallback(async () => {
const url = new URL(
process.env.NEXT_PUBLIC_CONN_DETAILS_ENDPOINT ?? "/connection-details",
process.env.NEXT_PUBLIC_CONN_DETAILS_ENDPOINT ??
"/api/connection-details",
window.location.origin
);
const response = await fetch(url.toString());
Expand Down

0 comments on commit c75b3a0

Please sign in to comment.