import { Controller, Get, Headers, HttpCode, Param, PayloadTooLargeException, Post, Req, } from '@nestjs/common'; import { conversationIdSchema } from '@repo/contracts'; import { AllowAnonymous, Session, type UserSession, } from '@thallesp/nestjs-better-auth'; import type { Request } from 'express'; import type { Auth } from '../auth/auth'; import { CallsService } from './calls.service'; import { AtMost } from '../rate-limit/at-most'; import { SkipThrottle } from '@nestjs/throttler'; // Reports are a few kilobytes; nothing genuine comes near this. const WEBHOOK_MAX_BYTES = 256 * 1024; @Controller() export class CallsController { constructor(private readonly calls: CallsService) {} /** The calls going on in the user's conversations and cauldrons. */ @Get('calls') overview(@Session() session: UserSession) { return this.calls.overview(session.user.id); } /** What the browser needs to join the call here; the first one in starts it. */ @Post('conversations/:id/call') @AtMost(20, { seconds: 60 }) @HttpCode(200) join( @Session() session: UserSession, @Param('id', { schema: conversationIdSchema }) conversationId: string, ) { return this.calls.join(session.user.id, conversationId); } /** * Where the media server reports who joined and left. No session: the * report is signed with the server's own key, over the body exactly as * sent, which is why the body is read here and not parsed on the way in * (its type, application/webhook+json, isn't one the parsers take). */ @Post('livekit/webhook') @AllowAnonymous() // All of them come from the one media server, as fast as people join. @SkipThrottle() @HttpCode(200) async webhook( @Req() req: Request, @Headers('authorization') authorization: string | undefined, ) { await this.calls.handleWebhook(await readText(req), authorization); } } async function readText(req: Request): Promise { const chunks: Buffer[] = []; let size = 0; for await (const chunk of req as AsyncIterable) { size += chunk.length; if (size > WEBHOOK_MAX_BYTES) throw new PayloadTooLargeException(); chunks.push(chunk); } return Buffer.concat(chunks).toString('utf8'); }