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.any.js 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. // @flow
  2. import { readyToClose } from '../../../features/mobile/external-api/actions';
  3. import {
  4. ACTION_PINNED,
  5. ACTION_UNPINNED,
  6. createOfferAnswerFailedEvent,
  7. createPinnedEvent,
  8. sendAnalytics
  9. } from '../../analytics';
  10. import { reloadNow } from '../../app/actions';
  11. import { removeLobbyChatParticipant } from '../../chat/actions.any';
  12. import { openDisplayNamePrompt } from '../../display-name';
  13. import { NOTIFICATION_TIMEOUT_TYPE, showErrorNotification, showWarningNotification } from '../../notifications';
  14. import { CONNECTION_ESTABLISHED, CONNECTION_FAILED, connectionDisconnected } from '../connection';
  15. import { validateJwt } from '../jwt';
  16. import { JitsiConferenceErrors } from '../lib-jitsi-meet';
  17. import { MEDIA_TYPE } from '../media';
  18. import {
  19. getLocalParticipant,
  20. getParticipantById,
  21. getPinnedParticipant,
  22. PARTICIPANT_ROLE,
  23. PARTICIPANT_UPDATED,
  24. PIN_PARTICIPANT
  25. } from '../participants';
  26. import { MiddlewareRegistry } from '../redux';
  27. import { TRACK_ADDED, TRACK_REMOVED } from '../tracks';
  28. import {
  29. CONFERENCE_FAILED,
  30. CONFERENCE_JOINED,
  31. CONFERENCE_SUBJECT_CHANGED,
  32. CONFERENCE_WILL_LEAVE,
  33. SEND_TONES,
  34. SET_PENDING_SUBJECT_CHANGE,
  35. SET_ROOM
  36. } from './actionTypes';
  37. import {
  38. conferenceFailed,
  39. conferenceWillLeave,
  40. createConference,
  41. setLocalSubject,
  42. setSubject
  43. } from './actions';
  44. import { CONFERENCE_LEAVE_REASONS, TRIGGER_READY_TO_CLOSE_REASONS } from './constants';
  45. import {
  46. _addLocalTracksToConference,
  47. _removeLocalTracksFromConference,
  48. forEachConference,
  49. getCurrentConference
  50. } from './functions';
  51. import logger from './logger';
  52. declare var APP: Object;
  53. /**
  54. * Handler for before unload event.
  55. */
  56. let beforeUnloadHandler;
  57. /**
  58. * Implements the middleware of the feature base/conference.
  59. *
  60. * @param {Store} store - The redux store.
  61. * @returns {Function}
  62. */
  63. MiddlewareRegistry.register(store => next => action => {
  64. switch (action.type) {
  65. case CONFERENCE_FAILED:
  66. return _conferenceFailed(store, next, action);
  67. case CONFERENCE_JOINED:
  68. return _conferenceJoined(store, next, action);
  69. case CONNECTION_ESTABLISHED:
  70. return _connectionEstablished(store, next, action);
  71. case CONNECTION_FAILED:
  72. return _connectionFailed(store, next, action);
  73. case CONFERENCE_SUBJECT_CHANGED:
  74. return _conferenceSubjectChanged(store, next, action);
  75. case CONFERENCE_WILL_LEAVE:
  76. _conferenceWillLeave(store);
  77. break;
  78. case PARTICIPANT_UPDATED:
  79. return _updateLocalParticipantInConference(store, next, action);
  80. case PIN_PARTICIPANT:
  81. return _pinParticipant(store, next, action);
  82. case SEND_TONES:
  83. return _sendTones(store, next, action);
  84. case SET_ROOM:
  85. return _setRoom(store, next, action);
  86. case TRACK_ADDED:
  87. case TRACK_REMOVED:
  88. return _trackAddedOrRemoved(store, next, action);
  89. }
  90. return next(action);
  91. });
  92. /**
  93. * Makes sure to leave a failed conference in order to release any allocated
  94. * resources like peer connections, emit participant left events, etc.
  95. *
  96. * @param {Store} store - The redux store in which the specified {@code action}
  97. * is being dispatched.
  98. * @param {Dispatch} next - The redux {@code dispatch} function to dispatch the
  99. * specified {@code action} to the specified {@code store}.
  100. * @param {Action} action - The redux action {@code CONFERENCE_FAILED} which is
  101. * being dispatched in the specified {@code store}.
  102. * @private
  103. * @returns {Object} The value returned by {@code next(action)}.
  104. */
  105. function _conferenceFailed({ dispatch, getState }, next, action) {
  106. const result = next(action);
  107. const { conference, error } = action;
  108. const { enableForcedReload } = getState()['features/base/config'];
  109. // Handle specific failure reasons.
  110. switch (error.name) {
  111. case JitsiConferenceErrors.CONFERENCE_DESTROYED: {
  112. const [ reason ] = error.params;
  113. dispatch(showWarningNotification({
  114. description: reason,
  115. titleKey: 'dialog.sessTerminated'
  116. }, NOTIFICATION_TIMEOUT_TYPE.LONG));
  117. if (TRIGGER_READY_TO_CLOSE_REASONS.includes(reason)) {
  118. if (typeof APP === undefined) {
  119. dispatch(readyToClose());
  120. } else {
  121. APP.API.notifyReadyToClose();
  122. }
  123. }
  124. break;
  125. }
  126. case JitsiConferenceErrors.CONFERENCE_RESTARTED: {
  127. if (enableForcedReload) {
  128. dispatch(showErrorNotification({
  129. description: 'Restart initiated because of a bridge failure',
  130. titleKey: 'dialog.sessionRestarted'
  131. }, NOTIFICATION_TIMEOUT_TYPE.LONG));
  132. }
  133. break;
  134. }
  135. case JitsiConferenceErrors.CONNECTION_ERROR: {
  136. const [ msg ] = error.params;
  137. dispatch(connectionDisconnected(getState()['features/base/connection'].connection));
  138. dispatch(showErrorNotification({
  139. descriptionArguments: { msg },
  140. descriptionKey: msg ? 'dialog.connectErrorWithMsg' : 'dialog.connectError',
  141. titleKey: 'connection.CONNFAIL'
  142. }, NOTIFICATION_TIMEOUT_TYPE.LONG));
  143. break;
  144. }
  145. case JitsiConferenceErrors.OFFER_ANSWER_FAILED:
  146. sendAnalytics(createOfferAnswerFailedEvent());
  147. break;
  148. }
  149. if (typeof APP === 'undefined') {
  150. !error.recoverable
  151. && conference
  152. && conference.leave(CONFERENCE_LEAVE_REASONS.UNRECOVERABLE_ERROR).catch(reason => {
  153. // Even though we don't care too much about the failure, it may be
  154. // good to know that it happen, so log it (on the info level).
  155. logger.info('JitsiConference.leave() rejected with:', reason);
  156. });
  157. } else {
  158. // FIXME: Workaround for the web version. Currently, the creation of the
  159. // conference is handled by /conference.js and appropriate failure handlers
  160. // are set there.
  161. _removeUnloadHandler(getState);
  162. }
  163. if (enableForcedReload && error?.name === JitsiConferenceErrors.CONFERENCE_RESTARTED) {
  164. dispatch(conferenceWillLeave(conference));
  165. dispatch(reloadNow());
  166. }
  167. return result;
  168. }
  169. /**
  170. * Does extra sync up on properties that may need to be updated after the
  171. * conference was joined.
  172. *
  173. * @param {Store} store - The redux store in which the specified {@code action}
  174. * is being dispatched.
  175. * @param {Dispatch} next - The redux {@code dispatch} function to dispatch the
  176. * specified {@code action} to the specified {@code store}.
  177. * @param {Action} action - The redux action {@code CONFERENCE_JOINED} which is
  178. * being dispatched in the specified {@code store}.
  179. * @private
  180. * @returns {Object} The value returned by {@code next(action)}.
  181. */
  182. function _conferenceJoined({ dispatch, getState }, next, action) {
  183. const result = next(action);
  184. const { conference } = action;
  185. const { pendingSubjectChange } = getState()['features/base/conference'];
  186. const {
  187. disableBeforeUnloadHandlers = false,
  188. requireDisplayName
  189. } = getState()['features/base/config'];
  190. dispatch(removeLobbyChatParticipant(true));
  191. pendingSubjectChange && dispatch(setSubject(pendingSubjectChange));
  192. // FIXME: Very dirty solution. This will work on web only.
  193. // When the user closes the window or quits the browser, lib-jitsi-meet
  194. // handles the process of leaving the conference. This is temporary solution
  195. // that should cover the described use case as part of the effort to
  196. // implement the conferenceWillLeave action for web.
  197. beforeUnloadHandler = () => {
  198. dispatch(conferenceWillLeave(conference));
  199. };
  200. window.addEventListener(disableBeforeUnloadHandlers ? 'unload' : 'beforeunload', beforeUnloadHandler);
  201. if (requireDisplayName
  202. && !getLocalParticipant(getState)?.name
  203. && !conference.isHidden()) {
  204. dispatch(openDisplayNamePrompt(undefined));
  205. }
  206. return result;
  207. }
  208. /**
  209. * Notifies the feature base/conference that the action
  210. * {@code CONNECTION_ESTABLISHED} is being dispatched within a specific redux
  211. * store.
  212. *
  213. * @param {Store} store - The redux store in which the specified {@code action}
  214. * is being dispatched.
  215. * @param {Dispatch} next - The redux {@code dispatch} function to dispatch the
  216. * specified {@code action} to the specified {@code store}.
  217. * @param {Action} action - The redux action {@code CONNECTION_ESTABLISHED}
  218. * which is being dispatched in the specified {@code store}.
  219. * @private
  220. * @returns {Object} The value returned by {@code next(action)}.
  221. */
  222. function _connectionEstablished({ dispatch }, next, action) {
  223. const result = next(action);
  224. // FIXME: Workaround for the web version. Currently, the creation of the
  225. // conference is handled by /conference.js.
  226. typeof APP === 'undefined' && dispatch(createConference());
  227. return result;
  228. }
  229. /**
  230. * Logs jwt validation errors from xmpp and from the client-side validator.
  231. *
  232. * @param {string} message -The error message from xmpp.
  233. * @param {Object} state - The redux state.
  234. * @returns {void}
  235. */
  236. function _logJwtErrors(message, state) {
  237. const { jwt } = state['features/base/jwt'];
  238. if (!jwt) {
  239. return;
  240. }
  241. const errorKeys = validateJwt(jwt);
  242. message && logger.error(`JWT error: ${message}`);
  243. errorKeys.length && logger.error('JWT parsing error:', errorKeys);
  244. }
  245. /**
  246. * Notifies the feature base/conference that the action
  247. * {@code CONNECTION_FAILED} is being dispatched within a specific redux
  248. * store.
  249. *
  250. * @param {Store} store - The redux store in which the specified {@code action}
  251. * is being dispatched.
  252. * @param {Dispatch} next - The redux {@code dispatch} function to dispatch the
  253. * specified {@code action} to the specified {@code store}.
  254. * @param {Action} action - The redux action {@code CONNECTION_FAILED} which is
  255. * being dispatched in the specified {@code store}.
  256. * @private
  257. * @returns {Object} The value returned by {@code next(action)}.
  258. */
  259. function _connectionFailed({ dispatch, getState }, next, action) {
  260. _logJwtErrors(action.error.message, getState());
  261. const result = next(action);
  262. _removeUnloadHandler(getState);
  263. // FIXME: Workaround for the web version. Currently, the creation of the
  264. // conference is handled by /conference.js and appropriate failure handlers
  265. // are set there.
  266. if (typeof APP === 'undefined') {
  267. const { connection } = action;
  268. const { error } = action;
  269. forEachConference(getState, conference => {
  270. // It feels that it would make things easier if JitsiConference
  271. // in lib-jitsi-meet would monitor it's connection and emit
  272. // CONFERENCE_FAILED when it's dropped. It has more knowledge on
  273. // whether it can recover or not. But because the reload screen
  274. // and the retry logic is implemented in the app maybe it can be
  275. // left this way for now.
  276. if (conference.getConnection() === connection) {
  277. // XXX Note that on mobile the error type passed to
  278. // connectionFailed is always an object with .name property.
  279. // This fact needs to be checked prior to enabling this logic on
  280. // web.
  281. const conferenceAction
  282. = conferenceFailed(conference, error.name);
  283. // Copy the recoverable flag if set on the CONNECTION_FAILED
  284. // action to not emit recoverable action caused by
  285. // a non-recoverable one.
  286. if (typeof error.recoverable !== 'undefined') {
  287. conferenceAction.error.recoverable = error.recoverable;
  288. }
  289. dispatch(conferenceAction);
  290. }
  291. return true;
  292. });
  293. }
  294. return result;
  295. }
  296. /**
  297. * Notifies the feature base/conference that the action
  298. * {@code CONFERENCE_SUBJECT_CHANGED} is being dispatched within a specific
  299. * redux store.
  300. *
  301. * @param {Store} store - The redux store in which the specified {@code action}
  302. * is being dispatched.
  303. * @param {Dispatch} next - The redux {@code dispatch} function to dispatch the
  304. * specified {@code action} to the specified {@code store}.
  305. * @param {Action} action - The redux action {@code CONFERENCE_SUBJECT_CHANGED}
  306. * which is being dispatched in the specified {@code store}.
  307. * @private
  308. * @returns {Object} The value returned by {@code next(action)}.
  309. */
  310. function _conferenceSubjectChanged({ dispatch, getState }, next, action) {
  311. const result = next(action);
  312. const { subject } = getState()['features/base/conference'];
  313. if (subject) {
  314. dispatch({
  315. type: SET_PENDING_SUBJECT_CHANGE,
  316. subject: undefined
  317. });
  318. }
  319. typeof APP === 'object' && APP.API.notifySubjectChanged(subject);
  320. return result;
  321. }
  322. /**
  323. * Notifies the feature base/conference that the action
  324. * {@code CONFERENCE_WILL_LEAVE} is being dispatched within a specific redux
  325. * store.
  326. *
  327. * @private
  328. * @param {Object} store - The redux store.
  329. * @returns {void}
  330. */
  331. function _conferenceWillLeave({ getState }: { getState: Function }) {
  332. _removeUnloadHandler(getState);
  333. }
  334. /**
  335. * Notifies the feature base/conference that the action {@code PIN_PARTICIPANT}
  336. * is being dispatched within a specific redux store. Pins the specified remote
  337. * participant in the associated conference, ignores the local participant.
  338. *
  339. * @param {Store} store - The redux store in which the specified {@code action}
  340. * is being dispatched.
  341. * @param {Dispatch} next - The redux {@code dispatch} function to dispatch the
  342. * specified {@code action} to the specified {@code store}.
  343. * @param {Action} action - The redux action {@code PIN_PARTICIPANT} which is
  344. * being dispatched in the specified {@code store}.
  345. * @private
  346. * @returns {Object} The value returned by {@code next(action)}.
  347. */
  348. function _pinParticipant({ getState }, next, action) {
  349. const state = getState();
  350. const { conference } = state['features/base/conference'];
  351. if (!conference) {
  352. return next(action);
  353. }
  354. const id = action.participant.id;
  355. const participantById = getParticipantById(state, id);
  356. const pinnedParticipant = getPinnedParticipant(state);
  357. const actionName = id ? ACTION_PINNED : ACTION_UNPINNED;
  358. const local
  359. = (participantById && participantById.local)
  360. || (!id && pinnedParticipant && pinnedParticipant.local);
  361. let participantIdForEvent;
  362. if (local) {
  363. participantIdForEvent = local;
  364. } else {
  365. participantIdForEvent
  366. = actionName === ACTION_PINNED ? id : pinnedParticipant && pinnedParticipant.id;
  367. }
  368. sendAnalytics(createPinnedEvent(
  369. actionName,
  370. participantIdForEvent,
  371. {
  372. local,
  373. 'participant_count': conference.getParticipantCount()
  374. }));
  375. return next(action);
  376. }
  377. /**
  378. * Removes the unload handler.
  379. *
  380. * @param {Function} getState - The redux getState function.
  381. * @returns {void}
  382. */
  383. function _removeUnloadHandler(getState) {
  384. if (typeof beforeUnloadHandler !== 'undefined') {
  385. const { disableBeforeUnloadHandlers = false } = getState()['features/base/config'];
  386. window.removeEventListener(disableBeforeUnloadHandlers ? 'unload' : 'beforeunload', beforeUnloadHandler);
  387. beforeUnloadHandler = undefined;
  388. }
  389. }
  390. /**
  391. * Requests the specified tones to be played.
  392. *
  393. * @param {Store} store - The redux store in which the specified {@code action}
  394. * is being dispatched.
  395. * @param {Dispatch} next - The redux {@code dispatch} function to dispatch the
  396. * specified {@code action} to the specified {@code store}.
  397. * @param {Action} action - The redux action {@code SEND_TONES} which is
  398. * being dispatched in the specified {@code store}.
  399. * @private
  400. * @returns {Object} The value returned by {@code next(action)}.
  401. */
  402. function _sendTones({ getState }, next, action) {
  403. const state = getState();
  404. const { conference } = state['features/base/conference'];
  405. if (conference) {
  406. const { duration, tones, pause } = action;
  407. conference.sendTones(tones, duration, pause);
  408. }
  409. return next(action);
  410. }
  411. /**
  412. * Notifies the feature base/conference that the action
  413. * {@code SET_ROOM} is being dispatched within a specific
  414. * redux store.
  415. *
  416. * @param {Store} store - The redux store in which the specified {@code action}
  417. * is being dispatched.
  418. * @param {Dispatch} next - The redux {@code dispatch} function to dispatch the
  419. * specified {@code action} to the specified {@code store}.
  420. * @param {Action} action - The redux action {@code SET_ROOM}
  421. * which is being dispatched in the specified {@code store}.
  422. * @private
  423. * @returns {Object} The value returned by {@code next(action)}.
  424. */
  425. function _setRoom({ dispatch, getState }, next, action) {
  426. const state = getState();
  427. const { localSubject, subject } = state['features/base/config'];
  428. const { room } = action;
  429. if (room) {
  430. // Set the stored subject.
  431. dispatch(setLocalSubject(localSubject));
  432. dispatch(setSubject(subject));
  433. }
  434. return next(action);
  435. }
  436. /**
  437. * Synchronizes local tracks from state with local tracks in JitsiConference
  438. * instance.
  439. *
  440. * @param {Store} store - The redux store.
  441. * @param {Object} action - Action object.
  442. * @private
  443. * @returns {Promise}
  444. */
  445. function _syncConferenceLocalTracksWithState({ getState }, action) {
  446. const conference = getCurrentConference(getState);
  447. let promise;
  448. if (conference) {
  449. const track = action.track.jitsiTrack;
  450. if (action.type === TRACK_ADDED) {
  451. promise = _addLocalTracksToConference(conference, [ track ]);
  452. } else {
  453. promise = _removeLocalTracksFromConference(conference, [ track ]);
  454. }
  455. }
  456. return promise || Promise.resolve();
  457. }
  458. /**
  459. * Notifies the feature base/conference that the action {@code TRACK_ADDED}
  460. * or {@code TRACK_REMOVED} is being dispatched within a specific redux store.
  461. *
  462. * @param {Store} store - The redux store in which the specified {@code action}
  463. * is being dispatched.
  464. * @param {Dispatch} next - The redux {@code dispatch} function to dispatch the
  465. * specified {@code action} to the specified {@code store}.
  466. * @param {Action} action - The redux action {@code TRACK_ADDED} or
  467. * {@code TRACK_REMOVED} which is being dispatched in the specified
  468. * {@code store}.
  469. * @private
  470. * @returns {Object} The value returned by {@code next(action)}.
  471. */
  472. function _trackAddedOrRemoved(store, next, action) {
  473. const track = action.track;
  474. // TODO All track swapping should happen here instead of conference.js.
  475. // Since we swap the tracks for the web client in conference.js, ignore
  476. // presenter tracks here and do not add/remove them to/from the conference.
  477. if (track && track.local && track.mediaType !== MEDIA_TYPE.PRESENTER) {
  478. return (
  479. _syncConferenceLocalTracksWithState(store, action)
  480. .then(() => next(action)));
  481. }
  482. return next(action);
  483. }
  484. /**
  485. * Updates the conference object when the local participant is updated.
  486. *
  487. * @param {Store} store - The redux store in which the specified {@code action}
  488. * is being dispatched.
  489. * @param {Dispatch} next - The redux {@code dispatch} function to dispatch the
  490. * specified {@code action} to the specified {@code store}.
  491. * @param {Action} action - The redux action which is being dispatched in the
  492. * specified {@code store}.
  493. * @private
  494. * @returns {Object} The value returned by {@code next(action)}.
  495. */
  496. function _updateLocalParticipantInConference({ dispatch, getState }, next, action) {
  497. const { conference } = getState()['features/base/conference'];
  498. const { participant } = action;
  499. const result = next(action);
  500. const localParticipant = getLocalParticipant(getState);
  501. if (conference && participant.id === localParticipant?.id) {
  502. if ('name' in participant) {
  503. conference.setDisplayName(participant.name);
  504. }
  505. if ('role' in participant && participant.role === PARTICIPANT_ROLE.MODERATOR) {
  506. const { pendingSubjectChange, subject } = getState()['features/base/conference'];
  507. // When the local user role is updated to moderator and we have a pending subject change
  508. // which was not reflected we need to set it (the first time we tried was before becoming moderator).
  509. if (typeof pendingSubjectChange !== 'undefined' && pendingSubjectChange !== subject) {
  510. dispatch(setSubject(pendingSubjectChange));
  511. }
  512. }
  513. }
  514. return result;
  515. }