feat: restore original recording consent functionality

- Remove custom ConsentDialogButton and WherebyEmbed components
- Merge RoomClient logic back into main room page
- Restore original consent UI: blue button with toast modal
- Maintain calendar integration features for ICS-enabled rooms
- Add consent-handler.md documentation of original functionality
- Preserve focus management and accessibility features
This commit is contained in:
2025-09-10 17:31:34 -06:00
parent 78a30b37c8
commit 1557af1ac9
4 changed files with 811 additions and 239 deletions

125
consent-handler.md Normal file
View File

@@ -0,0 +1,125 @@
# Recording Consent Handler Documentation
This document describes the recording consent functionality found in the main branch of Reflector.
## Overview
The recording consent system manages user consent for storing meeting audio recordings on servers. It only appears when `recording_type` is set to "cloud" and shows a prominent blue button with toast-based consent dialog.
## Components and Files
### 1. ConsentDialogButton Component
**Location**: `www/app/[roomName]/page.tsx:206-234`
**Visual Appearance**:
- **Button text**: "Meeting is being recorded"
- **Button color**: Blue (`colorPalette="blue"`)
- **Position**: Absolute positioned at `top="56px"` `left="8px"`
- **Z-index**: 1000 (appears above video)
- **Size**: Small (`size="sm"`)
- **Icon**: FaBars icon from react-icons/fa6
**Behavior**:
- Only shows when:
- Consent context is ready
- User hasn't already given consent for this meeting
- Not currently loading consent submission
- Recording type requires consent (cloud recording)
### 2. Consent Modal/Toast
**Location**: `www/app/[roomName]/page.tsx:107-196` (useConsentDialog hook)
**Visual Appearance**:
- **Background**: Semi-transparent white (`bg="rgba(255, 255, 255, 0.7)"`)
- **Border radius**: Large (`borderRadius="lg"`)
- **Box shadow**: Large (`boxShadow="lg"`)
- **Max width**: Medium (`maxW="md"`)
- **Position**: Top placement toast
**Content**:
- **Main text**: "Can we have your permission to store this meeting's audio recording on our servers?"
- **Font**: Medium size, medium weight, center aligned
**Buttons**:
1. **Decline Button**:
- Text: "No, delete after transcription"
- Style: Ghost variant, small size
- Action: Sets consent to false
2. **Accept Button**:
- Text: "Yes, store the audio"
- Style: Primary color palette, small size
- Action: Sets consent to true
- Has special focus management for accessibility
### 3. Recording Consent Context
**Location**: `www/app/recordingConsentContext.tsx`
**Key Features**:
- Uses localStorage to persist consent decisions
- Keeps track of up to 5 recent meeting consent decisions
- Provides three main functions:
- `state`: Current context state (ready/not ready + consent set)
- `touch(meetingId)`: Mark consent as given for a meeting
- `hasConsent(meetingId)`: Check if consent already given
**localStorage Key**: `"recording_consent_meetings"`
### 4. Focus Management
**Location**: `www/app/[roomName]/page.tsx:39-74` (useConsentWherebyFocusManagement hook)
**Purpose**: Manages focus between the consent button and Whereby video embed for accessibility
- Initially focuses the accept button
- Handles Whereby "ready" events to refocus consent
- Restores original focus when consent dialog closes
### 5. API Integration
**Hook**: `useMeetingAudioConsent()` from `../lib/apiHooks`
**Endpoint**: Submits consent decision to `/meetings/{meeting_id}/consent` with body:
```json
{
"consent_given": boolean
}
```
## Logic Flow
1. **Trigger Condition**:
- Meeting has `recording_type === "cloud"`
- User hasn't already consented for this meeting
2. **Button Display**:
- Blue "Meeting is being recorded" button appears over video
3. **User Interaction**:
- Click button → Opens consent toast modal
- User chooses "Yes" or "No"
- Decision sent to API
- Meeting ID added to local consent cache
- Modal closes
4. **State Management**:
- Consent decision cached locally for this meeting
- Button disappears after consent given
- No further prompts for this meeting
## Integration Points
- **Room Component**: Main integration in `www/app/[roomName]/page.tsx:324-329`
- **Conditional Rendering**: Only shows when `recordingTypeRequiresConsent(recordingType)` returns true
- **Authentication**: Requires user to be authenticated
- **Whereby Integration**: Coordinates with video embed focus management
## Key Features
- **Non-blocking**: User can interact with video while consent prompt is visible
- **Persistent**: Consent decisions remembered across sessions
- **Accessible**: Proper focus management and keyboard navigation
- **Conditional**: Only appears for cloud recordings requiring consent
- **Toast-based**: Uses toast system for non-intrusive user experience

