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 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. // @flow
  2. import {
  3. ACTION_PINNED,
  4. ACTION_UNPINNED,
  5. createOfferAnswerFailedEvent,
  6. createPinnedEvent,
  7. sendAnalytics
  8. } from '../../analytics';
  9. import { openDisplayNamePrompt } from '../../display-name';
  10. import { showErrorNotification } from '../../notifications';
  11. import { CONNECTION_ESTABLISHED, CONNECTION_FAILED, connectionDisconnected } from '../connection';
  12. import { JitsiConferenceErrors } from '../lib-jitsi-meet';
  13. import { MEDIA_TYPE } from '../media';
  14. import {
  15. getLocalParticipant,
  16. getParticipantById,
  17. getPinnedParticipant,
  18. PARTICIPANT_ROLE,
  19. PARTICIPANT_UPDATED,
  20. PIN_PARTICIPANT
  21. } from '../participants';
  22. import { MiddlewareRegistry, StateListenerRegistry } from '../redux';
  23. import { TRACK_ADDED, TRACK_REMOVED } from '../tracks';
  24. import {
  25. CONFERENCE_FAILED,
  26. CONFERENCE_JOINED,
  27. CONFERENCE_SUBJECT_CHANGED,
  28. CONFERENCE_WILL_LEAVE,
  29. DATA_CHANNEL_OPENED,
  30. SEND_TONES,
  31. SET_PENDING_SUBJECT_CHANGE,
  32. SET_ROOM
  33. } from './actionTypes';
  34. import {
  35. conferenceFailed,
  36. conferenceWillLeave,
  37. createConference,
  38. setSubject
  39. } from './actions';
  40. import {
  41. _addLocalTracksToConference,
  42. _removeLocalTracksFromConference,
  43. forEachConference,
  44. getCurrentConference
  45. } from './functions';
  46. import logger from './logger';
  47. declare var APP: Object;
  48. /**
  49. * Handler for before unload event.
  50. */
  51. let beforeUnloadHandler;
  52. /**
  53. * Implements the middleware of the feature base/conference.
  54. *
  55. * @param {Store} store - The redux store.
  56. * @returns {Function}
  57. */
  58. MiddlewareRegistry.register(store => next => action => {
  59. switch (action.type) {
  60. case CONFERENCE_FAILED:
  61. return _conferenceFailed(store, next, action);
  62. case CONFERENCE_JOINED:
  63. return _conferenceJoined(store, next, action);
  64. case CONNECTION_ESTABLISHED:
  65. return _connectionEstablished(store, next, action);
  66. case CONNECTION_FAILED:
  67. return _connectionFailed(store, next, action);
  68. case CONFERENCE_SUBJECT_CHANGED:
  69. return _conferenceSubjectChanged(store, next, action);
  70. case CONFERENCE_WILL_LEAVE:
  71. _conferenceWillLeave();
  72. break;
  73. case DATA_CHANNEL_OPENED:
  74. return _syncReceiveVideoQuality(store, next, action);
  75. case PARTICIPANT_UPDATED:
  76. return _updateLocalParticipantInConference(store, next, action);
  77. case PIN_PARTICIPANT:
  78. return _pinParticipant(store, next, action);
  79. case SEND_TONES:
  80. return _sendTones(store, next, action);
  81. case SET_ROOM:
  82. return _setRoom(store, next, action);
  83. case TRACK_ADDED:
  84. case TRACK_REMOVED:
  85. return _trackAddedOrRemoved(store, next, action);
  86. }
  87. return next(action);
  88. });
  89. /**
  90. * Registers a change handler for state['features/base/conference'] to update
  91. * the preferred video quality levels based on user preferred and internal
  92. * settings.
  93. */
  94. StateListenerRegistry.register(
  95. /* selector */ state => state['features/base/conference'],
  96. /* listener */ (currentState, store, previousState = {}) => {
  97. const {
  98. conference,
  99. maxReceiverVideoQuality,
  100. preferredVideoQuality
  101. } = currentState;
  102. const changedConference = conference !== previousState.conference;
  103. const changedPreferredVideoQuality
  104. = preferredVideoQuality !== previousState.preferredVideoQuality;
  105. const changedMaxVideoQuality = maxReceiverVideoQuality !== previousState.maxReceiverVideoQuality;
  106. if (changedConference || changedPreferredVideoQuality || changedMaxVideoQuality) {
  107. _setReceiverVideoConstraint(conference, preferredVideoQuality, maxReceiverVideoQuality);
  108. }
  109. if (changedConference || changedPreferredVideoQuality) {
  110. _setSenderVideoConstraint(conference, preferredVideoQuality);
  111. }
  112. });
  113. /**
  114. * Makes sure to leave a failed conference in order to release any allocated
  115. * resources like peer connections, emit participant left events, etc.
  116. *
  117. * @param {Store} store - The redux store in which the specified {@code action}
  118. * is being dispatched.
  119. * @param {Dispatch} next - The redux {@code dispatch} function to dispatch the
  120. * specified {@code action} to the specified {@code store}.
  121. * @param {Action} action - The redux action {@code CONFERENCE_FAILED} which is
  122. * being dispatched in the specified {@code store}.
  123. * @private
  124. * @returns {Object} The value returned by {@code next(action)}.
  125. */
  126. function _conferenceFailed({ dispatch, getState }, next, action) {
  127. const result = next(action);
  128. const { conference, error } = action;
  129. // Handle specific failure reasons.
  130. switch (error.name) {
  131. case JitsiConferenceErrors.CONFERENCE_DESTROYED: {
  132. const [ reason ] = error.params;
  133. dispatch(showErrorNotification({
  134. description: reason,
  135. titleKey: 'dialog.sessTerminated'
  136. }));
  137. if (typeof APP !== 'undefined') {
  138. APP.UI.hideStats();
  139. }
  140. break;
  141. }
  142. case JitsiConferenceErrors.CONNECTION_ERROR: {
  143. const [ msg ] = error.params;
  144. dispatch(connectionDisconnected(getState()['features/base/connection'].connection));
  145. dispatch(showErrorNotification({
  146. descriptionArguments: { msg },
  147. descriptionKey: msg ? 'dialog.connectErrorWithMsg' : 'dialog.connectError',
  148. titleKey: 'connection.CONNFAIL'
  149. }));
  150. break;
  151. }
  152. case JitsiConferenceErrors.OFFER_ANSWER_FAILED:
  153. sendAnalytics(createOfferAnswerFailedEvent());
  154. break;
  155. }
  156. // FIXME: Workaround for the web version. Currently, the creation of the
  157. // conference is handled by /conference.js and appropriate failure handlers
  158. // are set there.
  159. if (typeof APP !== 'undefined') {
  160. if (typeof beforeUnloadHandler !== 'undefined') {
  161. window.removeEventListener('beforeunload', beforeUnloadHandler);
  162. beforeUnloadHandler = undefined;
  163. }
  164. return result;
  165. }
  166. // XXX After next(action), it is clear whether the error is recoverable.
  167. !error.recoverable
  168. && conference
  169. && conference.leave().catch(reason => {
  170. // Even though we don't care too much about the failure, it may be
  171. // good to know that it happen, so log it (on the info level).
  172. logger.info('JitsiConference.leave() rejected with:', reason);
  173. });
  174. return result;
  175. }
  176. /**
  177. * Does extra sync up on properties that may need to be updated after the
  178. * conference was joined.
  179. *
  180. * @param {Store} store - The redux store in which the specified {@code action}
  181. * is being dispatched.
  182. * @param {Dispatch} next - The redux {@code dispatch} function to dispatch the
  183. * specified {@code action} to the specified {@code store}.
  184. * @param {Action} action - The redux action {@code CONFERENCE_JOINED} which is
  185. * being dispatched in the specified {@code store}.
  186. * @private
  187. * @returns {Object} The value returned by {@code next(action)}.
  188. */
  189. function _conferenceJoined({ dispatch, getState }, next, action) {
  190. const result = next(action);
  191. const { conference } = action;
  192. const { pendingSubjectChange } = getState()['features/base/conference'];
  193. const { requireDisplayName } = getState()['features/base/config'];
  194. pendingSubjectChange && dispatch(setSubject(pendingSubjectChange));
  195. // FIXME: Very dirty solution. This will work on web only.
  196. // When the user closes the window or quits the browser, lib-jitsi-meet
  197. // handles the process of leaving the conference. This is temporary solution
  198. // that should cover the described use case as part of the effort to
  199. // implement the conferenceWillLeave action for web.
  200. beforeUnloadHandler = () => {
  201. dispatch(conferenceWillLeave(conference));
  202. };
  203. window.addEventListener('beforeunload', beforeUnloadHandler);
  204. if (requireDisplayName
  205. && !getLocalParticipant(getState)?.name
  206. && !conference.isHidden()) {
  207. dispatch(openDisplayNamePrompt(undefined));
  208. }
  209. return result;
  210. }
  211. /**
  212. * Notifies the feature base/conference that the action
  213. * {@code CONNECTION_ESTABLISHED} is being dispatched within a specific redux
  214. * store.
  215. *
  216. * @param {Store} store - The redux store in which the specified {@code action}
  217. * is being dispatched.
  218. * @param {Dispatch} next - The redux {@code dispatch} function to dispatch the
  219. * specified {@code action} to the specified {@code store}.
  220. * @param {Action} action - The redux action {@code CONNECTION_ESTABLISHED}
  221. * which is being dispatched in the specified {@code store}.
  222. * @private
  223. * @returns {Object} The value returned by {@code next(action)}.
  224. */
  225. function _connectionEstablished({ dispatch }, next, action) {
  226. const result = next(action);
  227. // FIXME: Workaround for the web version. Currently, the creation of the
  228. // conference is handled by /conference.js.
  229. typeof APP === 'undefined' && dispatch(createConference());
  230. return result;
  231. }
  232. /**
  233. * Notifies the feature base/conference that the action
  234. * {@code CONNECTION_FAILED} is being dispatched within a specific redux
  235. * store.
  236. *
  237. * @param {Store} store - The redux store in which the specified {@code action}
  238. * is being dispatched.
  239. * @param {Dispatch} next - The redux {@code dispatch} function to dispatch the
  240. * specified {@code action} to the specified {@code store}.
  241. * @param {Action} action - The redux action {@code CONNECTION_FAILED} which is
  242. * being dispatched in the specified {@code store}.
  243. * @private
  244. * @returns {Object} The value returned by {@code next(action)}.
  245. */
  246. function _connectionFailed({ dispatch, getState }, next, action) {
  247. const result = next(action);
  248. if (typeof beforeUnloadHandler !== 'undefined') {
  249. window.removeEventListener('beforeunload', beforeUnloadHandler);
  250. beforeUnloadHandler = undefined;
  251. }
  252. // FIXME: Workaround for the web version. Currently, the creation of the
  253. // conference is handled by /conference.js and appropriate failure handlers
  254. // are set there.
  255. if (typeof APP === 'undefined') {
  256. const { connection } = action;
  257. const { error } = action;
  258. forEachConference(getState, conference => {
  259. // It feels that it would make things easier if JitsiConference
  260. // in lib-jitsi-meet would monitor it's connection and emit
  261. // CONFERENCE_FAILED when it's dropped. It has more knowledge on
  262. // whether it can recover or not. But because the reload screen
  263. // and the retry logic is implemented in the app maybe it can be
  264. // left this way for now.
  265. if (conference.getConnection() === connection) {
  266. // XXX Note that on mobile the error type passed to
  267. // connectionFailed is always an object with .name property.
  268. // This fact needs to be checked prior to enabling this logic on
  269. // web.
  270. const conferenceAction
  271. = conferenceFailed(conference, error.name);
  272. // Copy the recoverable flag if set on the CONNECTION_FAILED
  273. // action to not emit recoverable action caused by
  274. // a non-recoverable one.
  275. if (typeof error.recoverable !== 'undefined') {
  276. conferenceAction.error.recoverable = error.recoverable;
  277. }
  278. dispatch(conferenceAction);
  279. }
  280. return true;
  281. });
  282. }
  283. return result;
  284. }
  285. /**
  286. * Notifies the feature base/conference that the action
  287. * {@code CONFERENCE_SUBJECT_CHANGED} is being dispatched within a specific
  288. * redux store.
  289. *
  290. * @param {Store} store - The redux store in which the specified {@code action}
  291. * is being dispatched.
  292. * @param {Dispatch} next - The redux {@code dispatch} function to dispatch the
  293. * specified {@code action} to the specified {@code store}.
  294. * @param {Action} action - The redux action {@code CONFERENCE_SUBJECT_CHANGED}
  295. * which is being dispatched in the specified {@code store}.
  296. * @private
  297. * @returns {Object} The value returned by {@code next(action)}.
  298. */
  299. function _conferenceSubjectChanged({ dispatch, getState }, next, action) {
  300. const result = next(action);
  301. const { subject } = getState()['features/base/conference'];
  302. if (subject) {
  303. dispatch({
  304. type: SET_PENDING_SUBJECT_CHANGE,
  305. subject: undefined
  306. });
  307. }
  308. typeof APP === 'object' && APP.API.notifySubjectChanged(subject);
  309. return result;
  310. }
  311. /**
  312. * Notifies the feature base/conference that the action
  313. * {@code CONFERENCE_WILL_LEAVE} is being dispatched within a specific redux
  314. * store.
  315. *
  316. * @private
  317. * @returns {void}
  318. */
  319. function _conferenceWillLeave() {
  320. if (typeof beforeUnloadHandler !== 'undefined') {
  321. window.removeEventListener('beforeunload', beforeUnloadHandler);
  322. beforeUnloadHandler = undefined;
  323. }
  324. }
  325. /**
  326. * Notifies the feature base/conference that the action {@code PIN_PARTICIPANT}
  327. * is being dispatched within a specific redux store. Pins the specified remote
  328. * participant in the associated conference, ignores the local participant.
  329. *
  330. * @param {Store} store - The redux store in which the specified {@code action}
  331. * is being dispatched.
  332. * @param {Dispatch} next - The redux {@code dispatch} function to dispatch the
  333. * specified {@code action} to the specified {@code store}.
  334. * @param {Action} action - The redux action {@code PIN_PARTICIPANT} which is
  335. * being dispatched in the specified {@code store}.
  336. * @private
  337. * @returns {Object} The value returned by {@code next(action)}.
  338. */
  339. function _pinParticipant({ getState }, next, action) {
  340. const state = getState();
  341. const { conference } = state['features/base/conference'];
  342. if (!conference) {
  343. return next(action);
  344. }
  345. const participants = state['features/base/participants'];
  346. const id = action.participant.id;
  347. const participantById = getParticipantById(participants, id);
  348. const pinnedParticipant = getPinnedParticipant(participants);
  349. const actionName = id ? ACTION_PINNED : ACTION_UNPINNED;
  350. const local
  351. = (participantById && participantById.local)
  352. || (!id && pinnedParticipant && pinnedParticipant.local);
  353. let participantIdForEvent;
  354. if (local) {
  355. participantIdForEvent = local;
  356. } else {
  357. participantIdForEvent
  358. = actionName === ACTION_PINNED ? id : pinnedParticipant && pinnedParticipant.id;
  359. }
  360. sendAnalytics(createPinnedEvent(
  361. actionName,
  362. participantIdForEvent,
  363. {
  364. local,
  365. 'participant_count': conference.getParticipantCount()
  366. }));
  367. return next(action);
  368. }
  369. /**
  370. * Requests the specified tones to be played.
  371. *
  372. * @param {Store} store - The redux store in which the specified {@code action}
  373. * is being dispatched.
  374. * @param {Dispatch} next - The redux {@code dispatch} function to dispatch the
  375. * specified {@code action} to the specified {@code store}.
  376. * @param {Action} action - The redux action {@code SEND_TONES} which is
  377. * being dispatched in the specified {@code store}.
  378. * @private
  379. * @returns {Object} The value returned by {@code next(action)}.
  380. */
  381. function _sendTones({ getState }, next, action) {
  382. const state = getState();
  383. const { conference } = state['features/base/conference'];
  384. if (conference) {
  385. const { duration, tones, pause } = action;
  386. conference.sendTones(tones, duration, pause);
  387. }
  388. return next(action);
  389. }
  390. /**
  391. * Helper function for updating the preferred receiver video constraint, based
  392. * on the user preference and the internal maximum.
  393. *
  394. * @param {JitsiConference} conference - The JitsiConference instance for the
  395. * current call.
  396. * @param {number} preferred - The user preferred max frame height.
  397. * @param {number} max - The maximum frame height the application should
  398. * receive.
  399. * @returns {void}
  400. */
  401. function _setReceiverVideoConstraint(conference, preferred, max) {
  402. if (conference) {
  403. const value = Math.min(preferred, max);
  404. conference.setReceiverVideoConstraint(value);
  405. logger.info(`setReceiverVideoConstraint: ${value}`);
  406. }
  407. }
  408. /**
  409. * Helper function for updating the preferred sender video constraint, based
  410. * on the user preference.
  411. *
  412. * @param {JitsiConference} conference - The JitsiConference instance for the
  413. * current call.
  414. * @param {number} preferred - The user preferred max frame height.
  415. * @returns {void}
  416. */
  417. function _setSenderVideoConstraint(conference, preferred) {
  418. if (conference) {
  419. conference.setSenderVideoConstraint(preferred)
  420. .catch(err => {
  421. logger.error(`Changing sender resolution to ${preferred} failed - ${err} `);
  422. });
  423. }
  424. }
  425. /**
  426. * Notifies the feature base/conference that the action
  427. * {@code SET_ROOM} is being dispatched within a specific
  428. * redux store.
  429. *
  430. * @param {Store} store - The redux store in which the specified {@code action}
  431. * is being dispatched.
  432. * @param {Dispatch} next - The redux {@code dispatch} function to dispatch the
  433. * specified {@code action} to the specified {@code store}.
  434. * @param {Action} action - The redux action {@code SET_ROOM}
  435. * which is being dispatched in the specified {@code store}.
  436. * @private
  437. * @returns {Object} The value returned by {@code next(action)}.
  438. */
  439. function _setRoom({ dispatch, getState }, next, action) {
  440. const state = getState();
  441. const { subject } = state['features/base/config'];
  442. const { room } = action;
  443. if (room) {
  444. // Set the stored subject.
  445. dispatch(setSubject(subject));
  446. }
  447. return next(action);
  448. }
  449. /**
  450. * Synchronizes local tracks from state with local tracks in JitsiConference
  451. * instance.
  452. *
  453. * @param {Store} store - The redux store.
  454. * @param {Object} action - Action object.
  455. * @private
  456. * @returns {Promise}
  457. */
  458. function _syncConferenceLocalTracksWithState({ getState }, action) {
  459. const conference = getCurrentConference(getState);
  460. let promise;
  461. if (conference) {
  462. const track = action.track.jitsiTrack;
  463. if (action.type === TRACK_ADDED) {
  464. promise = _addLocalTracksToConference(conference, [ track ]);
  465. } else {
  466. promise = _removeLocalTracksFromConference(conference, [ track ]);
  467. }
  468. }
  469. return promise || Promise.resolve();
  470. }
  471. /**
  472. * Sets the maximum receive video quality.
  473. *
  474. * @param {Store} store - The redux store in which the specified {@code action}
  475. * is being dispatched.
  476. * @param {Dispatch} next - The redux {@code dispatch} function to dispatch the
  477. * specified {@code action} to the specified {@code store}.
  478. * @param {Action} action - The redux action {@code DATA_CHANNEL_STATUS_CHANGED}
  479. * which is being dispatched in the specified {@code store}.
  480. * @private
  481. * @returns {Object} The value returned by {@code next(action)}.
  482. */
  483. function _syncReceiveVideoQuality({ getState }, next, action) {
  484. const {
  485. conference,
  486. maxReceiverVideoQuality,
  487. preferredVideoQuality
  488. } = getState()['features/base/conference'];
  489. _setReceiverVideoConstraint(
  490. conference,
  491. preferredVideoQuality,
  492. maxReceiverVideoQuality);
  493. return next(action);
  494. }
  495. /**
  496. * Notifies the feature base/conference that the action {@code TRACK_ADDED}
  497. * or {@code TRACK_REMOVED} is being dispatched within a specific redux store.
  498. *
  499. * @param {Store} store - The redux store in which the specified {@code action}
  500. * is being dispatched.
  501. * @param {Dispatch} next - The redux {@code dispatch} function to dispatch the
  502. * specified {@code action} to the specified {@code store}.
  503. * @param {Action} action - The redux action {@code TRACK_ADDED} or
  504. * {@code TRACK_REMOVED} which is being dispatched in the specified
  505. * {@code store}.
  506. * @private
  507. * @returns {Object} The value returned by {@code next(action)}.
  508. */
  509. function _trackAddedOrRemoved(store, next, action) {
  510. const track = action.track;
  511. // TODO All track swapping should happen here instead of conference.js.
  512. // Since we swap the tracks for the web client in conference.js, ignore
  513. // presenter tracks here and do not add/remove them to/from the conference.
  514. if (track && track.local && track.mediaType !== MEDIA_TYPE.PRESENTER) {
  515. return (
  516. _syncConferenceLocalTracksWithState(store, action)
  517. .then(() => next(action)));
  518. }
  519. return next(action);
  520. }
  521. /**
  522. * Updates the conference object when the local participant is updated.
  523. *
  524. * @param {Store} store - The redux store in which the specified {@code action}
  525. * is being dispatched.
  526. * @param {Dispatch} next - The redux {@code dispatch} function to dispatch the
  527. * specified {@code action} to the specified {@code store}.
  528. * @param {Action} action - The redux action which is being dispatched in the
  529. * specified {@code store}.
  530. * @private
  531. * @returns {Object} The value returned by {@code next(action)}.
  532. */
  533. function _updateLocalParticipantInConference({ dispatch, getState }, next, action) {
  534. const { conference } = getState()['features/base/conference'];
  535. const { participant } = action;
  536. const result = next(action);
  537. const localParticipant = getLocalParticipant(getState);
  538. if (conference && participant.id === localParticipant.id) {
  539. if ('name' in participant) {
  540. conference.setDisplayName(participant.name);
  541. }
  542. if ('role' in participant && participant.role === PARTICIPANT_ROLE.MODERATOR) {
  543. const { pendingSubjectChange, subject } = getState()['features/base/conference'];
  544. // When the local user role is updated to moderator and we have a pending subject change
  545. // which was not reflected we need to set it (the first time we tried was before becoming moderator).
  546. if (pendingSubjectChange !== subject) {
  547. dispatch(setSubject(pendingSubjectChange));
  548. }
  549. }
  550. }
  551. return result;
  552. }