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

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