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

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