Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extract reducers to common package #17090

Open
wants to merge 12 commits into
base: feat/rust-bluetooth
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { BluetoothDevice } from '@trezor/transport-bluetooth';

import { remapKnownDevicesForLinux } from '../remapKnownDevicesForLinux';

const nearbyDeviceA: BluetoothDevice = {
id: 'New-Id-A',
data: [],
name: 'Trezor A',
lastUpdatedTimestamp: 1,
address: 'Address-Trezor-A-Staying-Same',
connected: false,
paired: false,
rssi: 0,
};

const nearbyDeviceC: BluetoothDevice = {
id: 'C',
data: [],
name: 'Trezor C',
lastUpdatedTimestamp: 1,
address: 'Address-Trezor-C',
connected: false,
paired: false,
rssi: 0,
};

const knownDeviceB: BluetoothDevice = {
id: 'B',
data: [],
name: 'Trezor A',
lastUpdatedTimestamp: 1,
address: 'Address-Trezor-B',
connected: false,
paired: false,
rssi: 0,
};

const knownDeviceA: BluetoothDevice = {
id: 'Original-Id A',
data: [],
name: 'Trezor B',
lastUpdatedTimestamp: 2,
address: 'Address-Trezor-A-Staying-Same',
connected: false,
paired: false,
rssi: 0,
};

describe(remapKnownDevicesForLinux.name, () => {
it('remaps the changed id of the device, while leaving the others intact', () => {
const result = remapKnownDevicesForLinux({
nearbyDevices: [nearbyDeviceA, nearbyDeviceC],
knownDevices: [knownDeviceA, knownDeviceB],
});

expect(result).toEqual([
{
address: 'Address-Trezor-A-Staying-Same',
connected: false,
data: [],
id: 'New-Id-A',
lastUpdatedTimestamp: 2,
name: 'Trezor B',
paired: false,
rssi: 0,
},
knownDeviceB, // Is kept as it is
]);
});
});
39 changes: 0 additions & 39 deletions packages/suite/src/actions/bluetooth/bluetoothActions.ts

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { BLUETOOTH_PREFIX } from '@suite-common/bluetooth';
import { createThunk } from '@suite-common/redux-utils';
import { bluetoothIpc } from '@trezor/transport-bluetooth';

import { BLUETOOTH_PREFIX } from './bluetoothActions';

type ThunkResponse = ReturnType<typeof bluetoothIpc.connectDevice>;

