All files / atlas-mobile-ts/src/navigation AuthorizedNavigator.tsx

0% Statements 0/106
0% Branches 0/28
0% Functions 0/21
0% Lines 0/104

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
/* Copyright (C) Click & Push Accessibility, Inc - All Rights Reserved
 * Unauthorized copying of this file, via any medium is strictly prohibited
 * Proprietary and confidential
 * Written and maintained by the Click & Push Development team 
 * <dev@clicknpush.ca>, January 2022
 */
 
import { FontAwesome } from '@expo/vector-icons';
import { BottomTabBarOptions, BottomTabNavigationProp, createBottomTabNavigator } from "@react-navigation/bottom-tabs";
import { observer } from "mobx-react";
import React, { useEffect } from "react";
import { AppState, Platform, SafeAreaView, View, Text, Alert } from 'react-native';
import OutdoorMap from "../components/Map/MainMapComponent/OutdoorMap";
import Profile from "../components/Profile/Profile";
import { colors, SECURESTORE_NOTIFTOKEN } from "../utils/GlobalUtils";
import  {check, checkMultiple, PERMISSIONS, requestMultiple} from 'react-native-permissions'
import { Feed } from '../components/Feed/Feed';
import { authStore } from '../libs/auth/AuthStore';
import { getItemAsync } from 'expo-secure-store';
import Constants from 'expo-constants';
import * as Notifications from 'expo-notifications'
import { useAuth } from '../hooks/useAuth';
import { NavigationContainerRef, RouteProp } from '@react-navigation/native';
import { QueryClient, useQuery } from 'react-query';
import { useProfile } from '../hooks/useProfile';
import { NotifType } from '../types';
import Badge from '../components/Badge';
import MapNavigator from './MapNavigator';
 
Notifications.setNotificationHandler({
    handleNotification: async () => ({
      shouldShowAlert: true,
      shouldPlaySound: false,
      shouldSetBadge: false,
    }),
});
 
const MainTabs = createBottomTabNavigator();
 
const tabBarOptions: BottomTabBarOptions = {
    //keyboardHidesTabBar: true,
    activeTintColor: 'white',
    activeBackgroundColor: '#e35555',
    inactiveTintColor: "lightgray",
    
    style: {backgroundColor: colors.red, height: 60, justifyContent: 'center'},
    labelStyle: {marginBottom: 7},
    iconStyle: {marginBottom: 7}
} 
 
/**
 * Permitted screens for the Auth tabs navigator. 
 * @category Navigation
 * @typedef
 */
 export type AuthTabsParamList = {
    Map: {selectedLandmark: string, selectedLandmarks: string[]},
    Profile: React.FC,
}
 
export type AuthTabsNavigationProp = BottomTabNavigationProp<AuthTabsParamList>
 
export const navigationRef = React.createRef<NavigationContainerRef>()
 
export const navigate = (name: string, params?) => {
    navigationRef.current.navigate(name, params)
}
 
/**
 * The root navigator for all authorized screens ({@link Map}, {@link Profile}). It uses a [React Navigation Bottom Tabs Navigator]{@link https://reactnavigation.org/docs/bottom-tab-navigator/} the main navigation mechanism.
 * @category Navigation
 * @component
 */
