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.js 12KB

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