Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: add roomId and role support for beam & customers #1784

Merged
merged 3 commits into from
Sep 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 44 additions & 14 deletions apps/100ms-custom-app/src/App.jsx
Original file line number Diff line number Diff line change
@@ -1,29 +1,59 @@
import React from 'react';
import React, { useEffect, useState } from 'react';
import { Flex, HMSPrebuilt } from '@100mslive/roomkit-react';
import { useOverridePrebuiltLayout } from './hooks/useOverridePrebuiltLayout';
import { getRoomCodeFromUrl } from './utils/utils';
import { useSearchParam } from './hooks/useSearchParam';
import {
getAuthTokenUsingRoomIdRole,
getRoomCodeFromUrl,
getRoomIdRoleFromUrl,
} from './utils/utils';

const App = () => {
const roomCode = getRoomCodeFromUrl();
const [authToken, setAuthToken] = useState(useSearchParam('auth_token'));
// added subdomain in query param for easy testing in vercel links
const subdomain = useSearchParam('subdomain') || window.location.hostname;
const { roomId, role } = getRoomIdRoleFromUrl();
const { overrideLayout, isHeadless } = useOverridePrebuiltLayout();

useEffect(() => {
if (!roomCode && !authToken) {
(async function getAuthToken() {
const token = await getAuthTokenUsingRoomIdRole({
subdomain,
roomId,
role,
userId: 'beam',
});
setAuthToken(token);
})();
}
}, [authToken, role, roomCode, roomId, subdomain]);

return (
<Flex
className="prebuilt-wrapper"
direction="column"
css={{ size: '100%', overflowY: 'hidden', bg: '$background_dim' }}
>
<HMSPrebuilt
roomCode={roomCode}
screens={overrideLayout ? overrideLayout : undefined}
options={{
userName: isHeadless ? 'Beam' : undefined,
endpoints: {
tokenByRoomCode: process.env.REACT_APP_TOKEN_BY_ROOM_CODE_ENDPOINT,
roomLayout: process.env.REACT_APP_ROOM_LAYOUT_ENDPOINT,
init: process.env.REACT_APP_INIT_ENDPOINT,
},
}}
/>
{(authToken || roomCode) && (
<HMSPrebuilt
roomCode={roomCode}
authToken={authToken}
roomId={roomId}
role={role}
screens={overrideLayout ? overrideLayout : undefined}
options={{
userName: isHeadless ? 'Beam' : undefined,
endpoints: {
tokenByRoomCode:
process.env.REACT_APP_TOKEN_BY_ROOM_CODE_ENDPOINT,
roomLayout: process.env.REACT_APP_ROOM_LAYOUT_ENDPOINT,
init: process.env.REACT_APP_INIT_ENDPOINT,
},
}}
/>
)}
</Flex>
);
};
Expand Down
43 changes: 42 additions & 1 deletion apps/100ms-custom-app/src/utils/utils.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,28 @@
import axios from 'axios';
import cookies from 'js-cookies';

function isRoomCode(str) {
const regex = /^[A-Za-z]{3}(-[A-Za-z]{3,4}){2}$/;
regex.test(str);
}

export const getRoomCodeFromUrl = () => {
const path = window.location.pathname;
const regex = /(\/streaming)?\/(preview|meeting)\/(?<code>[^/]+)/;
return path.match(regex)?.groups?.code || null;
const roomCode = path.match(regex)?.groups?.code || null;
return isRoomCode(roomCode) ? roomCode : null;
};

export const getRoomIdRoleFromUrl = () => {
const path = window.location.pathname;
const regex =
/(\/streaming)?\/(preview|meeting)\/(?<roomId>[^/]+)\/(?<role>[^/]+)/;
const roomId = path.match(regex)?.groups?.roomId || null;
const role = path.match(regex)?.groups?.role || null;
return {
roomId,
role,
};
};

