您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

middleware.ts 20KB

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