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

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