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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. /* eslint-disable lines-around-comment */
  2. import { AnyAction } from 'redux';
  3. import { IReduxState, IStore } from '../app/types';
  4. import { APP_WILL_MOUNT, APP_WILL_UNMOUNT } from '../base/app/actionTypes';
  5. import { CONFERENCE_JOINED } from '../base/conference/actionTypes';
  6. import { getCurrentConference } from '../base/conference/functions';
  7. import { IJitsiConference } from '../base/conference/reducer';
  8. import { openDialog } from '../base/dialog/actions';
  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. // @ts-ignore
  33. import { showToolbox } from '../toolbox/actions';
  34. import { ADD_MESSAGE, CLOSE_CHAT, OPEN_CHAT, SEND_MESSAGE, SET_IS_POLL_TAB_FOCUSED } from './actionTypes';
  35. import { addMessage, clearMessages, closeChat } from './actions.any';
  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. (id: string, message: string, timestamp: number) => {
  201. _onConferenceMessageReceived(store, { id,
  202. message,
  203. timestamp,
  204. privateMessage: false });
  205. }
  206. );
  207. conference.on(
  208. JitsiConferenceEvents.PRIVATE_MESSAGE_RECEIVED,
  209. (id: string, message: string, timestamp: number) => {
  210. _onConferenceMessageReceived(store, {
  211. id,
  212. message,
  213. timestamp,
  214. privateMessage: true
  215. });
  216. }
  217. );
  218. conference.on(
  219. JitsiConferenceEvents.ENDPOINT_MESSAGE_RECEIVED,
  220. (...args: any) => {
  221. const state = store.getState();
  222. if (!isReactionsEnabled(state)) {
  223. return;
  224. }
  225. // @ts-ignore
  226. store.dispatch(endpointMessageReceived(...args));
  227. if (args && args.length >= 2) {
  228. const [ { _id }, eventData ] = args;
  229. if (eventData.name === ENDPOINT_REACTION_NAME) {
  230. store.dispatch(pushReactions(eventData.reactions));
  231. _handleReceivedMessage(store, {
  232. id: _id,
  233. message: getReactionMessageFromBuffer(eventData.reactions),
  234. privateMessage: false,
  235. lobbyChat: false,
  236. timestamp: eventData.timestamp
  237. }, false, true);
  238. }
  239. }
  240. });
  241. conference.on(
  242. JitsiConferenceEvents.CONFERENCE_ERROR, (errorType: string, error: Error) => {
  243. errorType === JitsiConferenceErrors.CHAT_ERROR && _handleChatError(store, error);
  244. });
  245. }
  246. /**
  247. * Handles a received message.
  248. *
  249. * @param {Object} store - Redux store.
  250. * @param {Object} message - The message object.
  251. * @returns {void}
  252. */
  253. function _onConferenceMessageReceived(store: IStore, { id, message, timestamp, privateMessage }: {
  254. id: string; message: string; privateMessage: boolean; timestamp: number; }) {
  255. const isGif = isGifMessage(message);
  256. if (isGif) {
  257. _handleGifMessageReceived(store, id, message);
  258. if (getGifDisplayMode(store.getState()) === 'tile') {
  259. return;
  260. }
  261. }
  262. _handleReceivedMessage(store, {
  263. id,
  264. message,
  265. privateMessage,
  266. lobbyChat: false,
  267. timestamp
  268. }, true, isGif);
  269. }
  270. /**
  271. * Handles a received gif message.
  272. *
  273. * @param {Object} store - Redux store.
  274. * @param {string} id - Id of the participant that sent the message.
  275. * @param {string} message - The message sent.
  276. * @returns {void}
  277. */
  278. function _handleGifMessageReceived(store: IStore, id: string, message: string) {
  279. const url = message.substring(GIF_PREFIX.length, message.length - 1);
  280. store.dispatch(addGif(id, url));
  281. }
  282. /**
  283. * Handles a chat error received from the xmpp server.
  284. *
  285. * @param {Store} store - The Redux store.
  286. * @param {string} error - The error message.
  287. * @returns {void}
  288. */
  289. function _handleChatError({ dispatch }: IStore, error: Error) {
  290. dispatch(addMessage({
  291. hasRead: true,
  292. messageType: MESSAGE_TYPE_ERROR,
  293. message: error,
  294. privateMessage: false,
  295. timestamp: Date.now()
  296. }));
  297. }
  298. /**
  299. * Function to handle an incoming chat message from lobby room.
  300. *
  301. * @param {string} message - The message received.
  302. * @param {string} participantId - The participant id.
  303. * @returns {Function}
  304. */
  305. export function handleLobbyMessageReceived(message: string, participantId: string) {
  306. return async (dispatch: IStore['dispatch'], getState: IStore['getState']) => {
  307. _handleReceivedMessage({ dispatch,
  308. getState }, { id: participantId,
  309. message,
  310. privateMessage: false,
  311. lobbyChat: true,
  312. timestamp: Date.now() });
  313. };
  314. }
  315. /**
  316. * Function to get lobby chat user display name.
  317. *
  318. * @param {Store} state - The Redux store.
  319. * @param {string} id - The knocking participant id.
  320. * @returns {string}
  321. */
  322. function getLobbyChatDisplayName(state: IReduxState, id: string) {
  323. const { knockingParticipants } = state['features/lobby'];
  324. const { lobbyMessageRecipient } = state['features/chat'];
  325. if (id === lobbyMessageRecipient?.id) {
  326. return lobbyMessageRecipient.name;
  327. }
  328. const knockingParticipant = knockingParticipants.find(p => p.id === id);
  329. if (knockingParticipant) {
  330. return knockingParticipant.name;
  331. }
  332. }
  333. /**
  334. * Function to handle an incoming chat message.
  335. *
  336. * @param {Store} store - The Redux store.
  337. * @param {Object} message - The message object.
  338. * @param {boolean} shouldPlaySound - Whether or not to play the incoming message sound.
  339. * @param {boolean} isReaction - Whether or not the message is a reaction message.
  340. * @returns {void}
  341. */
  342. function _handleReceivedMessage({ dispatch, getState }: IStore,
  343. { id, message, privateMessage, timestamp, lobbyChat }: {
  344. id: string; lobbyChat: boolean; message: string; privateMessage: boolean; timestamp: number; },
  345. shouldPlaySound = true,
  346. isReaction = false
  347. ) {
  348. // Logic for all platforms:
  349. const state = getState();
  350. const { isOpen: isChatOpen } = state['features/chat'];
  351. const { soundsIncomingMessage: soundEnabled, userSelectedNotifications } = state['features/base/settings'];
  352. if (soundEnabled && shouldPlaySound && !isChatOpen) {
  353. dispatch(playSound(INCOMING_MSG_SOUND_ID));
  354. }
  355. // Provide a default for for the case when a message is being
  356. // backfilled for a participant that has left the conference.
  357. const participant = getParticipantById(state, id) || { local: undefined };
  358. const localParticipant = getLocalParticipant(getState);
  359. const displayName = lobbyChat
  360. ? getLobbyChatDisplayName(state, id)
  361. : getParticipantDisplayName(state, id);
  362. const hasRead = participant.local || isChatOpen;
  363. const timestampToDate = timestamp ? new Date(timestamp) : new Date();
  364. const millisecondsTimestamp = timestampToDate.getTime();
  365. // skip message notifications on join (the messages having timestamp - coming from the history)
  366. const shouldShowNotification = userSelectedNotifications?.['notify.chatMessages']
  367. && !hasRead && !isReaction && !timestamp;
  368. dispatch(addMessage({
  369. displayName,
  370. hasRead,
  371. id,
  372. messageType: participant.local ? MESSAGE_TYPE_LOCAL : MESSAGE_TYPE_REMOTE,
  373. message,
  374. privateMessage,
  375. lobbyChat,
  376. recipient: getParticipantDisplayName(state, localParticipant?.id ?? ''),
  377. timestamp: millisecondsTimestamp,
  378. isReaction
  379. }));
  380. if (shouldShowNotification) {
  381. dispatch(showMessageNotification({
  382. title: displayName,
  383. description: message
  384. }, NOTIFICATION_TIMEOUT_TYPE.MEDIUM));
  385. }
  386. if (typeof APP !== 'undefined') {
  387. // Logic for web only:
  388. APP.API.notifyReceivedChatMessage({
  389. body: message,
  390. id,
  391. nick: displayName,
  392. privateMessage,
  393. ts: timestamp
  394. });
  395. }
  396. }
  397. /**
  398. * Persists the sent private messages as if they were received over the muc.
  399. *
  400. * This is required as we rely on the fact that we receive all messages from the muc that we send
  401. * (as they are sent to everybody), but we don't receive the private messages we send to another participant.
  402. * But those messages should be in the store as well, otherwise they don't appear in the chat window.
  403. *
  404. * @param {Store} store - The Redux store.
  405. * @param {string} recipientID - The ID of the recipient the private message was sent to.
  406. * @param {string} message - The sent message.
  407. * @param {boolean} isLobbyPrivateMessage - Is a lobby message.
  408. * @returns {void}
  409. */
  410. function _persistSentPrivateMessage({ dispatch, getState }: IStore, recipientID: string,
  411. message: string, isLobbyPrivateMessage = false) {
  412. const state = getState();
  413. const localParticipant = getLocalParticipant(state);
  414. if (!localParticipant?.id) {
  415. return;
  416. }
  417. const displayName = getParticipantDisplayName(state, localParticipant.id);
  418. const { lobbyMessageRecipient } = state['features/chat'];
  419. dispatch(addMessage({
  420. displayName,
  421. hasRead: true,
  422. id: localParticipant.id,
  423. messageType: MESSAGE_TYPE_LOCAL,
  424. message,
  425. privateMessage: !isLobbyPrivateMessage,
  426. lobbyChat: isLobbyPrivateMessage,
  427. recipient: isLobbyPrivateMessage
  428. ? lobbyMessageRecipient?.name
  429. : getParticipantDisplayName(getState, recipientID),
  430. timestamp: Date.now()
  431. }));
  432. }
  433. /**
  434. * Returns the ID of the participant who we may have wanted to send the message
  435. * that we're about to send.
  436. *
  437. * @param {Object} state - The Redux state.
  438. * @param {Object} action - The action being dispatched now.
  439. * @returns {string?}
  440. */
  441. function _shouldSendPrivateMessageTo(state: IReduxState, action: AnyAction) {
  442. if (action.ignorePrivacy) {
  443. // Shortcut: this is only true, if we already displayed the notice, so no need to show it again.
  444. return undefined;
  445. }
  446. const { messages, privateMessageRecipient } = state['features/chat'];
  447. if (privateMessageRecipient) {
  448. // We're already sending a private message, no need to warn about privacy.
  449. return undefined;
  450. }
  451. if (!messages.length) {
  452. // No messages yet, no need to warn for privacy.
  453. return undefined;
  454. }
  455. // Platforms sort messages differently
  456. const lastMessage = navigator.product === 'ReactNative'
  457. ? messages[0] : messages[messages.length - 1];
  458. if (lastMessage.messageType === MESSAGE_TYPE_LOCAL) {
  459. // The sender is probably aware of any private messages as already sent
  460. // a message since then. Doesn't make sense to display the notice now.
  461. return undefined;
  462. }
  463. if (lastMessage.privateMessage) {
  464. // We show the notice if the last received message was private.
  465. return lastMessage.id;
  466. }
  467. // But messages may come rapidly, we want to protect our users from mis-sending a message
  468. // even when there was a reasonable recently received private message.
  469. const now = Date.now();
  470. const recentPrivateMessages = messages.filter(
  471. message =>
  472. message.messageType !== MESSAGE_TYPE_LOCAL
  473. && message.privateMessage
  474. && message.timestamp + PRIVACY_NOTICE_TIMEOUT > now);
  475. const recentPrivateMessage = navigator.product === 'ReactNative'
  476. ? recentPrivateMessages[0] : recentPrivateMessages[recentPrivateMessages.length - 1];
  477. if (recentPrivateMessage) {
  478. return recentPrivateMessage.id;
  479. }
  480. return undefined;
  481. }