Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

middleware.ts 18KB

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