Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

middleware.js 19KB

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