Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

middleware.js 19KB

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