BlueWallet/App.js

295 lines
10 KiB
JavaScript
Raw Normal View History

2020-05-27 13:12:17 +02:00
import 'react-native-gesture-handler'; // should be on top
import React, { useContext, useEffect, useRef } from 'react';
import {
AppState,
NativeModules,
NativeEventEmitter,
Linking,
Platform,
StyleSheet,
UIManager,
useColorScheme,
View,
2022-06-19 15:05:30 +02:00
LogBox,
} from 'react-native';
2023-10-20 19:59:56 +02:00
import { NavigationContainer, CommonActions } from '@react-navigation/native';
2020-05-27 13:12:17 +02:00
import { SafeAreaProvider } from 'react-native-safe-area-context';
import { navigationRef } from './NavigationService';
import * as NavigationService from './NavigationService';
import { Chain } from './models/bitcoinUnits';
import DeeplinkSchemaMatch from './class/deeplink-schema-match';
2020-07-20 15:38:46 +02:00
import loc from './loc';
import { BlueDefaultTheme, BlueDarkTheme } from './components/themes';
import BlueClipboard from './blue_modules/clipboard';
import { BlueStorageContext } from './blue_modules/storage-context';
import WatchConnectivity from './WatchConnectivity';
import Notifications from './blue_modules/notifications';
import Biometric from './class/biometrics';
import WidgetCommunication from './components/WidgetCommunication';
import ActionSheet from './screen/ActionSheet';
import triggerHapticFeedback, { HapticFeedbackTypes } from './blue_modules/hapticFeedback';
2024-01-19 01:28:06 +01:00
import MenuElements from './components/MenuElements';
2024-01-28 16:11:08 +01:00
import { updateExchangeRate } from './blue_modules/currency';
2024-03-24 04:48:44 +01:00
import { NavigationProvider } from './components/NavigationProvider';
import A from './blue_modules/analytics';
import HandOffComponentListener from './components/HandOffComponentListener';
2024-04-30 00:54:19 +02:00
import DeviceQuickActions from './components/DeviceQuickActions';
2024-05-13 02:34:22 +02:00
import MainRoot from './Navigation';
2022-02-12 18:03:10 +01:00
const eventEmitter = Platform.OS === 'ios' ? new NativeEventEmitter(NativeModules.EventEmitter) : undefined;
const { SplashScreen } = NativeModules;
LogBox.ignoreLogs(['Require cycle:', 'Battery state `unknown` and monitoring disabled, this is normal for simulators and tvOS.']);
2022-06-19 15:05:30 +02:00
const ClipboardContentType = Object.freeze({
BITCOIN: 'BITCOIN',
LIGHTNING: 'LIGHTNING',
});
if (Platform.OS === 'android') {
if (UIManager.setLayoutAnimationEnabledExperimental) {
UIManager.setLayoutAnimationEnabledExperimental(true);
}
}
2020-10-11 09:07:22 +02:00
const App = () => {
2023-09-17 18:28:54 +02:00
const {
walletsInitialized,
wallets,
addWallet,
saveToDisk,
fetchAndSaveWalletTransactions,
refreshAllWalletTransactions,
setSharedCosigner,
} = useContext(BlueStorageContext);
2020-10-11 09:07:22 +02:00
const appState = useRef(AppState.currentState);
const clipboardContent = useRef();
2020-10-11 09:07:22 +02:00
const colorScheme = useColorScheme();
2021-01-01 20:15:40 +01:00
const onNotificationReceived = async notification => {
2020-12-27 18:04:32 +01:00
const payload = Object.assign({}, notification, notification.data);
if (notification.data && notification.data.data) Object.assign(payload, notification.data.data);
2021-01-01 20:15:40 +01:00
payload.foreground = true;
await Notifications.addNotification(payload);
// if user is staring at the app when he receives the notification we process it instantly
// so app refetches related wallet
if (payload.foreground) await processPushNotifications();
};
2020-10-11 09:07:22 +02:00
const addListeners = () => {
2024-03-24 04:48:44 +01:00
const urlSubscription = Linking.addEventListener('url', handleOpenURL);
const appStateSubscription = AppState.addEventListener('change', handleAppStateChange);
const notificationSubscription = eventEmitter?.addListener('onNotificationReceived', onNotificationReceived);
// Store subscriptions in a ref or state to remove them later
return {
urlSubscription,
appStateSubscription,
notificationSubscription,
};
2020-06-21 02:16:05 +02:00
};
2024-03-24 04:48:44 +01:00
useEffect(() => {
if (walletsInitialized) {
const subscriptions = addListeners();
// Cleanup function
return () => {
subscriptions.urlSubscription?.remove();
subscriptions.appStateSubscription?.remove();
subscriptions.notificationSubscription?.remove();
};
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [walletsInitialized]); // Re-run when walletsInitialized changes
/**
* Processes push notifications stored in AsyncStorage. Might navigate to some screen.
*
* @returns {Promise<boolean>} returns TRUE if notification was processed _and acted_ upon, i.e. navigation happened
* @private
*/
2020-10-11 09:07:22 +02:00
const processPushNotifications = async () => {
2021-09-07 21:30:07 +02:00
if (!walletsInitialized) {
console.log('not processing push notifications because wallets are not initialized');
return;
}
await new Promise(resolve => setTimeout(resolve, 200));
// sleep needed as sometimes unsuspend is faster than notification module actually saves notifications to async storage
const notifications2process = await Notifications.getStoredNotifications();
2021-01-01 20:15:40 +01:00
await Notifications.clearStoredNotifications();
Notifications.setApplicationIconBadgeNumber(0);
2020-12-29 23:54:56 +01:00
const deliveredNotifications = await Notifications.getDeliveredNotifications();
2021-01-01 20:15:40 +01:00
setTimeout(() => Notifications.removeAllDeliveredNotifications(), 5000); // so notification bubble wont disappear too fast
for (const payload of notifications2process) {
2021-01-02 00:39:26 +01:00
const wasTapped = payload.foreground === false || (payload.foreground === true && payload.userInteraction);
console.log('processing push notification:', payload);
let wallet;
switch (+payload.type) {
case 2:
case 3:
wallet = wallets.find(w => w.weOwnAddress(payload.address));
break;
case 1:
case 4:
wallet = wallets.find(w => w.weOwnTransaction(payload.txid || payload.hash));
break;
}
if (wallet) {
const walletID = wallet.getID();
fetchAndSaveWalletTransactions(walletID);
if (wasTapped) {
2021-08-31 15:54:29 +02:00
if (payload.type !== 3 || wallet.chain === Chain.OFFCHAIN) {
NavigationService.dispatch(
CommonActions.navigate({
name: 'WalletTransactions',
params: {
walletID,
walletType: wallet.type,
},
}),
);
} else {
NavigationService.navigate('ReceiveDetailsRoot', {
screen: 'ReceiveDetails',
params: {
walletID,
2021-08-31 15:54:29 +02:00
address: payload.address,
},
2021-08-31 15:54:29 +02:00
});
}
2021-01-01 20:15:40 +01:00
return true;
}
} else {
2021-01-01 20:15:40 +01:00
console.log('could not find wallet while processing push notification, NOP');
}
2021-01-01 20:15:40 +01:00
} // end foreach notifications loop
2021-01-01 20:15:40 +01:00
if (deliveredNotifications.length > 0) {
// notification object is missing userInfo. We know we received a notification but don't have sufficient
// data to refresh 1 wallet. let's refresh all.
2020-12-30 03:13:56 +01:00
refreshAllWalletTransactions();
}
2021-01-01 20:15:40 +01:00
// if we are here - we did not act upon any push
return false;
2020-10-11 09:07:22 +02:00
};
2020-10-11 09:07:22 +02:00
const handleAppStateChange = async nextAppState => {
2021-09-09 21:36:35 +02:00
if (wallets.length === 0) return;
if ((appState.current.match(/background/) && nextAppState === 'active') || nextAppState === undefined) {
setTimeout(() => A(A.ENUM.APP_UNSUSPENDED), 2000);
2024-01-28 16:11:08 +01:00
updateExchangeRate();
2021-09-09 21:36:35 +02:00
const processed = await processPushNotifications();
if (processed) return;
2023-03-30 02:46:11 +02:00
const clipboard = await BlueClipboard().getClipboardContent();
2021-09-09 21:36:35 +02:00
const isAddressFromStoredWallet = wallets.some(wallet => {
if (wallet.chain === Chain.ONCHAIN) {
// checking address validity is faster than unwrapping hierarchy only to compare it to garbage
return wallet.isAddressValid && wallet.isAddressValid(clipboard) && wallet.weOwnAddress(clipboard);
} else {
return wallet.isInvoiceGeneratedByWallet(clipboard) || wallet.weOwnAddress(clipboard);
2019-03-05 02:04:40 +01:00
}
2021-09-09 21:36:35 +02:00
});
const isBitcoinAddress = DeeplinkSchemaMatch.isBitcoinAddress(clipboard);
const isLightningInvoice = DeeplinkSchemaMatch.isLightningInvoice(clipboard);
const isLNURL = DeeplinkSchemaMatch.isLnUrl(clipboard);
const isBothBitcoinAndLightning = DeeplinkSchemaMatch.isBothBitcoinAndLightning(clipboard);
if (
!isAddressFromStoredWallet &&
clipboardContent.current !== clipboard &&
(isBitcoinAddress || isLightningInvoice || isLNURL || isBothBitcoinAndLightning)
) {
let contentType;
2021-09-09 21:36:35 +02:00
if (isBitcoinAddress) {
contentType = ClipboardContentType.BITCOIN;
2021-09-09 21:36:35 +02:00
} else if (isLightningInvoice || isLNURL) {
contentType = ClipboardContentType.LIGHTNING;
2021-09-09 21:36:35 +02:00
} else if (isBothBitcoinAndLightning) {
contentType = ClipboardContentType.BITCOIN;
2021-09-09 21:36:35 +02:00
}
showClipboardAlert({ contentType });
}
2021-09-09 21:36:35 +02:00
clipboardContent.current = clipboard;
}
if (nextAppState) {
appState.current = nextAppState;
}
};
2020-10-11 09:07:22 +02:00
const handleOpenURL = event => {
2023-09-17 18:28:54 +02:00
DeeplinkSchemaMatch.navigationRouteFor(event, value => NavigationService.navigate(...value), {
wallets,
addWallet,
saveToDisk,
setSharedCosigner,
});
};
const showClipboardAlert = ({ contentType }) => {
triggerHapticFeedback(HapticFeedbackTypes.ImpactLight);
2023-03-30 02:46:11 +02:00
BlueClipboard()
.getClipboardContent()
.then(clipboard => {
2024-03-13 22:44:53 +01:00
ActionSheet.showActionSheetWithOptions(
{
2023-03-30 02:46:11 +02:00
title: loc._.clipboard,
message: contentType === ClipboardContentType.BITCOIN ? loc.wallets.clipboard_bitcoin : loc.wallets.clipboard_lightning,
2024-03-13 22:44:53 +01:00
options: [loc._.cancel, loc._.continue],
cancelButtonIndex: 0,
},
buttonIndex => {
switch (buttonIndex) {
case 0: // Cancel
break;
2024-03-13 22:54:32 +01:00
case 1:
2024-03-13 22:44:53 +01:00
handleOpenURL({ url: clipboard });
break;
}
},
);
2023-03-30 02:46:11 +02:00
});
};
useEffect(() => {
2024-01-25 03:53:33 +01:00
if (Platform.OS === 'ios') {
// Call hide to setup the listener on the native side
2024-01-30 16:41:52 +01:00
SplashScreen?.addObserver();
2024-01-25 03:53:33 +01:00
}
}, []);
2020-10-11 09:07:22 +02:00
return (
2024-04-30 00:54:19 +02:00
<NavigationContainer ref={navigationRef} theme={colorScheme === 'dark' ? BlueDarkTheme : BlueDefaultTheme}>
<NavigationProvider>
<SafeAreaProvider>
<View style={styles.root}>
2024-05-13 02:34:22 +02:00
<MainRoot />
2024-03-24 04:48:44 +01:00
<Notifications onProcessNotifications={processPushNotifications} />
<MenuElements />
<DeviceQuickActions />
2024-03-24 15:52:10 +01:00
<Biometric />
<HandOffComponentListener />
2024-04-30 00:54:19 +02:00
</View>
<WatchConnectivity />
<WidgetCommunication />
</SafeAreaProvider>
</NavigationProvider>
</NavigationContainer>
2020-10-11 09:07:22 +02:00
);
};
const styles = StyleSheet.create({
root: {
flex: 1,
},
});
2020-10-11 09:07:22 +02:00
export default App;