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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  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;
  104. }
  105. const { participant, data } = action;
  106. if (data?.name === ENDPOINT_REACTION_NAME) {
  107. store.dispatch(pushReactions(data.reactions));
  108. _handleReceivedMessage(store, {
  109. id: 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 { id, json: data } = action;
  120. if (data?.type === MESSAGE_TYPE_SYSTEM && data.message) {
  121. _handleReceivedMessage(store, {
  122. displayName: data.displayName ?? i18next.t('chat.systemDisplayName'),
  123. id,
  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. id: 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-next-line max-params
  237. (id: string, message: string, timestamp: number, displayName: string, isGuest?: boolean) => {
  238. _onConferenceMessageReceived(store, {
  239. id: id || displayName, // in case of messages coming from visitors we can have unknown id
  240. message,
  241. timestamp,
  242. displayName,
  243. isGuest,
  244. privateMessage: false });
  245. }
  246. );
  247. conference.on(
  248. JitsiConferenceEvents.PRIVATE_MESSAGE_RECEIVED,
  249. (id: string, message: string, timestamp: number) => {
  250. _onConferenceMessageReceived(store, {
  251. id,
  252. message,
  253. timestamp,
  254. privateMessage: true
  255. });
  256. }
  257. );
  258. conference.on(
  259. JitsiConferenceEvents.CONFERENCE_ERROR, (errorType: string, error: Error) => {
  260. errorType === JitsiConferenceErrors.CHAT_ERROR && _handleChatError(store, error);
  261. });
  262. }
  263. /**
  264. * Handles a received message.
  265. *
  266. * @param {Object} store - Redux store.
  267. * @param {Object} message - The message object.
  268. * @returns {void}
  269. */
  270. function _onConferenceMessageReceived(store: IStore, { displayName, id, isGuest, message, timestamp, privateMessage }: {
  271. displayName?: string; id: string; isGuest?: boolean;
  272. message: string; privateMessage: boolean; timestamp: number; }) {
  273. const isGif = isGifMessage(message);
  274. if (isGif) {
  275. _handleGifMessageReceived(store, id, message);
  276. if (getGifDisplayMode(store.getState()) === 'tile') {
  277. return;
  278. }
  279. }
  280. _handleReceivedMessage(store, {
  281. displayName,
  282. id,
  283. isGuest,
  284. message,
  285. privateMessage,
  286. lobbyChat: false,
  287. timestamp
  288. }, true, isGif);
  289. }
  290. /**
  291. * Handles a received gif message.
  292. *
  293. * @param {Object} store - Redux store.
  294. * @param {string} id - Id of the participant that sent the message.
  295. * @param {string} message - The message sent.
  296. * @returns {void}
  297. */
  298. function _handleGifMessageReceived(store: IStore, id: string, message: string) {
  299. const url = message.substring(GIF_PREFIX.length, message.length - 1);
  300. store.dispatch(addGif(id, url));
  301. }
  302. /**
  303. * Handles a chat error received from the xmpp server.
  304. *
  305. * @param {Store} store - The Redux store.
  306. * @param {string} error - The error message.
  307. * @returns {void}
  308. */
  309. function _handleChatError({ dispatch }: IStore, error: Error) {
  310. dispatch(addMessage({
  311. hasRead: true,
  312. messageType: MESSAGE_TYPE_ERROR,
  313. message: error,
  314. privateMessage: false,
  315. timestamp: Date.now()
  316. }));
  317. }
  318. /**
  319. * Function to handle an incoming chat message from lobby room.
  320. *
  321. * @param {string} message - The message received.
  322. * @param {string} participantId - The participant id.
  323. * @returns {Function}
  324. */
  325. export function handleLobbyMessageReceived(message: string, participantId: string) {
  326. return async (dispatch: IStore['dispatch'], getState: IStore['getState']) => {
  327. _handleReceivedMessage({ dispatch,
  328. getState }, { id: participantId,
  329. message,
  330. privateMessage: false,
  331. lobbyChat: true,
  332. timestamp: Date.now() });
  333. };
  334. }
  335. /**
  336. * Function to get lobby chat user display name.
  337. *
  338. * @param {Store} state - The Redux store.
  339. * @param {string} id - The knocking participant id.
  340. * @returns {string}
  341. */
  342. function getLobbyChatDisplayName(state: IReduxState, id: string) {
  343. const { knockingParticipants } = state['features/lobby'];
  344. const { lobbyMessageRecipient } = state['features/chat'];
  345. if (id === lobbyMessageRecipient?.id) {
  346. return lobbyMessageRecipient.name;
  347. }
  348. const knockingParticipant = knockingParticipants.find(p => p.id === id);
  349. if (knockingParticipant) {
  350. return knockingParticipant.name;
  351. }
  352. }
  353. /**
  354. * Function to handle an incoming chat message.
  355. *
  356. * @param {Store} store - The Redux store.
  357. * @param {Object} message - The message object.
  358. * @param {boolean} shouldPlaySound - Whether to play the incoming message sound.
  359. * @param {boolean} isReaction - Whether the message is a reaction message.
  360. * @returns {void}
  361. */
  362. function _handleReceivedMessage({ dispatch, getState }: IStore,
  363. { displayName, id, isGuest, message, privateMessage, timestamp, lobbyChat }: {
  364. displayName?: string; id: string; isGuest?: boolean; lobbyChat: boolean;
  365. message: string; privateMessage: boolean; timestamp: number; },
  366. shouldPlaySound = true,
  367. isReaction = false
  368. ) {
  369. // Logic for all platforms:
  370. const state = getState();
  371. const { isOpen: isChatOpen } = state['features/chat'];
  372. const { soundsIncomingMessage: soundEnabled, userSelectedNotifications } = state['features/base/settings'];
  373. if (soundEnabled && shouldPlaySound && !isChatOpen) {
  374. dispatch(playSound(INCOMING_MSG_SOUND_ID));
  375. }
  376. // Provide a default for the case when a message is being
  377. // backfilled for a participant that has left the conference.
  378. const participant = getParticipantById(state, id) || { local: undefined };
  379. const localParticipant = getLocalParticipant(getState);
  380. let displayNameToShow = lobbyChat
  381. ? getLobbyChatDisplayName(state, id)
  382. : displayName || getParticipantDisplayName(state, id);
  383. const hasRead = participant.local || isChatOpen;
  384. const timestampToDate = timestamp ? new Date(timestamp) : new Date();
  385. const millisecondsTimestamp = timestampToDate.getTime();
  386. // skip message notifications on join (the messages having timestamp - coming from the history)
  387. const shouldShowNotification = userSelectedNotifications?.['notify.chatMessages']
  388. && !hasRead && !isReaction && !timestamp;
  389. if (isGuest) {
  390. displayNameToShow = `${displayNameToShow} ${i18next.t('visitors.chatIndicator')}`;
  391. }
  392. dispatch(addMessage({
  393. displayName: displayNameToShow,
  394. hasRead,
  395. id,
  396. messageType: participant.local ? MESSAGE_TYPE_LOCAL : MESSAGE_TYPE_REMOTE,
  397. message,
  398. privateMessage,
  399. lobbyChat,
  400. recipient: getParticipantDisplayName(state, localParticipant?.id ?? ''),
  401. timestamp: millisecondsTimestamp,
  402. isReaction
  403. }));
  404. if (shouldShowNotification) {
  405. dispatch(showMessageNotification({
  406. title: displayNameToShow,
  407. description: message
  408. }, NOTIFICATION_TIMEOUT_TYPE.MEDIUM));
  409. }
  410. if (typeof APP !== 'undefined') {
  411. // Logic for web only:
  412. APP.API.notifyReceivedChatMessage({
  413. body: message,
  414. id,
  415. nick: displayNameToShow,
  416. privateMessage,
  417. ts: timestamp
  418. });
  419. }
  420. }
  421. /**
  422. * Persists the sent private messages as if they were received over the muc.
  423. *
  424. * This is required as we rely on the fact that we receive all messages from the muc that we send
  425. * (as they are sent to everybody), but we don't receive the private messages we send to another participant.
  426. * But those messages should be in the store as well, otherwise they don't appear in the chat window.
  427. *
  428. * @param {Store} store - The Redux store.
  429. * @param {string} recipientID - The ID of the recipient the private message was sent to.
  430. * @param {string} message - The sent message.
  431. * @param {boolean} isLobbyPrivateMessage - Is a lobby message.
  432. * @returns {void}
  433. */
  434. function _persistSentPrivateMessage({ dispatch, getState }: IStore, recipientID: string,
  435. message: string, isLobbyPrivateMessage = false) {
  436. const state = getState();
  437. const localParticipant = getLocalParticipant(state);
  438. if (!localParticipant?.id) {
  439. return;
  440. }
  441. const displayName = getParticipantDisplayName(state, localParticipant.id);
  442. const { lobbyMessageRecipient } = state['features/chat'];
  443. dispatch(addMessage({
  444. displayName,
  445. hasRead: true,
  446. id: localParticipant.id,
  447. messageType: MESSAGE_TYPE_LOCAL,
  448. message,
  449. privateMessage: !isLobbyPrivateMessage,
  450. lobbyChat: isLobbyPrivateMessage,
  451. recipient: isLobbyPrivateMessage
  452. ? lobbyMessageRecipient?.name
  453. : getParticipantDisplayName(getState, recipientID),
  454. timestamp: Date.now()
  455. }));
  456. }
  457. /**
  458. * Returns the ID of the participant who we may have wanted to send the message
  459. * that we're about to send.
  460. *
  461. * @param {Object} state - The Redux state.
  462. * @param {Object} action - The action being dispatched now.
  463. * @returns {string?}
  464. */
  465. function _shouldSendPrivateMessageTo(state: IReduxState, action: AnyAction) {
  466. if (action.ignorePrivacy) {
  467. // Shortcut: this is only true, if we already displayed the notice, so no need to show it again.
  468. return undefined;
  469. }
  470. const { messages, privateMessageRecipient } = state['features/chat'];
  471. if (privateMessageRecipient) {
  472. // We're already sending a private message, no need to warn about privacy.
  473. return undefined;
  474. }
  475. if (!messages.length) {
  476. // No messages yet, no need to warn for privacy.
  477. return undefined;
  478. }
  479. // Platforms sort messages differently
  480. const lastMessage = navigator.product === 'ReactNative'
  481. ? messages[0] : messages[messages.length - 1];
  482. if (lastMessage.messageType === MESSAGE_TYPE_LOCAL) {
  483. // The sender is probably aware of any private messages as already sent
  484. // a message since then. Doesn't make sense to display the notice now.
  485. return undefined;
  486. }
  487. if (lastMessage.privateMessage) {
  488. // We show the notice if the last received message was private.
  489. return lastMessage.id;
  490. }
  491. // But messages may come rapidly, we want to protect our users from mis-sending a message
  492. // even when there was a reasonable recently received private message.
  493. const now = Date.now();
  494. const recentPrivateMessages = messages.filter(
  495. message =>
  496. message.messageType !== MESSAGE_TYPE_LOCAL
  497. && message.privateMessage
  498. && message.timestamp + PRIVACY_NOTICE_TIMEOUT > now);
  499. const recentPrivateMessage = navigator.product === 'ReactNative'
  500. ? recentPrivateMessages[0] : recentPrivateMessages[recentPrivateMessages.length - 1];
  501. if (recentPrivateMessage) {
  502. return recentPrivateMessage.id;
  503. }
  504. return undefined;
  505. }