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

middleware.js 19KB

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