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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  1. // @flow
  2. import { reloadNow } from '../../app';
  3. import { openDisplayNamePrompt } from '../../display-name';
  4. import {
  5. ACTION_PINNED,
  6. ACTION_UNPINNED,
  7. createConnectionEvent,
  8. createOfferAnswerFailedEvent,
  9. createPinnedEvent,
  10. sendAnalytics
  11. } from '../../analytics';
  12. import { CONNECTION_ESTABLISHED, CONNECTION_FAILED } from '../connection';
  13. import { JitsiConferenceErrors } from '../lib-jitsi-meet';
  14. import {
  15. getLocalParticipant,
  16. getParticipantById,
  17. getPinnedParticipant,
  18. PARTICIPANT_UPDATED,
  19. PIN_PARTICIPANT
  20. } from '../participants';
  21. import { MiddlewareRegistry, StateListenerRegistry } from '../redux';
  22. import { TRACK_ADDED, TRACK_REMOVED } from '../tracks';
  23. import {
  24. conferenceFailed,
  25. conferenceWillLeave,
  26. createConference,
  27. setSubject
  28. } from './actions';
  29. import {
  30. CONFERENCE_FAILED,
  31. CONFERENCE_JOINED,
  32. CONFERENCE_SUBJECT_CHANGED,
  33. CONFERENCE_WILL_LEAVE,
  34. DATA_CHANNEL_OPENED,
  35. SET_PENDING_SUBJECT_CHANGE,
  36. SET_ROOM
  37. } from './actionTypes';
  38. import {
  39. _addLocalTracksToConference,
  40. _removeLocalTracksFromConference,
  41. forEachConference,
  42. getCurrentConference
  43. } from './functions';
  44. import logger from './logger';
  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_SUBJECT_CHANGED:
  67. return _conferenceSubjectChanged(store, next, action);
  68. case CONFERENCE_WILL_LEAVE:
  69. _conferenceWillLeave();
  70. break;
  71. case DATA_CHANNEL_OPENED:
  72. return _syncReceiveVideoQuality(store, next, action);
  73. case PARTICIPANT_UPDATED:
  74. return _updateLocalParticipantInConference(store, next, action);
  75. case PIN_PARTICIPANT:
  76. return _pinParticipant(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. const { conference, error } = action;
  125. if (error.name === JitsiConferenceErrors.OFFER_ANSWER_FAILED) {
  126. sendAnalytics(createOfferAnswerFailedEvent());
  127. }
  128. // FIXME: Workaround for the web version. Currently, the creation of the
  129. // conference is handled by /conference.js and appropriate failure handlers
  130. // are set there.
  131. if (typeof APP !== 'undefined') {
  132. if (typeof beforeUnloadHandler !== 'undefined') {
  133. window.removeEventListener('beforeunload', beforeUnloadHandler);
  134. beforeUnloadHandler = undefined;
  135. }
  136. return result;
  137. }
  138. // XXX After next(action), it is clear whether the error is recoverable.
  139. !error.recoverable
  140. && conference
  141. && conference.leave().catch(reason => {
  142. // Even though we don't care too much about the failure, it may be
  143. // good to know that it happen, so log it (on the info level).
  144. logger.info('JitsiConference.leave() rejected with:', reason);
  145. });
  146. return result;
  147. }
  148. /**
  149. * Does extra sync up on properties that may need to be updated after the
  150. * conference was joined.
  151. *
  152. * @param {Store} store - The redux store in which the specified {@code action}
  153. * is being dispatched.
  154. * @param {Dispatch} next - The redux {@code dispatch} function to dispatch the
  155. * specified {@code action} to the specified {@code store}.
  156. * @param {Action} action - The redux action {@code CONFERENCE_JOINED} which is
  157. * being dispatched in the specified {@code store}.
  158. * @private
  159. * @returns {Object} The value returned by {@code next(action)}.
  160. */
  161. function _conferenceJoined({ dispatch, getState }, next, action) {
  162. const result = next(action);
  163. const { conference } = action;
  164. const { pendingSubjectChange } = getState()['features/base/conference'];
  165. const { requireDisplayName } = getState()['features/base/config'];
  166. pendingSubjectChange && dispatch(setSubject(pendingSubjectChange));
  167. // FIXME: Very dirty solution. This will work on web only.
  168. // When the user closes the window or quits the browser, lib-jitsi-meet
  169. // handles the process of leaving the conference. This is temporary solution
  170. // that should cover the described use case as part of the effort to
  171. // implement the conferenceWillLeave action for web.
  172. beforeUnloadHandler = () => {
  173. dispatch(conferenceWillLeave(conference));
  174. };
  175. window.addEventListener('beforeunload', beforeUnloadHandler);
  176. if (requireDisplayName
  177. && !getLocalParticipant(getState)?.name
  178. && !conference.isHidden()) {
  179. dispatch(openDisplayNamePrompt(undefined));
  180. }
  181. return result;
  182. }
  183. /**
  184. * Notifies the feature base/conference that the action
  185. * {@code CONNECTION_ESTABLISHED} is being dispatched within a specific redux
  186. * store.
  187. *
  188. * @param {Store} store - The redux store in which the specified {@code action}
  189. * is being dispatched.
  190. * @param {Dispatch} next - The redux {@code dispatch} function to dispatch the
  191. * specified {@code action} to the specified {@code store}.
  192. * @param {Action} action - The redux action {@code CONNECTION_ESTABLISHED}
  193. * which is being dispatched in the specified {@code store}.
  194. * @private
  195. * @returns {Object} The value returned by {@code next(action)}.
  196. */
  197. function _connectionEstablished({ dispatch }, next, action) {
  198. const result = next(action);
  199. // FIXME: Workaround for the web version. Currently, the creation of the
  200. // conference is handled by /conference.js.
  201. typeof APP === 'undefined' && dispatch(createConference());
  202. return result;
  203. }
  204. /**
  205. * Notifies the feature base/conference that the action
  206. * {@code CONNECTION_FAILED} is being dispatched within a specific redux
  207. * store.
  208. *
  209. * @param {Store} store - The redux store in which the specified {@code action}
  210. * is being dispatched.
  211. * @param {Dispatch} next - The redux {@code dispatch} function to dispatch the
  212. * specified {@code action} to the specified {@code store}.
  213. * @param {Action} action - The redux action {@code CONNECTION_FAILED} which is
  214. * being dispatched in the specified {@code store}.
  215. * @private
  216. * @returns {Object} The value returned by {@code next(action)}.
  217. */
  218. function _connectionFailed({ dispatch, getState }, next, action) {
  219. // In the case of a split-brain error, reload early and prevent further
  220. // handling of the action.
  221. if (_isMaybeSplitBrainError(getState, action)) {
  222. dispatch(reloadNow());
  223. return;
  224. }
  225. const result = next(action);
  226. if (typeof beforeUnloadHandler !== 'undefined') {
  227. window.removeEventListener('beforeunload', beforeUnloadHandler);
  228. beforeUnloadHandler = undefined;
  229. }
  230. // FIXME: Workaround for the web version. Currently, the creation of the
  231. // conference is handled by /conference.js and appropriate failure handlers
  232. // are set there.
  233. if (typeof APP === 'undefined') {
  234. const { connection } = action;
  235. const { error } = action;
  236. forEachConference(getState, conference => {
  237. // It feels that it would make things easier if JitsiConference
  238. // in lib-jitsi-meet would monitor it's connection and emit
  239. // CONFERENCE_FAILED when it's dropped. It has more knowledge on
  240. // whether it can recover or not. But because the reload screen
  241. // and the retry logic is implemented in the app maybe it can be
  242. // left this way for now.
  243. if (conference.getConnection() === connection) {
  244. // XXX Note that on mobile the error type passed to
  245. // connectionFailed is always an object with .name property.
  246. // This fact needs to be checked prior to enabling this logic on
  247. // web.
  248. const conferenceAction
  249. = conferenceFailed(conference, error.name);
  250. // Copy the recoverable flag if set on the CONNECTION_FAILED
  251. // action to not emit recoverable action caused by
  252. // a non-recoverable one.
  253. if (typeof error.recoverable !== 'undefined') {
  254. conferenceAction.error.recoverable = error.recoverable;
  255. }
  256. dispatch(conferenceAction);
  257. }
  258. return true;
  259. });
  260. }
  261. return result;
  262. }
  263. /**
  264. * Notifies the feature base/conference that the action
  265. * {@code CONFERENCE_SUBJECT_CHANGED} is being dispatched within a specific
  266. * redux store.
  267. *
  268. * @param {Store} store - The redux store in which the specified {@code action}
  269. * is being dispatched.
  270. * @param {Dispatch} next - The redux {@code dispatch} function to dispatch the
  271. * specified {@code action} to the specified {@code store}.
  272. * @param {Action} action - The redux action {@code CONFERENCE_SUBJECT_CHANGED}
  273. * which is being dispatched in the specified {@code store}.
  274. * @private
  275. * @returns {Object} The value returned by {@code next(action)}.
  276. */
  277. function _conferenceSubjectChanged({ dispatch, getState }, next, action) {
  278. const result = next(action);
  279. const { subject } = getState()['features/base/conference'];
  280. if (subject) {
  281. dispatch({
  282. type: SET_PENDING_SUBJECT_CHANGE,
  283. subject: undefined
  284. });
  285. }
  286. typeof APP === 'object' && APP.API.notifySubjectChanged(subject);
  287. return result;
  288. }
  289. /**
  290. * Notifies the feature base/conference that the action
  291. * {@code CONFERENCE_WILL_LEAVE} is being dispatched within a specific redux
  292. * store.
  293. *
  294. * @private
  295. * @returns {void}
  296. */
  297. function _conferenceWillLeave() {
  298. if (typeof beforeUnloadHandler !== 'undefined') {
  299. window.removeEventListener('beforeunload', beforeUnloadHandler);
  300. beforeUnloadHandler = undefined;
  301. }
  302. }
  303. /**
  304. * Returns whether or not a CONNECTION_FAILED action is for a possible split
  305. * brain error. A split brain error occurs when at least two users join a
  306. * conference on different bridges. It is assumed the split brain scenario
  307. * occurs very early on in the call.
  308. *
  309. * @param {Function} getState - The redux function for fetching the current
  310. * state.
  311. * @param {Action} action - The redux action {@code CONNECTION_FAILED} which is
  312. * being dispatched in the specified {@code store}.
  313. * @private
  314. * @returns {boolean}
  315. */
  316. function _isMaybeSplitBrainError(getState, action) {
  317. const { error } = action;
  318. const isShardChangedError = error
  319. && error.message === 'item-not-found'
  320. && error.details
  321. && error.details.shard_changed;
  322. if (isShardChangedError) {
  323. const state = getState();
  324. const { timeEstablished } = state['features/base/connection'];
  325. const { _immediateReloadThreshold } = state['features/base/config'];
  326. const timeSinceConnectionEstablished
  327. = timeEstablished && Date.now() - timeEstablished;
  328. const reloadThreshold = typeof _immediateReloadThreshold === 'number'
  329. ? _immediateReloadThreshold : 1500;
  330. const isWithinSplitBrainThreshold = !timeEstablished
  331. || timeSinceConnectionEstablished <= reloadThreshold;
  332. sendAnalytics(createConnectionEvent('failed', {
  333. ...error,
  334. connectionEstablished: timeEstablished,
  335. splitBrain: isWithinSplitBrainThreshold,
  336. timeSinceConnectionEstablished
  337. }));
  338. return isWithinSplitBrainThreshold;
  339. }
  340. return false;
  341. }
  342. /**
  343. * Notifies the feature base/conference that the action {@code PIN_PARTICIPANT}
  344. * is being dispatched within a specific redux store. Pins the specified remote
  345. * participant in the associated conference, ignores the local participant.
  346. *
  347. * @param {Store} store - The redux store in which the specified {@code action}
  348. * is being dispatched.
  349. * @param {Dispatch} next - The redux {@code dispatch} function to dispatch the
  350. * specified {@code action} to the specified {@code store}.
  351. * @param {Action} action - The redux action {@code PIN_PARTICIPANT} which is
  352. * being dispatched in the specified {@code store}.
  353. * @private
  354. * @returns {Object} The value returned by {@code next(action)}.
  355. */
  356. function _pinParticipant({ getState }, next, action) {
  357. const state = getState();
  358. const { conference } = state['features/base/conference'];
  359. if (!conference) {
  360. return next(action);
  361. }
  362. const participants = state['features/base/participants'];
  363. const id = action.participant.id;
  364. const participantById = getParticipantById(participants, id);
  365. const pinnedParticipant = getPinnedParticipant(participants);
  366. const actionName = id ? ACTION_PINNED : ACTION_UNPINNED;
  367. const local
  368. = (participantById && participantById.local)
  369. || (!id && pinnedParticipant && pinnedParticipant.local);
  370. let participantIdForEvent;
  371. if (local) {
  372. participantIdForEvent = local;
  373. } else {
  374. participantIdForEvent
  375. = actionName === ACTION_PINNED ? id : pinnedParticipant && pinnedParticipant.id;
  376. }
  377. sendAnalytics(createPinnedEvent(
  378. actionName,
  379. participantIdForEvent,
  380. {
  381. local,
  382. 'participant_count': conference.getParticipantCount()
  383. }));
  384. return next(action);
  385. }
  386. /**
  387. * Helper function for updating the preferred receiver video constraint, based
  388. * on the user preference and the internal maximum.
  389. *
  390. * @param {JitsiConference} conference - The JitsiConference instance for the
  391. * current call.
  392. * @param {number} preferred - The user preferred max frame height.
  393. * @param {number} max - The maximum frame height the application should
  394. * receive.
  395. * @returns {void}
  396. */
  397. function _setReceiverVideoConstraint(conference, preferred, max) {
  398. if (conference) {
  399. conference.setReceiverVideoConstraint(Math.min(preferred, max));
  400. }
  401. }
  402. /**
  403. * Notifies the feature base/conference that the action
  404. * {@code SET_ROOM} is being dispatched within a specific
  405. * redux store.
  406. *
  407. * @param {Store} store - The redux store in which the specified {@code action}
  408. * is being dispatched.
  409. * @param {Dispatch} next - The redux {@code dispatch} function to dispatch the
  410. * specified {@code action} to the specified {@code store}.
  411. * @param {Action} action - The redux action {@code SET_ROOM}
  412. * which is being dispatched in the specified {@code store}.
  413. * @private
  414. * @returns {Object} The value returned by {@code next(action)}.
  415. */
  416. function _setRoom({ dispatch, getState }, next, action) {
  417. const state = getState();
  418. const { subject } = state['features/base/config'];
  419. const { room } = action;
  420. if (room) {
  421. // Set the stored subject.
  422. dispatch(setSubject(subject));
  423. }
  424. return next(action);
  425. }
  426. /**
  427. * Synchronizes local tracks from state with local tracks in JitsiConference
  428. * instance.
  429. *
  430. * @param {Store} store - The redux store.
  431. * @param {Object} action - Action object.
  432. * @private
  433. * @returns {Promise}
  434. */
  435. function _syncConferenceLocalTracksWithState({ getState }, action) {
  436. const conference = getCurrentConference(getState);
  437. let promise;
  438. if (conference) {
  439. const track = action.track.jitsiTrack;
  440. if (action.type === TRACK_ADDED) {
  441. promise = _addLocalTracksToConference(conference, [ track ]);
  442. } else {
  443. promise = _removeLocalTracksFromConference(conference, [ track ]);
  444. }
  445. }
  446. return promise || Promise.resolve();
  447. }
  448. /**
  449. * Sets the maximum receive video quality.
  450. *
  451. * @param {Store} store - The redux store in which the specified {@code action}
  452. * is being dispatched.
  453. * @param {Dispatch} next - The redux {@code dispatch} function to dispatch the
  454. * specified {@code action} to the specified {@code store}.
  455. * @param {Action} action - The redux action {@code DATA_CHANNEL_STATUS_CHANGED}
  456. * which is being dispatched in the specified {@code store}.
  457. * @private
  458. * @returns {Object} The value returned by {@code next(action)}.
  459. */
  460. function _syncReceiveVideoQuality({ getState }, next, action) {
  461. const {
  462. conference,
  463. maxReceiverVideoQuality,
  464. preferredReceiverVideoQuality
  465. } = getState()['features/base/conference'];
  466. _setReceiverVideoConstraint(
  467. conference,
  468. preferredReceiverVideoQuality,
  469. maxReceiverVideoQuality);
  470. return next(action);
  471. }
  472. /**
  473. * Notifies the feature base/conference that the action {@code TRACK_ADDED}
  474. * or {@code TRACK_REMOVED} is being dispatched within a specific redux store.
  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 TRACK_ADDED} or
  481. * {@code TRACK_REMOVED} which is being dispatched in the specified
  482. * {@code store}.
  483. * @private
  484. * @returns {Object} The value returned by {@code next(action)}.
  485. */
  486. function _trackAddedOrRemoved(store, next, action) {
  487. const track = action.track;
  488. if (track && track.local) {
  489. return (
  490. _syncConferenceLocalTracksWithState(store, action)
  491. .then(() => next(action)));
  492. }
  493. return next(action);
  494. }
  495. /**
  496. * Updates the conference object when the local participant is updated.
  497. *
  498. * @param {Store} store - The redux store in which the specified {@code action}
  499. * is being dispatched.
  500. * @param {Dispatch} next - The redux {@code dispatch} function to dispatch the
  501. * specified {@code action} to the specified {@code store}.
  502. * @param {Action} action - The redux action which is being dispatched in the
  503. * specified {@code store}.
  504. * @private
  505. * @returns {Object} The value returned by {@code next(action)}.
  506. */
  507. function _updateLocalParticipantInConference({ getState }, next, action) {
  508. const { conference } = getState()['features/base/conference'];
  509. const { participant } = action;
  510. const result = next(action);
  511. if (conference && participant.local && 'name' in participant) {
  512. conference.setDisplayName(participant.name);
  513. }
  514. return result;
  515. }