Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

middleware.js 12KB

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