BlueWallet/App.js

323 lines
11 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 InitRoot from './Navigation';
import BlueClipboard from './blue_modules/clipboard';
import { BlueStorageContext } from './blue_modules/storage-context';
import WatchConnectivity from './WatchConnectivity';
import DeviceQuickActions from './class/quick-actions';
import Notifications from './blue_modules/notifications';
import Biometric from './class/biometrics';
import WidgetCommunication from './blue_modules/WidgetCommunication';
import ActionSheet from './screen/ActionSheet';
import HandoffComponent from './components/handoff';
2021-09-25 17:04:45 +02:00
import Privacy from './blue_modules/Privacy';
import triggerHapticFeedback, { HapticFeedbackTypes } from './blue_modules/hapticFeedback';
2024-01-19 01:28:06 +01:00
import MenuElements from './components/MenuElements';
const A = require('./blue_modules/analytics');
2021-09-09 21:36:35 +02:00
const currency = require('./blue_modules/currency');
2022-02-12 18:03:10 +01:00
const eventEmitter = Platform.OS === 'ios' ? new NativeEventEmitter(NativeModules.EventEmitter) : undefined;
2024-01-25 03:53:33 +01:00
const { EventEmitter, 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();
};
const onUserActivityOpen = data => {
switch (data.activityType) {
case HandoffComponent.activityTypes.ReceiveOnchain:
NavigationService.navigate('ReceiveDetailsRoot', {
screen: 'ReceiveDetails',
params: {
address: data.userInfo.address,
},
});
break;
case HandoffComponent.activityTypes.Xpub:
NavigationService.navigate('WalletXpubRoot', {
screen: 'WalletXpub',
params: {
2021-09-25 18:05:43 +02:00
xpub: data.userInfo.xpub,
},
});
break;
default:
break;
}
};
2020-10-11 09:07:22 +02:00
useEffect(() => {
if (walletsInitialized) {
addListeners();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [walletsInitialized]);
2020-10-11 09:07:22 +02:00
const addListeners = () => {
Linking.addEventListener('url', handleOpenURL);
AppState.addEventListener('change', handleAppStateChange);
2021-09-26 20:55:56 +02:00
EventEmitter?.getMostRecentUserActivity()
.then(onUserActivityOpen)
.catch(() => console.log('No userActivity object sent'));
2020-10-11 09:07:22 +02:00
handleAppStateChange(undefined);
2021-01-01 20:15:40 +01:00
/*
When a notification on iOS is shown while the app is on foreground;
On willPresent on AppDelegate.m
*/
2022-02-12 18:03:10 +01:00
eventEmitter?.addListener('onNotificationReceived', onNotificationReceived);
eventEmitter?.addListener('onUserActivityOpen', onUserActivityOpen);
2020-06-21 02:16:05 +02:00
};
/**
* 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);
currency.updateExchangeRate();
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 => {
if (Platform.OS === 'ios' || Platform.OS === 'macos') {
ActionSheet.showActionSheetWithOptions(
2021-10-08 16:32:43 +02:00
{
2023-03-30 02:46:11 +02:00
options: [loc._.cancel, loc._.continue],
title: loc._.clipboard,
message: contentType === ClipboardContentType.BITCOIN ? loc.wallets.clipboard_bitcoin : loc.wallets.clipboard_lightning,
cancelButtonIndex: 0,
},
buttonIndex => {
if (buttonIndex === 1) {
2021-10-08 16:32:43 +02:00
handleOpenURL({ url: clipboard });
2023-03-30 02:46:11 +02:00
}
2021-10-08 16:32:43 +02:00
},
2023-03-30 02:46:11 +02:00
);
} else {
ActionSheet.showActionSheetWithOptions({
buttons: [
{ text: loc._.cancel, style: 'cancel', onPress: () => {} },
{
text: loc._.continue,
style: 'default',
onPress: () => {
handleOpenURL({ url: clipboard });
},
},
],
title: loc._.clipboard,
message: contentType === ClipboardContentType.BITCOIN ? loc.wallets.clipboard_bitcoin : loc.wallets.clipboard_lightning,
});
}
});
};
useEffect(() => {
2024-01-25 03:53:33 +01:00
if (Platform.OS === 'ios') {
// Call hide to setup the listener on the native side
SplashScreen.addObserver();
}
}, []);
2020-10-11 09:07:22 +02:00
return (
<SafeAreaProvider>
<View style={styles.root}>
<NavigationContainer ref={navigationRef} theme={colorScheme === 'dark' ? BlueDarkTheme : BlueDefaultTheme}>
<InitRoot />
<Notifications onProcessNotifications={processPushNotifications} />
2024-01-19 01:28:06 +01:00
<MenuElements />
<DeviceQuickActions />
2020-10-11 09:07:22 +02:00
</NavigationContainer>
</View>
2023-10-30 17:38:12 +01:00
<WatchConnectivity />
<Biometric />
2020-11-02 14:11:28 +01:00
<WidgetCommunication />
2021-09-25 17:04:45 +02:00
<Privacy />
2020-10-11 09:07:22 +02:00
</SafeAreaProvider>
);
};
const styles = StyleSheet.create({
root: {
flex: 1,
},
});
2020-10-11 09:07:22 +02:00
export default App;