您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

middleware.ts 19KB

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