您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

middleware.js 22KB

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