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

middleware.js 20KB

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