Live location sharing - refresh beacon expiry in room (#8116)

* add duration dropdown to live location picker

Signed-off-by: Kerry Archibald <kerrya@element.io>

* tidy comments

Signed-off-by: Kerry Archibald <kerrya@element.io>

* setup component

Signed-off-by: Kerry Archibald <kerrya@element.io>

* replace references to beaconInfoId with beacon.identifier

Signed-off-by: Kerry Archibald <kerrya@element.io>

* icon

Signed-off-by: Kerry Archibald <kerrya@element.io>

* component for styled live beacon icon

Signed-off-by: Kerry Archibald <kerrya@element.io>

* emit liveness change whenever livebeaconIds changes

Signed-off-by: Kerry Archibald <kerrya@element.io>

* Handle multiple live beacons in room share warning, test

Signed-off-by: Kerry Archibald <kerrya@element.io>

* un xdescribe beaconstore tests

Signed-off-by: Kerry Archibald <kerrya@element.io>

* missed copyrights

Signed-off-by: Kerry Archibald <kerrya@element.io>

* i18n

Signed-off-by: Kerry Archibald <kerrya@element.io>

* refresh beacon time remaining

Signed-off-by: Kerry Archibald <kerrya@element.io>

* kill timeout

Signed-off-by: Kerry Archibald <kerrya@element.io>

* use useInterval

Signed-off-by: Kerry Archibald <kerrya@element.io>

* beacon not optional in useMsRemaining

Signed-off-by: Kerry Archibald <kerrya@element.io>

* just use single "you are sharing" message

Signed-off-by: Kerry Archibald <kerrya@element.io>

* trigger

Signed-off-by: Kerry Archibald <kerrya@element.io>

* i18n

Signed-off-by: Kerry Archibald <kerrya@element.io>

* i18n again

Signed-off-by: Kerry Archibald <kerrya@element.io>
This commit is contained in:
Kerry 2022-03-23 11:12:58 +01:00 committed by GitHub
parent 9b2944294c
commit 752ad6a9f9
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 201 additions and 43 deletions

View file

@ -14,9 +14,9 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
import React, { useEffect, useState } from 'react'; import React, { useCallback, useEffect, useState } from 'react';
import classNames from 'classnames'; import classNames from 'classnames';
import { Room } from 'matrix-js-sdk/src/matrix'; import { Room, Beacon } from 'matrix-js-sdk/src/matrix';
import { _t } from '../../../languageHandler'; import { _t } from '../../../languageHandler';
import { useEventEmitterState } from '../../../hooks/useEventEmitter'; import { useEventEmitterState } from '../../../hooks/useEventEmitter';
@ -26,25 +26,57 @@ import StyledLiveBeaconIcon from './StyledLiveBeaconIcon';
import { formatDuration } from '../../../DateUtils'; import { formatDuration } from '../../../DateUtils';
import { getBeaconMsUntilExpiry, sortBeaconsByLatestExpiry } from '../../../utils/beacon'; import { getBeaconMsUntilExpiry, sortBeaconsByLatestExpiry } from '../../../utils/beacon';
import Spinner from '../elements/Spinner'; import Spinner from '../elements/Spinner';
import { useInterval } from '../../../hooks/useTimeout';
interface Props { interface Props {
roomId: Room['roomId']; roomId: Room['roomId'];
} }
const MINUTE_MS = 60000;
const HOUR_MS = MINUTE_MS * 60;
const getUpdateInterval = (ms: number) => {
// every 10 mins when more than an hour
if (ms > HOUR_MS) {
return MINUTE_MS * 10;
}
// every minute when more than a minute
if (ms > MINUTE_MS) {
return MINUTE_MS;
}
// otherwise every second
return 1000;
};
const useMsRemaining = (beacon: Beacon): number => {
const [msRemaining, setMsRemaining] = useState(() => getBeaconMsUntilExpiry(beacon));
useEffect(() => {
setMsRemaining(getBeaconMsUntilExpiry(beacon));
}, [beacon]);
const updateMsRemaining = useCallback(() => {
const ms = getBeaconMsUntilExpiry(beacon);
setMsRemaining(ms);
}, [beacon]);
useInterval(updateMsRemaining, getUpdateInterval(msRemaining));
return msRemaining;
};
/** /**
* It's technically possible to have multiple live beacons in one room * It's technically possible to have multiple live beacons in one room
* Select the latest expiry to display, * Select the latest expiry to display,
* and kill all beacons on stop sharing * and kill all beacons on stop sharing
*/ */
type LiveBeaconsState = { type LiveBeaconsState = {
liveBeaconIds: string[]; beacon?: Beacon;
msRemaining?: number;
onStopSharing?: () => void; onStopSharing?: () => void;
stoppingInProgress?: boolean; stoppingInProgress?: boolean;
}; };
const useLiveBeacons = (roomId: Room['roomId']): LiveBeaconsState => { const useLiveBeacons = (roomId: Room['roomId']): LiveBeaconsState => {
const [stoppingInProgress, setStoppingInProgress] = useState(false); const [stoppingInProgress, setStoppingInProgress] = useState(false);
const liveBeaconIds = useEventEmitterState( const liveBeaconIds = useEventEmitterState(
OwnBeaconStore.instance, OwnBeaconStore.instance,
OwnBeaconStoreEvent.LivenessChange, OwnBeaconStoreEvent.LivenessChange,
@ -57,7 +89,7 @@ const useLiveBeacons = (roomId: Room['roomId']): LiveBeaconsState => {
}, [liveBeaconIds]); }, [liveBeaconIds]);
if (!liveBeaconIds?.length) { if (!liveBeaconIds?.length) {
return { liveBeaconIds }; return {};
} }
// select the beacon with latest expiry to display expiry time // select the beacon with latest expiry to display expiry time
@ -77,40 +109,43 @@ const useLiveBeacons = (roomId: Room['roomId']): LiveBeaconsState => {
} }
}; };
const msRemaining = getBeaconMsUntilExpiry(beacon); return { onStopSharing, beacon, stoppingInProgress };
};
return { liveBeaconIds, onStopSharing, msRemaining, stoppingInProgress }; const LiveTimeRemaining: React.FC<{ beacon: Beacon }> = ({ beacon }) => {
const msRemaining = useMsRemaining(beacon);
const timeRemaining = formatDuration(msRemaining);
const liveTimeRemaining = _t(`%(timeRemaining)s left`, { timeRemaining });
return <span
data-test-id='room-live-share-expiry'
className="mx_RoomLiveShareWarning_expiry"
>{ liveTimeRemaining }</span>;
}; };
const RoomLiveShareWarning: React.FC<Props> = ({ roomId }) => { const RoomLiveShareWarning: React.FC<Props> = ({ roomId }) => {
const { const {
liveBeaconIds,
onStopSharing, onStopSharing,
msRemaining, beacon,
stoppingInProgress, stoppingInProgress,
} = useLiveBeacons(roomId); } = useLiveBeacons(roomId);
if (!liveBeaconIds?.length) { if (!beacon) {
return null; return null;
} }
const timeRemaining = formatDuration(msRemaining);
const liveTimeRemaining = _t(`%(timeRemaining)s left`, { timeRemaining });
return <div return <div
className={classNames('mx_RoomLiveShareWarning')} className={classNames('mx_RoomLiveShareWarning')}
> >
<StyledLiveBeaconIcon className="mx_RoomLiveShareWarning_icon" /> <StyledLiveBeaconIcon className="mx_RoomLiveShareWarning_icon" />
<span className="mx_RoomLiveShareWarning_label"> <span className="mx_RoomLiveShareWarning_label">
{ _t('You are sharing %(count)s live locations', { count: liveBeaconIds.length }) } { _t('You are sharing your live location') }
</span> </span>
{ stoppingInProgress ? { stoppingInProgress ?
<span className='mx_RoomLiveShareWarning_spinner'><Spinner h={16} w={16} /></span> : <span className='mx_RoomLiveShareWarning_spinner'><Spinner h={16} w={16} /></span> :
<span <LiveTimeRemaining beacon={beacon} />
data-test-id='room-live-share-expiry'
className="mx_RoomLiveShareWarning_expiry"
>{ liveTimeRemaining }</span>
} }
<AccessibleButton <AccessibleButton
data-test-id='room-live-share-stop-sharing' data-test-id='room-live-share-stop-sharing'

View file

@ -2862,8 +2862,6 @@
"Join the beta": "Join the beta", "Join the beta": "Join the beta",
"You are sharing your live location": "You are sharing your live location", "You are sharing your live location": "You are sharing your live location",
"%(timeRemaining)s left": "%(timeRemaining)s left", "%(timeRemaining)s left": "%(timeRemaining)s left",
"You are sharing %(count)s live locations|other": "You are sharing %(count)s live locations",
"You are sharing %(count)s live locations|one": "You are sharing your live location",
"Stop sharing": "Stop sharing", "Stop sharing": "Stop sharing",
"Avatar": "Avatar", "Avatar": "Avatar",
"This room is public": "This room is public", "This room is public": "This room is public",

View file

@ -44,13 +44,17 @@ describe('<RoomLiveShareWarning />', () => {
// 14.03.2022 16:15 // 14.03.2022 16:15
const now = 1647270879403; const now = 1647270879403;
const MINUTE_MS = 60000;
const HOUR_MS = 3600000; const HOUR_MS = 3600000;
// mock the date so events are stable for snapshots etc // mock the date so events are stable for snapshots etc
jest.spyOn(global.Date, 'now').mockReturnValue(now); jest.spyOn(global.Date, 'now').mockReturnValue(now);
const room1Beacon1 = makeBeaconInfoEvent(aliceId, room1Id, { isLive: true, timeout: HOUR_MS }); const room1Beacon1 = makeBeaconInfoEvent(aliceId, room1Id, {
const room2Beacon1 = makeBeaconInfoEvent(aliceId, room2Id, { isLive: true, timeout: HOUR_MS }); isLive: true,
const room2Beacon2 = makeBeaconInfoEvent(aliceId, room2Id, { isLive: true, timeout: HOUR_MS * 12 }); timeout: HOUR_MS,
const room3Beacon1 = makeBeaconInfoEvent(aliceId, room3Id, { isLive: true, timeout: HOUR_MS }); }, '$0');
const room2Beacon1 = makeBeaconInfoEvent(aliceId, room2Id, { isLive: true, timeout: HOUR_MS }, '$1');
const room2Beacon2 = makeBeaconInfoEvent(aliceId, room2Id, { isLive: true, timeout: HOUR_MS * 12 }, '$2');
const room3Beacon1 = makeBeaconInfoEvent(aliceId, room3Id, { isLive: true, timeout: HOUR_MS }, '$3');
// make fresh rooms every time // make fresh rooms every time
// as we update room state // as we update room state
@ -67,7 +71,8 @@ describe('<RoomLiveShareWarning />', () => {
const advanceDateAndTime = (ms: number) => { const advanceDateAndTime = (ms: number) => {
// bc liveness check uses Date.now we have to advance this mock // bc liveness check uses Date.now we have to advance this mock
jest.spyOn(global.Date, 'now').mockReturnValue(now + ms); jest.spyOn(global.Date, 'now').mockReturnValue(Date.now() + ms);
// then advance time for the interval by the same amount // then advance time for the interval by the same amount
jest.advanceTimersByTime(ms); jest.advanceTimersByTime(ms);
}; };
@ -105,6 +110,8 @@ describe('<RoomLiveShareWarning />', () => {
jest.spyOn(global.Date, 'now').mockRestore(); jest.spyOn(global.Date, 'now').mockRestore();
}); });
const getExpiryText = wrapper => findByTestId(wrapper, 'room-live-share-expiry').text();
it('renders nothing when user has no live beacons at all', async () => { it('renders nothing when user has no live beacons at all', async () => {
await makeOwnBeaconStore(); await makeOwnBeaconStore();
const component = getComponent(); const component = getComponent();
@ -137,7 +144,7 @@ describe('<RoomLiveShareWarning />', () => {
const component = getComponent({ roomId: room2Id }); const component = getComponent({ roomId: room2Id });
expect(component).toMatchSnapshot(); expect(component).toMatchSnapshot();
// later expiry displayed // later expiry displayed
expect(findByTestId(component, 'room-live-share-expiry').text()).toEqual('12h left'); expect(getExpiryText(component)).toEqual('12h left');
}); });
it('removes itself when user stops having live beacons', async () => { it('removes itself when user stops having live beacons', async () => {
@ -146,7 +153,9 @@ describe('<RoomLiveShareWarning />', () => {
expect(component.html()).toBeTruthy(); expect(component.html()).toBeTruthy();
// time travel until room1Beacon1 is expired // time travel until room1Beacon1 is expired
advanceDateAndTime(HOUR_MS + 1); act(() => {
advanceDateAndTime(HOUR_MS + 1);
});
act(() => { act(() => {
mockClient.emit(BeaconEvent.LivenessChange, false, new Beacon(room1Beacon1)); mockClient.emit(BeaconEvent.LivenessChange, false, new Beacon(room1Beacon1));
component.setProps({}); component.setProps({});
@ -168,6 +177,29 @@ describe('<RoomLiveShareWarning />', () => {
expect(component.html()).toBeTruthy(); expect(component.html()).toBeTruthy();
}); });
it('updates beacon time left periodically', () => {
const component = getComponent({ roomId: room1Id });
expect(getExpiryText(component)).toEqual('1h left');
act(() => {
advanceDateAndTime(MINUTE_MS * 25);
});
expect(getExpiryText(component)).toEqual('35m left');
});
it('clears expiry time interval on unmount', () => {
const clearIntervalSpy = jest.spyOn(global, 'clearInterval');
const component = getComponent({ roomId: room1Id });
expect(getExpiryText(component)).toEqual('1h left');
act(() => {
component.unmount();
});
expect(clearIntervalSpy).toHaveBeenCalled();
});
describe('stopping beacons', () => { describe('stopping beacons', () => {
it('stops beacon on stop sharing click', () => { it('stops beacon on stop sharing click', () => {
const component = getComponent({ roomId: room2Id }); const component = getComponent({ roomId: room2Id });
@ -184,25 +216,28 @@ describe('<RoomLiveShareWarning />', () => {
it('displays again with correct state after stopping a beacon', () => { it('displays again with correct state after stopping a beacon', () => {
// make sure the loading state is reset correctly after removing a beacon // make sure the loading state is reset correctly after removing a beacon
const component = getComponent({ roomId: room2Id }); const component = getComponent({ roomId: room1Id });
// stop the beacon
act(() => { act(() => {
findByTestId(component, 'room-live-share-stop-sharing').at(0).simulate('click'); findByTestId(component, 'room-live-share-stop-sharing').at(0).simulate('click');
}); });
// time travel until room1Beacon1 is expired // time travel until room1Beacon1 is expired
advanceDateAndTime(HOUR_MS + 1); act(() => {
advanceDateAndTime(HOUR_MS + 1);
});
act(() => { act(() => {
mockClient.emit(BeaconEvent.LivenessChange, false, new Beacon(room1Beacon1)); mockClient.emit(BeaconEvent.LivenessChange, false, new Beacon(room1Beacon1));
}); });
const newLiveBeacon = makeBeaconInfoEvent(aliceId, room2Id, { isLive: true }); const newLiveBeacon = makeBeaconInfoEvent(aliceId, room1Id, { isLive: true });
act(() => { act(() => {
mockClient.emit(BeaconEvent.New, newLiveBeacon, new Beacon(newLiveBeacon)); mockClient.emit(BeaconEvent.New, newLiveBeacon, new Beacon(newLiveBeacon));
}); });
// button not disabled and expiry time shown // button not disabled and expiry time shown
expect(findByTestId(component, 'room-live-share-stop-sharing').at(0).props().disabled).toBeFalsy(); expect(findByTestId(component, 'room-live-share-stop-sharing').at(0).props().disabled).toBeFalsy();
expect(findByTestId(component, 'room-live-share-expiry').text()).toEqual('11h left'); expect(findByTestId(component, 'room-live-share-expiry').text()).toEqual('1h left');
}); });
}); });
}); });

View file

@ -19,12 +19,57 @@ exports[`<RoomLiveShareWarning /> when user has live beacons renders correctly w
> >
You are sharing your live location You are sharing your live location
</span> </span>
<span <LiveTimeRemaining
className="mx_RoomLiveShareWarning_expiry" beacon={
data-test-id="room-live-share-expiry" Beacon {
"_beaconInfo": Object {
"assetType": "m.self",
"description": undefined,
"live": true,
"timeout": 3600000,
"timestamp": 1647270879403,
},
"_events": Object {
"Beacon.LivenessChange": Array [
[Function],
[Function],
],
"Beacon.new": [Function],
"Beacon.update": [Function],
},
"_eventsCount": 3,
"_isLive": true,
"_maxListeners": undefined,
"livenessWatchInterval": 1000000000002,
"roomId": "$room1:server.org",
"rootEvent": Object {
"content": Object {
"org.matrix.msc3488.asset": Object {
"type": "m.self",
},
"org.matrix.msc3488.ts": 1647270879403,
"org.matrix.msc3489.beacon_info": Object {
"description": undefined,
"live": true,
"timeout": 3600000,
},
},
"event_id": "$0",
"room_id": "$room1:server.org",
"state_key": "@alice:server.org",
"type": "org.matrix.msc3489.beacon_info.@alice:server.org.2",
},
Symbol(kCapture): false,
}
}
> >
1h left <span
</span> className="mx_RoomLiveShareWarning_expiry"
data-test-id="room-live-share-expiry"
>
1h left
</span>
</LiveTimeRemaining>
<AccessibleButton <AccessibleButton
data-test-id="room-live-share-stop-sharing" data-test-id="room-live-share-stop-sharing"
disabled={false} disabled={false}
@ -67,14 +112,59 @@ exports[`<RoomLiveShareWarning /> when user has live beacons renders correctly w
<span <span
className="mx_RoomLiveShareWarning_label" className="mx_RoomLiveShareWarning_label"
> >
You are sharing 2 live locations You are sharing your live location
</span> </span>
<span <LiveTimeRemaining
className="mx_RoomLiveShareWarning_expiry" beacon={
data-test-id="room-live-share-expiry" Beacon {
"_beaconInfo": Object {
"assetType": "m.self",
"description": undefined,
"live": true,
"timeout": 43200000,
"timestamp": 1647270879403,
},
"_events": Object {
"Beacon.LivenessChange": Array [
[Function],
[Function],
],
"Beacon.new": [Function],
"Beacon.update": [Function],
},
"_eventsCount": 3,
"_isLive": true,
"_maxListeners": undefined,
"livenessWatchInterval": 1000000000010,
"roomId": "$room2:server.org",
"rootEvent": Object {
"content": Object {
"org.matrix.msc3488.asset": Object {
"type": "m.self",
},
"org.matrix.msc3488.ts": 1647270879403,
"org.matrix.msc3489.beacon_info": Object {
"description": undefined,
"live": true,
"timeout": 43200000,
},
},
"event_id": "$2",
"room_id": "$room2:server.org",
"state_key": "@alice:server.org",
"type": "org.matrix.msc3489.beacon_info.@alice:server.org.4",
},
Symbol(kCapture): false,
}
}
> >
12h left <span
</span> className="mx_RoomLiveShareWarning_expiry"
data-test-id="room-live-share-expiry"
>
12h left
</span>
</LiveTimeRemaining>
<AccessibleButton <AccessibleButton
data-test-id="room-live-share-stop-sharing" data-test-id="room-live-share-stop-sharing"
disabled={false} disabled={false}