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

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