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.ts 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  1. /* eslint-disable lines-around-comment */
  2. import debounce from 'lodash/debounce';
  3. import { NativeEventEmitter, NativeModules } from 'react-native';
  4. import { AnyAction } from 'redux';
  5. // @ts-expect-error
  6. import { ENDPOINT_TEXT_MESSAGE_NAME } from '../../../../modules/API/constants';
  7. import { appNavigate } from '../../app/actions.native';
  8. import { IStore } from '../../app/types';
  9. import { APP_WILL_MOUNT, APP_WILL_UNMOUNT } from '../../base/app/actionTypes';
  10. import {
  11. CONFERENCE_BLURRED,
  12. CONFERENCE_FAILED,
  13. CONFERENCE_FOCUSED,
  14. CONFERENCE_JOINED,
  15. CONFERENCE_LEFT,
  16. CONFERENCE_WILL_JOIN,
  17. SET_ROOM
  18. } from '../../base/conference/actionTypes';
  19. import { JITSI_CONFERENCE_URL_KEY } from '../../base/conference/constants';
  20. import {
  21. forEachConference,
  22. getCurrentConference,
  23. isRoomValid
  24. } from '../../base/conference/functions';
  25. import { IJitsiConference } from '../../base/conference/reducer';
  26. import { CONNECTION_DISCONNECTED } from '../../base/connection/actionTypes';
  27. import {
  28. JITSI_CONNECTION_CONFERENCE_KEY,
  29. JITSI_CONNECTION_URL_KEY
  30. } from '../../base/connection/constants';
  31. import { getURLWithoutParams } from '../../base/connection/utils';
  32. import {
  33. JitsiConferenceEvents } from '../../base/lib-jitsi-meet';
  34. import { SET_AUDIO_MUTED, SET_VIDEO_MUTED } from '../../base/media/actionTypes';
  35. import { toggleCameraFacingMode } from '../../base/media/actions';
  36. import { MEDIA_TYPE, VIDEO_TYPE } from '../../base/media/constants';
  37. import { PARTICIPANT_JOINED, PARTICIPANT_LEFT } from '../../base/participants/actionTypes';
  38. import {
  39. getLocalParticipant,
  40. getParticipantById,
  41. getRemoteParticipants,
  42. isScreenShareParticipantById
  43. } from '../../base/participants/functions';
  44. import MiddlewareRegistry from '../../base/redux/MiddlewareRegistry';
  45. import StateListenerRegistry from '../../base/redux/StateListenerRegistry';
  46. import { toggleScreensharing } from '../../base/tracks/actions.native';
  47. import { getLocalTracks, isLocalTrackMuted } from '../../base/tracks/functions.native';
  48. import { ITrack } from '../../base/tracks/types';
  49. import { CLOSE_CHAT, OPEN_CHAT } from '../../chat/actionTypes';
  50. import { closeChat, openChat, sendMessage, setPrivateMessageRecipient } from '../../chat/actions.native';
  51. import { setRequestingSubtitles } from '../../subtitles/actions.any';
  52. import { muteLocal } from '../../video-menu/actions.native';
  53. import { ENTER_PICTURE_IN_PICTURE } from '../picture-in-picture/actionTypes';
  54. // @ts-ignore
  55. import { isExternalAPIAvailable } from '../react-native-sdk/functions';
  56. import { READY_TO_CLOSE } from './actionTypes';
  57. import { setParticipantsWithScreenShare } from './actions';
  58. import { participantToParticipantInfo, sendEvent } from './functions';
  59. import logger from './logger';
  60. /**
  61. * Event which will be emitted on the native side when a chat message is received
  62. * through the channel.
  63. */
  64. const CHAT_MESSAGE_RECEIVED = 'CHAT_MESSAGE_RECEIVED';
  65. /**
  66. * Event which will be emitted on the native side when the chat dialog is displayed/closed.
  67. */
  68. const CHAT_TOGGLED = 'CHAT_TOGGLED';
  69. /**
  70. * Event which will be emitted on the native side to indicate the conference
  71. * has ended either by user request or because an error was produced.
  72. */
  73. const CONFERENCE_TERMINATED = 'CONFERENCE_TERMINATED';
  74. /**
  75. * Event which will be emitted on the native side to indicate a message was received
  76. * through the channel.
  77. */
  78. const ENDPOINT_TEXT_MESSAGE_RECEIVED = 'ENDPOINT_TEXT_MESSAGE_RECEIVED';
  79. /**
  80. * Event which will be emitted on the native side to indicate a participant togggles
  81. * the screen share.
  82. */
  83. const SCREEN_SHARE_TOGGLED = 'SCREEN_SHARE_TOGGLED';
  84. /**
  85. * Event which will be emitted on the native side with the participant info array.
  86. */
  87. const PARTICIPANTS_INFO_RETRIEVED = 'PARTICIPANTS_INFO_RETRIEVED';
  88. const externalAPIEnabled = isExternalAPIAvailable();
  89. let eventEmitter: any;
  90. const { ExternalAPI } = NativeModules;
  91. if (externalAPIEnabled) {
  92. eventEmitter = new NativeEventEmitter(ExternalAPI);
  93. }
  94. /**
  95. * Middleware that captures Redux actions and uses the ExternalAPI module to
  96. * turn them into native events so the application knows about them.
  97. *
  98. * @param {Store} store - Redux store.
  99. * @returns {Function}
  100. */
  101. externalAPIEnabled && MiddlewareRegistry.register(store => next => action => {
  102. const oldAudioMuted = store.getState()['features/base/media'].audio.muted;
  103. const result = next(action);
  104. const { type } = action;
  105. switch (type) {
  106. case APP_WILL_MOUNT:
  107. _registerForNativeEvents(store);
  108. break;
  109. case APP_WILL_UNMOUNT:
  110. _unregisterForNativeEvents();
  111. break;
  112. case CONFERENCE_FAILED: {
  113. const { error, ...data } = action;
  114. // XXX Certain CONFERENCE_FAILED errors are recoverable i.e. they have
  115. // prevented the user from joining a specific conference but the app may
  116. // be able to eventually join the conference. For example, the app will
  117. // ask the user for a password upon
  118. // JitsiConferenceErrors.PASSWORD_REQUIRED and will retry joining the
  119. // conference afterwards. Such errors are to not reach the native
  120. // counterpart of the External API (or at least not in the
  121. // fatality/finality semantics attributed to
  122. // conferenceFailed:/onConferenceFailed).
  123. if (!error.recoverable) {
  124. _sendConferenceEvent(store, /* action */ {
  125. error: _toErrorString(error),
  126. ...data
  127. });
  128. }
  129. break;
  130. }
  131. case CONFERENCE_LEFT:
  132. _sendConferenceEvent(store, action);
  133. break;
  134. case CONFERENCE_JOINED:
  135. _sendConferenceEvent(store, action);
  136. _registerForEndpointTextMessages(store);
  137. break;
  138. case CONFERENCE_BLURRED:
  139. sendEvent(store, CONFERENCE_BLURRED, {});
  140. break;
  141. case CONFERENCE_FOCUSED:
  142. sendEvent(store, CONFERENCE_FOCUSED, {});
  143. break;
  144. case CONNECTION_DISCONNECTED: {
  145. // FIXME: This is a hack. See the description in the JITSI_CONNECTION_CONFERENCE_KEY constant definition.
  146. // Check if this connection was attached to any conference.
  147. // If it wasn't, fake a CONFERENCE_TERMINATED event.
  148. const { connection } = action;
  149. const conference = connection[JITSI_CONNECTION_CONFERENCE_KEY];
  150. if (!conference) {
  151. // This action will arrive late, so the locationURL stored on the state is no longer valid.
  152. const locationURL = connection[JITSI_CONNECTION_URL_KEY];
  153. sendEvent(
  154. store,
  155. CONFERENCE_TERMINATED,
  156. /* data */ {
  157. url: _normalizeUrl(locationURL)
  158. });
  159. }
  160. break;
  161. }
  162. case ENTER_PICTURE_IN_PICTURE:
  163. sendEvent(store, type, /* data */ {});
  164. break;
  165. case OPEN_CHAT:
  166. case CLOSE_CHAT: {
  167. sendEvent(
  168. store,
  169. CHAT_TOGGLED,
  170. /* data */ {
  171. isOpen: action.type === OPEN_CHAT
  172. });
  173. break;
  174. }
  175. case PARTICIPANT_JOINED:
  176. case PARTICIPANT_LEFT: {
  177. // Skip these events while not in a conference. SDK users can still retrieve them.
  178. const { conference } = store.getState()['features/base/conference'];
  179. if (!conference) {
  180. break;
  181. }
  182. const { participant } = action;
  183. const isVirtualScreenshareParticipant = isScreenShareParticipantById(store.getState(), participant.id);
  184. if (isVirtualScreenshareParticipant) {
  185. break;
  186. }
  187. sendEvent(
  188. store,
  189. action.type,
  190. participantToParticipantInfo(participant) /* data */
  191. );
  192. break;
  193. }
  194. case READY_TO_CLOSE:
  195. sendEvent(store, type, /* data */ {});
  196. break;
  197. case SET_ROOM:
  198. _maybeTriggerEarlyConferenceWillJoin(store, action);
  199. break;
  200. case SET_AUDIO_MUTED:
  201. if (action.muted !== oldAudioMuted) {
  202. sendEvent(
  203. store,
  204. 'AUDIO_MUTED_CHANGED',
  205. /* data */ {
  206. muted: action.muted
  207. });
  208. }
  209. break;
  210. case SET_VIDEO_MUTED:
  211. sendEvent(
  212. store,
  213. 'VIDEO_MUTED_CHANGED',
  214. /* data */ {
  215. muted: action.muted
  216. });
  217. break;
  218. }
  219. return result;
  220. });
  221. /**
  222. * Listen for changes to the known media tracks and look
  223. * for updates to screen shares for emitting native events.
  224. * The listener is debounced to avoid state thrashing that might occur,
  225. * especially when switching in or out of p2p.
  226. */
  227. externalAPIEnabled && StateListenerRegistry.register(
  228. /* selector */ state => state['features/base/tracks'],
  229. /* listener */ debounce((tracks: ITrack[], store: IStore) => {
  230. const oldScreenShares = store.getState()['features/mobile/external-api'].screenShares || [];
  231. const newScreenShares = tracks
  232. .filter(track => track.mediaType === MEDIA_TYPE.SCREENSHARE || track.videoType === VIDEO_TYPE.DESKTOP)
  233. .map(track => track.participantId);
  234. oldScreenShares.forEach(participantId => {
  235. if (!newScreenShares.includes(participantId)) {
  236. sendEvent(
  237. store,
  238. SCREEN_SHARE_TOGGLED,
  239. /* data */ {
  240. participantId,
  241. sharing: false
  242. });
  243. }
  244. });
  245. newScreenShares.forEach(participantId => {
  246. if (!oldScreenShares.includes(participantId)) {
  247. sendEvent(
  248. store,
  249. SCREEN_SHARE_TOGGLED,
  250. /* data */ {
  251. participantId,
  252. sharing: true
  253. });
  254. }
  255. });
  256. store.dispatch(setParticipantsWithScreenShare(newScreenShares));
  257. }, 100));
  258. /**
  259. * Registers for events sent from the native side via NativeEventEmitter.
  260. *
  261. * @param {Store} store - The redux store.
  262. * @private
  263. * @returns {void}
  264. */
  265. function _registerForNativeEvents(store: IStore) {
  266. const { getState, dispatch } = store;
  267. eventEmitter.addListener(ExternalAPI.HANG_UP, () => {
  268. dispatch(appNavigate(undefined));
  269. });
  270. eventEmitter.addListener(ExternalAPI.SET_AUDIO_MUTED, ({ muted }: any) => {
  271. dispatch(muteLocal(muted, MEDIA_TYPE.AUDIO));
  272. });
  273. eventEmitter.addListener(ExternalAPI.SET_VIDEO_MUTED, ({ muted }: any) => {
  274. dispatch(muteLocal(muted, MEDIA_TYPE.VIDEO));
  275. });
  276. eventEmitter.addListener(ExternalAPI.SEND_ENDPOINT_TEXT_MESSAGE, ({ to, message }: any) => {
  277. const conference = getCurrentConference(getState());
  278. try {
  279. conference?.sendEndpointMessage(to, {
  280. name: ENDPOINT_TEXT_MESSAGE_NAME,
  281. text: message
  282. });
  283. } catch (error) {
  284. logger.warn('Cannot send endpointMessage', error);
  285. }
  286. });
  287. eventEmitter.addListener(ExternalAPI.TOGGLE_SCREEN_SHARE, ({ enabled }: any) => {
  288. dispatch(toggleScreensharing(enabled));
  289. });
  290. eventEmitter.addListener(ExternalAPI.RETRIEVE_PARTICIPANTS_INFO, ({ requestId }: any) => {
  291. const participantsInfo = [];
  292. const remoteParticipants = getRemoteParticipants(store);
  293. const localParticipant = getLocalParticipant(store);
  294. localParticipant && participantsInfo.push(participantToParticipantInfo(localParticipant));
  295. remoteParticipants.forEach(participant => {
  296. if (!participant.fakeParticipant) {
  297. participantsInfo.push(participantToParticipantInfo(participant));
  298. }
  299. });
  300. sendEvent(
  301. store,
  302. PARTICIPANTS_INFO_RETRIEVED,
  303. /* data */ {
  304. participantsInfo,
  305. requestId
  306. });
  307. });
  308. eventEmitter.addListener(ExternalAPI.OPEN_CHAT, ({ to }: any) => {
  309. const participant = getParticipantById(store, to);
  310. dispatch(openChat(participant));
  311. });
  312. eventEmitter.addListener(ExternalAPI.CLOSE_CHAT, () => {
  313. dispatch(closeChat());
  314. });
  315. eventEmitter.addListener(ExternalAPI.SEND_CHAT_MESSAGE, ({ message, to }: any) => {
  316. const participant = getParticipantById(store, to);
  317. if (participant) {
  318. dispatch(setPrivateMessageRecipient(participant));
  319. }
  320. dispatch(sendMessage(message));
  321. });
  322. eventEmitter.addListener(ExternalAPI.SET_CLOSED_CAPTIONS_ENABLED, ({ enabled }: any) => {
  323. dispatch(setRequestingSubtitles(enabled));
  324. });
  325. eventEmitter.addListener(ExternalAPI.TOGGLE_CAMERA, () => {
  326. dispatch(toggleCameraFacingMode());
  327. });
  328. }
  329. /**
  330. * Unregister for events sent from the native side via NativeEventEmitter.
  331. *
  332. * @private
  333. * @returns {void}
  334. */
  335. function _unregisterForNativeEvents() {
  336. eventEmitter.removeAllListeners(ExternalAPI.HANG_UP);
  337. eventEmitter.removeAllListeners(ExternalAPI.SET_AUDIO_MUTED);
  338. eventEmitter.removeAllListeners(ExternalAPI.SET_VIDEO_MUTED);
  339. eventEmitter.removeAllListeners(ExternalAPI.SEND_ENDPOINT_TEXT_MESSAGE);
  340. eventEmitter.removeAllListeners(ExternalAPI.TOGGLE_SCREEN_SHARE);
  341. eventEmitter.removeAllListeners(ExternalAPI.RETRIEVE_PARTICIPANTS_INFO);
  342. eventEmitter.removeAllListeners(ExternalAPI.OPEN_CHAT);
  343. eventEmitter.removeAllListeners(ExternalAPI.CLOSE_CHAT);
  344. eventEmitter.removeAllListeners(ExternalAPI.SEND_CHAT_MESSAGE);
  345. eventEmitter.removeAllListeners(ExternalAPI.SET_CLOSED_CAPTIONS_ENABLED);
  346. eventEmitter.removeAllListeners(ExternalAPI.TOGGLE_CAMERA);
  347. }
  348. /**
  349. * Registers for endpoint messages sent on conference data channel.
  350. *
  351. * @param {Store} store - The redux store.
  352. * @private
  353. * @returns {void}
  354. */
  355. function _registerForEndpointTextMessages(store: IStore) {
  356. const conference = getCurrentConference(store.getState());
  357. conference?.on(
  358. JitsiConferenceEvents.ENDPOINT_MESSAGE_RECEIVED,
  359. (...args: any[]) => {
  360. if (args && args.length >= 2) {
  361. const [ sender, eventData ] = args;
  362. if (eventData.name === ENDPOINT_TEXT_MESSAGE_NAME) {
  363. sendEvent(
  364. store,
  365. ENDPOINT_TEXT_MESSAGE_RECEIVED,
  366. /* data */ {
  367. message: eventData.text,
  368. senderId: sender._id
  369. });
  370. }
  371. }
  372. });
  373. conference?.on(
  374. JitsiConferenceEvents.MESSAGE_RECEIVED,
  375. (id: string, message: string, timestamp: number) => {
  376. sendEvent(
  377. store,
  378. CHAT_MESSAGE_RECEIVED,
  379. /* data */ {
  380. senderId: id,
  381. message,
  382. isPrivate: false,
  383. timestamp
  384. });
  385. }
  386. );
  387. conference?.on(
  388. JitsiConferenceEvents.PRIVATE_MESSAGE_RECEIVED,
  389. (id: string, message: string, timestamp: number) => {
  390. sendEvent(
  391. store,
  392. CHAT_MESSAGE_RECEIVED,
  393. /* data */ {
  394. senderId: id,
  395. message,
  396. isPrivate: true,
  397. timestamp
  398. });
  399. }
  400. );
  401. }
  402. /**
  403. * Returns a {@code String} representation of a specific error {@code Object}.
  404. *
  405. * @param {Error|Object|string} error - The error {@code Object} to return a
  406. * {@code String} representation of.
  407. * @returns {string} A {@code String} representation of the specified
  408. * {@code error}.
  409. */
  410. function _toErrorString(
  411. error: Error | { message?: string; name?: string; } | string) {
  412. // XXX In lib-jitsi-meet and jitsi-meet we utilize errors in the form of
  413. // strings, Error instances, and plain objects which resemble Error.
  414. return (
  415. error
  416. ? typeof error === 'string'
  417. ? error
  418. : Error.prototype.toString.apply(error)
  419. : '');
  420. }
  421. /**
  422. * If {@link SET_ROOM} action happens for a valid conference room this method
  423. * will emit an early {@link CONFERENCE_WILL_JOIN} event to let the external API
  424. * know that a conference is being joined. Before that happens a connection must
  425. * be created and only then base/conference feature would emit
  426. * {@link CONFERENCE_WILL_JOIN}. That is fine for the Jitsi Meet app, because
  427. * that's the a conference instance gets created, but it's too late for
  428. * the external API to learn that. The latter {@link CONFERENCE_WILL_JOIN} is
  429. * swallowed in {@link _swallowEvent}.
  430. *
  431. * @param {Store} store - The redux store.
  432. * @param {Action} action - The redux action.
  433. * @returns {void}
  434. */
  435. function _maybeTriggerEarlyConferenceWillJoin(store: IStore, action: AnyAction) {
  436. const { locationURL } = store.getState()['features/base/connection'];
  437. const { room } = action;
  438. isRoomValid(room) && locationURL && sendEvent(
  439. store,
  440. CONFERENCE_WILL_JOIN,
  441. /* data */ {
  442. url: _normalizeUrl(locationURL)
  443. });
  444. }
  445. /**
  446. * Normalizes the given URL for presentation over the external API.
  447. *
  448. * @param {URL} url -The URL to normalize.
  449. * @returns {string} - The normalized URL as a string.
  450. */
  451. function _normalizeUrl(url: URL) {
  452. return getURLWithoutParams(url).href;
  453. }
  454. /**
  455. * Sends an event to the native counterpart of the External API for a specific
  456. * conference-related redux action.
  457. *
  458. * @param {Store} store - The redux store.
  459. * @param {Action} action - The redux action.
  460. * @returns {void}
  461. */
  462. function _sendConferenceEvent(
  463. store: IStore,
  464. action: {
  465. conference: IJitsiConference;
  466. isAudioMuted?: boolean;
  467. type: string;
  468. url?: string;
  469. }) {
  470. const { conference, type, ...data } = action;
  471. // For these (redux) actions, conference identifies a JitsiConference
  472. // instance. The external API cannot transport such an object so we have to
  473. // transport an "equivalent".
  474. if (conference) { // @ts-ignore
  475. data.url = _normalizeUrl(conference[JITSI_CONFERENCE_URL_KEY]);
  476. const localTracks = getLocalTracks(store.getState()['features/base/tracks']);
  477. const isAudioMuted = isLocalTrackMuted(localTracks, MEDIA_TYPE.AUDIO);
  478. data.isAudioMuted = isAudioMuted;
  479. }
  480. if (_swallowEvent(store, action, data)) {
  481. return;
  482. }
  483. let type_;
  484. switch (type) {
  485. case CONFERENCE_FAILED:
  486. case CONFERENCE_LEFT:
  487. type_ = CONFERENCE_TERMINATED;
  488. break;
  489. default:
  490. type_ = type;
  491. break;
  492. }
  493. sendEvent(store, type_, data);
  494. }
  495. /**
  496. * Determines whether to not send a {@code CONFERENCE_LEFT} event to the native
  497. * counterpart of the External API.
  498. *
  499. * @param {Object} store - The redux store.
  500. * @param {Action} action - The redux action which is causing the sending of the
  501. * event.
  502. * @param {Object} data - The details/specifics of the event to send determined
  503. * by/associated with the specified {@code action}.
  504. * @returns {boolean} If the specified event is to not be sent, {@code true};
  505. * otherwise, {@code false}.
  506. */
  507. function _swallowConferenceLeft({ getState }: IStore, action: AnyAction, { url }: { url: string; }) {
  508. // XXX Internally, we work with JitsiConference instances. Externally
  509. // though, we deal with URL strings. The relation between the two is many to
  510. // one so it's technically and practically possible (by externally loading
  511. // the same URL string multiple times) to try to send CONFERENCE_LEFT
  512. // externally for a URL string which identifies a JitsiConference that the
  513. // app is internally legitimately working with.
  514. let swallowConferenceLeft = false;
  515. url
  516. && forEachConference(getState, (conference, conferenceURL) => {
  517. if (conferenceURL && conferenceURL.toString() === url) {
  518. swallowConferenceLeft = true;
  519. }
  520. return !swallowConferenceLeft;
  521. });
  522. return swallowConferenceLeft;
  523. }
  524. /**
  525. * Determines whether to not send a specific event to the native counterpart of
  526. * the External API.
  527. *
  528. * @param {Object} store - The redux store.
  529. * @param {Action} action - The redux action which is causing the sending of the
  530. * event.
  531. * @param {Object} data - The details/specifics of the event to send determined
  532. * by/associated with the specified {@code action}.
  533. * @returns {boolean} If the specified event is to not be sent, {@code true};
  534. * otherwise, {@code false}.
  535. */
  536. function _swallowEvent(store: IStore, action: AnyAction, data: any) {
  537. switch (action.type) {
  538. case CONFERENCE_LEFT:
  539. return _swallowConferenceLeft(store, action, data);
  540. default:
  541. return false;
  542. }
  543. }