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

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