選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

middleware.ts 20KB

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