You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

middleware.js 13KB

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