export const getAuthInfo = () => {
Expand Down Expand Up @@ -142,3 +160,26 @@ export const getWithRetry = async (url, headers) => {
console.error('max retry done for get-details', error);
throw error;
};

export const getAuthTokenUsingRoomIdRole = async function ({
subdomain = '',
roomId = '',
role = '',
userId = '',
}) {
try {
const resp = await fetch(`${apiBasePath}${subdomain}/api/token`, {
method: 'POST',
body: JSON.stringify({
room_id: roomId,
role,
user_id: userId,
}),
});
const { token = '' } = await resp.json();
return token;
} catch (e) {
console.error('failed to getAuthTokenUsingRoomIdRole', e);
throw Error('failed to get auth token using roomid and role');
}
};
29 changes: 26 additions & 3 deletions packages/roomkit-react/src/Prebuilt/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,9 @@ export type HMSPrebuiltProps = {
themes?: Theme[];
options?: HMSPrebuiltOptions;
screens?: Screens;
authToken?: string;
roomId?: string;
role?: string;
onLeave?: () => void;
};

Expand All @@ -88,6 +91,9 @@ export const HMSPrebuilt = React.forwardRef<HMSPrebuiltRefType, HMSPrebuiltProps
(
{
roomCode = '',
authToken = '',
roomId = '',
role = '',
logo,
typography,
themes,
Expand Down Expand Up @@ -155,6 +161,15 @@ export const HMSPrebuilt = React.forwardRef<HMSPrebuiltRefType, HMSPrebuiltProps
screens,
};

if (!roomCode && !(authToken && roomId && role)) {
console.error(`
HMSPrebuilt can be initialised by providing:
either just "roomCode" or "authToken" and "roomId" and "role".
Please check if you are providing the above values for initialising prebuilt.
`);
throw Error('Incorrect initializing params for HMSPrebuilt component');
}

if (!hydrated) {
return null;
}
Expand All @@ -166,6 +181,8 @@ export const HMSPrebuilt = React.forwardRef<HMSPrebuiltRefType, HMSPrebuiltProps
<HMSPrebuiltContext.Provider
value={{
roomCode,
roomId,
role,
onLeave,
userName,
userId,
Expand Down Expand Up @@ -221,7 +238,7 @@ export const HMSPrebuilt = React.forwardRef<HMSPrebuiltRefType, HMSPrebuiltProps
'-webkit-text-size-adjust': '100%',
}}
>
<AppRoutes authTokenByRoomCodeEndpoint={tokenByRoomCodeEndpoint} />
<AppRoutes authTokenByRoomCodeEndpoint={tokenByRoomCodeEndpoint} defaultAuthToken={authToken} />
</Box>
</HMSThemeProvider>
);
Expand Down Expand Up @@ -326,7 +343,13 @@ const Router = ({ children }: { children: ReactElement }) => {
);
};

function AppRoutes({ authTokenByRoomCodeEndpoint }: { authTokenByRoomCodeEndpoint: string }) {
function AppRoutes({
authTokenByRoomCodeEndpoint,
defaultAuthToken,
}: {
authTokenByRoomCodeEndpoint: string;
defaultAuthToken?: string;
}) {
const roomLayout = useRoomLayout();
const { screenType } = useRoomLayoutConferencingScreen();
return (
Expand All @@ -339,7 +362,7 @@ function AppRoutes({ authTokenByRoomCodeEndpoint }: { authTokenByRoomCodeEndpoin
<RemoteStopScreenshare />
<KeyboardHandler />
<BeamSpeakerLabelsLogging />
<AuthToken authTokenByRoomCodeEndpoint={authTokenByRoomCodeEndpoint} />
<AuthToken authTokenByRoomCodeEndpoint={authTokenByRoomCodeEndpoint} defaultAuthToken={defaultAuthToken} />
{roomLayout && (
<Routes>
<Route path="/*" element={<RouteList />} />
Expand Down
1 change: 0 additions & 1 deletion packages/roomkit-react/src/Prebuilt/common/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ export const QUERY_PARAM_SKIP_PREVIEW = 'skip_preview';
export const QUERY_PARAM_SKIP_PREVIEW_HEADFUL = 'skip_preview_headful';
export const QUERY_PARAM_NAME = 'name';
export const QUERY_PARAM_VIEW_MODE = 'ui_mode';
export const QUERY_PARAM_AUTH_TOKEN = 'auth_token';
export const QUERY_PARAM_PREVIEW_AS_ROLE = 'preview_as_role';
export const UI_MODE_GRID = 'grid';
export const MAX_TOASTS = 5;
Expand Down
7 changes: 3 additions & 4 deletions packages/roomkit-react/src/Prebuilt/components/AuthToken.jsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import React, { useEffect, useState } from 'react';
import { useSearchParam } from 'react-use';
import { useHMSActions } from '@100mslive/react-sdk';
import { styled } from '../../Theme';
import { useHMSPrebuiltContext } from '../AppContext';
import { ErrorDialog } from '../primitives/DialogContent';
import { useSetAppDataByKey, useTokenEndpoint } from './AppData/useUISettings';
import { APP_DATA, QUERY_PARAM_AUTH_TOKEN } from '../common/constants';
import { APP_DATA } from '../common/constants';

/**
* query params exposed -
Expand All @@ -16,12 +15,12 @@ import { APP_DATA, QUERY_PARAM_AUTH_TOKEN } from '../common/constants';
* auth_token=123 => uses the passed in token to join instead of fetching from token endpoint
* ui_mode=activespeaker => lands in active speaker mode after joining the room
*/
const AuthToken = React.memo(({ authTokenByRoomCodeEndpoint }) => {
const AuthToken = React.memo(({ authTokenByRoomCodeEndpoint, defaultAuthToken }) => {
const hmsActions = useHMSActions();
const tokenEndpoint = useTokenEndpoint();
const { roomCode, userId } = useHMSPrebuiltContext();
const [error, setError] = useState({ title: '', body: '' });
let authToken = useSearchParam(QUERY_PARAM_AUTH_TOKEN);
let authToken = defaultAuthToken;
const [, setAuthTokenInAppData] = useSetAppDataByKey(APP_DATA.authToken);

useEffect(() => {
Expand Down