-
Notifications
You must be signed in to change notification settings - Fork 193
Expand file tree
/
Copy pathApp.tsx
More file actions
286 lines (268 loc) · 9.42 KB
/
Copy pathApp.tsx
File metadata and controls
286 lines (268 loc) · 9.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
import { StatusBar, useColorScheme } from 'react-native';
import './gesture-handler';
import React, { useState, useEffect, useRef } from 'react';
import {
Platform,
View,
PlatformColor,
AppState,
AppStateStatus,
} from 'react-native';
import { enableScreens } from 'react-native-screens';
enableScreens();
import {
CometChatIncomingCall,
CometChatThemeProvider,
CometChatUIEventHandler,
CometChatUIEvents,
CometChatUIKit,
UIKitSettings,
} from '@cometchat/chat-uikit-react-native';
import { SafeAreaProvider, SafeAreaView } from 'react-native-safe-area-context';
import { GestureHandlerRootView } from 'react-native-gesture-handler';
import { CometChat } from '@cometchat/chat-sdk-react-native';
import RootStackNavigator from './src/navigation/RootStackNavigator';
import { AppConstants } from './src/utils/AppConstants';
import { requestAndroidPermissions } from './src/utils/helper';
import AsyncStorage from '@react-native-async-storage/async-storage';
function App() {
const isDarkMode = useColorScheme() === 'dark';
return (
<GestureHandlerRootView style={{ flex: 1 }}>
<SafeAreaProvider>
<StatusBar barStyle={isDarkMode ? 'light-content' : 'dark-content'} />
<AppContent />
</SafeAreaProvider>
</GestureHandlerRootView>
);
}
const AppContent = (): React.ReactElement => {
const [callReceived, setCallReceived] = useState(false);
const incomingCall = useRef<CometChat.Call | CometChat.CustomMessage | null>(
null,
);
const [isInitializing, setIsInitializing] = useState(true);
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [userLoggedIn, setUserLoggedIn] = useState(false);
const [hasValidAppCredentials, setHasValidAppCredentials] = useState(false);
// Listener ID for registering and removing CometChat listeners.
const listenerId = 'app';
/**
* Initialize CometChat UIKit and configure Google Sign-In.
* Retrieves credentials from AsyncStorage and uses fallback constants if needed.
*/
useEffect(() => {
async function init() {
try {
// Retrieve stored app credentials or default to an empty object.
const AppData = (await AsyncStorage.getItem('appCredentials')) || '{}';
const storedCredentials = JSON.parse(AppData);
// Determine the final credentials (from AsyncStorage or AppConstants).
const finalAppId = storedCredentials.appId || AppConstants.appId;
const finalAuthKey = storedCredentials.authKey || AppConstants.authKey;
const finalRegion = storedCredentials.region || AppConstants.region;
// Set hasValidAppCredentials based on whether all values are available.
if (finalAppId && finalAuthKey && finalRegion) {
setHasValidAppCredentials(true);
} else {
setHasValidAppCredentials(false);
}
await CometChatUIKit.init({
appId: finalAppId,
authKey: finalAuthKey,
region: finalRegion,
subscriptionType: CometChat.AppSettings
.SUBSCRIPTION_TYPE_ALL_USERS as UIKitSettings['subscriptionType'],
});
// If a user is already logged in, update the state.
const loggedInUser = CometChatUIKit.loggedInUser;
if (loggedInUser) {
setIsLoggedIn(true);
}
} catch (error) {
console.log('Error during initialization', error);
} finally {
// Mark initialization as complete.
setIsInitializing(false);
}
}
init();
}, []);
/**
* Monitor app state changes to verify the logged-in status and clear notifications.
* When the app becomes active, it cancels Android notifications and checks the login status.
*/
useEffect(() => {
if (Platform.OS === 'android') {
// Request required Android permissions for notifications.
requestAndroidPermissions();
}
const handleAppStateChange = async (nextState: AppStateStatus) => {
if (nextState === 'active') {
try {
// Verify if there is a valid logged-in user.
const chatUser = await CometChat.getLoggedinUser();
setIsLoggedIn(!!chatUser);
} catch (error) {
console.log('Error verifying CometChat user on resume:', error);
}
}
};
const subscription = AppState.addEventListener(
'change',
handleAppStateChange,
);
return () => subscription.remove();
}, []);
/**
* Attach CometChat login listener to handle login and logout events.
* Updates user login status accordingly.
*/
useEffect(() => {
CometChat.addLoginListener(
listenerId,
new CometChat.LoginListener({
loginSuccess: () => {
setUserLoggedIn(true);
},
loginFailure: (e: CometChat.CometChatException) => {
console.log('LoginListener :: loginFailure', e.message);
},
logoutSuccess: () => {
setUserLoggedIn(false);
},
logoutFailure: (e: CometChat.CometChatException) => {
console.log('LoginListener :: logoutFailure', e.message);
},
}),
);
// Clean up the login listener on component unmount.
return () => {
CometChat.removeLoginListener(listenerId);
};
}, []);
/**
* Attach CometChat call listeners to handle incoming, outgoing, and cancelled call events.
* Also handles UI events for call end.
*/
useEffect(() => {
// Listener for call events.
CometChat.addCallListener(
listenerId,
new CometChat.CallListener({
onIncomingCallReceived: (call: CometChat.Call) => {
// Check if there's already an active call
try {
const activeCall = CometChat.getActiveCall();
if (activeCall) {
// If there's an active call, reject the incoming call with busy status
setTimeout(() => {
CometChat.rejectCall(
call.getSessionId(),
CometChat.CALL_STATUS.BUSY,
)
.then(() => {
console.log('Incoming call rejected due to active call');
})
.catch(error => {
console.error(
'Error rejecting call with busy status:',
error,
);
});
}, 2000);
} else {
// No active call, proceed with normal incoming call handling
// Hide any bottom sheet UI before showing the incoming call screen.
CometChatUIEventHandler.emitUIEvent(
CometChatUIEvents.ccToggleBottomSheet,
{
isBottomSheetVisible: false,
},
);
// Store the incoming call and update state.
incomingCall.current = call;
setCallReceived(true);
}
} catch (error) {
console.error('Error getting active call:', error);
// If error getting active call, proceed with normal handling
CometChatUIEventHandler.emitUIEvent(
CometChatUIEvents.ccToggleBottomSheet,
{
isBottomSheetVisible: false,
},
);
incomingCall.current = call;
setCallReceived(true);
}
},
onOutgoingCallRejected: () => {
// Clear the call state if outgoing call is rejected.
incomingCall.current = null;
setCallReceived(false);
},
onIncomingCallCancelled: () => {
// Clear the call state if the incoming call is cancelled.
incomingCall.current = null;
setCallReceived(false);
},
}),
);
// Additional listener to handle call end events.
CometChatUIEventHandler.addCallListener(listenerId, {
ccCallEnded: () => {
incomingCall.current = null;
setCallReceived(false);
},
});
// Remove call listeners on cleanup.
return () => {
CometChatUIEventHandler.removeCallListener(listenerId);
CometChat.removeCallListener(listenerId);
};
}, [userLoggedIn]);
// Show a blank/splash screen while the app is initializing.
if (isInitializing) {
return (
<View
style={{
flex: 1,
backgroundColor: Platform.select({
ios: PlatformColor('systemBackgroundColor'),
android: PlatformColor('?android:attr/colorBackground'),
}),
}}
/>
);
}
// Once initialization is complete, render the main app UI.
return (
<SafeAreaView edges={['top', 'bottom']} style={{ flex: 1 }}>
<CometChatThemeProvider>
{/* Render the incoming call UI if the user is logged in and a call is received */}
{isLoggedIn && callReceived && incomingCall.current ? (
<CometChatIncomingCall
call={incomingCall.current}
onDecline={() => {
// Handle call decline by clearing the incoming call state.
incomingCall.current = null;
setCallReceived(false);
}}
style={{
containerStyle: {
marginTop: Platform.OS === 'android' ? 40 : 0,
},
}}
/>
) : null}
{/* Render the main navigation stack, passing the login status as a prop */}
<RootStackNavigator
isLoggedIn={isLoggedIn}
hasValidAppCredentials={hasValidAppCredentials}
/>
</CometChatThemeProvider>
</SafeAreaView>
);
};
export default App;