Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

middleware.ts 20KB

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