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.ts 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  1. import { AnyAction } from 'redux';
  2. import { IReduxState, IStore } from '../app/types';
  3. import { APP_WILL_MOUNT, APP_WILL_UNMOUNT } from '../base/app/actionTypes';
  4. import {
  5. CONFERENCE_JOINED,
  6. ENDPOINT_MESSAGE_RECEIVED,
  7. NON_PARTICIPANT_MESSAGE_RECEIVED
  8. } from '../base/conference/actionTypes';
  9. import { getCurrentConference } from '../base/conference/functions';
  10. import { IJitsiConference } from '../base/conference/reducer';
  11. import { openDialog } from '../base/dialog/actions';
  12. import i18next from '../base/i18n/i18next';
  13. import {
  14. JitsiConferenceErrors,
  15. JitsiConferenceEvents
  16. } from '../base/lib-jitsi-meet';
  17. import {
  18. getLocalParticipant,
  19. getParticipantById,
  20. getParticipantDisplayName
  21. } from '../base/participants/functions';
  22. import MiddlewareRegistry from '../base/redux/MiddlewareRegistry';
  23. import StateListenerRegistry from '../base/redux/StateListenerRegistry';
  24. import { playSound, registerSound, unregisterSound } from '../base/sounds/actions';
  25. import { addGif } from '../gifs/actions';
  26. import { GIF_PREFIX } from '../gifs/constants';
  27. import { getGifDisplayMode, isGifMessage } from '../gifs/function.any';
  28. import { showMessageNotification } from '../notifications/actions';
  29. import { NOTIFICATION_TIMEOUT_TYPE } from '../notifications/constants';
  30. import { resetNbUnreadPollsMessages } from '../polls/actions';
  31. import { ADD_REACTION_MESSAGE } from '../reactions/actionTypes';
  32. import { pushReactions } from '../reactions/actions.any';
  33. import { ENDPOINT_REACTION_NAME } from '../reactions/constants';
  34. import { getReactionMessageFromBuffer, isReactionsEnabled } from '../reactions/functions.any';
  35. import { showToolbox } from '../toolbox/actions';
  36. import { ADD_MESSAGE, CLOSE_CHAT, OPEN_CHAT, SEND_MESSAGE, SET_IS_POLL_TAB_FOCUSED } from './actionTypes';
  37. import { addMessage, clearMessages, closeChat } from './actions.any';
  38. import { ChatPrivacyDialog } from './components';
  39. import {
  40. INCOMING_MSG_SOUND_ID,
  41. LOBBY_CHAT_MESSAGE,
  42. MESSAGE_TYPE_ERROR,
  43. MESSAGE_TYPE_LOCAL,
  44. MESSAGE_TYPE_REMOTE,
  45. MESSAGE_TYPE_SYSTEM
  46. } from './constants';
  47. import { getUnreadCount } from './functions';
  48. import { INCOMING_MSG_SOUND_FILE } from './sounds';
  49. /**
  50. * Timeout for when to show the privacy notice after a private message was received.
  51. *
  52. * E.g. If this value is 20 secs (20000ms), then we show the privacy notice when sending a non private
  53. * message after we have received a private message in the last 20 seconds.
  54. */
  55. const PRIVACY_NOTICE_TIMEOUT = 20 * 1000;
  56. /**
  57. * Implements the middleware of the chat feature.
  58. *
  59. * @param {Store} store - The redux store.
  60. * @returns {Function}
  61. */
  62. MiddlewareRegistry.register(store => next => action => {
  63. const { dispatch, getState } = store;
  64. const localParticipant = getLocalParticipant(getState());
  65. let isOpen, unreadCount;
  66. switch (action.type) {
  67. case ADD_MESSAGE:
  68. unreadCount = getUnreadCount(getState());
  69. if (action.isReaction) {
  70. action.hasRead = false;
  71. } else {
  72. unreadCount = action.hasRead ? 0 : unreadCount + 1;
  73. }
  74. isOpen = getState()['features/chat'].isOpen;
  75. if (typeof APP !== 'undefined') {
  76. APP.API.notifyChatUpdated(unreadCount, isOpen);
  77. }
  78. break;
  79. case APP_WILL_MOUNT:
  80. dispatch(
  81. registerSound(INCOMING_MSG_SOUND_ID, INCOMING_MSG_SOUND_FILE));
  82. break;
  83. case APP_WILL_UNMOUNT:
  84. dispatch(unregisterSound(INCOMING_MSG_SOUND_ID));
  85. break;
  86. case CONFERENCE_JOINED:
  87. _addChatMsgListener(action.conference, store);
  88. break;
  89. case CLOSE_CHAT: {
  90. const isPollTabOpen = getState()['features/chat'].isPollsTabFocused;
  91. unreadCount = 0;
  92. if (typeof APP !== 'undefined') {
  93. APP.API.notifyChatUpdated(unreadCount, false);
  94. }
  95. if (isPollTabOpen) {
  96. dispatch(resetNbUnreadPollsMessages());
  97. }
  98. break;
  99. }
  100. case ENDPOINT_MESSAGE_RECEIVED: {
  101. const state = store.getState();
  102. if (!isReactionsEnabled(state)) {
  103. return next(action);
  104. }
  105. const { participant, data } = action;
  106. if (data?.name === ENDPOINT_REACTION_NAME) {
  107. store.dispatch(pushReactions(data.reactions));
  108. _handleReceivedMessage(store, {
  109. participantId: participant.getId(),
  110. message: getReactionMessageFromBuffer(data.reactions),
  111. privateMessage: false,
  112. lobbyChat: false,
  113. timestamp: data.timestamp
  114. }, false, true);
  115. }
  116. break;
  117. }
  118. case NON_PARTICIPANT_MESSAGE_RECEIVED: {
  119. const { participantId, json: data } = action;
  120. if (data?.type === MESSAGE_TYPE_SYSTEM && data.message) {
  121. _handleReceivedMessage(store, {
  122. displayName: data.displayName ?? i18next.t('chat.systemDisplayName'),
  123. participantId,
  124. lobbyChat: false,
  125. message: data.message,
  126. privateMessage: true,
  127. timestamp: Date.now()
  128. });
  129. }
  130. break;
  131. }
  132. case OPEN_CHAT:
  133. unreadCount = 0;
  134. if (typeof APP !== 'undefined') {
  135. APP.API.notifyChatUpdated(unreadCount, true);
  136. }
  137. break;
  138. case SET_IS_POLL_TAB_FOCUSED: {
  139. dispatch(resetNbUnreadPollsMessages());
  140. break;
  141. }
  142. case SEND_MESSAGE: {
  143. const state = store.getState();
  144. const conference = getCurrentConference(state);
  145. if (conference) {
  146. // There may be cases when we intend to send a private message but we forget to set the
  147. // recipient. This logic tries to mitigate this risk.
  148. const shouldSendPrivateMessageTo = _shouldSendPrivateMessageTo(state, action);
  149. const participantExists = shouldSendPrivateMessageTo
  150. && getParticipantById(state, shouldSendPrivateMessageTo);
  151. if (shouldSendPrivateMessageTo && participantExists) {
  152. dispatch(openDialog(ChatPrivacyDialog, {
  153. message: action.message,
  154. participantID: shouldSendPrivateMessageTo
  155. }));
  156. } else {
  157. // Sending the message if privacy notice doesn't need to be shown.
  158. const { privateMessageRecipient, isLobbyChatActive, lobbyMessageRecipient }
  159. = state['features/chat'];
  160. if (typeof APP !== 'undefined') {
  161. APP.API.notifySendingChatMessage(action.message, Boolean(privateMessageRecipient));
  162. }
  163. if (isLobbyChatActive && lobbyMessageRecipient) {
  164. conference.sendLobbyMessage({
  165. type: LOBBY_CHAT_MESSAGE,
  166. message: action.message
  167. }, lobbyMessageRecipient.id);
  168. _persistSentPrivateMessage(store, lobbyMessageRecipient.id, action.message, true);
  169. } else if (privateMessageRecipient) {
  170. conference.sendPrivateTextMessage(privateMessageRecipient.id, action.message);
  171. _persistSentPrivateMessage(store, privateMessageRecipient.id, action.message);
  172. } else {
  173. conference.sendTextMessage(action.message);
  174. }
  175. }
  176. }
  177. break;
  178. }
  179. case ADD_REACTION_MESSAGE: {
  180. if (localParticipant?.id) {
  181. _handleReceivedMessage(store, {
  182. participantId: localParticipant.id,
  183. message: action.message,
  184. privateMessage: false,
  185. timestamp: Date.now(),
  186. lobbyChat: false
  187. }, false, true);
  188. }
  189. }
  190. }
  191. return next(action);
  192. });
  193. /**
  194. * Set up state change listener to perform maintenance tasks when the conference
  195. * is left or failed, e.g. Clear messages or close the chat modal if it's left
  196. * open.
  197. */
  198. StateListenerRegistry.register(
  199. state => getCurrentConference(state),
  200. (conference, { dispatch, getState }, previousConference) => {
  201. if (conference !== previousConference) {
  202. // conference changed, left or failed...
  203. if (getState()['features/chat'].isOpen) {
  204. // Closes the chat if it's left open.
  205. dispatch(closeChat());
  206. }
  207. // Clear chat messages.
  208. dispatch(clearMessages());
  209. }
  210. });
  211. StateListenerRegistry.register(
  212. state => state['features/chat'].isOpen,
  213. (isOpen, { dispatch }) => {
  214. if (typeof APP !== 'undefined' && isOpen) {
  215. dispatch(showToolbox());
  216. }
  217. }
  218. );
  219. /**
  220. * Registers listener for {@link JitsiConferenceEvents.MESSAGE_RECEIVED} that
  221. * will perform various chat related activities.
  222. *
  223. * @param {JitsiConference} conference - The conference instance on which the
  224. * new event listener will be registered.
  225. * @param {Object} store - The redux store object.
  226. * @private
  227. * @returns {void}
  228. */
  229. function _addChatMsgListener(conference: IJitsiConference, store: IStore) {
  230. if (store.getState()['features/base/config'].iAmRecorder) {
  231. // We don't register anything on web if we are in iAmRecorder mode
  232. return;
  233. }
  234. conference.on(
  235. JitsiConferenceEvents.MESSAGE_RECEIVED,
  236. /* eslint-disable max-params */
  237. (participantId: string, message: string, timestamp: number,
  238. displayName: string, isGuest: boolean, messageId: string) => {
  239. /* eslint-enable max-params */
  240. _onConferenceMessageReceived(store, {
  241. // in case of messages coming from visitors we can have unknown id
  242. participantId: participantId || displayName,
  243. message,
  244. timestamp,
  245. displayName,
  246. isGuest,
  247. messageId,
  248. privateMessage: false });
  249. }
  250. );
  251. conference.on(
  252. JitsiConferenceEvents.PRIVATE_MESSAGE_RECEIVED,
  253. (participantId: string, message: string, timestamp: number, messageId: string) => {
  254. _onConferenceMessageReceived(store, {
  255. participantId,
  256. message,
  257. timestamp,
  258. messageId,
  259. privateMessage: true
  260. });
  261. }
  262. );
  263. conference.on(
  264. JitsiConferenceEvents.CONFERENCE_ERROR, (errorType: string, error: Error) => {
  265. errorType === JitsiConferenceErrors.CHAT_ERROR && _handleChatError(store, error);
  266. });
  267. }
  268. /**
  269. * Handles a received message.
  270. *
  271. * @param {Object} store - Redux store.
  272. * @param {Object} message - The message object.
  273. * @returns {void}
  274. */
  275. function _onConferenceMessageReceived(store: IStore,
  276. { displayName, isGuest, message, messageId, participantId, privateMessage, timestamp }: {
  277. displayName?: string; isGuest?: boolean; message: string; messageId?: string;
  278. participantId: string; privateMessage: boolean; timestamp: number; }
  279. ) {
  280. const isGif = isGifMessage(message);
  281. if (isGif) {
  282. _handleGifMessageReceived(store, participantId, message);
  283. if (getGifDisplayMode(store.getState()) === 'tile') {
  284. return;
  285. }
  286. }
  287. _handleReceivedMessage(store, {
  288. displayName,
  289. isGuest,
  290. participantId,
  291. message,
  292. privateMessage,
  293. lobbyChat: false,
  294. timestamp,
  295. messageId
  296. }, true, isGif);
  297. }
  298. /**
  299. * Handles a received gif message.
  300. *
  301. * @param {Object} store - Redux store.
  302. * @param {string} participantId - Id of the participant that sent the message.
  303. * @param {string} message - The message sent.
  304. * @returns {void}
  305. */
  306. function _handleGifMessageReceived(store: IStore, participantId: string, message: string) {
  307. const url = message.substring(GIF_PREFIX.length, message.length - 1);
  308. store.dispatch(addGif(participantId, url));
  309. }
  310. /**
  311. * Handles a chat error received from the xmpp server.
  312. *
  313. * @param {Store} store - The Redux store.
  314. * @param {string} error - The error message.
  315. * @returns {void}
  316. */
  317. function _handleChatError({ dispatch }: IStore, error: Error) {
  318. dispatch(addMessage({
  319. hasRead: true,
  320. messageType: MESSAGE_TYPE_ERROR,
  321. message: error,
  322. privateMessage: false,
  323. timestamp: Date.now()
  324. }));
  325. }
  326. /**
  327. * Function to handle an incoming chat message from lobby room.
  328. *
  329. * @param {string} message - The message received.
  330. * @param {string} participantId - The participant id.
  331. * @returns {Function}
  332. */
  333. export function handleLobbyMessageReceived(message: string, participantId: string) {
  334. return async (dispatch: IStore['dispatch'], getState: IStore['getState']) => {
  335. _handleReceivedMessage({ dispatch,
  336. getState }, { participantId,
  337. message,
  338. privateMessage: false,
  339. lobbyChat: true,
  340. timestamp: Date.now() });
  341. };
  342. }
  343. /**
  344. * Function to get lobby chat user display name.
  345. *
  346. * @param {Store} state - The Redux store.
  347. * @param {string} participantId - The knocking participant id.
  348. * @returns {string}
  349. */
  350. function getLobbyChatDisplayName(state: IReduxState, participantId: string) {
  351. const { knockingParticipants } = state['features/lobby'];
  352. const { lobbyMessageRecipient } = state['features/chat'];
  353. if (participantId === lobbyMessageRecipient?.id) {
  354. return lobbyMessageRecipient.name;
  355. }
  356. const knockingParticipant = knockingParticipants.find(p => p.id === participantId);
  357. if (knockingParticipant) {
  358. return knockingParticipant.name;
  359. }
  360. }
  361. /**
  362. * Function to handle an incoming chat message.
  363. *
  364. * @param {Store} store - The Redux store.
  365. * @param {Object} message - The message object.
  366. * @param {boolean} shouldPlaySound - Whether to play the incoming message sound.
  367. * @param {boolean} isReaction - Whether the message is a reaction message.
  368. * @returns {void}
  369. */
  370. function _handleReceivedMessage({ dispatch, getState }: IStore,
  371. { displayName, isGuest, lobbyChat, message, messageId, participantId, privateMessage, timestamp }: {
  372. displayName?: string; isGuest?: boolean; lobbyChat: boolean; message: string;
  373. messageId?: string; participantId: string; privateMessage: boolean; timestamp: number; },
  374. shouldPlaySound = true,
  375. isReaction = false
  376. ) {
  377. // Logic for all platforms:
  378. const state = getState();
  379. const { isOpen: isChatOpen } = state['features/chat'];
  380. const { soundsIncomingMessage: soundEnabled, userSelectedNotifications } = state['features/base/settings'];
  381. if (soundEnabled && shouldPlaySound && !isChatOpen) {
  382. dispatch(playSound(INCOMING_MSG_SOUND_ID));
  383. }
  384. // Provide a default for the case when a message is being
  385. // backfilled for a participant that has left the conference.
  386. const participant = getParticipantById(state, participantId) || { local: undefined };
  387. const localParticipant = getLocalParticipant(getState);
  388. let displayNameToShow = lobbyChat
  389. ? getLobbyChatDisplayName(state, participantId)
  390. : displayName || getParticipantDisplayName(state, participantId);
  391. const hasRead = participant.local || isChatOpen;
  392. const timestampToDate = timestamp ? new Date(timestamp) : new Date();
  393. const millisecondsTimestamp = timestampToDate.getTime();
  394. // skip message notifications on join (the messages having timestamp - coming from the history)
  395. const shouldShowNotification = userSelectedNotifications?.['notify.chatMessages']
  396. && !hasRead && !isReaction && !timestamp;
  397. if (isGuest) {
  398. displayNameToShow = `${displayNameToShow} ${i18next.t('visitors.chatIndicator')}`;
  399. }
  400. dispatch(addMessage({
  401. displayName: displayNameToShow,
  402. hasRead,
  403. participantId,
  404. messageType: participant.local ? MESSAGE_TYPE_LOCAL : MESSAGE_TYPE_REMOTE,
  405. message,
  406. privateMessage,
  407. lobbyChat,
  408. recipient: getParticipantDisplayName(state, localParticipant?.id ?? ''),
  409. timestamp: millisecondsTimestamp,
  410. messageId,
  411. isReaction
  412. }));
  413. if (shouldShowNotification) {
  414. dispatch(showMessageNotification({
  415. title: displayNameToShow,
  416. description: message
  417. }, NOTIFICATION_TIMEOUT_TYPE.MEDIUM));
  418. }
  419. if (typeof APP !== 'undefined') {
  420. // Logic for web only:
  421. APP.API.notifyReceivedChatMessage({
  422. body: message,
  423. from: participantId,
  424. nick: displayNameToShow,
  425. privateMessage,
  426. ts: timestamp
  427. });
  428. }
  429. }
  430. /**
  431. * Persists the sent private messages as if they were received over the muc.
  432. *
  433. * This is required as we rely on the fact that we receive all messages from the muc that we send
  434. * (as they are sent to everybody), but we don't receive the private messages we send to another participant.
  435. * But those messages should be in the store as well, otherwise they don't appear in the chat window.
  436. *
  437. * @param {Store} store - The Redux store.
  438. * @param {string} recipientID - The ID of the recipient the private message was sent to.
  439. * @param {string} message - The sent message.
  440. * @param {boolean} isLobbyPrivateMessage - Is a lobby message.
  441. * @returns {void}
  442. */
  443. function _persistSentPrivateMessage({ dispatch, getState }: IStore, recipientID: string,
  444. message: string, isLobbyPrivateMessage = false) {
  445. const state = getState();
  446. const localParticipant = getLocalParticipant(state);
  447. if (!localParticipant?.id) {
  448. return;
  449. }
  450. const displayName = getParticipantDisplayName(state, localParticipant.id);
  451. const { lobbyMessageRecipient } = state['features/chat'];
  452. dispatch(addMessage({
  453. displayName,
  454. hasRead: true,
  455. participantId: localParticipant.id,
  456. messageType: MESSAGE_TYPE_LOCAL,
  457. message,
  458. privateMessage: !isLobbyPrivateMessage,
  459. lobbyChat: isLobbyPrivateMessage,
  460. recipient: isLobbyPrivateMessage
  461. ? lobbyMessageRecipient?.name
  462. : getParticipantDisplayName(getState, recipientID),
  463. timestamp: Date.now()
  464. }));
  465. }
  466. /**
  467. * Returns the ID of the participant who we may have wanted to send the message
  468. * that we're about to send.
  469. *
  470. * @param {Object} state - The Redux state.
  471. * @param {Object} action - The action being dispatched now.
  472. * @returns {string?}
  473. */
  474. function _shouldSendPrivateMessageTo(state: IReduxState, action: AnyAction) {
  475. if (action.ignorePrivacy) {
  476. // Shortcut: this is only true, if we already displayed the notice, so no need to show it again.
  477. return undefined;
  478. }
  479. const { messages, privateMessageRecipient } = state['features/chat'];
  480. if (privateMessageRecipient) {
  481. // We're already sending a private message, no need to warn about privacy.
  482. return undefined;
  483. }
  484. if (!messages.length) {
  485. // No messages yet, no need to warn for privacy.
  486. return undefined;
  487. }
  488. // Platforms sort messages differently
  489. const lastMessage = navigator.product === 'ReactNative'
  490. ? messages[0] : messages[messages.length - 1];
  491. if (lastMessage.messageType === MESSAGE_TYPE_LOCAL) {
  492. // The sender is probably aware of any private messages as already sent
  493. // a message since then. Doesn't make sense to display the notice now.
  494. return undefined;
  495. }
  496. if (lastMessage.privateMessage) {
  497. // We show the notice if the last received message was private.
  498. return lastMessage.participantId;
  499. }
  500. // But messages may come rapidly, we want to protect our users from mis-sending a message
  501. // even when there was a reasonable recently received private message.
  502. const now = Date.now();
  503. const recentPrivateMessages = messages.filter(
  504. message =>
  505. message.messageType !== MESSAGE_TYPE_LOCAL
  506. && message.privateMessage
  507. && message.timestamp + PRIVACY_NOTICE_TIMEOUT > now);
  508. const recentPrivateMessage = navigator.product === 'ReactNative'
  509. ? recentPrivateMessages[0] : recentPrivateMessages[recentPrivateMessages.length - 1];
  510. if (recentPrivateMessage) {
  511. return recentPrivateMessage.participantId;
  512. }
  513. return undefined;
  514. }