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

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