Skip to content

Commit

Permalink
chore(react-native): get apikey from endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
santhoshvai committed Nov 15, 2023
1 parent bfeba2a commit 4a75763
Show file tree
Hide file tree
Showing 16 changed files with 142 additions and 143 deletions.
2 changes: 0 additions & 2 deletions .github/workflows/react-native-workflow.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@ env:
APP_STORE_CONNECT_API_KEY_KEY_ID: ${{ secrets.APP_STORE_CONNECT_API_KEY_KEY_ID }}
APP_STORE_CONNECT_API_KEY_ISSUER_ID: ${{ secrets.APP_STORE_CONNECT_API_KEY_ISSUER_ID }}
APP_STORE_CONNECT_API_KEY_KEY: ${{ secrets.APP_STORE_CONNECT_API_KEY_KEY }}
STREAM_API_KEY: ${{ vars.STREAM_DOGFOOD_API_KEY }}
STREAM_API_SECRET: ${{ secrets.STREAM_DOGFOOD_API_SECRET }}
STREAM_SDK_TEST_APP: ${{ secrets.STREAM_SDK_TEST_APP }}
STREAM_SDK_TEST_ACCOUNT_EMAIL: ${{ secrets.STREAM_SDK_TEST_ACCOUNT_EMAIL }}
STREAM_SDK_TEST_ACCOUNT_PASSWORD: ${{ secrets.STREAM_SDK_TEST_ACCOUNT_PASSWORD }}
Expand Down
1 change: 0 additions & 1 deletion sample-apps/react-native/dogfood/config.js

This file was deleted.

4 changes: 0 additions & 4 deletions sample-apps/react-native/dogfood/env.d.ts

This file was deleted.

1 change: 0 additions & 1 deletion sample-apps/react-native/dogfood/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@
"@types/express": "^4",
"@types/jest": "^29.2.1",
"@types/react": "^18.2.28",
"@types/react-native-dotenv": "^0.2.0",
"@types/react-native-incall-manager": "^3.2.1",
"@types/react-native-video": "^5",
"@types/react-test-renderer": "^18.0.0",
Expand Down
10 changes: 1 addition & 9 deletions sample-apps/react-native/dogfood/src/components/ChatWrapper.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
import React, { PropsWithChildren, useCallback, useMemo } from 'react';
import React, { PropsWithChildren, useMemo } from 'react';
import { Chat, OverlayProvider, Streami18n } from 'stream-chat-react-native';
import { useChatClient } from '../hooks/useChatClient';
import { AuthenticationProgress } from './AuthenticatingProgress';
import { StreamChatGenerics } from '../../types';
import { useAppGlobalStoreValue } from '../contexts/AppContext';
import { createToken } from '../modules/helpers/createToken';
import { useStreamChatTheme } from '../hooks/useTheme';
import { STREAM_API_KEY } from '../../config';

