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

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