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

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