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

middleware.js 18KB

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