-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp.js
485 lines (444 loc) · 15.6 KB
/
App.js
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
// React Native imports
import { Alert, BackHandler, Button, Pressable, StyleSheet, Text, TouchableOpacity, View, Platform } from 'react-native';
import { useEffect, useState } from 'react';
// Application bottom bar screens
import HomeScreen from './screens/HomeScreen';
import ChatScreen from './screens/ChatScreen';
import SettingsScreen from './screens/SettingsScreen';
// Other application screens
import LoginScreen from './screens/LoginScreen';
import MessagingWindow from './screens/MessagingWindow';
import InitialSetupScreen from './screens/InitialSetupScreen';
import ChatInfoScreen from './screens/ChatInfoScreen';
import PoliciesScreen from './screens/PoliciesScreen';
import AgeScreen from './screens/AgeScreen';
// Navigation library imports
import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { createStackNavigator } from '@react-navigation/stack';
import { MaterialCommunityIcons } from '@expo/vector-icons';
import 'react-native-gesture-handler';
// App state and global handlers
import { appState } from './lib/AppState';
import MessagingHandler from './lib/MessagingHandler';
import { serverInfo } from './lib/ServerInfo';
// Notification imports
import * as Device from 'expo-device';
import * as Notifications from 'expo-notifications';
import UIDEntryScreen from './screens/UIDEntryScreen';
// Prevent screenshotting
import { usePreventScreenCapture, addScreenshotListener } from 'expo-screen-capture';
import RNExitApp from 'react-native-exit-app';
// Cryptography
import CryptoES from 'crypto-es';
import RSAKey from 'react-native-rsa-expo';
import uuid from 'react-native-uuid';
// Set the global notification handler
Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowAlert: true,
shouldPlaySound: true,
shouldSetBadge: false,
}),
});
// The Expo EAS project id
const EXPO_PROJECT_ID = '0a28d370-c13d-4c08-a572-a8d30e00e05f';
/**
* Sends a push notification to a specified user
* @param {String} expoPushToken The push token to send a notification to
*
* Copied from the Expo docs, https://docs.expo.dev/push-notifications/push-notifications-setup/.
*/
async function sendPushNotification(expoPushToken) {
const message = {
to: expoPushToken,
sound: 'default',
title: 'Original Title',
body: 'And here is the body!',
data: { someData: 'goes here' },
};
await fetch('https://exp.host/--/api/v2/push/send', {
method: 'POST',
headers: {
Accept: 'application/json',
'Accept-encoding': 'gzip, deflate',
'Content-Type': 'application/json',
},
body: JSON.stringify(message),
});
}
/**
* Sets the client up to receive push notifications and generates a token
* @returns The push notification token
*
* Copied from the expo docs, https://docs.expo.dev/push-notifications/push-notifications-setup/.
*/
async function registerForPushNotificationsAsync() {
let token;
if (Device.isDevice) {
const { status: existingStatus } = await Notifications.getPermissionsAsync();
let finalStatus = existingStatus;
if (existingStatus !== 'granted') {
const { status } = await Notifications.requestPermissionsAsync();
finalStatus = status;
console.log(finalStatus);
}
if (finalStatus !== 'granted') {
alert('Push notification permission denied. Please go to settings and allow push notifications for the app.');
return;
}
token = (await Notifications.getExpoPushTokenAsync({
projectId: EXPO_PROJECT_ID,
})).data;
appState.notifications.expoPushToken = token;
} else {
alert('Must use physical device for Push Notifications');
}
if (Platform.OS === 'android') {
Notifications.setNotificationChannelAsync('default', {
name: 'default',
importance: Notifications.AndroidImportance.MAX,
vibrationPattern: [0, 250, 250, 250],
lightColor: '#FF231F7C',
});
}
return token;
}
// Create the global navigation handlers
const Stack = createStackNavigator();
const Tab = createBottomTabNavigator();
// Cache the options for the application screens
const appScreenOptions = {
headerShown: true,
headerStyle: {
backgroundColor: '#880808',
},
headerTintColor: '#fff',
};
// Cache the options for the login screens
const loginScreenOptions = {
headerStyle: {
backgroundColor: '#880808',
},
headerTintColor: '#fff'
};
// Create a stack for the chat screen
function ChatStack({ }) {
return (
<Stack.Navigator
initialRouteName='ChatScreen'
screenOptions={appScreenOptions}
>
<Stack.Screen
name='ChatScreen'
options={{ title: 'Chat' }}
>
{(props) => <ChatScreen {...props} />}
</Stack.Screen>
<Stack.Screen
name='MessagingWindow'
/* Change the Screen title based on the parameter passed to route in the navigation function */
options={ ({ navigation, route }) => ({
title: route.params.chatTitle, headerBackTitle: 'Chats',
headerRight: () => {
if (Platform.OS === 'ios') {
return (
<Button
onPress={() => { navigation.navigate('ChatInfoScreen', { chatTitle: route.params.chatTitle, chatId: route.params.chatId }) }}
title='Info'
color='#fff'
/>
);
}
return (
<TouchableOpacity
onPress={() => { navigation.navigate('ChatInfoScreen', { chatTitle: route.params.chatTitle, chatId: route.params.chatId }) }}
>
<Text style={{
color: 'white',
padding: '4%',
}}>INFO</Text>
</TouchableOpacity>
);
}
}) }
>
{(props) => {
return <MessagingWindow {...props} />;
}}
</Stack.Screen>
<Stack.Screen
name='ChatInfoScreen'
/* Change the Screen title based on the parameter passed to route in the navigation function */
options={ ({ route }) => ({ title: `${route.params.chatTitle} Users`, headerBackTitle: `Chat` }) }
>
{(props) => {
return <ChatInfoScreen {...props} />;
}}
</Stack.Screen>
</Stack.Navigator>
);
}
// Create a stack for the home screen
function HomeStack() {
return (
<Stack.Navigator
initialRouteName='HomeScreen'
screenOptions={appScreenOptions}
>
<Stack.Screen
name='HomeScreen'
component={HomeScreen}
options={{ title: 'Home' }}
/>
</Stack.Navigator>
);
}
// Create a stack for the settings screen
function SettingsStack() {
return (
<Stack.Navigator
initialRouteName='SettingsScreen'
screenOptions={appScreenOptions}
>
<Stack.Screen
name='SettingsScreen'
component={SettingsScreen}
options={{ title: 'Settings' }}
/>
</Stack.Navigator>
);
}
// Create a function for the global app
export default function App() {
// Store the login state information in the App state because it is irrelevant to global application and because the app needs to rerender when the login state is changed
const [loginState, setLoginState] = useState({
loginState: 0,
privateKey: '',
publicKey: '',
});
// When the app starts
useEffect(() => {
// If the push notifications have not been initialized
if (appState.notifications.expoPushToken === null || appState.notifications.notificationListener === null || appState.notifications.responseListener === null) {
// // Wait one second before prompting notifications
// setTimeout(() => {
// // Register for push notifications and set the token in the global app state
// registerForPushNotificationsAsync().then(token => {
// console.log(`Registered for push notifications with token ${token}`)
// appState.notifications.expoPushToken = token;
// });
// // Set the notification listener
// appState.notifications.notificationListener = Notifications.addNotificationReceivedListener(notification => {
// appState.notifications.currentNotification = notification;
// });
// // Set the response listener
// appState.notifications.responseListener = Notifications.addNotificationResponseReceivedListener(response => {
// // Handle this later
// });
// }, 1000);
// Register for push notifications and set the token in the global app state
registerForPushNotificationsAsync().then(token => {
console.log(`Registered for push notifications with token ${token}`)
appState.notifications.expoPushToken = token;
});
// Set the notification listener
appState.notifications.notificationListener = Notifications.addNotificationReceivedListener(notification => {
appState.notifications.currentNotification = notification;
});
// Set the response listener
appState.notifications.responseListener = Notifications.addNotificationResponseReceivedListener(response => {
// Handle this later
});
/**
* FUTURE DEVELOPMENT NOTICE:
* The documentation at https://docs.expo.dev/push-notifications/push-notifications-setup/ had the following extra lines in its example:
return () => {
Notifications.removeNotificationSubscription(notificationListener.current);
Notifications.removeNotificationSubscription(responseListener.current);
};
* All of which I deemed unnecessary for this application as the app uses global state management rather than App.js component level state.
*/
}
});;
// When the login state is changed
useEffect(() => {
// If the login state is fully unlocked and the messaging handler is unset
if (loginState.loginState === 1 && appState.messagingHandler === null) {
// Create the messaging handler using the login state data
appState.messagingHandler = new MessagingHandler(loginState.publicKey, loginState.privateKey);
}
}, [loginState]);
// Handles setting the login state in child components
const handleSetLoginState = (newLoginState) => {
// Set the login state in the global state
appState.loginState = newLoginState.loginState;
// Set the application state
setLoginState(newLoginState);
}
// Prevents screenshotting any portion of the application
usePreventScreenCapture();
// Screenshot lockout handler
const handleScreenshotLock = () => {
// Create the request data contents
const contents = {
requestIdentifier: uuid.v4(),
lockoutRequest: 'Attempted screenshot',
};
// Hash the contents
const payloadHash = CryptoES.SHA256(JSON.stringify(contents)).toString();
// RSA encrypt the hash to sign the data
const rsa = new RSAKey();
rsa.setPrivateString(appState.messagingHandler.priKey);
const signature = rsa.encryptPrivate(payloadHash);
// Send the lockout request to the server
fetch(serverInfo.serverAddress + '/api/v1/lockout', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
authToken: appState.messagingHandler.pubKey,
signature: signature,
contents: contents,
}),
})
.then((response) => response.json())
.then((responseJson) => {
Alert.alert(
'Unknown Server Error',
`An unknown error has occurred. Please contact support for further assistance. Code E110.`,
[
{ text: 'Ok', onPress: () => {
// Exit the app once OK is pressed
// RNExitApp.exitApp();
} }
],
{ cancelable: false },
);
});
};
// If a user attempts to screenshot the application, lock the user out
//addScreenshotListener(handleScreenshotLock);
// If the login state is not logged in
if (loginState.loginState === 0) {
// Return the login screen state
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name='Login' options={loginScreenOptions}>
{(props) => <LoginScreen {...props} setAppLoginState={handleSetLoginState} />}
</Stack.Screen>
<Stack.Screen name='Policies Screen' options={loginScreenOptions}>
{(props) => <PoliciesScreen {...props} />}
</Stack.Screen>
<Stack.Screen name='Age Verification' options={loginScreenOptions}>
{(props) => <AgeScreen {...props} />}
</Stack.Screen>
<Stack.Screen name='UID Entry' options={loginScreenOptions}>
{(props) => <UIDEntryScreen {...props} />}
</Stack.Screen>
<Stack.Screen name='Initial Setup' options={loginScreenOptions}>
{(props) => <InitialSetupScreen {...props} />}
</Stack.Screen>
</Stack.Navigator>
</NavigationContainer>
);
}
// If the app is fully unlocked
if (loginState.loginState === 1) {
// Return the full application
return (
<NavigationContainer>
<Tab.Navigator
initialRouteName='Home'
screenOptions={{
headerShown: false,
tabBarLabelStyle: {
color: 'white',
fontWeight: 'bold',
},
tabBarStyle: {
backgroundColor: '#880808'
},
tabBarActiveTintColor: '#d4af37',
tabBarInactiveTintColor: 'white',
}}
>
<Tab.Screen
name='Chat'
options={{
tabBarLabel: 'Chat',
tabBarIcon: ({ color, size }) => (
<MaterialCommunityIcons name='message' color={color} size={size} />
),
}}
>
{(props) => <ChatStack {...props} />}
</Tab.Screen>
<Tab.Screen
name='Home'
component={HomeStack}
options={{
tabBarLabel: 'Home',
tabBarIcon: ({ color, size }) => (
<MaterialCommunityIcons name='home' color={color} size={size} />
),
}}
/>
<Tab.Screen
name='Settings'
component={SettingsStack}
options={{
tabBarLabel: 'Settings',
tabBarIcon: ({ color, size }) => (
<MaterialCommunityIcons name='cog' color={color} size={size} />
),
}}
/>
</Tab.Navigator>
</NavigationContainer>
);
}
// If the app is in lockdown mode (partial/pseudo unlock)
if (loginState.loginState === 2) {
// Return the navigator without the chat option
return (
<NavigationContainer>
<Tab.Navigator
initialRouteName='Home'
screenOptions={{
headerShown: false
}}
>
<Tab.Screen
name='Home'
component={HomeStack}
options={{
tabBarLabel: 'Home',
tabBarIcon: ({ color, size }) => (
<MaterialCommunityIcons name='home' color={color} size={size} />
),
}}
/>
<Tab.Screen
name='Settings'
component={SettingsStack}
options={{
tabBarLabel: 'Settings',
tabBarIcon: ({ color, size }) => (
<MaterialCommunityIcons name='cog' color={color} size={size} />
),
}}
/>
</Tab.Navigator>
</NavigationContainer>
);
}
// The navigation had an error, display that
return (
<View>
<Text>There was an error with the navigation system, code APP10.</Text>
</View>
);
}