View File

@@ -1,147 +0,0 @@
"use client";
import { useEffect } from "react";
import { Box, Spinner, Text } from "@chakra-ui/react";
import { useRouter } from "next/navigation";
import {
useRoomGetByName,
useRoomActiveMeetings,
useRoomUpcomingMeetings,
useRoomsCreateMeeting,
} from "../lib/apiHooks";
import type { components } from "../reflector-api";
import MeetingSelection from "./MeetingSelection";
import { useAuth } from "../lib/AuthProvider";
import useRoomMeeting from "./useRoomMeeting";
import dynamic from "next/dynamic";
const WherebyEmbed = dynamic(() => import("../lib/WherebyWebinarEmbed"), {
ssr: false,
});
type Meeting = components["schemas"]["Meeting"];
interface RoomClientProps {
params: {
roomName: string;
};
}
export default function RoomClient({ params }: RoomClientProps) {
const roomName = params.roomName;
const router = useRouter();
const auth = useAuth();
// Fetch room details using React Query
const roomQuery = useRoomGetByName(roomName);
const activeMeetingsQuery = useRoomActiveMeetings(roomName);
const upcomingMeetingsQuery = useRoomUpcomingMeetings(roomName);
const createMeetingMutation = useRoomsCreateMeeting();
const room = roomQuery.data;
const activeMeetings = activeMeetingsQuery.data || [];
const upcomingMeetings = upcomingMeetingsQuery.data || [];
// For non-ICS rooms, create a meeting and get Whereby URL
const roomMeeting = useRoomMeeting(
room && !room.ics_enabled ? roomName : null,
);
const roomUrl =
roomMeeting?.response?.host_room_url || roomMeeting?.response?.room_url;
const isLoading = auth.status === "loading" || roomQuery.isLoading;
const isOwner =
auth.status === "authenticated" && room
? auth.user?.id === room.user_id
: false;
const handleMeetingSelect = (selectedMeeting: Meeting) => {
// Navigate to specific meeting using path segment
router.push(`/${roomName}/${selectedMeeting.id}`);
};
const handleCreateUnscheduled = async () => {
try {
// Create a new unscheduled meeting
const newMeeting = await createMeetingMutation.mutateAsync({
params: {
path: { room_name: roomName },
},
});
handleMeetingSelect(newMeeting);
} catch (err) {
console.error("Failed to create meeting:", err);
}
};
// Handle room not found
useEffect(() => {
if (roomQuery.isError) {
router.push("/");
}
}, [roomQuery.isError, router]);
if (isLoading) {
return (
<Box
display="flex"
justifyContent="center"
alignItems="center"
height="100vh"
bg="gray.50"
p={4}
>
<Spinner color="blue.500" size="xl" />
</Box>
);
}
if (!room) {
return (
<Box
display="flex"
justifyContent="center"
alignItems="center"
height="100vh"
bg="gray.50"
p={4}
>
<Text fontSize="lg">Room not found</Text>
</Box>
);
}
// For ICS-enabled rooms, show meeting selection
if (room.ics_enabled) {
return (
<MeetingSelection
roomName={roomName}
isOwner={isOwner}
isSharedRoom={room?.is_shared || false}
authLoading={["loading", "refreshing"].includes(auth.status)}
onMeetingSelect={handleMeetingSelect}
onCreateUnscheduled={handleCreateUnscheduled}
/>
);
}
// For non-ICS rooms, show Whereby embed directly
if (roomUrl) {
return <WherebyEmbed roomUrl={roomUrl} />;
}
// Loading state for non-ICS rooms while creating meeting
return (
<Box
display="flex"
justifyContent="center"
alignItems="center"
height="100vh"
bg="gray.50"
p={4}
>
<Spinner color="blue.500" size="xl" />
</Box>
);
}

View File

