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

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