BlueWallet/components/CompanionDelegates.tsx

242 lines
9.1 KiB
TypeScript
Raw Normal View History

2020-05-27 13:12:17 +02:00
import 'react-native-gesture-handler'; // should be on top
2024-05-20 11:54:13 +02:00
2024-05-13 18:43:57 +02:00
import { CommonActions } from '@react-navigation/native';
2024-05-20 11:54:13 +02:00
import React, { lazy, Suspense, useCallback, useEffect, useRef } from 'react';
import { AppState, AppStateStatus, Linking, NativeEventEmitter, NativeModules, Platform } from 'react-native';
2024-05-20 11:54:13 +02:00
import A from '../blue_modules/analytics';
2024-05-13 18:43:57 +02:00
import BlueClipboard from '../blue_modules/clipboard';
import { updateExchangeRate } from '../blue_modules/currency';
2024-05-20 11:54:13 +02:00
import triggerHapticFeedback, { HapticFeedbackTypes } from '../blue_modules/hapticFeedback';
import Notifications from '../blue_modules/notifications';
2024-05-14 19:17:03 +02:00
import { LightningCustodianWallet } from '../class';
2024-05-20 11:54:13 +02:00
import DeeplinkSchemaMatch from '../class/deeplink-schema-match';
import loc from '../loc';
import { Chain } from '../models/bitcoinUnits';
import { navigationRef } from '../NavigationService';
2024-05-14 19:36:31 +02:00
import ActionSheet from '../screen/ActionSheet';
import { useStorage } from '../hooks/context/useStorage';
2024-05-14 19:36:31 +02:00
const MenuElements = lazy(() => import('../components/MenuElements'));
const DeviceQuickActions = lazy(() => import('../components/DeviceQuickActions'));
const HandOffComponentListener = lazy(() => import('../components/HandOffComponentListener'));
const WidgetCommunication = lazy(() => import('../components/WidgetCommunication'));
2024-05-18 17:36:30 +02:00
const WatchConnectivity = lazy(() => import('./WatchConnectivity'));
2024-05-14 19:36:31 +02:00
// @ts-ignore: NativeModules.EventEmitter is not typed
2022-02-12 18:03:10 +01:00
const eventEmitter = Platform.OS === 'ios' ? new NativeEventEmitter(NativeModules.EventEmitter) : undefined;
const ClipboardContentType = Object.freeze({
BITCOIN: 'BITCOIN',
LIGHTNING: 'LIGHTNING',
});
2024-05-13 18:43:57 +02:00
const CompanionDelegates = () => {
const { wallets, addWallet, saveToDisk, fetchAndSaveWalletTransactions, refreshAllWalletTransactions, setSharedCosigner } = useStorage();
2024-05-14 19:17:03 +02:00
const appState = useRef<AppStateStatus>(AppState.currentState);
const clipboardContent = useRef<undefined | string>();
2024-05-14 19:36:31 +02:00
const processPushNotifications = useCallback(async () => {
await new Promise(resolve => setTimeout(resolve, 200));
2024-05-14 19:36:31 +02:00
// @ts-ignore: Notifications type is not defined
const notifications2process = await Notifications.getStoredNotifications();
2024-05-14 19:36:31 +02:00
// @ts-ignore: Notifications type is not defined
2021-01-01 20:15:40 +01:00
await Notifications.clearStoredNotifications();
2024-05-14 19:36:31 +02:00
// @ts-ignore: Notifications type is not defined
2021-01-01 20:15:40 +01:00
Notifications.setApplicationIconBadgeNumber(0);
2024-05-14 19:36:31 +02:00
// @ts-ignore: Notifications type is not defined
2020-12-29 23:54:56 +01:00
const deliveredNotifications = await Notifications.getDeliveredNotifications();
2024-05-14 19:36:31 +02:00
// @ts-ignore: Notifications type is not defined
setTimeout(() => Notifications.removeAllDeliveredNotifications(), 5000);
2021-01-01 20:15:40 +01:00
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) {
2024-05-14 19:17:03 +02:00
navigationRef.dispatch(
2021-08-31 15:54:29 +02:00
CommonActions.navigate({
name: 'WalletTransactions',
params: {
walletID,
walletType: wallet.type,
},
}),
);
} else {
2024-05-14 19:17:03 +02:00
navigationRef.navigate('ReceiveDetailsRoot', {
2021-08-31 15:54:29 +02:00
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');
}
2024-05-14 19:36:31 +02:00
}
2021-01-01 20:15:40 +01:00
if (deliveredNotifications.length > 0) {
2020-12-30 03:13:56 +01:00
refreshAllWalletTransactions();
}
2021-01-01 20:15:40 +01:00
return false;
2024-05-14 19:36:31 +02:00
}, [fetchAndSaveWalletTransactions, refreshAllWalletTransactions, wallets]);
const handleOpenURL = useCallback(
(event: { url: string }) => {
DeeplinkSchemaMatch.navigationRouteFor(event, value => navigationRef.navigate(...value), {
wallets,
addWallet,
saveToDisk,
setSharedCosigner,
2021-09-09 21:36:35 +02:00
});
2024-05-14 19:36:31 +02:00
},
[addWallet, saveToDisk, setSharedCosigner, wallets],
);
const showClipboardAlert = useCallback(
({ contentType }: { contentType: undefined | string }) => {
triggerHapticFeedback(HapticFeedbackTypes.ImpactLight);
BlueClipboard()
.getClipboardContent()
.then(clipboard => {
ActionSheet.showActionSheetWithOptions(
{
title: loc._.clipboard,
message: contentType === ClipboardContentType.BITCOIN ? loc.wallets.clipboard_bitcoin : loc.wallets.clipboard_lightning,
options: [loc._.cancel, loc._.continue],
cancelButtonIndex: 0,
},
buttonIndex => {
switch (buttonIndex) {
case 0:
break;
case 1:
handleOpenURL({ url: clipboard });
break;
}
},
);
});
},
[handleOpenURL],
);
const handleAppStateChange = useCallback(
async (nextAppState: AppStateStatus | undefined) => {
if (wallets.length === 0) return;
if ((appState.current.match(/background/) && nextAppState === 'active') || nextAppState === undefined) {
setTimeout(() => A(A.ENUM.APP_UNSUSPENDED), 2000);
updateExchangeRate();
const processed = await processPushNotifications();
if (processed) return;
const clipboard = await BlueClipboard().getClipboardContent();
const isAddressFromStoredWallet = wallets.some(wallet => {
if (wallet.chain === Chain.ONCHAIN) {
return wallet.isAddressValid && wallet.isAddressValid(clipboard) && wallet.weOwnAddress(clipboard);
} else {
return (wallet as LightningCustodianWallet).isInvoiceGeneratedByWallet(clipboard) || wallet.weOwnAddress(clipboard);
}
});
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;
if (isBitcoinAddress) {
contentType = ClipboardContentType.BITCOIN;
} else if (isLightningInvoice || isLNURL) {
contentType = ClipboardContentType.LIGHTNING;
} else if (isBothBitcoinAndLightning) {
contentType = ClipboardContentType.BITCOIN;
}
showClipboardAlert({ contentType });
2021-09-09 21:36:35 +02:00
}
2024-05-14 19:36:31 +02:00
clipboardContent.current = clipboard;
}
2024-05-14 19:36:31 +02:00
if (nextAppState) {
appState.current = nextAppState;
}
},
[processPushNotifications, showClipboardAlert, wallets],
);
const onNotificationReceived = useCallback(
async (notification: { data: { data: any } }) => {
const payload = Object.assign({}, notification, notification.data);
if (notification.data && notification.data.data) Object.assign(payload, notification.data.data);
// @ts-ignore: Notifications type is not defined
payload.foreground = true;
// @ts-ignore: Notifications type is not defined
await Notifications.addNotification(payload);
// @ts-ignore: Notifications type is not defined
if (payload.foreground) await processPushNotifications();
},
[processPushNotifications],
);
const addListeners = useCallback(() => {
const urlSubscription = Linking.addEventListener('url', handleOpenURL);
const appStateSubscription = AppState.addEventListener('change', handleAppStateChange);
const notificationSubscription = eventEmitter?.addListener('onNotificationReceived', onNotificationReceived);
return {
urlSubscription,
appStateSubscription,
notificationSubscription,
};
}, [handleOpenURL, handleAppStateChange, onNotificationReceived]);
useEffect(() => {
const subscriptions = addListeners();
return () => {
subscriptions.urlSubscription?.remove();
subscriptions.appStateSubscription?.remove();
subscriptions.notificationSubscription?.remove();
};
}, [addListeners]);
2020-10-11 09:07:22 +02:00
return (
2024-05-13 18:43:57 +02:00
<>
<Notifications onProcessNotifications={processPushNotifications} />
2024-05-14 19:36:31 +02:00
<Suspense fallback={null}>
<MenuElements />
<DeviceQuickActions />
<HandOffComponentListener />
<WidgetCommunication />
<WatchConnectivity />
</Suspense>
2024-05-13 18:43:57 +02:00
</>
2020-10-11 09:07:22 +02:00
);
};
2024-05-13 18:43:57 +02:00
export default CompanionDelegates;