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

middleware.js 20KB

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