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

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