您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

middleware.js 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  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 { LOAD_CONFIG_ERROR } from '../../base/config';
  19. import {
  20. CONNECTION_DISCONNECTED,
  21. CONNECTION_FAILED,
  22. JITSI_CONNECTION_CONFERENCE_KEY,
  23. JITSI_CONNECTION_URL_KEY,
  24. getURLWithoutParams
  25. } from '../../base/connection';
  26. import { JitsiConferenceEvents } from '../../base/lib-jitsi-meet';
  27. import { MEDIA_TYPE } from '../../base/media';
  28. import { SET_AUDIO_MUTED, SET_VIDEO_MUTED } from '../../base/media/actionTypes';
  29. import {
  30. PARTICIPANT_JOINED,
  31. PARTICIPANT_LEFT,
  32. getParticipantById,
  33. getRemoteParticipants,
  34. getLocalParticipant
  35. } from '../../base/participants';
  36. import { MiddlewareRegistry, StateListenerRegistry } from '../../base/redux';
  37. import { toggleScreensharing } from '../../base/tracks';
  38. import { OPEN_CHAT, CLOSE_CHAT } from '../../chat';
  39. import { openChat } from '../../chat/actions';
  40. import { sendMessage, setPrivateMessageRecipient, closeChat } from '../../chat/actions.any';
  41. import { muteLocal } from '../../video-menu/actions';
  42. import { ENTER_PICTURE_IN_PICTURE } from '../picture-in-picture';
  43. import { setParticipantsWithScreenShare } from './actions';
  44. import { sendEvent } from './functions';
  45. import logger from './logger';
  46. /**
  47. * Event which will be emitted on the native side when a chat message is received
  48. * through the channel.
  49. */
  50. const CHAT_MESSAGE_RECEIVED = 'CHAT_MESSAGE_RECEIVED';
  51. /**
  52. * Event which will be emitted on the native side when the chat dialog is displayed/closed.
  53. */
  54. const CHAT_TOGGLED = 'CHAT_TOGGLED';
  55. /**
  56. * Event which will be emitted on the native side to indicate the conference
  57. * has ended either by user request or because an error was produced.
  58. */
  59. const CONFERENCE_TERMINATED = 'CONFERENCE_TERMINATED';
  60. /**
  61. * Event which will be emitted on the native side to indicate a message was received
  62. * through the channel.
  63. */
  64. const ENDPOINT_TEXT_MESSAGE_RECEIVED = 'ENDPOINT_TEXT_MESSAGE_RECEIVED';
  65. /**
  66. * Event which will be emitted on the native side to indicate a participant togggles
  67. * the screen share.
  68. */
  69. const SCREEN_SHARE_TOGGLED = 'SCREEN_SHARE_TOGGLED';
  70. /**
  71. * Event which will be emitted on the native side with the participant info array.
  72. */
  73. const PARTICIPANTS_INFO_RETRIEVED = 'PARTICIPANTS_INFO_RETRIEVED';
  74. const { ExternalAPI } = NativeModules;
  75. const eventEmitter = new NativeEventEmitter(ExternalAPI);
  76. /**
  77. * Middleware that captures Redux actions and uses the ExternalAPI module to
  78. * turn them into native events so the application knows about them.
  79. *
  80. * @param {Store} store - Redux store.
  81. * @returns {Function}
  82. */
  83. MiddlewareRegistry.register(store => next => action => {
  84. const result = next(action);
  85. const { type } = action;
  86. switch (type) {
  87. case APP_WILL_MOUNT:
  88. _registerForNativeEvents(store);
  89. break;
  90. case APP_WILL_UNMOUNT:
  91. _unregisterForNativeEvents();
  92. break;
  93. case CONFERENCE_FAILED: {
  94. const { error, ...data } = action;
  95. // XXX Certain CONFERENCE_FAILED errors are recoverable i.e. they have
  96. // prevented the user from joining a specific conference but the app may
  97. // be able to eventually join the conference. For example, the app will
  98. // ask the user for a password upon
  99. // JitsiConferenceErrors.PASSWORD_REQUIRED and will retry joining the
  100. // conference afterwards. Such errors are to not reach the native
  101. // counterpart of the External API (or at least not in the
  102. // fatality/finality semantics attributed to
  103. // conferenceFailed:/onConferenceFailed).
  104. if (!error.recoverable) {
  105. _sendConferenceEvent(store, /* action */ {
  106. error: _toErrorString(error),
  107. ...data
  108. });
  109. }
  110. break;
  111. }
  112. case CONFERENCE_LEFT:
  113. case CONFERENCE_WILL_JOIN:
  114. _sendConferenceEvent(store, action);
  115. break;
  116. case CONFERENCE_JOINED:
  117. _sendConferenceEvent(store, action);
  118. _registerForEndpointTextMessages(store);
  119. break;
  120. case CONNECTION_DISCONNECTED: {
  121. // FIXME: This is a hack. See the description in the JITSI_CONNECTION_CONFERENCE_KEY constant definition.
  122. // Check if this connection was attached to any conference. If it wasn't, fake a CONFERENCE_TERMINATED event.
  123. const { connection } = action;
  124. const conference = connection[JITSI_CONNECTION_CONFERENCE_KEY];
  125. if (!conference) {
  126. // This action will arrive late, so the locationURL stored on the state is no longer valid.
  127. const locationURL = connection[JITSI_CONNECTION_URL_KEY];
  128. sendEvent(
  129. store,
  130. CONFERENCE_TERMINATED,
  131. /* data */ {
  132. url: _normalizeUrl(locationURL)
  133. });
  134. }
  135. break;
  136. }
  137. case CONNECTION_FAILED:
  138. !action.error.recoverable
  139. && _sendConferenceFailedOnConnectionError(store, action);
  140. break;
  141. case ENTER_PICTURE_IN_PICTURE:
  142. sendEvent(store, type, /* data */ {});
  143. break;
  144. case LOAD_CONFIG_ERROR: {
  145. const { error, locationURL } = action;
  146. sendEvent(
  147. store,
  148. CONFERENCE_TERMINATED,
  149. /* data */ {
  150. error: _toErrorString(error),
  151. url: _normalizeUrl(locationURL)
  152. });
  153. break;
  154. }
  155. case OPEN_CHAT:
  156. case CLOSE_CHAT: {
  157. sendEvent(
  158. store,
  159. CHAT_TOGGLED,
  160. /* data */ {
  161. isOpen: action.type === OPEN_CHAT
  162. });
  163. break;
  164. }
  165. case PARTICIPANT_JOINED:
  166. case PARTICIPANT_LEFT: {
  167. // Skip these events while not in a conference. SDK users can still retrieve them.
  168. const { conference } = store.getState()['features/base/conference'];
  169. if (!conference) {
  170. break;
  171. }
  172. const { participant } = action;
  173. sendEvent(
  174. store,
  175. action.type,
  176. _participantToParticipantInfo(participant) /* data */
  177. );
  178. break;
  179. }
  180. case SET_ROOM:
  181. _maybeTriggerEarlyConferenceWillJoin(store, action);
  182. break;
  183. case SET_AUDIO_MUTED:
  184. sendEvent(
  185. store,
  186. 'AUDIO_MUTED_CHANGED',
  187. /* data */ {
  188. muted: action.muted
  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. * Sends {@link CONFERENCE_TERMINATED} event when the {@link CONNECTION_FAILED}
  483. * occurs. It should be done only if the connection fails before the conference
  484. * instance is created. Otherwise the eventual failure event is supposed to be
  485. * emitted by the base/conference feature.
  486. *
  487. * @param {Store} store - The redux store.
  488. * @param {Action} action - The redux action.
  489. * @returns {void}
  490. */
  491. function _sendConferenceFailedOnConnectionError(store, action) {
  492. const { locationURL } = store.getState()['features/base/connection'];
  493. const { connection } = action;
  494. locationURL
  495. && forEachConference(
  496. store,
  497. // If there's any conference in the base/conference state then the
  498. // base/conference feature is supposed to emit a failure.
  499. conference => conference.getConnection() !== connection)
  500. && sendEvent(
  501. store,
  502. CONFERENCE_TERMINATED,
  503. /* data */ {
  504. url: _normalizeUrl(locationURL),
  505. error: action.error.name
  506. });
  507. }
  508. /**
  509. * Determines whether to not send a {@code CONFERENCE_LEFT} event to the native
  510. * counterpart of the External API.
  511. *
  512. * @param {Object} store - The redux store.
  513. * @param {Action} action - The redux action which is causing the sending of the
  514. * event.
  515. * @param {Object} data - The details/specifics of the event to send determined
  516. * by/associated with the specified {@code action}.
  517. * @returns {boolean} If the specified event is to not be sent, {@code true};
  518. * otherwise, {@code false}.
  519. */
  520. function _swallowConferenceLeft({ getState }, action, { url }) {
  521. // XXX Internally, we work with JitsiConference instances. Externally
  522. // though, we deal with URL strings. The relation between the two is many to
  523. // one so it's technically and practically possible (by externally loading
  524. // the same URL string multiple times) to try to send CONFERENCE_LEFT
  525. // externally for a URL string which identifies a JitsiConference that the
  526. // app is internally legitimately working with.
  527. let swallowConferenceLeft = false;
  528. url
  529. && forEachConference(getState, (conference, conferenceURL) => {
  530. if (conferenceURL && conferenceURL.toString() === url) {
  531. swallowConferenceLeft = true;
  532. }
  533. return !swallowConferenceLeft;
  534. });
  535. return swallowConferenceLeft;
  536. }
  537. /**
  538. * Determines whether to not send a specific event to the native counterpart of
  539. * the External API.
  540. *
  541. * @param {Object} store - The redux store.
  542. * @param {Action} action - The redux action which is causing the sending of the
  543. * event.
  544. * @param {Object} data - The details/specifics of the event to send determined
  545. * by/associated with the specified {@code action}.
  546. * @returns {boolean} If the specified event is to not be sent, {@code true};
  547. * otherwise, {@code false}.
  548. */
  549. function _swallowEvent(store, action, data) {
  550. switch (action.type) {
  551. case CONFERENCE_LEFT:
  552. return _swallowConferenceLeft(store, action, data);
  553. case CONFERENCE_WILL_JOIN:
  554. // CONFERENCE_WILL_JOIN is dispatched to the external API on SET_ROOM,
  555. // before the connection is created, so we need to swallow the original
  556. // one emitted by base/conference.
  557. return true;
  558. default:
  559. return false;
  560. }
  561. }