Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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