Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

middleware.js 20KB

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