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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. // @flow
  2. import { reloadNow } from '../../app';
  3. import {
  4. ACTION_PINNED,
  5. ACTION_UNPINNED,
  6. createAudioOnlyChangedEvent,
  7. createConnectionEvent,
  8. createPinnedEvent,
  9. sendAnalytics
  10. } from '../../analytics';
  11. import { CONNECTION_ESTABLISHED, CONNECTION_FAILED } from '../connection';
  12. import { setVideoMuted, VIDEO_MUTISM_AUTHORITY } from '../media';
  13. import {
  14. getLocalParticipant,
  15. getParticipantById,
  16. getPinnedParticipant,
  17. PIN_PARTICIPANT
  18. } from '../participants';
  19. import { MiddlewareRegistry, StateListenerRegistry } from '../redux';
  20. import UIEvents from '../../../../service/UI/UIEvents';
  21. import { TRACK_ADDED, TRACK_REMOVED } from '../tracks';
  22. import {
  23. conferenceFailed,
  24. conferenceLeft,
  25. createConference,
  26. setLastN
  27. } from './actions';
  28. import {
  29. CONFERENCE_FAILED,
  30. CONFERENCE_JOINED,
  31. DATA_CHANNEL_OPENED,
  32. SET_AUDIO_ONLY,
  33. SET_LASTN,
  34. SET_ROOM
  35. } from './actionTypes';
  36. import {
  37. _addLocalTracksToConference,
  38. forEachConference,
  39. _handleParticipantError,
  40. _removeLocalTracksFromConference
  41. } from './functions';
  42. const logger = require('jitsi-meet-logger').getLogger(__filename);
  43. declare var APP: Object;
  44. /**
  45. * Implements the middleware of the feature base/conference.
  46. *
  47. * @param {Store} store - The redux store.
  48. * @returns {Function}
  49. */
  50. MiddlewareRegistry.register(store => next => action => {
  51. switch (action.type) {
  52. case CONFERENCE_FAILED:
  53. return _conferenceFailed(store, next, action);
  54. case CONFERENCE_JOINED:
  55. return _conferenceJoined(store, next, action);
  56. case CONNECTION_ESTABLISHED:
  57. return _connectionEstablished(store, next, action);
  58. case CONNECTION_FAILED:
  59. return _connectionFailed(store, next, action);
  60. case DATA_CHANNEL_OPENED:
  61. return _syncReceiveVideoQuality(store, next, action);
  62. case PIN_PARTICIPANT:
  63. return _pinParticipant(store, next, action);
  64. case SET_AUDIO_ONLY:
  65. return _setAudioOnly(store, next, action);
  66. case SET_LASTN:
  67. return _setLastN(store, next, action);
  68. case SET_ROOM:
  69. return _setRoom(store, next, action);
  70. case TRACK_ADDED:
  71. case TRACK_REMOVED:
  72. return _trackAddedOrRemoved(store, next, action);
  73. }
  74. return next(action);
  75. });
  76. /**
  77. * Registers a change handler for state['features/base/conference'] to update
  78. * the preferred video quality levels based on user preferred and internal
  79. * settings.
  80. */
  81. StateListenerRegistry.register(
  82. /* selector */ state => state['features/base/conference'],
  83. /* listener */ (currentState, store, previousState = {}) => {
  84. const {
  85. conference,
  86. maxReceiverVideoQuality,
  87. preferredReceiverVideoQuality
  88. } = currentState;
  89. const changedPreferredVideoQuality = preferredReceiverVideoQuality
  90. !== previousState.preferredReceiverVideoQuality;
  91. const changedMaxVideoQuality = maxReceiverVideoQuality
  92. !== previousState.maxReceiverVideoQuality;
  93. if (changedPreferredVideoQuality || changedMaxVideoQuality) {
  94. _setReceiverVideoConstraint(
  95. conference,
  96. preferredReceiverVideoQuality,
  97. maxReceiverVideoQuality);
  98. }
  99. });
  100. /**
  101. * Makes sure to leave a failed conference in order to release any allocated
  102. * resources like peer connections, emit participant left events, etc.
  103. *
  104. * @param {Store} store - The redux store in which the specified {@code action}
  105. * is being dispatched.
  106. * @param {Dispatch} next - The redux {@code dispatch} function to dispatch the
  107. * specified {@code action} to the specified {@code store}.
  108. * @param {Action} action - The redux action {@code CONFERENCE_FAILED} which is
  109. * being dispatched in the specified {@code store}.
  110. * @private
  111. * @returns {Object} The value returned by {@code next(action)}.
  112. */
  113. function _conferenceFailed(store, next, action) {
  114. const result = next(action);
  115. // FIXME: Workaround for the web version. Currently, the creation of the
  116. // conference is handled by /conference.js and appropriate failure handlers
  117. // are set there.
  118. if (typeof APP !== 'undefined') {
  119. return result;
  120. }
  121. // XXX After next(action), it is clear whether the error is recoverable.
  122. const { conference, error } = action;
  123. !error.recoverable
  124. && conference
  125. && conference.leave().catch(reason => {
  126. // Even though we don't care too much about the failure, it may be
  127. // good to know that it happen, so log it (on the info level).
  128. logger.info('JitsiConference.leave() rejected with:', reason);
  129. });
  130. return result;
  131. }
  132. /**
  133. * Does extra sync up on properties that may need to be updated after the
  134. * conference was joined.
  135. *
  136. * @param {Store} store - The redux store in which the specified {@code action}
  137. * is being dispatched.
  138. * @param {Dispatch} next - The redux {@code dispatch} function to dispatch the
  139. * specified {@code action} to the specified {@code store}.
  140. * @param {Action} action - The redux action {@code CONFERENCE_JOINED} which is
  141. * being dispatched in the specified {@code store}.
  142. * @private
  143. * @returns {Object} The value returned by {@code next(action)}.
  144. */
  145. function _conferenceJoined({ dispatch, getState }, next, action) {
  146. const result = next(action);
  147. const { audioOnly, conference } = getState()['features/base/conference'];
  148. // FIXME On Web the audio only mode for "start audio only" is toggled before
  149. // conference is added to the redux store ("on conference joined" action)
  150. // and the LastN value needs to be synchronized here.
  151. audioOnly && conference.getLastN() !== 0 && dispatch(setLastN(0));
  152. return result;
  153. }
  154. /**
  155. * Notifies the feature base/conference that the action
  156. * {@code CONNECTION_ESTABLISHED} is being dispatched within a specific redux
  157. * store.
  158. *
  159. * @param {Store} store - The redux store in which the specified {@code action}
  160. * is being dispatched.
  161. * @param {Dispatch} next - The redux {@code dispatch} function to dispatch the
  162. * specified {@code action} to the specified {@code store}.
  163. * @param {Action} action - The redux action {@code CONNECTION_ESTABLISHED}
  164. * which is being dispatched in the specified {@code store}.
  165. * @private
  166. * @returns {Object} The value returned by {@code next(action)}.
  167. */
  168. function _connectionEstablished({ dispatch }, next, action) {
  169. const result = next(action);
  170. // FIXME: Workaround for the web version. Currently, the creation of the
  171. // conference is handled by /conference.js.
  172. typeof APP === 'undefined' && dispatch(createConference());
  173. return result;
  174. }
  175. /**
  176. * Notifies the feature base/conference that the action
  177. * {@code CONNECTION_FAILED} is being dispatched within a specific redux
  178. * store.
  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 CONNECTION_FAILED} 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 _connectionFailed({ dispatch, getState }, next, action) {
  190. // In the case of a split-brain error, reload early and prevent further
  191. // handling of the action.
  192. if (_isMaybeSplitBrainError(getState, action)) {
  193. dispatch(reloadNow());
  194. return;
  195. }
  196. const result = next(action);
  197. // FIXME: Workaround for the web version. Currently, the creation of the
  198. // conference is handled by /conference.js and appropriate failure handlers
  199. // are set there.
  200. if (typeof APP === 'undefined') {
  201. const { connection } = action;
  202. const { error } = action;
  203. forEachConference(getState, conference => {
  204. // It feels that it would make things easier if JitsiConference
  205. // in lib-jitsi-meet would monitor it's connection and emit
  206. // CONFERENCE_FAILED when it's dropped. It has more knowledge on
  207. // whether it can recover or not. But because the reload screen
  208. // and the retry logic is implemented in the app maybe it can be
  209. // left this way for now.
  210. if (conference.getConnection() === connection) {
  211. // XXX Note that on mobile the error type passed to
  212. // connectionFailed is always an object with .name property.
  213. // This fact needs to be checked prior to enabling this logic on
  214. // web.
  215. const conferenceAction
  216. = conferenceFailed(conference, error.name);
  217. // Copy the recoverable flag if set on the CONNECTION_FAILED
  218. // action to not emit recoverable action caused by
  219. // a non-recoverable one.
  220. if (typeof error.recoverable !== 'undefined') {
  221. conferenceAction.error.recoverable = error.recoverable;
  222. }
  223. dispatch(conferenceAction);
  224. }
  225. return true;
  226. });
  227. }
  228. return result;
  229. }
  230. /**
  231. * Returns whether or not a CONNECTION_FAILED action is for a possible split
  232. * brain error. A split brain error occurs when at least two users join a
  233. * conference on different bridges. It is assumed the split brain scenario
  234. * occurs very early on in the call.
  235. *
  236. * @param {Function} getState - The redux function for fetching the current
  237. * state.
  238. * @param {Action} action - The redux action {@code CONNECTION_FAILED} which is
  239. * being dispatched in the specified {@code store}.
  240. * @private
  241. * @returns {boolean}
  242. */
  243. function _isMaybeSplitBrainError(getState, action) {
  244. const { error } = action;
  245. const isShardChangedError = error
  246. && error.message === 'item-not-found'
  247. && error.details
  248. && error.details.shard_changed;
  249. if (isShardChangedError) {
  250. const state = getState();
  251. const { timeEstablished } = state['features/base/connection'];
  252. const { _immediateReloadThreshold } = state['features/base/config'];
  253. const timeSinceConnectionEstablished
  254. = timeEstablished && Date.now() - timeEstablished;
  255. const reloadThreshold = typeof _immediateReloadThreshold === 'number'
  256. ? _immediateReloadThreshold : 1500;
  257. const isWithinSplitBrainThreshold = !timeEstablished
  258. || timeSinceConnectionEstablished <= reloadThreshold;
  259. sendAnalytics(createConnectionEvent('failed', {
  260. ...error,
  261. connectionEstablished: timeEstablished,
  262. splitBrain: isWithinSplitBrainThreshold,
  263. timeSinceConnectionEstablished
  264. }));
  265. return isWithinSplitBrainThreshold;
  266. }
  267. return false;
  268. }
  269. /**
  270. * Notifies the feature base/conference that the action {@code PIN_PARTICIPANT}
  271. * is being dispatched within a specific redux store. Pins the specified remote
  272. * participant in the associated conference, ignores the local participant.
  273. *
  274. * @param {Store} store - The redux store in which the specified {@code action}
  275. * is being dispatched.
  276. * @param {Dispatch} next - The redux {@code dispatch} function to dispatch the
  277. * specified {@code action} to the specified {@code store}.
  278. * @param {Action} action - The redux action {@code PIN_PARTICIPANT} which is
  279. * being dispatched in the specified {@code store}.
  280. * @private
  281. * @returns {Object} The value returned by {@code next(action)}.
  282. */
  283. function _pinParticipant({ getState }, next, action) {
  284. const state = getState();
  285. const { conference } = state['features/base/conference'];
  286. if (!conference) {
  287. return next(action);
  288. }
  289. const participants = state['features/base/participants'];
  290. const id = action.participant.id;
  291. const participantById = getParticipantById(participants, id);
  292. if (typeof APP !== 'undefined') {
  293. const pinnedParticipant = getPinnedParticipant(participants);
  294. const actionName = id ? ACTION_PINNED : ACTION_UNPINNED;
  295. const local
  296. = (participantById && participantById.local)
  297. || (!id && pinnedParticipant && pinnedParticipant.local);
  298. sendAnalytics(createPinnedEvent(
  299. actionName,
  300. local ? 'local' : id,
  301. {
  302. local,
  303. 'participant_count': conference.getParticipantCount()
  304. }));
  305. }
  306. // The following condition prevents signaling to pin local participant and
  307. // shared videos. The logic is:
  308. // - If we have an ID, we check if the participant identified by that ID is
  309. // local or a bot/fake participant (such as with shared video).
  310. // - If we don't have an ID (i.e. no participant identified by an ID), we
  311. // check for local participant. If she's currently pinned, then this
  312. // action will unpin her and that's why we won't signal here too.
  313. let pin;
  314. if (participantById) {
  315. pin = !participantById.local && !participantById.isFakeParticipant;
  316. } else {
  317. const localParticipant = getLocalParticipant(participants);
  318. pin = !localParticipant || !localParticipant.pinned;
  319. }
  320. if (pin) {
  321. try {
  322. conference.pinParticipant(id);
  323. } catch (err) {
  324. _handleParticipantError(err);
  325. }
  326. }
  327. return next(action);
  328. }
  329. /**
  330. * Sets the audio-only flag for the current conference. When audio-only is set,
  331. * local video is muted and last N is set to 0 to avoid receiving remote video.
  332. *
  333. * @param {Store} store - The redux store in which the specified {@code action}
  334. * is being dispatched.
  335. * @param {Dispatch} next - The redux {@code dispatch} function to dispatch the
  336. * specified {@code action} to the specified {@code store}.
  337. * @param {Action} action - The redux action {@code SET_AUDIO_ONLY} which is
  338. * being dispatched in the specified {@code store}.
  339. * @private
  340. * @returns {Object} The value returned by {@code next(action)}.
  341. */
  342. function _setAudioOnly({ dispatch, getState }, next, action) {
  343. const { audioOnly: oldValue } = getState()['features/base/conference'];
  344. const result = next(action);
  345. const { audioOnly: newValue } = getState()['features/base/conference'];
  346. // Send analytics. We could've done it in the action creator setAudioOnly.
  347. // I don't know why it has to happen as early as possible but the analytics
  348. // were originally sent before the SET_AUDIO_ONLY action was even dispatched
  349. // in the redux store so I'm now sending the analytics as early as possible.
  350. if (oldValue !== newValue) {
  351. sendAnalytics(createAudioOnlyChangedEvent(newValue));
  352. logger.log(`Audio-only ${newValue ? 'enabled' : 'disabled'}`);
  353. }
  354. // Set lastN to 0 in case audio-only is desired; leave it as undefined,
  355. // otherwise, and the default lastN value will be chosen automatically.
  356. dispatch(setLastN(newValue ? 0 : undefined));
  357. // Mute/unmute the local video.
  358. dispatch(
  359. setVideoMuted(
  360. newValue,
  361. VIDEO_MUTISM_AUTHORITY.AUDIO_ONLY,
  362. action.ensureVideoTrack));
  363. if (typeof APP !== 'undefined') {
  364. // TODO This should be a temporary solution that lasts only until video
  365. // tracks and all ui is moved into react/redux on the web.
  366. APP.UI.emitEvent(UIEvents.TOGGLE_AUDIO_ONLY, newValue);
  367. }
  368. return result;
  369. }
  370. /**
  371. * Sets the last N (value) of the video channel in the conference.
  372. *
  373. * @param {Store} store - The redux store in which the specified {@code action}
  374. * is being dispatched.
  375. * @param {Dispatch} next - The redux {@code dispatch} function to dispatch the
  376. * specified {@code action} to the specified {@code store}.
  377. * @param {Action} action - The redux action {@code SET_LASTN} which is being
  378. * dispatched in the specified {@code store}.
  379. * @private
  380. * @returns {Object} The value returned by {@code next(action)}.
  381. */
  382. function _setLastN({ getState }, next, action) {
  383. const { conference } = getState()['features/base/conference'];
  384. if (conference) {
  385. try {
  386. conference.setLastN(action.lastN);
  387. } catch (err) {
  388. console.error(`Failed to set lastN: ${err}`);
  389. }
  390. }
  391. return next(action);
  392. }
  393. /**
  394. * Helper function for updating the preferred receiver video constraint, based
  395. * on the user preference and the internal maximum.
  396. *
  397. * @param {JitsiConference} conference - The JitsiConference instance for the
  398. * current call.
  399. * @param {number} preferred - The user preferred max frame height.
  400. * @param {number} max - The maximum frame height the application should
  401. * receive.
  402. * @returns {void}
  403. */
  404. function _setReceiverVideoConstraint(conference, preferred, max) {
  405. if (conference) {
  406. conference.setReceiverVideoConstraint(Math.min(preferred, max));
  407. }
  408. }
  409. /**
  410. * Notifies the feature {@code base/conference} that the redix action
  411. * {@link SET_ROOM} is being dispatched within a specific redux store.
  412. *
  413. * @param {Store} store - The redux store in which the specified {@code action}
  414. * is being dispatched.
  415. * @param {Dispatch} next - The redux {@code dispatch} function to dispatch the
  416. * specified {@code action} to the specified {@code store}.
  417. * @param {Action} action - The redux action {@code SET_ROOM} which is being
  418. * dispatched in the specified {@code store}.
  419. * @private
  420. * @returns {Object} The value returned by {@code next(action)}.
  421. */
  422. function _setRoom({ dispatch, getState }, next, action) {
  423. const result = next(action);
  424. // By the time SET_ROOM is dispatched, base/connection's locationURL and
  425. // base/conference's leaving should be the only conference-related sources
  426. // of truth.
  427. const state = getState();
  428. const { leaving } = state['features/base/conference'];
  429. const { locationURL } = state['features/base/connection'];
  430. const dispatchConferenceLeft = new Set();
  431. // Figure out which of the JitsiConferences referenced by base/conference
  432. // have not dispatched or are not likely to dispatch CONFERENCE_FAILED and
  433. // CONFERENCE_LEFT.
  434. forEachConference(state, (conference, url) => {
  435. if (conference !== leaving && url && url !== locationURL) {
  436. dispatchConferenceLeft.add(conference);
  437. }
  438. return true; // All JitsiConference instances are to be examined.
  439. });
  440. // Dispatch CONFERENCE_LEFT for the JitsiConferences referenced by
  441. // base/conference which have not dispatched or are not likely to dispatch
  442. // CONFERENCE_FAILED or CONFERENCE_LEFT.
  443. for (const conference of dispatchConferenceLeft) {
  444. dispatch(conferenceLeft(conference));
  445. }
  446. return result;
  447. }
  448. /**
  449. * Synchronizes local tracks from state with local tracks in JitsiConference
  450. * instance.
  451. *
  452. * @param {Store} store - The redux store.
  453. * @param {Object} action - Action object.
  454. * @private
  455. * @returns {Promise}
  456. */
  457. function _syncConferenceLocalTracksWithState({ getState }, action) {
  458. const state = getState()['features/base/conference'];
  459. const { conference } = state;
  460. let promise;
  461. // XXX The conference may already be in the process of being left, that's
  462. // why we should not add/remove local tracks to such conference.
  463. if (conference && conference !== state.leaving) {
  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. if (track && track.local) {
  514. return (
  515. _syncConferenceLocalTracksWithState(store, action)
  516. .then(() => next(action)));
  517. }
  518. return next(action);
  519. }