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 21KB

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