export const bluetoothConnectDeviceThunk = createThunk<ThunkResponse, { id: string }, void>(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { BLUETOOTH_PREFIX, bluetoothScanStatusAction } from '@suite-common/bluetooth';
import { createThunk } from '@suite-common/redux-utils';
import { bluetoothIpc } from '@trezor/transport-bluetooth';

import { BLUETOOTH_PREFIX } from './bluetoothActions';

export const bluetoothStartScanningThunk = createThunk<void, void, void>(
`${BLUETOOTH_PREFIX}/bluetoothStartScanningThunk`,
_ => {
(_, { dispatch }) => {
dispatch(bluetoothScanStatusAction({ status: 'running' }));
// This can fail, but if there is an error we already got it from `adapter-event`
// and user is informed about it (bluetooth turned-off, ...)
bluetoothIpc.startScan();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { BLUETOOTH_PREFIX, bluetoothScanStatusAction } from '@suite-common/bluetooth';
import { createThunk } from '@suite-common/redux-utils';
import { bluetoothIpc } from '@trezor/transport-bluetooth';

import { BLUETOOTH_PREFIX } from './bluetoothActions';

export const bluetoothStopScanningThunk = createThunk<void, void, void>(
`${BLUETOOTH_PREFIX}/bluetoothStopScanningThunk`,
_ => {
(_, { dispatch }) => {
dispatch(bluetoothScanStatusAction({ status: 'idle' }));
// This can fail, but there is nothing we can do about it
bluetoothIpc.stopScan();
},
Expand Down
32 changes: 22 additions & 10 deletions packages/suite/src/actions/bluetooth/initBluetoothThunk.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import { createThunk } from '@suite-common/redux-utils/';
import { DeviceConnectionStatus, bluetoothIpc } from '@trezor/transport-bluetooth';
import { Without } from '@trezor/type-utils';

import {
BLUETOOTH_PREFIX,
bluetoothAdapterEventAction,
bluetoothConnectDeviceEventAction,
bluetoothDeviceListUpdate,
} from './bluetoothActions';
bluetoothKnownDevicesUpdateAction,
bluetoothNearbyDevicesUpdateAction,
selectKnownDevices,
} from '@suite-common/bluetooth';
import { createThunk } from '@suite-common/redux-utils/';
import { BluetoothDevice, DeviceConnectionStatus, bluetoothIpc } from '@trezor/transport-bluetooth';
import { Without } from '@trezor/type-utils';

import { remapKnownDevicesForLinux } from './remapKnownDevicesForLinux';
import { selectSuiteFlags } from '../../reducers/suite/suiteReducer';

type DeviceConnectionStatusWithOptionalId = Without<DeviceConnectionStatus, 'id'> & {
Expand All @@ -28,9 +31,18 @@ export const initBluetoothThunk = createThunk<void, void, void>(
dispatch(bluetoothAdapterEventAction({ isPowered }));
});

bluetoothIpc.on('device-list-update', devices => {
console.warn('device-list-update', devices);
dispatch(bluetoothDeviceListUpdate({ devices }));
bluetoothIpc.on('device-list-update', nearbyDevices => {
console.warn('device-list-update', nearbyDevices);

const knownDevices = selectKnownDevices<BluetoothDevice>(getState());

const remappedKnownDevices = remapKnownDevicesForLinux({
knownDevices,
nearbyDevices,
});

dispatch(bluetoothKnownDevicesUpdateAction({ knownDevices: remappedKnownDevices }));
dispatch(bluetoothNearbyDevicesUpdateAction({ nearbyDevices }));
});

bluetoothIpc.on('device-connection-status', connectionStatus => {
Expand All @@ -49,7 +61,7 @@ export const initBluetoothThunk = createThunk<void, void, void>(
});

// TODO: this should be called after trezor/connect init?
const knownDevices = getState().bluetooth.pairedDevices;
const knownDevices = selectKnownDevices<BluetoothDevice>(getState());
await bluetoothIpc.init({ knownDevices });
},
);
27 changes: 27 additions & 0 deletions packages/suite/src/actions/bluetooth/remapKnownDevicesForLinux.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { BluetoothDevice } from '@trezor/transport-bluetooth';

type RemapKnownDevicesForLinuxParams = {
knownDevices: BluetoothDevice[];
nearbyDevices: BluetoothDevice[];
};

/**
* On linux, when bluetooth adapter is turned off/on again, the paired
* devices will get different `id`, but `address` will remain the same.
*
* Therefore, we have to remap the knownDevices to change the `id`.
*/
export const remapKnownDevicesForLinux = ({
knownDevices,
nearbyDevices,
}: RemapKnownDevicesForLinuxParams): BluetoothDevice[] =>
knownDevices.map(knownDevice => {
const nearbyDeviceWithSameAddress = nearbyDevices.find(
nearbyDevice =>
nearbyDevice.address === knownDevice.address && nearbyDevice.id !== knownDevice.id,
);

return nearbyDeviceWithSameAddress
? { ...knownDevice, id: nearbyDeviceWithSameAddress.id }
: knownDevice;
});
4 changes: 2 additions & 2 deletions packages/suite/src/actions/suite/storageActions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,8 @@ export const saveCoinjoinDebugSettings = () => async (_dispatch: Dispatch, getSt

export const saveKnownDevices = () => async (_dispatch: Dispatch, getState: GetState) => {
if (!(await db.isAccessible())) return;
const { pairedDevices } = getState().bluetooth;
db.addItem('knownDevices', { bluetooth: pairedDevices }, 'devices', true);
const { knownDevices } = getState().bluetooth;
db.addItem('knownDevices', { bluetooth: knownDevices }, 'devices', true);
};

export const saveFormDraft = async (key: string, draft: FieldValues) => {
Expand Down
59 changes: 25 additions & 34 deletions packages/suite/src/components/suite/bluetooth/BluetoothConnect.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
import { useCallback, useEffect, useState } from 'react';

import {
bluetoothConnectDeviceEventAction,
bluetoothScanStatusAction,
prepareSelectAllDevices,
selectAdapterStatus,
selectScanStatus,
} from '@suite-common/bluetooth';
import { notificationsActions } from '@suite-common/toast-notifications';
import { Card, Column, ElevationUp } from '@trezor/components';
import TrezorConnect from '@trezor/connect';
import { spacings } from '@trezor/theme';
import { BluetoothDevice } from '@trezor/transport-bluetooth';
import { TimerId } from '@trezor/type-utils';

import { BluetoothDeviceList } from './BluetoothDeviceList';
Expand All @@ -14,19 +21,10 @@ import { BluetoothSelectedDevice } from './BluetoothSelectedDevice';
import { BluetoothTips } from './BluetoothTips';
import { BluetoothNotEnabled } from './errors/BluetoothNotEnabled';
import { BluetoothVersionNotCompatible } from './errors/BluetoothVersionNotCompatible';
import {
bluetoothConnectDeviceEventAction,
bluetoothScanStatusAction,
} from '../../../actions/bluetooth/bluetoothActions';
import { bluetoothConnectDeviceThunk } from '../../../actions/bluetooth/bluetoothConnectDeviceThunk';
import { bluetoothStartScanningThunk } from '../../../actions/bluetooth/bluetoothStartScanningThunk';
import { bluetoothStopScanningThunk } from '../../../actions/bluetooth/bluetoothStopScanningThunk';
import { useDispatch, useSelector } from '../../../hooks/suite';
import {
selectBluetoothDeviceList,
selectBluetoothEnabled,
selectBluetoothScanStatus,
} from '../../../reducers/bluetooth/bluetoothSelectors';

const SCAN_TIMEOUT = 30_000;

Expand All @@ -35,17 +33,21 @@ type BluetoothConnectProps = {
uiMode: 'spatial' | 'card';
};

const selectAllDevices = prepareSelectAllDevices<BluetoothDevice>();
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This has to be done to create generic selector with memoized output. Consulted with @Nodonisko


export const BluetoothConnect = ({ onClose, uiMode }: BluetoothConnectProps) => {
const dispatch = useDispatch();
const [selectedDeviceId, setSelectedDeviceId] = useState<string | null>(null);
const [scannerTimerId, setScannerTimerId] = useState<TimerId | null>(null);

const isBluetoothEnabled = useSelector(selectBluetoothEnabled);
const scanStatus = useSelector(selectBluetoothScanStatus);
const deviceList = useSelector(selectBluetoothDeviceList);
const devices = Object.values(deviceList);
const bluetoothAdapterStatus = useSelector(selectAdapterStatus);
const scanStatus = useSelector(selectScanStatus);
const devices = useSelector(selectAllDevices);

const selectedDevice = selectedDeviceId !== null ? deviceList[selectedDeviceId] ?? null : null;
const selectedDevice =
selectedDeviceId !== null
? devices.find(device => device.device.id === selectedDeviceId)
: undefined;

useEffect(() => {
dispatch(bluetoothStartScanningThunk());
Expand All @@ -64,7 +66,7 @@ export const BluetoothConnect = ({ onClose, uiMode }: BluetoothConnectProps) =>
useEffect(() => {
// Intentionally no `clearScamTimer`, this is first run and if we use this we would create infinite re-render
const timerId = setTimeout(() => {
dispatch(bluetoothScanStatusAction({ status: 'done' }));
dispatch(bluetoothScanStatusAction({ status: 'idle' }));
}, SCAN_TIMEOUT);

setScannerTimerId(timerId);
Expand All @@ -76,14 +78,13 @@ export const BluetoothConnect = ({ onClose, uiMode }: BluetoothConnectProps) =>

clearScamTimer();
const timerId = setTimeout(() => {
dispatch(bluetoothScanStatusAction({ status: 'done' }));
dispatch(bluetoothScanStatusAction({ status: 'idle' }));
}, SCAN_TIMEOUT);
setScannerTimerId(timerId);
};

const onSelect = async (id: string) => {
setSelectedDeviceId(id);

const result = await dispatch(bluetoothConnectDeviceThunk({ id })).unwrap();

if (!result.success) {
Expand All @@ -100,27 +101,16 @@ export const BluetoothConnect = ({ onClose, uiMode }: BluetoothConnectProps) =>
}),
);
} else {
// Todo: What to do with error in this flow? UI-Wise

dispatch(
bluetoothConnectDeviceEventAction({
id,
connectionStatus: { type: 'connected' },
}),
);

// WAIT for connect event, TODO: figure out better way
const closePopupAfterConnection = () => {
TrezorConnect.off('device-connect', closePopupAfterConnection);
TrezorConnect.off('device-connect_unacquired', closePopupAfterConnection);
// setSelectedDeviceStatus({ type: 'error', id }); // Todo: what here?
};
TrezorConnect.on('device-connect', closePopupAfterConnection);
TrezorConnect.on('device-connect_unacquired', closePopupAfterConnection);
}
};

if (!isBluetoothEnabled) {
if (bluetoothAdapterStatus === 'disabled') {
return <BluetoothNotEnabled onCancel={onClose} />;
}

Expand All @@ -133,16 +123,17 @@ export const BluetoothConnect = ({ onClose, uiMode }: BluetoothConnectProps) =>
console.log('selectedDevice', selectedDevice);

// This is fake, we scan for devices all the time
const isScanning = scanStatus !== 'done';
const scanFailed = devices.length === 0 && scanStatus === 'done';
const isScanning = scanStatus === 'running';
const scanFailed = devices.length === 0 && scanStatus === 'idle';

const handlePairingCancel = () => {
setSelectedDeviceId(null);
onReScanClick();
};

if (
selectedDevice !== null &&
selectedDevice !== undefined &&
selectedDevice.status !== null &&
selectedDevice.status.type === 'pairing' &&
(selectedDevice.status.pin?.length ?? 0) > 0
) {
Expand All @@ -155,7 +146,7 @@ export const BluetoothConnect = ({ onClose, uiMode }: BluetoothConnectProps) =>
);
}

if (selectedDevice !== null) {
if (selectedDevice !== undefined) {
return <BluetoothSelectedDevice device={selectedDevice} onReScanClick={onReScanClick} />;
}

Expand Down
Loading
Loading