const AuthorizedNavigator: React.FC = () => {
    const {notifications, refetchNotifications, markNotificationAsRead } = useProfile(authStore.userId)
 
    const {getNotificationTokenFromServer, ensureNotificationTokenExistsOnServer} = useAuth()
 
    const { profile, toggleTipsAsync } = useProfile(authStore.userId)
 
    /**
     * If the user has their preferences configured to show tips, show them on page load. Recheck every time show_tips changes
     */
    useEffect(() => {
        const showTip = () =>  {
            if (profile?.show_tips) {
                console.log('[Profile]: User has tips configured, showing tips.')
                Alert.alert(
                    'Welcome!', 
                    "There are 3 ways to add a landmark to the map: \n\n - Press and hold where you'd like to add it on the map \n\n - Press the add button to add a landmark at your current location \n\n - Press the mic button and use voice commands.", 
                    [{text: "Don't show this again", onPress: async () => await toggleTipsAsync()}, {text: 'Ok'}]
                )   
            }
            else {
                console.log('[Profile]: User does not have tips configured, not showing tips')
            }
        }
        showTip();
    }, [profile?.show_tips])
 
    const handleNotificationInteraction = async (notifData: any) => {
        await markNotificationAsRead(notifData.notif_id)
        await refetchNotifications()
        Iif (notifData?.notif_type as NotifType == 'landmark-like' || notifData?.notif_type as NotifType == 'near-landmark')
            navigate('Map', {selectedLandmark: notifData.landmark_id})
        Iif (notifData?.notif_type as NotifType == 'near-landmarks')
            navigate('Map', {selectedLandmarks: notifData.landmarks})
    }
 
    const registerForPushNotificationsAsync = async () => {
        if (Constants.isDevice) {
            const { status: existingStatus } = await Notifications.getPermissionsAsync();
            let finalStatus = existingStatus;
            Iif (existingStatus !== 'granted') {
                const { status } = await Notifications.requestPermissionsAsync();
                finalStatus = status;
            }
            Iif (finalStatus !== 'granted') {
                alert('Failed to get push token for push notification!');
                await authStore.setNotificationTokenAsync('')
                return;
            }
 
            let token = authStore.notificationToken
 
            // try getting from memory
            Iif (!token) {
                // try getting token from SecureStore 
                console.log('[Notifcations]: Attempting to get token from SecureStore...')
                token = await getItemAsync(SECURESTORE_NOTIFTOKEN)
                if (token) {
                    console.log('[Notifications]: Found notification token in, setting it as current token')
                    await authStore.setNotificationTokenAsync(token)
                }
                else {
                    // try getting token from server db 
                    console.log('[Notifcations]: Attempting to get token from SecureStore...')
                    console.log('[Notifcations]: Couldn\'t find token in SecureStore. Attempting to get notification token from server...')
                    token = await getNotificationTokenFromServer()
                    if (token) {
                        console.log(token)
                        console.log('[Notificaitons]: Found token on server, setting it as current token')
                        await authStore.setNotificationTokenAsync(token[0])
                    }
                    else {
                        // get new token from expo and save it to the server
                        console.log('[Notifcations]: Couldn\'t find token in server. Getting new token from expo...')
                        token = (await Notifications.getExpoPushTokenAsync()).data;      
                        await authStore.setNotificationTokenAsync(token)
                    }
                }
            }
 
            // ensure that notificationToken exists on the server
            await ensureNotificationTokenExistsOnServer(token, 5)
 
        } 
        else {
            console.warn('[Notifcations]: A physical device must be used for push notifications');
            authStore.setNotificationTokenAsync('')
            return 
        }
        
        Iif (Platform.OS === 'android') {
            Notifications.setNotificationChannelAsync('default', {
                name: 'default',
                importance: Notifications.AndroidImportance.MAX,
                vibrationPattern: [0, 250, 250, 250],
                lightColor: '#FF231F7C',
            });
        }   
    };
      
    useEffect(() => {
        /**
         * useEffect hook that is responsible for registering an appState "change" handler that will call {@linkcode checkToken} each time the app is opened or closed on the device.
         * @memberOf Atlas
         */
        const initializePushNotifications = async () => {
        Iif (authStore.userId) {
            await registerForPushNotificationsAsync()
            Iif (authStore.notificationToken) {
                const notifReceivedSubscription = Notifications.addNotificationReceivedListener(async notification => { 
                    await refetchNotifications()
                })
        
                const notifResponseReceivedSubscription = Notifications.addNotificationResponseReceivedListener(async response => {
                    const notifData = response.notification.request.content.data
                    handleNotificationInteraction(notifData)
                });
        
                return () => {
                    notifReceivedSubscription.remove()
                    notifResponseReceivedSubscription.remove()
                }; 
            }
        }
        }
        initializePushNotifications();
    }, [authStore.userId]);
 
    useEffect(() => {
 
    }, [])
 
    const getIconSize = (focused: boolean): number => {
        if (focused) {
            return 20
        }
        else {
            return 17
        } 
    }
 
    const renderFeedBadge = () => {
        const newNotifAmount = notifications?.filter(notif => !notif.read).length
 
        return newNotifAmount > 0 ? <Badge positioning={{top: 8, left: 13,}} value={newNotifAmount}/> : null
    }
 
    return(
        <SafeAreaView style={{height: '100%'}}>
            {/* <AdMobBanner adUnitID="ca-app-pub-3940256099942544/6300978111" /> */}
            <MainTabs.Navigator 
                sceneContainerStyle={{flex:1}}     
                initialRouteName="Map"
                tabBarOptions={tabBarOptions}>
                <MainTabs.Screen name="Map" component={MapNavigator} options={{tabBarIcon: ({color, focused}) => (<FontAwesome name={focused ? 'map' : 'map-o'} size={getIconSize(focused)} color={color} style={{position: 'absolute', top: 10}}/>)}}/>
                <MainTabs.Screen name="Feed" options={{tabBarIcon: ({color, focused}) => (
                    <View style={{position: 'absolute', top: 10}}>
                        <FontAwesome name={focused ? 'bell' : 'bell-o'} size={getIconSize(focused)} color={color} />
                        {renderFeedBadge()}
                    </View>
                )}}>
                    {() => <Feed notifications={notifications} handleNotifInteraction={handleNotificationInteraction} />}
                </MainTabs.Screen>
                <MainTabs.Screen name="Profile" component={Profile} options={{tabBarIcon: ({color, focused}) => (<FontAwesome name={focused ? 'user' : 'user-o'} size={getIconSize(focused)} color={color} style={{position: 'absolute', top: 10}}/>)}} />
            </MainTabs.Navigator>
        </SafeAreaView>
        
    )
}
 
export default observer(AuthorizedNavigator);