@@ -1,10 +1,234 @@
"use client"; "use client";
import { useEffect, useState } from "react"; import { useCallback, useEffect, useRef, useState } from "react";
import { Box, Spinner, Text, VStack } from "@chakra-ui/react"; import { Box, Button, HStack, Icon, Spinner, Text, VStack } from "@chakra-ui/react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { useRoomGetByName } from "../../lib/apiHooks"; import { useRoomGetByName, useRoomJoinMeeting, useMeetingAudioConsent } from "../../lib/apiHooks";
import { useRecordingConsent } from "../../recordingConsentContext";
import { toaster } from "../../components/ui/toaster";
import { FaBars } from "react-icons/fa6";
import MinimalHeader from "../../components/MinimalHeader"; import MinimalHeader from "../../components/MinimalHeader";
import type { components } from "../../reflector-api";
type Meeting = components["schemas"]["Meeting"];
// next throws even with "use client"
const useWhereby = () => {
const [wherebyLoaded, setWherebyLoaded] = useState(false);
useEffect(() => {
if (typeof window !== "undefined") {
import("@whereby.com/browser-sdk/embed")
.then(() => {
setWherebyLoaded(true);
})
.catch(console.error.bind(console));
}
}, []);
return wherebyLoaded;
};
// Consent functionality from main branch
const useConsentWherebyFocusManagement = (
acceptButtonRef: React.RefObject<HTMLButtonElement>,
wherebyRef: React.RefObject<HTMLElement>,
) => {
const currentFocusRef = useRef<HTMLElement | null>(null);
useEffect(() => {
if (acceptButtonRef.current) {
acceptButtonRef.current.focus();
} else {
console.error(
"accept button ref not available yet for focus management - seems to be illegal state",
);
}
const handleWherebyReady = () => {
console.log("whereby ready - refocusing consent button");
currentFocusRef.current = document.activeElement as HTMLElement;
if (acceptButtonRef.current) {
acceptButtonRef.current.focus();
}
};
if (wherebyRef.current) {
wherebyRef.current.addEventListener("ready", handleWherebyReady);
} else {
console.warn(
"whereby ref not available yet for focus management - seems to be illegal state. not waiting, focus management off.",
);
}
return () => {
wherebyRef.current?.removeEventListener("ready", handleWherebyReady);
currentFocusRef.current?.focus();
};
}, []);
};
const useConsentDialog = (
meetingId: string,
wherebyRef: React.RefObject<HTMLElement>,
) => {
const { state: consentState, touch, hasConsent } = useRecordingConsent();
const [modalOpen, setModalOpen] = useState(false);
const audioConsentMutation = useMeetingAudioConsent();
const handleConsent = useCallback(
async (meetingId: string, given: boolean) => {
try {
await audioConsentMutation.mutateAsync({
params: {
path: {
meeting_id: meetingId,
},
},
body: {
consent_given: given,
},
});
touch(meetingId);
} catch (error) {
console.error("Error submitting consent:", error);
}
},
[audioConsentMutation, touch],
);
const showConsentModal = useCallback(() => {
if (modalOpen) return;
setModalOpen(true);
const toastId = toaster.create({
placement: "top",
duration: null,
render: ({ dismiss }) => {
const AcceptButton = () => {
const buttonRef = useRef<HTMLButtonElement>(null);
useConsentWherebyFocusManagement(buttonRef, wherebyRef);
return (
<Button
ref={buttonRef}
colorPalette="primary"
size="sm"
onClick={() => {
handleConsent(meetingId, true).then(() => {
/*signifies it's ok to now wait here.*/
});
dismiss();
}}
>
Yes, store the audio
</Button>
);
};
return (
<Box
p={6}
bg="rgba(255, 255, 255, 0.7)"
borderRadius="lg"
boxShadow="lg"
maxW="md"
mx="auto"
>
<VStack gap={4} alignItems="center">
<Text fontSize="md" textAlign="center" fontWeight="medium">
Can we have your permission to store this meeting's audio
recording on our servers?
</Text>
<HStack gap={4} justifyContent="center">
<Button
variant="ghost"
size="sm"
onClick={() => {
handleConsent(meetingId, false).then(() => {
/*signifies it's ok to now wait here.*/
});
dismiss();
}}
>
No, delete after transcription
</Button>
<AcceptButton />
</HStack>
</VStack>
</Box>
);
},
});
// Set modal state when toast is dismissed
toastId.then((id) => {
const checkToastStatus = setInterval(() => {
if (!toaster.isActive(id)) {
setModalOpen(false);
clearInterval(checkToastStatus);
}
}, 100);
});
// Handle escape key to close the toast
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === "Escape") {
toastId.then((id) => toaster.dismiss(id));
}
};
document.addEventListener("keydown", handleKeyDown);
const cleanup = () => {
toastId.then((id) => toaster.dismiss(id));
document.removeEventListener("keydown", handleKeyDown);
};
return cleanup;
}, [meetingId, handleConsent, wherebyRef, modalOpen]);
return {
showConsentModal,
consentState,
hasConsent,
consentLoading: audioConsentMutation.isPending,
};
};
function ConsentDialogButton({
meetingId,
wherebyRef,
}: {
meetingId: string;
wherebyRef: React.RefObject<HTMLElement>;
}) {
const { showConsentModal, consentState, hasConsent, consentLoading } =
useConsentDialog(meetingId, wherebyRef);
if (!consentState.ready || hasConsent(meetingId) || consentLoading) {
return null;
}
return (
<Button
position="absolute"
top="56px"
left="8px"
zIndex={1000}
colorPalette="blue"
size="sm"
onClick={showConsentModal}
>
Meeting is being recorded
<Icon as={FaBars} ml={2} />
</Button>
);
}
const recordingTypeRequiresConsent = (
recordingType: NonNullable<Meeting["recording_type"]>,
) => {
return recordingType === "cloud";
};
interface MeetingPageProps { interface MeetingPageProps {
params: { params: {
roomName: string; roomName: string;
@@ -15,27 +239,64 @@ interface MeetingPageProps {
export default function MeetingPage({ params }: MeetingPageProps) { export default function MeetingPage({ params }: MeetingPageProps) {
const { roomName, meetingId } = params; const { roomName, meetingId } = params;
const router = useRouter(); const router = useRouter();
const [attemptedJoin, setAttemptedJoin] = useState(false);
const wherebyLoaded = useWhereby();
const wherebyRef = useRef<HTMLElement>(null);
// Fetch room data // Fetch room data
const roomQuery = useRoomGetByName(roomName); const roomQuery = useRoomGetByName(roomName);
const joinMeetingMutation = useRoomJoinMeeting();
const room = roomQuery.data; const room = roomQuery.data;
const isLoading = roomQuery.isLoading; const isLoading = roomQuery.isLoading || (!attemptedJoin && room && !joinMeetingMutation.data);
const error = roomQuery.error;
// Try to join the meeting when room is loaded
// Redirect to selection if room not found
useEffect(() => { useEffect(() => {
if (roomQuery.isError) { if (room && !attemptedJoin && !joinMeetingMutation.isPending) {
setAttemptedJoin(true);
joinMeetingMutation.mutate({
params: {
path: {
room_name: roomName,
meeting_id: meetingId,
},
},
});
}
}, [room, attemptedJoin, joinMeetingMutation, roomName, meetingId]);
// Redirect to room lobby if meeting join fails (meeting finished/not found)
useEffect(() => {
if (joinMeetingMutation.isError || roomQuery.isError) {
router.push(`/${roomName}`); router.push(`/${roomName}`);
} }
}, [roomQuery.isError, router, roomName]); }, [joinMeetingMutation.isError, roomQuery.isError, router, roomName]);
// Get meeting data from join response
const meeting = joinMeetingMutation.data;
const roomUrl = meeting?.host_room_url || meeting?.room_url;
const recordingType = meeting?.recording_type;
const handleLeave = useCallback(() => {
router.push(`/${roomName}`);
}, [router, roomName]);
useEffect(() => {
if (!isLoading && !roomUrl && !wherebyLoaded) return;
wherebyRef.current?.addEventListener("leave", handleLeave);
return () => {
wherebyRef.current?.removeEventListener("leave", handleLeave);
};
}, [handleLeave, roomUrl, isLoading, wherebyLoaded]);
if (isLoading) { if (isLoading) {
return ( return (
<Box display="flex" flexDirection="column" minH="100vh"> <Box display="flex" flexDirection="column" minH="100vh">
<MinimalHeader <MinimalHeader
roomName={roomName} roomName={roomName}
displayName={room?.display_name || room?.name} displayName={room?.name}
showLeaveButton={false} showLeaveButton={false}
/> />
<Box <Box
@@ -55,64 +316,42 @@ export default function MeetingPage({ params }: MeetingPageProps) {
); );
} }
if (error || !room) { // If we have a successful meeting join with room URL, show Whereby embed
if (meeting && roomUrl && wherebyLoaded) {
return ( return (
<Box display="flex" flexDirection="column" minH="100vh"> <>
<MinimalHeader <whereby-embed
roomName={roomName} ref={wherebyRef}
displayName={room?.display_name || room?.name} room={roomUrl}
style={{ width: "100vw", height: "100vh" }}
/> />
<Box {recordingType && recordingTypeRequiresConsent(recordingType) && (
display="flex" <ConsentDialogButton
justifyContent="center" meetingId={meetingId}
alignItems="center" wherebyRef={wherebyRef}
flex="1" />
bg="gray.50" )}
p={4} </>
>
<Text fontSize="lg">Meeting not found</Text>
</Box>
</Box>
); );
} }
// This return should not be reached normally since we redirect on errors
// But keeping it as a fallback
return ( return (
<Box display="flex" flexDirection="column" minH="100vh"> <Box display="flex" flexDirection="column" minH="100vh">
<MinimalHeader <MinimalHeader
roomName={roomName} roomName={roomName}
displayName={room?.display_name || room?.name} displayName={room?.name}
/> />
<Box
<Box flex="1" bg="gray.50" p={4}> display="flex"
<VStack gap={4} align="stretch" maxW="container.lg" mx="auto"> justifyContent="center"
<Text fontSize="2xl" fontWeight="bold" textAlign="center"> alignItems="center"
Meeting Room flex="1"
</Text> bg="gray.50"
p={4}
<Box >
bg="white" <Text fontSize="lg">Meeting not available</Text>
borderRadius="md"
p={6}
textAlign="center"
minH="400px"
display="flex"
alignItems="center"
justifyContent="center"
>
<VStack gap={4}>
<Text fontSize="lg" color="gray.600">
Meeting Interface Coming Soon
</Text>
<Text fontSize="sm" color="gray.500">
This is where the video call, transcription, and meeting
controls will be displayed.
</Text>
<Text fontSize="sm" color="gray.500">
Meeting ID: {meetingId}
</Text>
</VStack>
</Box>
</VStack>
</Box> </Box>
</Box> </Box>
); );

View File

@@ -1,5 +1,34 @@
import { Metadata } from "next"; "use client";
import RoomClient from "./RoomClient";
import {
useCallback,
useEffect,
useRef,
useState,
useContext,
RefObject,
} from "react";
import {
Box,
Button,
Text,
VStack,
HStack,
Spinner,
Icon,
} from "@chakra-ui/react";
import { toaster } from "../components/ui/toaster";
import { useRouter } from "next/navigation";
import { notFound } from "next/navigation";
import { useRecordingConsent } from "../recordingConsentContext";
import { useMeetingAudioConsent, useRoomGetByName, useRoomActiveMeetings, useRoomUpcomingMeetings, useRoomsCreateMeeting } from "../lib/apiHooks";
import type { components } from "../reflector-api";
import MeetingSelection from "./MeetingSelection";
import useRoomMeeting from "./useRoomMeeting";
type Meeting = components["schemas"]["Meeting"];
import { FaBars } from "react-icons/fa6";
import { useAuth } from "../lib/AuthProvider";
export type RoomDetails = { export type RoomDetails = {
params: { params: {
@@ -7,42 +36,368 @@ export type RoomDetails = {
}; };
}; };
// Generate dynamic metadata for the room selection page // stages: we focus on the consent, then whereby steals focus, then we focus on the consent again, then return focus to whoever stole it initially
export async function generateMetadata({ const useConsentWherebyFocusManagement = (
params, acceptButtonRef: RefObject<HTMLButtonElement>,
}: RoomDetails): Promise<Metadata> { wherebyRef: RefObject<HTMLElement>,
const { roomName } = params; ) => {
const currentFocusRef = useRef<HTMLElement | null>(null);
try { useEffect(() => {
// Fetch room data server-side for metadata if (acceptButtonRef.current) {
const response = await fetch( acceptButtonRef.current.focus();
`${process.env.NEXT_PUBLIC_REFLECTOR_API_URL}/v1/rooms/name/${roomName}`, } else {
{ console.error(
headers: { "accept button ref not available yet for focus management - seems to be illegal state",
"Content-Type": "application/json", );
},
},
);
if (response.ok) {
const room = await response.json();
const displayName = room.display_name || room.name;
return {
title: `${displayName} Room - Select a Meeting`,
description: `Join a meeting in ${displayName}'s room on Reflector.`,
};
} }
} catch (error) {
console.error("Failed to fetch room for metadata:", error); const handleWherebyReady = () => {
console.log("whereby ready - refocusing consent button");
currentFocusRef.current = document.activeElement as HTMLElement;
if (acceptButtonRef.current) {
acceptButtonRef.current.focus();
}
};
if (wherebyRef.current) {
wherebyRef.current.addEventListener("ready", handleWherebyReady);
} else {
console.warn(
"whereby ref not available yet for focus management - seems to be illegal state. not waiting, focus management off.",
);
}
return () => {
wherebyRef.current?.removeEventListener("ready", handleWherebyReady);
currentFocusRef.current?.focus();
};
}, []);
};
const useConsentDialog = (
meetingId: string,
wherebyRef: RefObject<HTMLElement> /*accessibility*/,
) => {
const { state: consentState, touch, hasConsent } = useRecordingConsent();
// toast would open duplicates, even with using "id=" prop
const [modalOpen, setModalOpen] = useState(false);
const audioConsentMutation = useMeetingAudioConsent();
const handleConsent = useCallback(
async (meetingId: string, given: boolean) => {
try {
await audioConsentMutation.mutateAsync({
params: {
path: {
meeting_id: meetingId,
},
},
body: {
consent_given: given,
},
});
touch(meetingId);
} catch (error) {
console.error("Error submitting consent:", error);
}
},
[audioConsentMutation, touch],
);
const showConsentModal = useCallback(() => {
if (modalOpen) return;
setModalOpen(true);
const toastId = toaster.create({
placement: "top",
duration: null,
render: ({ dismiss }) => {
const AcceptButton = () => {
const buttonRef = useRef<HTMLButtonElement>(null);
useConsentWherebyFocusManagement(buttonRef, wherebyRef);
return (
<Button
ref={buttonRef}
colorPalette="primary"
size="sm"
onClick={() => {
handleConsent(meetingId, true).then(() => {
/*signifies it's ok to now wait here.*/
});
dismiss();
}}
>
Yes, store the audio
</Button>
);
};
return (
<Box
p={6}
bg="rgba(255, 255, 255, 0.7)"
borderRadius="lg"
boxShadow="lg"
maxW="md"
mx="auto"
>
<VStack gap={4} alignItems="center">
<Text fontSize="md" textAlign="center" fontWeight="medium">
Can we have your permission to store this meeting's audio
recording on our servers?
</Text>
<HStack gap={4} justifyContent="center">
<Button
variant="ghost"
size="sm"
onClick={() => {
handleConsent(meetingId, false).then(() => {
/*signifies it's ok to now wait here.*/
});
dismiss();
}}
>
No, delete after transcription
</Button>
<AcceptButton />
</HStack>
</VStack>
</Box>
);
},
});
// Set modal state when toast is dismissed
toastId.then((id) => {
const checkToastStatus = setInterval(() => {
if (!toaster.isActive(id)) {
setModalOpen(false);
clearInterval(checkToastStatus);
}
}, 100);
});
// Handle escape key to close the toast
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === "Escape") {
toastId.then((id) => toaster.dismiss(id));
}
};
document.addEventListener("keydown", handleKeyDown);
const cleanup = () => {
toastId.then((id) => toaster.dismiss(id));
document.removeEventListener("keydown", handleKeyDown);
};
return cleanup;
}, [meetingId, handleConsent, wherebyRef, modalOpen]);
return {
showConsentModal,
consentState,
hasConsent,
consentLoading: audioConsentMutation.isPending,
};
};
function ConsentDialogButton({
meetingId,
wherebyRef,
}: {
meetingId: string;
wherebyRef: React.RefObject<HTMLElement>;
}) {
const { showConsentModal, consentState, hasConsent, consentLoading } =
useConsentDialog(meetingId, wherebyRef);
if (!consentState.ready || hasConsent(meetingId) || consentLoading) {
return null;
} }
// Fallback if room fetch fails return (
return { <Button
title: `${roomName} Room - Select a Meeting`, position="absolute"
description: `Join a meeting in ${roomName}'s room on Reflector.`, top="56px"
}; left="8px"
zIndex={1000}
colorPalette="blue"
size="sm"
onClick={showConsentModal}
>
Meeting is being recorded
<Icon as={FaBars} ml={2} />
</Button>
);
} }
const recordingTypeRequiresConsent = (
recordingType: NonNullable<Meeting["recording_type"]>,
) => {
return recordingType === "cloud";
};
// next throws even with "use client"
const useWhereby = () => {
const [wherebyLoaded, setWherebyLoaded] = useState(false);
useEffect(() => {
if (typeof window !== "undefined") {
import("@whereby.com/browser-sdk/embed")
.then(() => {
setWherebyLoaded(true);
})
.catch(console.error.bind(console));
}
}, []);
return wherebyLoaded;
};
export default function Room(details: RoomDetails) { export default function Room(details: RoomDetails) {
return <RoomClient params={details.params} />; const wherebyLoaded = useWhereby();
const wherebyRef = useRef<HTMLElement>(null);
const roomName = details.params.roomName;
const router = useRouter();
const auth = useAuth();
const status = auth.status;
const isAuthenticated = status === "authenticated";
// Fetch room details using React Query
const roomQuery = useRoomGetByName(roomName);
const activeMeetingsQuery = useRoomActiveMeetings(roomName);
const upcomingMeetingsQuery = useRoomUpcomingMeetings(roomName);
const createMeetingMutation = useRoomsCreateMeeting();
const room = roomQuery.data;
const activeMeetings = activeMeetingsQuery.data || [];
const upcomingMeetings = upcomingMeetingsQuery.data || [];
// For non-ICS rooms, create a meeting and get Whereby URL
const roomMeeting = useRoomMeeting(
room && !room.ics_enabled ? roomName : null,
);
const roomUrl =
roomMeeting?.response?.host_room_url || roomMeeting?.response?.room_url;
const isLoading = status === "loading" || roomQuery.isLoading || roomMeeting?.loading;
const isOwner =
isAuthenticated && room
? auth.user?.id === room.user_id
: false;
const meetingId = roomMeeting?.response?.id;
const recordingType = roomMeeting?.response?.recording_type;
const handleMeetingSelect = (selectedMeeting: Meeting) => {
// Navigate to specific meeting using path segment
router.push(`/${roomName}/${selectedMeeting.id}`);
};
const handleCreateUnscheduled = async () => {
try {
// Create a new unscheduled meeting
const newMeeting = await createMeetingMutation.mutateAsync({
params: {
path: { room_name: roomName },
},
});
handleMeetingSelect(newMeeting);
} catch (err) {
console.error("Failed to create meeting:", err);
}
};
const handleLeave = useCallback(() => {
router.push("/browse");
}, [router]);
useEffect(() => {
if (
!isLoading &&
(roomQuery.isError || roomMeeting?.error) &&
"status" in (roomQuery.error || roomMeeting?.error || {}) &&
(roomQuery.error as any)?.status === 404
) {
notFound();
}
}, [isLoading, roomQuery.error, roomMeeting?.error]);
useEffect(() => {
if (isLoading || !isAuthenticated || !roomUrl || !wherebyLoaded) return;
wherebyRef.current?.addEventListener("leave", handleLeave);
return () => {
wherebyRef.current?.removeEventListener("leave", handleLeave);
};
}, [handleLeave, roomUrl, isLoading, isAuthenticated, wherebyLoaded]);
if (isLoading) {
return (
<Box
display="flex"
justifyContent="center"
alignItems="center"
height="100vh"
bg="gray.50"
p={4}
>
<Spinner color="blue.500" size="xl" />
</Box>
);
}
if (!room) {
return (
<Box
display="flex"
justifyContent="center"
alignItems="center"
height="100vh"
bg="gray.50"
p={4}
>
<Text fontSize="lg">Room not found</Text>
</Box>
);
}
// For ICS-enabled rooms, show meeting selection
if (room.ics_enabled) {
return (
<MeetingSelection
roomName={roomName}
isOwner={isOwner}
isSharedRoom={room?.is_shared || false}
authLoading={["loading", "refreshing"].includes(auth.status)}
onMeetingSelect={handleMeetingSelect}
onCreateUnscheduled={handleCreateUnscheduled}
/>
);
}
// For non-ICS rooms, show Whereby embed directly
return (
<>
{roomUrl && meetingId && wherebyLoaded && (
<>
<whereby-embed
ref={wherebyRef}
room={roomUrl}
style={{ width: "100vw", height: "100vh" }}
/>
{recordingType && recordingTypeRequiresConsent(recordingType) && (
<ConsentDialogButton
meetingId={meetingId}
wherebyRef={wherebyRef}
/>
)}
</>
)}
</>
);
} }