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

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