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

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