import { useEffect } from 'react' ; import { parse_linking_url_token } from '../../helper' ; import { Linking , Platform } from 'react-native' ; import RNNetworkExtension from 'react-native-network-extension' ; import { useStore } from '../../store/store' ; import StaticServer from '../../static_server' ; import { Navigation } from 'react-native-navigation' ; import SafariView from 'react-native-safari-view' ; import withClient from '../../providers/with_client' ; import logger from '../../logger' ; const LinkingListener = ( props ) => { const [ , { addProviderToken , setVPNStatus , notify , resetNotification } ] = useStore ( ) ; useEffect ( ( ) => { const networkStatusCallback = ( status ) => { logger . debug ( 'Network status: ' + status ) ; setVPNStatus ( status ) ; } ; const networkFailCallback = ( reason ) => { logger . debug ( 'Network failed, reason: ' + reason ) ; setVPNStatus ( 'Connect' ) ; } ; const handleCallback = async ( url ) => { resetNotification ( ) ; const providerToken = parse_linking_url_token ( url ) ; if ( providerToken ) { const client = props . client . createClient ( { provider : providerToken . provider , accessToken : providerToken . accessToken , } ) ; try { providerToken . account = await client . getAccount ( ) ; addProviderToken ( providerToken ) ; } catch ( e ) { notify ( 'error' , 'Cannot add provider token: ' + e . message ) ; } } else { notify ( 'error' , 'Cannot add provider token: Missing access token.' ) ; } StaticServer . stop ( ) ; Navigation . dismissAllModals ( ) ; SafariView . dismiss ( ) ; } ; const handleCallbackEvent = ( event ) => { handleCallback ( event . url ) ; } ; if ( Platform . OS === 'android' ) { Linking . getInitialURL ( ) . then ( ( url ) => { handleCallback ( url as string ) ; } ) ; } else { Linking . addEventListener ( 'url' , handleCallbackEvent ) ; } const vpnStatusListener = RNNetworkExtension . addEventListener ( 'status' , networkStatusCallback ) ; const vpnFailListener = RNNetworkExtension . addEventListener ( 'fail' , networkFailCallback ) ; return ( ) => { Linking . removeEventListener ( 'url' , handleCallbackEvent ) ; vpnStatusListener . remove ( ) ; RNNetworkExtension . removeEventListener ( 'status' , networkStatusCallback ) ; vpnFailListener . remove ( ) ; RNNetworkExtension . removeEventListener ( 'fail' , networkFailCallback ) ; } ; } , [ ] ) ; return props . children ; } ; export default withClient ( LinkingListener ) ;