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

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