Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

middleware.js 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  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. SET_ROOM
  13. } from '../../base/conference/actionTypes';
  14. import { JITSI_CONFERENCE_URL_KEY } from '../../base/conference/constants';
  15. import {
  16. forEachConference,
  17. getCurrentConference,
  18. isRoomValid
  19. } from '../../base/conference/functions';
  20. import { CONNECTION_DISCONNECTED } from '../../base/connection/actionTypes';
  21. import {
  22. JITSI_CONNECTION_CONFERENCE_KEY,
  23. JITSI_CONNECTION_URL_KEY
  24. } from '../../base/connection/constants';
  25. import { getURLWithoutParams } from '../../base/connection/utils';
  26. import {
  27. JitsiConferenceEvents } from '../../base/lib-jitsi-meet';
  28. import { SET_AUDIO_MUTED, SET_VIDEO_MUTED } from '../../base/media/actionTypes';
  29. import { MEDIA_TYPE } from '../../base/media/constants';
  30. import { PARTICIPANT_JOINED, PARTICIPANT_LEFT } from '../../base/participants/actionTypes';
  31. import {
  32. getLocalParticipant,
  33. getParticipantById,
  34. getRemoteParticipants,
  35. isScreenShareParticipant
  36. } from '../../base/participants/functions';
  37. import MiddlewareRegistry from '../../base/redux/MiddlewareRegistry';
  38. import StateListenerRegistry from '../../base/redux/StateListenerRegistry';
  39. import { toggleScreensharing } from '../../base/tracks/actions.native';
  40. import { getLocalTracks, isLocalTrackMuted } from '../../base/tracks/functions.native';
  41. import { CLOSE_CHAT, OPEN_CHAT } from '../../chat/actionTypes';
  42. import { openChat } from '../../chat/actions';
  43. import { closeChat, sendMessage, setPrivateMessageRecipient } from '../../chat/actions.any';
  44. import { setRequestingSubtitles } from '../../subtitles/actions.any';
  45. import { muteLocal } from '../../video-menu/actions';
  46. import { ENTER_PICTURE_IN_PICTURE } from '../picture-in-picture/actionTypes';
  47. import { READY_TO_CLOSE } from './actionTypes';
  48. import { setParticipantsWithScreenShare } from './actions';
  49. import { sendEvent } from './functions';
  50. import logger from './logger';
  51. /**
  52. * Event which will be emitted on the native side when a chat message is received
  53. * through the channel.
  54. */
  55. const CHAT_MESSAGE_RECEIVED = 'CHAT_MESSAGE_RECEIVED';
  56. /**
  57. * Event which will be emitted on the native side when the chat dialog is displayed/closed.
  58. */
  59. const CHAT_TOGGLED = 'CHAT_TOGGLED';
  60. /**
  61. * Event which will be emitted on the native side to indicate the conference
  62. * has ended either by user request or because an error was produced.
  63. */
  64. const CONFERENCE_TERMINATED = 'CONFERENCE_TERMINATED';
  65. /**
  66. * Event which will be emitted on the native side to indicate a message was received
  67. * through the channel.
  68. */
  69. const ENDPOINT_TEXT_MESSAGE_RECEIVED = 'ENDPOINT_TEXT_MESSAGE_RECEIVED';
  70. /**
  71. * Event which will be emitted on the native side to indicate a participant togggles
  72. * the screen share.
  73. */
  74. const SCREEN_SHARE_TOGGLED = 'SCREEN_SHARE_TOGGLED';
  75. /**
  76. * Event which will be emitted on the native side with the participant info array.
  77. */
  78. const PARTICIPANTS_INFO_RETRIEVED = 'PARTICIPANTS_INFO_RETRIEVED';
  79. const { ExternalAPI } = NativeModules;
  80. const eventEmitter = new NativeEventEmitter(ExternalAPI);
  81. /**
  82. * Middleware that captures Redux actions and uses the ExternalAPI module to
  83. * turn them into native events so the application knows about them.
  84. *
  85. * @param {Store} store - Redux store.
  86. * @returns {Function}
  87. */
  88. MiddlewareRegistry.register(store => next => action => {
  89. const oldAudioMuted = store.getState()['features/base/media'].audio.muted;
  90. const result = next(action);
  91. const { type } = action;
  92. switch (type) {
  93. case APP_WILL_MOUNT:
  94. _registerForNativeEvents(store);
  95. break;
  96. case APP_WILL_UNMOUNT:
  97. _unregisterForNativeEvents();
  98. break;
  99. case CONFERENCE_FAILED: {
  100. const { error, ...data } = action;
  101. // XXX Certain CONFERENCE_FAILED errors are recoverable i.e. they have
  102. // prevented the user from joining a specific conference but the app may
  103. // be able to eventually join the conference. For example, the app will
  104. // ask the user for a password upon
  105. // JitsiConferenceErrors.PASSWORD_REQUIRED and will retry joining the
  106. // conference afterwards. Such errors are to not reach the native
  107. // counterpart of the External API (or at least not in the
  108. // fatality/finality semantics attributed to
  109. // conferenceFailed:/onConferenceFailed).
  110. if (!error.recoverable) {
  111. _sendConferenceEvent(store, /* action */ {
  112. error: _toErrorString(error),
  113. ...data
  114. });
  115. }
  116. break;
  117. }
  118. case CONFERENCE_LEFT:
  119. _sendConferenceEvent(store, action);
  120. break;
  121. case CONFERENCE_JOINED:
  122. _sendConferenceEvent(store, action);
  123. _registerForEndpointTextMessages(store);
  124. break;
  125. case CONNECTION_DISCONNECTED: {
  126. // FIXME: This is a hack. See the description in the JITSI_CONNECTION_CONFERENCE_KEY constant definition.
  127. // Check if this connection was attached to any conference. If it wasn't, fake a CONFERENCE_TERMINATED event.
  128. const { connection } = action;
  129. const conference = connection[JITSI_CONNECTION_CONFERENCE_KEY];
  130. if (!conference) {
  131. // This action will arrive late, so the locationURL stored on the state is no longer valid.
  132. const locationURL = connection[JITSI_CONNECTION_URL_KEY];
  133. sendEvent(
  134. store,
  135. CONFERENCE_TERMINATED,
  136. /* data */ {
  137. url: _normalizeUrl(locationURL)
  138. });
  139. }
  140. break;
  141. }
  142. case ENTER_PICTURE_IN_PICTURE:
  143. sendEvent(store, type, /* data */ {});
  144. break;
  145. case OPEN_CHAT:
  146. case CLOSE_CHAT: {
  147. sendEvent(
  148. store,
  149. CHAT_TOGGLED,
  150. /* data */ {
  151. isOpen: action.type === OPEN_CHAT
  152. });
  153. break;
  154. }
  155. case PARTICIPANT_JOINED:
  156. case PARTICIPANT_LEFT: {
  157. // Skip these events while not in a conference. SDK users can still retrieve them.
  158. const { conference } = store.getState()['features/base/conference'];
  159. if (!conference) {
  160. break;
  161. }
  162. const { participant } = action;
  163. if (isScreenShareParticipant(participant)) {
  164. break;
  165. }
  166. sendEvent(
  167. store,
  168. action.type,
  169. _participantToParticipantInfo(participant) /* data */
  170. );
  171. break;
  172. }
  173. case READY_TO_CLOSE:
  174. sendEvent(store, type, /* data */ {});
  175. break;
  176. case SET_ROOM:
  177. _maybeTriggerEarlyConferenceWillJoin(store, action);
  178. break;
  179. case SET_AUDIO_MUTED:
  180. if (action.muted !== oldAudioMuted) {
  181. sendEvent(
  182. store,
  183. 'AUDIO_MUTED_CHANGED',
  184. /* data */ {
  185. muted: action.muted
  186. });
  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.fakeParticipant) {
  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. eventEmitter.addListener(ExternalAPI.SET_CLOSED_CAPTIONS_ENABLED, ({ enabled }) => {
  319. dispatch(setRequestingSubtitles(enabled));
  320. });
  321. }
  322. /**
  323. * Unregister for events sent from the native side via NativeEventEmitter.
  324. *
  325. * @private
  326. * @returns {void}
  327. */
  328. function _unregisterForNativeEvents() {
  329. eventEmitter.removeAllListeners(ExternalAPI.HANG_UP);
  330. eventEmitter.removeAllListeners(ExternalAPI.SET_AUDIO_MUTED);
  331. eventEmitter.removeAllListeners(ExternalAPI.SET_VIDEO_MUTED);
  332. eventEmitter.removeAllListeners(ExternalAPI.SEND_ENDPOINT_TEXT_MESSAGE);
  333. eventEmitter.removeAllListeners(ExternalAPI.TOGGLE_SCREEN_SHARE);
  334. eventEmitter.removeAllListeners(ExternalAPI.RETRIEVE_PARTICIPANTS_INFO);
  335. eventEmitter.removeAllListeners(ExternalAPI.OPEN_CHAT);
  336. eventEmitter.removeAllListeners(ExternalAPI.CLOSE_CHAT);
  337. eventEmitter.removeAllListeners(ExternalAPI.SEND_CHAT_MESSAGE);
  338. eventEmitter.removeAllListeners(ExternalAPI.SET_CLOSED_CAPTIONS_ENABLED);
  339. }
  340. /**
  341. * Registers for endpoint messages sent on conference data channel.
  342. *
  343. * @param {Store} store - The redux store.
  344. * @private
  345. * @returns {void}
  346. */
  347. function _registerForEndpointTextMessages(store) {
  348. const conference = getCurrentConference(store.getState());
  349. conference && conference.on(
  350. JitsiConferenceEvents.ENDPOINT_MESSAGE_RECEIVED,
  351. (...args) => {
  352. if (args && args.length >= 2) {
  353. const [ sender, eventData ] = args;
  354. if (eventData.name === ENDPOINT_TEXT_MESSAGE_NAME) {
  355. sendEvent(
  356. store,
  357. ENDPOINT_TEXT_MESSAGE_RECEIVED,
  358. /* data */ {
  359. message: eventData.text,
  360. senderId: sender._id
  361. });
  362. }
  363. }
  364. });
  365. conference.on(
  366. JitsiConferenceEvents.MESSAGE_RECEIVED,
  367. (id, message, timestamp) => {
  368. sendEvent(
  369. store,
  370. CHAT_MESSAGE_RECEIVED,
  371. /* data */ {
  372. senderId: id,
  373. message,
  374. isPrivate: false,
  375. timestamp
  376. });
  377. }
  378. );
  379. conference.on(
  380. JitsiConferenceEvents.PRIVATE_MESSAGE_RECEIVED,
  381. (id, message, timestamp) => {
  382. sendEvent(
  383. store,
  384. CHAT_MESSAGE_RECEIVED,
  385. /* data */ {
  386. senderId: id,
  387. message,
  388. isPrivate: true,
  389. timestamp
  390. });
  391. }
  392. );
  393. }
  394. /**
  395. * Returns a {@code String} representation of a specific error {@code Object}.
  396. *
  397. * @param {Error|Object|string} error - The error {@code Object} to return a
  398. * {@code String} representation of.
  399. * @returns {string} A {@code String} representation of the specified
  400. * {@code error}.
  401. */
  402. function _toErrorString(
  403. error: Error | { message: ?string, name: ?string } | string) {
  404. // XXX In lib-jitsi-meet and jitsi-meet we utilize errors in the form of
  405. // strings, Error instances, and plain objects which resemble Error.
  406. return (
  407. error
  408. ? typeof error === 'string'
  409. ? error
  410. : Error.prototype.toString.apply(error)
  411. : '');
  412. }
  413. /**
  414. * If {@link SET_ROOM} action happens for a valid conference room this method
  415. * will emit an early {@link CONFERENCE_WILL_JOIN} event to let the external API
  416. * know that a conference is being joined. Before that happens a connection must
  417. * be created and only then base/conference feature would emit
  418. * {@link CONFERENCE_WILL_JOIN}. That is fine for the Jitsi Meet app, because
  419. * that's the a conference instance gets created, but it's too late for
  420. * the external API to learn that. The latter {@link CONFERENCE_WILL_JOIN} is
  421. * swallowed in {@link _swallowEvent}.
  422. *
  423. * @param {Store} store - The redux store.
  424. * @param {Action} action - The redux action.
  425. * @returns {void}
  426. */
  427. function _maybeTriggerEarlyConferenceWillJoin(store, action) {
  428. const { locationURL } = store.getState()['features/base/connection'];
  429. const { room } = action;
  430. isRoomValid(room) && locationURL && sendEvent(
  431. store,
  432. CONFERENCE_WILL_JOIN,
  433. /* data */ {
  434. url: _normalizeUrl(locationURL)
  435. });
  436. }
  437. /**
  438. * Normalizes the given URL for presentation over the external API.
  439. *
  440. * @param {URL} url -The URL to normalize.
  441. * @returns {string} - The normalized URL as a string.
  442. */
  443. function _normalizeUrl(url: URL) {
  444. return getURLWithoutParams(url).href;
  445. }
  446. /**
  447. * Sends an event to the native counterpart of the External API for a specific
  448. * conference-related redux action.
  449. *
  450. * @param {Store} store - The redux store.
  451. * @param {Action} action - The redux action.
  452. * @returns {void}
  453. */
  454. function _sendConferenceEvent(
  455. store: Object,
  456. action: {
  457. conference: Object,
  458. type: string,
  459. url: ?string
  460. }) {
  461. const { conference, type, ...data } = action;
  462. // For these (redux) actions, conference identifies a JitsiConference
  463. // instance. The external API cannot transport such an object so we have to
  464. // transport an "equivalent".
  465. if (conference) {
  466. data.url = _normalizeUrl(conference[JITSI_CONFERENCE_URL_KEY]);
  467. const localTracks = getLocalTracks(store.getState()['features/base/tracks']);
  468. const isAudioMuted = isLocalTrackMuted(localTracks, MEDIA_TYPE.AUDIO);
  469. data.isAudioMuted = isAudioMuted;
  470. }
  471. if (_swallowEvent(store, action, data)) {
  472. return;
  473. }
  474. let type_;
  475. switch (type) {
  476. case CONFERENCE_FAILED:
  477. case CONFERENCE_LEFT:
  478. type_ = CONFERENCE_TERMINATED;
  479. break;
  480. default:
  481. type_ = type;
  482. break;
  483. }
  484. sendEvent(store, type_, data);
  485. }
  486. /**
  487. * Determines whether to not send a {@code CONFERENCE_LEFT} event to the native
  488. * counterpart of the External API.
  489. *
  490. * @param {Object} store - The redux store.
  491. * @param {Action} action - The redux action which is causing the sending of the
  492. * event.
  493. * @param {Object} data - The details/specifics of the event to send determined
  494. * by/associated with the specified {@code action}.
  495. * @returns {boolean} If the specified event is to not be sent, {@code true};
  496. * otherwise, {@code false}.
  497. */
  498. function _swallowConferenceLeft({ getState }, action, { url }) {
  499. // XXX Internally, we work with JitsiConference instances. Externally
  500. // though, we deal with URL strings. The relation between the two is many to
  501. // one so it's technically and practically possible (by externally loading
  502. // the same URL string multiple times) to try to send CONFERENCE_LEFT
  503. // externally for a URL string which identifies a JitsiConference that the
  504. // app is internally legitimately working with.
  505. let swallowConferenceLeft = false;
  506. url
  507. && forEachConference(getState, (conference, conferenceURL) => {
  508. if (conferenceURL && conferenceURL.toString() === url) {
  509. swallowConferenceLeft = true;
  510. }
  511. return !swallowConferenceLeft;
  512. });
  513. return swallowConferenceLeft;
  514. }
  515. /**
  516. * Determines whether to not send a specific event to the native counterpart of
  517. * the External API.
  518. *
  519. * @param {Object} store - The redux store.
  520. * @param {Action} action - The redux action which is causing the sending of the
  521. * event.
  522. * @param {Object} data - The details/specifics of the event to send determined
  523. * by/associated with the specified {@code action}.
  524. * @returns {boolean} If the specified event is to not be sent, {@code true};
  525. * otherwise, {@code false}.
  526. */
  527. function _swallowEvent(store, action, data) {
  528. switch (action.type) {
  529. case CONFERENCE_LEFT:
  530. return _swallowConferenceLeft(store, action, data);
  531. default:
  532. return false;
  533. }
  534. }