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

middleware.js 15KB

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