You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

middleware.web.ts 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. import { AnyAction } from 'redux';
  2. // @ts-expect-error
  3. import UIEvents from '../../../../service/UI/UIEvents';
  4. import { IStore } from '../../app/types';
  5. import { processExternalDeviceRequest } from '../../device-selection/functions';
  6. import { showNotification, showWarningNotification } from '../../notifications/actions';
  7. import { NOTIFICATION_TIMEOUT_TYPE } from '../../notifications/constants';
  8. import { replaceAudioTrackById, replaceVideoTrackById, setDeviceStatusWarning } from '../../prejoin/actions';
  9. import { isPrejoinPageVisible } from '../../prejoin/functions';
  10. import { APP_WILL_MOUNT, APP_WILL_UNMOUNT } from '../app/actionTypes';
  11. import JitsiMeetJS, { JitsiMediaDevicesEvents, JitsiTrackErrors } from '../lib-jitsi-meet';
  12. import MiddlewareRegistry from '../redux/MiddlewareRegistry';
  13. import { updateSettings } from '../settings/actions';
  14. import {
  15. CHECK_AND_NOTIFY_FOR_NEW_DEVICE,
  16. NOTIFY_CAMERA_ERROR,
  17. NOTIFY_MIC_ERROR,
  18. SET_AUDIO_INPUT_DEVICE,
  19. SET_VIDEO_INPUT_DEVICE,
  20. UPDATE_DEVICE_LIST
  21. } from './actionTypes';
  22. import {
  23. devicePermissionsChanged,
  24. removePendingDeviceRequests,
  25. setAudioInputDevice,
  26. setVideoInputDevice
  27. } from './actions';
  28. import {
  29. areDeviceLabelsInitialized,
  30. formatDeviceLabel,
  31. groupDevicesByKind,
  32. setAudioOutputDeviceId
  33. } from './functions';
  34. import logger from './logger';
  35. import { IDevicesState } from './types';
  36. const JITSI_TRACK_ERROR_TO_MESSAGE_KEY_MAP = {
  37. microphone: {
  38. [JitsiTrackErrors.CONSTRAINT_FAILED]: 'dialog.micConstraintFailedError',
  39. [JitsiTrackErrors.GENERAL]: 'dialog.micUnknownError',
  40. [JitsiTrackErrors.NOT_FOUND]: 'dialog.micNotFoundError',
  41. [JitsiTrackErrors.PERMISSION_DENIED]: 'dialog.micPermissionDeniedError',
  42. [JitsiTrackErrors.TIMEOUT]: 'dialog.micTimeoutError'
  43. },
  44. camera: {
  45. [JitsiTrackErrors.CONSTRAINT_FAILED]: 'dialog.cameraConstraintFailedError',
  46. [JitsiTrackErrors.GENERAL]: 'dialog.cameraUnknownError',
  47. [JitsiTrackErrors.NOT_FOUND]: 'dialog.cameraNotFoundError',
  48. [JitsiTrackErrors.PERMISSION_DENIED]: 'dialog.cameraPermissionDeniedError',
  49. [JitsiTrackErrors.UNSUPPORTED_RESOLUTION]: 'dialog.cameraUnsupportedResolutionError',
  50. [JitsiTrackErrors.TIMEOUT]: 'dialog.cameraTimeoutError'
  51. }
  52. };
  53. /**
  54. * A listener for device permissions changed reported from lib-jitsi-meet.
  55. */
  56. let permissionsListener: Function | undefined;
  57. /**
  58. * Logs the current device list.
  59. *
  60. * @param {Object} deviceList - Whatever is returned by {@link groupDevicesByKind}.
  61. * @returns {string}
  62. */
  63. function logDeviceList(deviceList: IDevicesState['availableDevices']) {
  64. const devicesToStr = (list?: MediaDeviceInfo[]) =>
  65. list?.map(device => `\t\t${device.label}[${device.deviceId}]`).join('\n');
  66. const audioInputs = devicesToStr(deviceList.audioInput);
  67. const audioOutputs = devicesToStr(deviceList.audioOutput);
  68. const videoInputs = devicesToStr(deviceList.videoInput);
  69. logger.debug('Device list updated:\n'
  70. + `audioInput:\n${audioInputs}\n`
  71. + `audioOutput:\n${audioOutputs}\n`
  72. + `videoInput:\n${videoInputs}`);
  73. }
  74. /**
  75. * Implements the middleware of the feature base/devices.
  76. *
  77. * @param {Store} store - Redux store.
  78. * @returns {Function}
  79. */
  80. // eslint-disable-next-line no-unused-vars
  81. MiddlewareRegistry.register(store => next => action => {
  82. switch (action.type) {
  83. case APP_WILL_MOUNT: {
  84. const _permissionsListener = (permissions: Object) => {
  85. store.dispatch(devicePermissionsChanged(permissions));
  86. };
  87. const { mediaDevices } = JitsiMeetJS;
  88. permissionsListener = _permissionsListener;
  89. mediaDevices.addEventListener(JitsiMediaDevicesEvents.PERMISSIONS_CHANGED, permissionsListener);
  90. Promise.all([
  91. mediaDevices.isDevicePermissionGranted('audio'),
  92. mediaDevices.isDevicePermissionGranted('video')
  93. ])
  94. .then(results => {
  95. _permissionsListener({
  96. audio: results[0],
  97. video: results[1]
  98. });
  99. })
  100. .catch(() => {
  101. // Ignore errors.
  102. });
  103. break;
  104. }
  105. case APP_WILL_UNMOUNT:
  106. if (typeof permissionsListener === 'function') {
  107. JitsiMeetJS.mediaDevices.removeEventListener(
  108. JitsiMediaDevicesEvents.PERMISSIONS_CHANGED, permissionsListener);
  109. permissionsListener = undefined;
  110. }
  111. break;
  112. case NOTIFY_CAMERA_ERROR: {
  113. if (!action.error) {
  114. break;
  115. }
  116. const { message, name } = action.error;
  117. const cameraJitsiTrackErrorMsg
  118. = JITSI_TRACK_ERROR_TO_MESSAGE_KEY_MAP.camera[name];
  119. const cameraErrorMsg = cameraJitsiTrackErrorMsg
  120. || JITSI_TRACK_ERROR_TO_MESSAGE_KEY_MAP
  121. .camera[JitsiTrackErrors.GENERAL];
  122. const additionalCameraErrorMsg = cameraJitsiTrackErrorMsg ? null : message;
  123. const titleKey = name === JitsiTrackErrors.PERMISSION_DENIED
  124. ? 'deviceError.cameraPermission' : 'deviceError.cameraError';
  125. store.dispatch(showWarningNotification({
  126. description: additionalCameraErrorMsg,
  127. descriptionKey: cameraErrorMsg,
  128. titleKey
  129. }, NOTIFICATION_TIMEOUT_TYPE.MEDIUM));
  130. if (isPrejoinPageVisible(store.getState())) {
  131. store.dispatch(setDeviceStatusWarning(titleKey));
  132. }
  133. break;
  134. }
  135. case NOTIFY_MIC_ERROR: {
  136. if (!action.error) {
  137. break;
  138. }
  139. const { message, name } = action.error;
  140. const micJitsiTrackErrorMsg
  141. = JITSI_TRACK_ERROR_TO_MESSAGE_KEY_MAP.microphone[name];
  142. const micErrorMsg = micJitsiTrackErrorMsg
  143. || JITSI_TRACK_ERROR_TO_MESSAGE_KEY_MAP
  144. .microphone[JitsiTrackErrors.GENERAL];
  145. const additionalMicErrorMsg = micJitsiTrackErrorMsg ? null : message;
  146. const titleKey = name === JitsiTrackErrors.PERMISSION_DENIED
  147. ? 'deviceError.microphonePermission'
  148. : 'deviceError.microphoneError';
  149. store.dispatch(showWarningNotification({
  150. description: additionalMicErrorMsg,
  151. descriptionKey: micErrorMsg,
  152. titleKey
  153. }, NOTIFICATION_TIMEOUT_TYPE.MEDIUM));
  154. if (isPrejoinPageVisible(store.getState())) {
  155. store.dispatch(setDeviceStatusWarning(titleKey));
  156. }
  157. break;
  158. }
  159. case SET_AUDIO_INPUT_DEVICE:
  160. if (isPrejoinPageVisible(store.getState())) {
  161. store.dispatch(replaceAudioTrackById(action.deviceId));
  162. } else {
  163. APP.UI.emitEvent(UIEvents.AUDIO_DEVICE_CHANGED, action.deviceId);
  164. }
  165. break;
  166. case SET_VIDEO_INPUT_DEVICE:
  167. if (isPrejoinPageVisible(store.getState())) {
  168. store.dispatch(replaceVideoTrackById(action.deviceId));
  169. } else {
  170. APP.UI.emitEvent(UIEvents.VIDEO_DEVICE_CHANGED, action.deviceId);
  171. }
  172. break;
  173. case UPDATE_DEVICE_LIST:
  174. logDeviceList(groupDevicesByKind(action.devices));
  175. if (areDeviceLabelsInitialized(store.getState())) {
  176. return _processPendingRequests(store, next, action);
  177. }
  178. break;
  179. case CHECK_AND_NOTIFY_FOR_NEW_DEVICE:
  180. _checkAndNotifyForNewDevice(store, action.newDevices, action.oldDevices);
  181. break;
  182. }
  183. return next(action);
  184. });
  185. /**
  186. * Does extra sync up on properties that may need to be updated after the
  187. * conference was joined.
  188. *
  189. * @param {Store} store - The redux store in which the specified {@code action}
  190. * is being dispatched.
  191. * @param {Dispatch} next - The redux {@code dispatch} function to dispatch the
  192. * specified {@code action} to the specified {@code store}.
  193. * @param {Action} action - The redux action {@code CONFERENCE_JOINED} which is
  194. * being dispatched in the specified {@code store}.
  195. * @private
  196. * @returns {Object} The value returned by {@code next(action)}.
  197. */
  198. function _processPendingRequests({ dispatch, getState }: IStore, next: Function, action: AnyAction) {
  199. const result = next(action);
  200. const state = getState();
  201. const { pendingRequests } = state['features/base/devices'];
  202. if (!pendingRequests || pendingRequests.length === 0) {
  203. return result;
  204. }
  205. pendingRequests.forEach((request: any) => {
  206. processExternalDeviceRequest(
  207. dispatch,
  208. getState,
  209. request,
  210. request.responseCallback);
  211. });
  212. dispatch(removePendingDeviceRequests());
  213. return result;
  214. }
  215. /**
  216. * Finds a new device by comparing new and old array of devices and dispatches
  217. * notification with the new device. For new devices with same groupId only one
  218. * notification will be shown, this is so to avoid showing multiple notifications
  219. * for audio input and audio output devices.
  220. *
  221. * @param {Store} store - The redux store in which the specified {@code action}
  222. * is being dispatched.
  223. * @param {MediaDeviceInfo[]} newDevices - The array of new devices we received.
  224. * @param {MediaDeviceInfo[]} oldDevices - The array of the old devices we have.
  225. * @private
  226. * @returns {void}
  227. */
  228. function _checkAndNotifyForNewDevice(store: IStore, newDevices: MediaDeviceInfo[], oldDevices: MediaDeviceInfo[]) {
  229. const { dispatch } = store;
  230. // let's intersect both newDevices and oldDevices and handle thew newly
  231. // added devices
  232. const onlyNewDevices = newDevices.filter(
  233. nDevice => !oldDevices.find(
  234. device => device.deviceId === nDevice.deviceId));
  235. // we group devices by groupID which normally is the grouping by physical device
  236. // plugging in headset we provide normally two device, one input and one output
  237. // and we want to show only one notification for this physical audio device
  238. const devicesGroupBy: {
  239. [key: string]: MediaDeviceInfo[];
  240. } = onlyNewDevices.reduce((accumulated: any, value) => {
  241. accumulated[value.groupId] = accumulated[value.groupId] || [];
  242. accumulated[value.groupId].push(value);
  243. return accumulated;
  244. }, {});
  245. Object.values(devicesGroupBy).forEach(devicesArray => {
  246. if (devicesArray.length < 1) {
  247. return;
  248. }
  249. // let's get the first device as a reference, we will use it for
  250. // label and type
  251. const newDevice = devicesArray[0];
  252. // we want to strip any device details that are not very
  253. // user friendly, like usb ids put in brackets at the end
  254. const description = formatDeviceLabel(newDevice.label);
  255. let titleKey;
  256. switch (newDevice.kind) {
  257. case 'videoinput': {
  258. titleKey = 'notify.newDeviceCameraTitle';
  259. break;
  260. }
  261. case 'audioinput' :
  262. case 'audiooutput': {
  263. titleKey = 'notify.newDeviceAudioTitle';
  264. break;
  265. }
  266. }
  267. if (!isPrejoinPageVisible(store.getState())) {
  268. dispatch(showNotification({
  269. description,
  270. titleKey,
  271. customActionNameKey: [ 'notify.newDeviceAction' ],
  272. customActionHandler: [ _useDevice.bind(undefined, store, devicesArray) ]
  273. }, NOTIFICATION_TIMEOUT_TYPE.MEDIUM));
  274. }
  275. });
  276. }
  277. /**
  278. * Set a device to be currently used, selected by the user.
  279. *
  280. * @param {Store} store - The redux store in which the specified {@code action}
  281. * is being dispatched.
  282. * @param {Array<MediaDeviceInfo|InputDeviceInfo>} devices - The devices to save.
  283. * @returns {boolean} - Returns true in order notifications to be dismissed.
  284. * @private
  285. */
  286. function _useDevice({ dispatch }: IStore, devices: MediaDeviceInfo[]) {
  287. devices.forEach(device => {
  288. switch (device.kind) {
  289. case 'videoinput': {
  290. dispatch(updateSettings({
  291. userSelectedCameraDeviceId: device.deviceId,
  292. userSelectedCameraDeviceLabel: device.label
  293. }));
  294. dispatch(setVideoInputDevice(device.deviceId));
  295. break;
  296. }
  297. case 'audioinput': {
  298. dispatch(updateSettings({
  299. userSelectedMicDeviceId: device.deviceId,
  300. userSelectedMicDeviceLabel: device.label
  301. }));
  302. dispatch(setAudioInputDevice(device.deviceId));
  303. break;
  304. }
  305. case 'audiooutput': {
  306. setAudioOutputDeviceId(
  307. device.deviceId,
  308. dispatch,
  309. true,
  310. device.label)
  311. .then(() => logger.log('changed audio output device'))
  312. .catch(err => {
  313. logger.warn(
  314. 'Failed to change audio output device.',
  315. 'Default or previously set audio output device will',
  316. ' be used instead.',
  317. err);
  318. });
  319. break;
  320. }
  321. }
  322. });
  323. return true;
  324. }