const streami18n = new Streami18n({
language: 'en',
Expand All @@ -26,14 +24,8 @@ export const ChatWrapper = ({ children }: PropsWithChildren<{}>) => {
[userId, userName, userImageUrl],
);

const tokenProvider = useCallback(async () => {
return await createToken({ user_id: userId });
}, [userId]);

const chatClient = useChatClient({
apiKey: STREAM_API_KEY,
userData: user,
tokenProvider: tokenProvider,
});
const theme = useStreamChatTheme();

Expand Down
31 changes: 17 additions & 14 deletions sample-apps/react-native/dogfood/src/components/VideoWrapper.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import {
import { useAppGlobalStoreValue } from '../contexts/AppContext';
import { createToken } from '../modules/helpers/createToken';
import translations from '../translations';
import { STREAM_API_KEY } from '../../config';

export const VideoWrapper = ({ children }: PropsWithChildren<{}>) => {
const userId = useAppGlobalStoreValue((store) => store.userId);
Expand All @@ -21,21 +20,25 @@ export const VideoWrapper = ({ children }: PropsWithChildren<{}>) => {
if (!userId || !userImageUrl) {
return;
}
const user = {
id: userId,
name: userName,
image: userImageUrl,
let _videoClient: StreamVideoClient | undefined;
const run = async () => {
const user = {
id: userId,
name: userName,
image: userImageUrl,
};
const { token, apiKey } = await createToken({ user_id: user.id });
_videoClient = new StreamVideoClient({
apiKey,
user,
token,
options: { logLevel: 'warn' },
});
setVideoClient(_videoClient);
};
const _videoClient = new StreamVideoClient({
apiKey: STREAM_API_KEY,
user,
tokenProvider: async () => createToken({ user_id: user.id }),
options: { logLevel: 'warn' },
});
setVideoClient(_videoClient);

run();
return () => {
_videoClient.disconnectUser();
_videoClient?.disconnectUser();
setVideoClient(undefined);
};
}, [userName, userId, userImageUrl]);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { StreamVideoClient } from '@stream-io/video-react-native-sdk';
import { useCallback, useEffect, useState } from 'react';
import { STREAM_API_KEY } from '../../config';
import { useEffect, useState } from 'react';

import { createToken } from '../modules/helpers/createToken';

type InitAnonymousVideoClientType = {
Expand All @@ -14,34 +14,32 @@ export const useAnonymousInitVideoClient = ({
}: InitAnonymousVideoClientType) => {
const [client, setClient] = useState<StreamVideoClient>();

const apiKey = STREAM_API_KEY;

const tokenProvider = useCallback(async () => {
const anonymousUser = {
id: '!anon',
};
const token = await createToken({
user_id: anonymousUser?.id,
call_cids: `${callType}:${callId}`,
});
return token;
}, [callId, callType]);

useEffect(() => {
const _client = new StreamVideoClient({
apiKey,
tokenProvider,
user: { type: 'anonymous' },
});
setClient(_client);
let _client: StreamVideoClient | undefined;
const run = async () => {
const anonymousUser = {
id: '!anon',
};
const { token, apiKey } = await createToken({
user_id: anonymousUser.id,
call_cids: `${callType}:${callId}`,
});
_client = new StreamVideoClient({
apiKey,
token,
user: { type: 'anonymous' },
});
setClient(_client);
};
run();

return () => {
_client
.disconnectUser()
?.disconnectUser()
.catch((error) => console.error('Unable to disconnect user', error));
setClient(undefined);
};
}, [apiKey, tokenProvider]);
}, [callId, callType]);

return client;
};
59 changes: 27 additions & 32 deletions sample-apps/react-native/dogfood/src/hooks/useChatClient.tsx
Original file line number Diff line number Diff line change
@@ -1,64 +1,59 @@
import { useEffect, useRef, useState } from 'react';
import {
StreamChat,
OwnUserResponse,
UserResponse,
TokenOrProvider,
} from 'stream-chat';
import { StreamChat, OwnUserResponse, UserResponse } from 'stream-chat';
import { StreamChatGenerics } from '../../types';
import { createToken } from '../modules/helpers/createToken';

export const useChatClient = <
SCG extends StreamChatGenerics = StreamChatGenerics,
>({
apiKey,
userData,
tokenProvider,
}: {
apiKey: string;
userData?: OwnUserResponse<SCG> | UserResponse<SCG>;
tokenProvider?: TokenOrProvider;
userData: OwnUserResponse<SCG> | UserResponse<SCG>;
}) => {
const [chatClient, setChatClient] = useState<StreamChat<SCG> | null>(null);
const [chatClient, setChatClient] = useState<StreamChat<SCG> | undefined>();
const disconnectRef = useRef(Promise.resolve());

useEffect(() => {
if (!userData) {
return;
}

const client = new StreamChat<SCG>(apiKey);
const connectUser = async () => {
await disconnectRef.current;
try {
await client.connectUser(userData, tokenProvider);
console.log(`[Chat client]: Connected user: ${userData.id}`);
} catch (e) {
console.error('[Chat client]: Failed to establish connection', e);
}
if (!didUserConnectInterrupt) {
setChatClient(client);
}
let connectPromise: Promise<void> | undefined;
let client: StreamChat<SCG> | undefined;
const run = async () => {
const { token, apiKey } = await createToken({ user_id: userData.id });
client = new StreamChat<SCG>(apiKey);
const connectUser = async () => {
await disconnectRef.current;
try {
await client?.connectUser(userData, token);
console.log(`[Chat client]: Connected user: ${userData.id}`);
} catch (e) {
console.error('[Chat client]: Failed to establish connection', e);
}
if (!didUserConnectInterrupt) {
setChatClient(client);
}
};
connectPromise = connectUser();
};

run();

let didUserConnectInterrupt = false;
const connectPromise = connectUser();

const cleanUp = async () => {
didUserConnectInterrupt = true;
await connectPromise;
try {
await client.disconnectUser();
await client?.disconnectUser();
console.log(`[Chat client]: Disconnected user: ${userData.id}`);
} catch (e) {
console.error('[Chat client]: Failed to disconnect', e);
}
setChatClient(null);
setChatClient(undefined);
};

return () => {
disconnectRef.current = cleanUp();
};
}, [apiKey, userData, tokenProvider]);
}, [userData]);

return chatClient;
};
Original file line number Diff line number Diff line change
@@ -1,20 +1,24 @@
import { STREAM_API_KEY } from '../../../config';

type ParamsType = {
user_id: string;
call_cids?: string;
};

export const createToken = async (params: ParamsType) => {
const endpoint = new URL(
'https://stream-calls-dogfood.vercel.app/api/auth/create-token',
);
endpoint.searchParams.set('api_key', STREAM_API_KEY);
type EnvironmentType = 'pronto' | 'demo';

export const createToken = async (
params: ParamsType,
environment: EnvironmentType = 'pronto',
) => {
const endpoint = new URL('https://pronto.getstream.io/api/auth/create-token');
endpoint.searchParams.set('user_id', params.user_id);
endpoint.searchParams.set('environment', environment);
endpoint.searchParams.set('exp', String(4 * 60 * 60)); // 4 hours
if (params.call_cids) {
endpoint.searchParams.set('call_cids', params.call_cids);
}
const response = await fetch(endpoint.toString()).then((res) => res.json());
return response.token as string;
return {
token: response.token as string,
apiKey: response.apiKey as string,
};
};
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import React, { useEffect, useMemo, useState } from 'react';
import { NativeStackScreenProps } from '@react-navigation/native-stack';
import {
Call,
Expand All @@ -10,7 +10,6 @@ import {
import { MeetingStackParamList } from '../../../types';
import { MeetingUI } from '../../components/MeetingUI';
import { createToken } from '../../modules/helpers/createToken';
import { STREAM_API_KEY } from '../../../config';

type Props = NativeStackScreenProps<
MeetingStackParamList,
Expand Down Expand Up @@ -39,28 +38,29 @@ export const GuestMeetingScreen = (props: Props) => {
[mode, guestUserId],
);

const tokenProvider = useCallback(async () => {
const token = await createToken({
user_id: '!anon',
call_cids: `${callType}:${callId}`,
});
return token;
}, [callId, callType]);

useEffect(() => {
const _videoClient = new StreamVideoClient({
apiKey: STREAM_API_KEY,
user: userToConnect,
tokenProvider: mode === 'anonymous' ? tokenProvider : undefined,
options: { logLevel: 'warn' },
});
setVideoClient(_videoClient);
let _videoClient: StreamVideoClient | undefined;
const run = async () => {
const { token, apiKey } = await createToken({
user_id: userToConnect.id ?? '!anon',
call_cids: mode === 'anonymous' ? `${callType}:${callId}` : undefined,
});
_videoClient = new StreamVideoClient({
apiKey,
user: userToConnect,
token,
options: { logLevel: 'warn' },
});
setVideoClient(_videoClient);
};

run();

return () => {
_videoClient?.disconnectUser();
setVideoClient(undefined);
};
}, [tokenProvider, userToConnect, mode]);
}, [userToConnect, mode, callId]);

const call = useMemo<Call | undefined>(() => {
if (!videoClient) {
Expand Down
9 changes: 3 additions & 6 deletions sample-apps/react-native/dogfood/src/utils/setPushConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { AndroidImportance } from '@notifee/react-native';
import { staticNavigate } from './staticNavigationUtils';
import { mmkvStorage } from '../contexts/createStoreContext';
import { createToken } from '../modules/helpers/createToken';
import { STREAM_API_KEY } from '../../config';
import { prontoCallId$ } from '../hooks/useProntoLinkEffect';

export function setPushConfig() {
Expand Down Expand Up @@ -81,13 +80,11 @@ const createStreamVideoClient = async () => {
name: userName,
imageUrl: userImageUrl,
};
const { token, apiKey } = await createToken({ user_id: user.id });
const client = new StreamVideoClient({
apiKey: STREAM_API_KEY,
apiKey,
user,
tokenProvider: async () => {
const token = await createToken({ user_id: user.id });
return token;
},
token,
});
return client;
};
Loading

0 comments on commit 4a75763

Please sign in to comment.