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

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