From b04c438d6f19472002b63a15d9e39b5d85379e47 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20N=C3=A9grier?= Date: Tue, 1 Jun 2021 16:43:16 +0200 Subject: [PATCH] Detect webcams unplugged --- front/src/Stores/MediaStore.ts | 56 +++++++++++++++++++++++++++++----- 1 file changed, 48 insertions(+), 8 deletions(-) diff --git a/front/src/Stores/MediaStore.ts b/front/src/Stores/MediaStore.ts index 51cba013..6d6fb4a8 100644 --- a/front/src/Stores/MediaStore.ts +++ b/front/src/Stores/MediaStore.ts @@ -209,10 +209,14 @@ function createVideoConstraintStore() { return { subscribe, - setDeviceId: (deviceId: string) => update((constraints) => { - constraints.deviceId = { - exact: deviceId - }; + setDeviceId: (deviceId: string|undefined) => update((constraints) => { + if (deviceId !== undefined) { + constraints.deviceId = { + exact: deviceId + }; + } else { + delete constraints.deviceId; + } return constraints; }), @@ -241,15 +245,19 @@ function createAudioConstraintStore() { return { subscribe, - setDeviceId: (deviceId: string) => update((constraints) => { + setDeviceId: (deviceId: string|undefined) => update((constraints) => { selectedDeviceId = deviceId; if (typeof(constraints) === 'boolean') { constraints = {} } - constraints.deviceId = { - exact: selectedDeviceId - }; + if (deviceId !== undefined) { + constraints.deviceId = { + exact: selectedDeviceId + }; + } else { + delete constraints.deviceId; + } return constraints; }) @@ -552,3 +560,35 @@ export const cameraListStore = derived(deviceListStore, ($deviceListStore) => { export const microphoneListStore = derived(deviceListStore, ($deviceListStore) => { return $deviceListStore.filter(device => device.kind === 'audioinput'); }); + +// TODO: detect the new webcam and automatically switch on it. +cameraListStore.subscribe((devices) => { + // If the selected camera is unplugged, let's remove the constraint on deviceId + const constraints = get(videoConstraintStore); + if (!constraints.deviceId) { + return; + } + + // If we cannot find the device ID, let's remove it. + // @ts-ignore + if (!devices.find(device => device.deviceId === constraints.deviceId.exact)) { + videoConstraintStore.setDeviceId(undefined); + } +}); + +microphoneListStore.subscribe((devices) => { + // If the selected camera is unplugged, let's remove the constraint on deviceId + const constraints = get(audioConstraintStore); + if (typeof constraints === 'boolean') { + return; + } + if (!constraints.deviceId) { + return; + } + + // If we cannot find the device ID, let's remove it. + // @ts-ignore + if (!devices.find(device => device.deviceId === constraints.deviceId.exact)) { + audioConstraintStore.setDeviceId(undefined); + } +});