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 19KB

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