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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  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, SET_VIDEO_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. case SET_VIDEO_MUTED:
  185. sendEvent(
  186. store,
  187. 'VIDEO_MUTED_CHANGED',
  188. /* data */ {
  189. muted: action.muted
  190. });
  191. break;
  192. }
  193. return result;
  194. });
  195. /**
  196. * Listen for changes to the known media tracks and look
  197. * for updates to screen shares for emitting native events.
  198. * The listener is debounced to avoid state thrashing that might occur,
  199. * especially when switching in or out of p2p.
  200. */
  201. StateListenerRegistry.register(
  202. /* selector */ state => state['features/base/tracks'],
  203. /* listener */ debounce((tracks, store) => {
  204. const oldScreenShares = store.getState()['features/mobile/external-api'].screenShares || [];
  205. const newScreenShares = tracks
  206. .filter(track => track.mediaType === 'video' && track.videoType === 'desktop')
  207. .map(track => track.participantId);
  208. oldScreenShares.forEach(participantId => {
  209. if (!newScreenShares.includes(participantId)) {
  210. sendEvent(
  211. store,
  212. SCREEN_SHARE_TOGGLED,
  213. /* data */ {
  214. participantId,
  215. sharing: false
  216. });
  217. }
  218. });
  219. newScreenShares.forEach(participantId => {
  220. if (!oldScreenShares.includes(participantId)) {
  221. sendEvent(
  222. store,
  223. SCREEN_SHARE_TOGGLED,
  224. /* data */ {
  225. participantId,
  226. sharing: true
  227. });
  228. }
  229. });
  230. store.dispatch(setParticipantsWithScreenShare(newScreenShares));
  231. }, 100));
  232. /**
  233. * Registers for events sent from the native side via NativeEventEmitter.
  234. *
  235. * @param {Store} store - The redux store.
  236. * @private
  237. * @returns {void}
  238. */
  239. function _registerForNativeEvents(store) {
  240. const { getState, dispatch } = store;
  241. eventEmitter.addListener(ExternalAPI.HANG_UP, () => {
  242. dispatch(appNavigate(undefined));
  243. });
  244. eventEmitter.addListener(ExternalAPI.SET_AUDIO_MUTED, ({ muted }) => {
  245. dispatch(muteLocal(muted, MEDIA_TYPE.AUDIO));
  246. });
  247. eventEmitter.addListener(ExternalAPI.SET_VIDEO_MUTED, ({ muted }) => {
  248. dispatch(muteLocal(muted, MEDIA_TYPE.VIDEO));
  249. });
  250. eventEmitter.addListener(ExternalAPI.SEND_ENDPOINT_TEXT_MESSAGE, ({ to, message }) => {
  251. const conference = getCurrentConference(getState());
  252. try {
  253. conference && conference.sendEndpointMessage(to, {
  254. name: ENDPOINT_TEXT_MESSAGE_NAME,
  255. text: message
  256. });
  257. } catch (error) {
  258. logger.warn('Cannot send endpointMessage', error);
  259. }
  260. });
  261. eventEmitter.addListener(ExternalAPI.TOGGLE_SCREEN_SHARE, ({ enabled }) => {
  262. dispatch(toggleScreensharing(enabled));
  263. });
  264. eventEmitter.addListener(ExternalAPI.RETRIEVE_PARTICIPANTS_INFO, ({ requestId }) => {
  265. const participantsInfo = getParticipants(store).map(participant => {
  266. return {
  267. isLocal: participant.local,
  268. email: participant.email,
  269. name: participant.name,
  270. participantId: participant.id,
  271. displayName: participant.displayName,
  272. avatarUrl: participant.avatarURL,
  273. role: participant.role
  274. };
  275. });
  276. sendEvent(
  277. store,
  278. PARTICIPANTS_INFO_RETRIEVED,
  279. /* data */ {
  280. participantsInfo,
  281. requestId
  282. });
  283. });
  284. eventEmitter.addListener(ExternalAPI.OPEN_CHAT, ({ to }) => {
  285. const participant = getParticipantById(store, to);
  286. dispatch(openChat(participant));
  287. });
  288. eventEmitter.addListener(ExternalAPI.CLOSE_CHAT, () => {
  289. dispatch(closeChat());
  290. });
  291. eventEmitter.addListener(ExternalAPI.SEND_CHAT_MESSAGE, ({ message, to }) => {
  292. const participant = getParticipantById(store, to);
  293. if (participant) {
  294. dispatch(setPrivateMessageRecipient(participant));
  295. }
  296. dispatch(sendMessage(message));
  297. });
  298. }
  299. /**
  300. * Registers for endpoint messages sent on conference data channel.
  301. *
  302. * @param {Store} store - The redux store.
  303. * @private
  304. * @returns {void}
  305. */
  306. function _registerForEndpointTextMessages(store) {
  307. const conference = getCurrentConference(store.getState());
  308. conference && conference.on(
  309. JitsiConferenceEvents.ENDPOINT_MESSAGE_RECEIVED,
  310. (...args) => {
  311. if (args && args.length >= 2) {
  312. const [ sender, eventData ] = args;
  313. if (eventData.name === ENDPOINT_TEXT_MESSAGE_NAME) {
  314. sendEvent(
  315. store,
  316. ENDPOINT_TEXT_MESSAGE_RECEIVED,
  317. /* data */ {
  318. message: eventData.text,
  319. senderId: sender._id
  320. });
  321. }
  322. }
  323. });
  324. conference.on(
  325. JitsiConferenceEvents.MESSAGE_RECEIVED,
  326. (id, message, timestamp) => {
  327. sendEvent(
  328. store,
  329. CHAT_MESSAGE_RECEIVED,
  330. /* data */ {
  331. senderId: id,
  332. message,
  333. isPrivate: false,
  334. timestamp
  335. });
  336. }
  337. );
  338. conference.on(
  339. JitsiConferenceEvents.PRIVATE_MESSAGE_RECEIVED,
  340. (id, message, timestamp) => {
  341. sendEvent(
  342. store,
  343. CHAT_MESSAGE_RECEIVED,
  344. /* data */ {
  345. senderId: id,
  346. message,
  347. isPrivate: true,
  348. timestamp
  349. });
  350. }
  351. );
  352. }
  353. /**
  354. * Returns a {@code String} representation of a specific error {@code Object}.
  355. *
  356. * @param {Error|Object|string} error - The error {@code Object} to return a
  357. * {@code String} representation of.
  358. * @returns {string} A {@code String} representation of the specified
  359. * {@code error}.
  360. */
  361. function _toErrorString(
  362. error: Error | { message: ?string, name: ?string } | string) {
  363. // XXX In lib-jitsi-meet and jitsi-meet we utilize errors in the form of
  364. // strings, Error instances, and plain objects which resemble Error.
  365. return (
  366. error
  367. ? typeof error === 'string'
  368. ? error
  369. : Error.prototype.toString.apply(error)
  370. : '');
  371. }
  372. /**
  373. * If {@link SET_ROOM} action happens for a valid conference room this method
  374. * will emit an early {@link CONFERENCE_WILL_JOIN} event to let the external API
  375. * know that a conference is being joined. Before that happens a connection must
  376. * be created and only then base/conference feature would emit
  377. * {@link CONFERENCE_WILL_JOIN}. That is fine for the Jitsi Meet app, because
  378. * that's the a conference instance gets created, but it's too late for
  379. * the external API to learn that. The latter {@link CONFERENCE_WILL_JOIN} is
  380. * swallowed in {@link _swallowEvent}.
  381. *
  382. * @param {Store} store - The redux store.
  383. * @param {Action} action - The redux action.
  384. * @returns {void}
  385. */
  386. function _maybeTriggerEarlyConferenceWillJoin(store, action) {
  387. const { locationURL } = store.getState()['features/base/connection'];
  388. const { room } = action;
  389. isRoomValid(room) && locationURL && sendEvent(
  390. store,
  391. CONFERENCE_WILL_JOIN,
  392. /* data */ {
  393. url: _normalizeUrl(locationURL)
  394. });
  395. }
  396. /**
  397. * Normalizes the given URL for presentation over the external API.
  398. *
  399. * @param {URL} url -The URL to normalize.
  400. * @returns {string} - The normalized URL as a string.
  401. */
  402. function _normalizeUrl(url: URL) {
  403. return getURLWithoutParams(url).href;
  404. }
  405. /**
  406. * Sends an event to the native counterpart of the External API for a specific
  407. * conference-related redux action.
  408. *
  409. * @param {Store} store - The redux store.
  410. * @param {Action} action - The redux action.
  411. * @returns {void}
  412. */
  413. function _sendConferenceEvent(
  414. store: Object,
  415. action: {
  416. conference: Object,
  417. type: string,
  418. url: ?string
  419. }) {
  420. const { conference, type, ...data } = action;
  421. // For these (redux) actions, conference identifies a JitsiConference
  422. // instance. The external API cannot transport such an object so we have to
  423. // transport an "equivalent".
  424. if (conference) {
  425. data.url = _normalizeUrl(conference[JITSI_CONFERENCE_URL_KEY]);
  426. }
  427. if (_swallowEvent(store, action, data)) {
  428. return;
  429. }
  430. let type_;
  431. switch (type) {
  432. case CONFERENCE_FAILED:
  433. case CONFERENCE_LEFT:
  434. type_ = CONFERENCE_TERMINATED;
  435. break;
  436. default:
  437. type_ = type;
  438. break;
  439. }
  440. sendEvent(store, type_, data);
  441. }
  442. /**
  443. * Sends {@link CONFERENCE_TERMINATED} event when the {@link CONNECTION_FAILED}
  444. * occurs. It should be done only if the connection fails before the conference
  445. * instance is created. Otherwise the eventual failure event is supposed to be
  446. * emitted by the base/conference feature.
  447. *
  448. * @param {Store} store - The redux store.
  449. * @param {Action} action - The redux action.
  450. * @returns {void}
  451. */
  452. function _sendConferenceFailedOnConnectionError(store, action) {
  453. const { locationURL } = store.getState()['features/base/connection'];
  454. const { connection } = action;
  455. locationURL
  456. && forEachConference(
  457. store,
  458. // If there's any conference in the base/conference state then the
  459. // base/conference feature is supposed to emit a failure.
  460. conference => conference.getConnection() !== connection)
  461. && sendEvent(
  462. store,
  463. CONFERENCE_TERMINATED,
  464. /* data */ {
  465. url: _normalizeUrl(locationURL),
  466. error: action.error.name
  467. });
  468. }
  469. /**
  470. * Determines whether to not send a {@code CONFERENCE_LEFT} event to the native
  471. * counterpart of the External API.
  472. *
  473. * @param {Object} store - The redux store.
  474. * @param {Action} action - The redux action which is causing the sending of the
  475. * event.
  476. * @param {Object} data - The details/specifics of the event to send determined
  477. * by/associated with the specified {@code action}.
  478. * @returns {boolean} If the specified event is to not be sent, {@code true};
  479. * otherwise, {@code false}.
  480. */
  481. function _swallowConferenceLeft({ getState }, action, { url }) {
  482. // XXX Internally, we work with JitsiConference instances. Externally
  483. // though, we deal with URL strings. The relation between the two is many to
  484. // one so it's technically and practically possible (by externally loading
  485. // the same URL string multiple times) to try to send CONFERENCE_LEFT
  486. // externally for a URL string which identifies a JitsiConference that the
  487. // app is internally legitimately working with.
  488. let swallowConferenceLeft = false;
  489. url
  490. && forEachConference(getState, (conference, conferenceURL) => {
  491. if (conferenceURL && conferenceURL.toString() === url) {
  492. swallowConferenceLeft = true;
  493. }
  494. return !swallowConferenceLeft;
  495. });
  496. return swallowConferenceLeft;
  497. }
  498. /**
  499. * Determines whether to not send a specific event to the native counterpart of
  500. * the External API.
  501. *
  502. * @param {Object} store - The redux store.
  503. * @param {Action} action - The redux action which is causing the sending of the
  504. * event.
  505. * @param {Object} data - The details/specifics of the event to send determined
  506. * by/associated with the specified {@code action}.
  507. * @returns {boolean} If the specified event is to not be sent, {@code true};
  508. * otherwise, {@code false}.
  509. */
  510. function _swallowEvent(store, action, data) {
  511. switch (action.type) {
  512. case CONFERENCE_LEFT:
  513. return _swallowConferenceLeft(store, action, data);
  514. case CONFERENCE_WILL_JOIN:
  515. // CONFERENCE_WILL_JOIN is dispatched to the external API on SET_ROOM,
  516. // before the connection is created, so we need to swallow the original
  517. // one emitted by base/conference.
  518. return true;
  519. default:
  520. return false;
  521. }
  522. }