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.js 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. // @flow
  2. import { type Dispatch } from 'redux';
  3. import { APP_WILL_MOUNT, APP_WILL_UNMOUNT } from '../base/app';
  4. import {
  5. CONFERENCE_JOINED,
  6. getCurrentConference
  7. } from '../base/conference';
  8. import { openDialog } from '../base/dialog';
  9. import {
  10. JitsiConferenceErrors,
  11. JitsiConferenceEvents
  12. } from '../base/lib-jitsi-meet';
  13. import {
  14. getLocalParticipant,
  15. getParticipantById,
  16. getParticipantDisplayName
  17. } from '../base/participants';
  18. import { MiddlewareRegistry, StateListenerRegistry } from '../base/redux';
  19. import { playSound, registerSound, unregisterSound } from '../base/sounds';
  20. import { addGif } from '../gifs/actions';
  21. import { GIF_PREFIX } from '../gifs/constants';
  22. import { getGifDisplayMode, isGifMessage } from '../gifs/functions';
  23. import { NOTIFICATION_TIMEOUT_TYPE, showMessageNotification } from '../notifications';
  24. import { resetNbUnreadPollsMessages } from '../polls/actions';
  25. import { ADD_REACTION_MESSAGE } from '../reactions/actionTypes';
  26. import { pushReactions } from '../reactions/actions.any';
  27. import { ENDPOINT_REACTION_NAME } from '../reactions/constants';
  28. import { getReactionMessageFromBuffer, isReactionsEnabled } from '../reactions/functions.any';
  29. import { endpointMessageReceived } from '../subtitles';
  30. import {
  31. showToolbox
  32. } from '../toolbox/actions';
  33. import { ADD_MESSAGE, SEND_MESSAGE, OPEN_CHAT, CLOSE_CHAT, SET_IS_POLL_TAB_FOCUSED } from './actionTypes';
  34. import { addMessage, clearMessages } from './actions';
  35. import { closeChat } from './actions.any';
  36. import { ChatPrivacyDialog } from './components';
  37. import {
  38. INCOMING_MSG_SOUND_ID,
  39. LOBBY_CHAT_MESSAGE,
  40. MESSAGE_TYPE_ERROR,
  41. MESSAGE_TYPE_LOCAL,
  42. MESSAGE_TYPE_REMOTE
  43. } from './constants';
  44. import { getUnreadCount } from './functions';
  45. import { INCOMING_MSG_SOUND_FILE } from './sounds';
  46. declare var APP: Object;
  47. declare var interfaceConfig : Object;
  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. _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. return next(action);
  155. });
  156. /**
  157. * Set up state change listener to perform maintenance tasks when the conference
  158. * is left or failed, e.g. Clear messages or close the chat modal if it's left
  159. * open.
  160. */
  161. StateListenerRegistry.register(
  162. state => getCurrentConference(state),
  163. (conference, { dispatch, getState }, previousConference) => {
  164. if (conference !== previousConference) {
  165. // conference changed, left or failed...
  166. if (getState()['features/chat'].isOpen) {
  167. // Closes the chat if it's left open.
  168. dispatch(closeChat());
  169. }
  170. // Clear chat messages.
  171. dispatch(clearMessages());
  172. }
  173. });
  174. StateListenerRegistry.register(
  175. state => state['features/chat'].isOpen,
  176. (isOpen, { dispatch }) => {
  177. if (typeof APP !== 'undefined' && isOpen) {
  178. dispatch(showToolbox());
  179. }
  180. }
  181. );
  182. /**
  183. * Registers listener for {@link JitsiConferenceEvents.MESSAGE_RECEIVED} that
  184. * will perform various chat related activities.
  185. *
  186. * @param {JitsiConference} conference - The conference instance on which the
  187. * new event listener will be registered.
  188. * @param {Object} store - The redux store object.
  189. * @private
  190. * @returns {void}
  191. */
  192. function _addChatMsgListener(conference, store) {
  193. if (store.getState()['features/base/config'].iAmRecorder) {
  194. // We don't register anything on web if we are in iAmRecorder mode
  195. return;
  196. }
  197. conference.on(
  198. JitsiConferenceEvents.MESSAGE_RECEIVED,
  199. (id, message, timestamp) => {
  200. _onConferenceMessageReceived(store, { id,
  201. message,
  202. timestamp,
  203. privateMessage: false });
  204. }
  205. );
  206. conference.on(
  207. JitsiConferenceEvents.PRIVATE_MESSAGE_RECEIVED,
  208. (id, message, timestamp) => {
  209. _onConferenceMessageReceived(store, {
  210. id,
  211. message,
  212. timestamp,
  213. privateMessage: true
  214. });
  215. }
  216. );
  217. conference.on(
  218. JitsiConferenceEvents.ENDPOINT_MESSAGE_RECEIVED,
  219. (...args) => {
  220. const state = store.getState();
  221. if (!isReactionsEnabled(state)) {
  222. return;
  223. }
  224. store.dispatch(endpointMessageReceived(...args));
  225. if (args && args.length >= 2) {
  226. const [ { _id }, eventData ] = args;
  227. if (eventData.name === ENDPOINT_REACTION_NAME) {
  228. store.dispatch(pushReactions(eventData.reactions));
  229. _handleReceivedMessage(store, {
  230. id: _id,
  231. message: getReactionMessageFromBuffer(eventData.reactions),
  232. privateMessage: false,
  233. lobbyChat: false,
  234. timestamp: eventData.timestamp
  235. }, false, true);
  236. }
  237. }
  238. });
  239. conference.on(
  240. JitsiConferenceEvents.CONFERENCE_ERROR, (errorType, error) => {
  241. errorType === JitsiConferenceErrors.CHAT_ERROR && _handleChatError(store, error);
  242. });
  243. }
  244. /**
  245. * Handles a received message.
  246. *
  247. * @param {Object} store - Redux store.
  248. * @param {Object} message - The message object.
  249. * @returns {void}
  250. */
  251. function _onConferenceMessageReceived(store, { id, message, timestamp, privateMessage }) {
  252. const isGif = isGifMessage(message);
  253. if (isGif) {
  254. _handleGifMessageReceived(store, id, message);
  255. if (getGifDisplayMode(store.getState()) === 'tile') {
  256. return;
  257. }
  258. }
  259. _handleReceivedMessage(store, {
  260. id,
  261. message,
  262. privateMessage,
  263. lobbyChat: false,
  264. timestamp
  265. }, true, isGif);
  266. }
  267. /**
  268. * Handles a received gif message.
  269. *
  270. * @param {Object} store - Redux store.
  271. * @param {string} id - Id of the participant that sent the message.
  272. * @param {string} message - The message sent.
  273. * @returns {void}
  274. */
  275. function _handleGifMessageReceived(store, id, message) {
  276. const url = message.substring(GIF_PREFIX.length, message.length - 1);
  277. store.dispatch(addGif(id, url));
  278. }
  279. /**
  280. * Handles a chat error received from the xmpp server.
  281. *
  282. * @param {Store} store - The Redux store.
  283. * @param {string} error - The error message.
  284. * @returns {void}
  285. */
  286. function _handleChatError({ dispatch }, error) {
  287. dispatch(addMessage({
  288. hasRead: true,
  289. messageType: MESSAGE_TYPE_ERROR,
  290. message: error,
  291. privateMessage: false,
  292. timestamp: Date.now()
  293. }));
  294. }
  295. /**
  296. * Function to handle an incoming chat message from lobby room.
  297. *
  298. * @param {string} message - The message received.
  299. * @param {string} participantId - The participant id.
  300. * @returns {Function}
  301. */
  302. export function handleLobbyMessageReceived(message: string, participantId: string) {
  303. return async (dispatch: Dispatch<any>, getState: Function) => {
  304. _handleReceivedMessage({ dispatch,
  305. getState }, { id: participantId,
  306. message,
  307. privateMessage: false,
  308. lobbyChat: true,
  309. timestamp: Date.now() });
  310. };
  311. }
  312. /**
  313. * Function to get lobby chat user display name.
  314. *
  315. * @param {Store} state - The Redux store.
  316. * @param {string} id - The knocking participant id.
  317. * @returns {string}
  318. */
  319. function getLobbyChatDisplayName(state, id) {
  320. const { knockingParticipants } = state['features/lobby'];
  321. const { lobbyMessageRecipient } = state['features/chat'];
  322. if (id === lobbyMessageRecipient.id) {
  323. return lobbyMessageRecipient.name;
  324. }
  325. const knockingParticipant = knockingParticipants.find(p => p.id === id);
  326. if (knockingParticipant) {
  327. return knockingParticipant.name;
  328. }
  329. }
  330. /**
  331. * Function to handle an incoming chat message.
  332. *
  333. * @param {Store} store - The Redux store.
  334. * @param {Object} message - The message object.
  335. * @param {boolean} shouldPlaySound - Whether or not to play the incoming message sound.
  336. * @param {boolean} isReaction - Whether or not the message is a reaction message.
  337. * @returns {void}
  338. */
  339. function _handleReceivedMessage({ dispatch, getState },
  340. { id, message, privateMessage, timestamp, lobbyChat },
  341. shouldPlaySound = true,
  342. isReaction = false
  343. ) {
  344. // Logic for all platforms:
  345. const state = getState();
  346. const { isOpen: isChatOpen } = state['features/chat'];
  347. const { iAmRecorder } = state['features/base/config'];
  348. const { soundsIncomingMessage: soundEnabled, userSelectedNotifications } = state['features/base/settings'];
  349. if (soundEnabled && shouldPlaySound && !isChatOpen) {
  350. dispatch(playSound(INCOMING_MSG_SOUND_ID));
  351. }
  352. // Provide a default for for the case when a message is being
  353. // backfilled for a participant that has left the conference.
  354. const participant = getParticipantById(state, id) || {};
  355. const localParticipant = getLocalParticipant(getState);
  356. const displayName = lobbyChat
  357. ? getLobbyChatDisplayName(state, id)
  358. : getParticipantDisplayName(state, id);
  359. const hasRead = participant.local || isChatOpen;
  360. const timestampToDate = timestamp ? new Date(timestamp) : new Date();
  361. const millisecondsTimestamp = timestampToDate.getTime();
  362. // skip message notifications on join (the messages having timestamp - coming from the history)
  363. const shouldShowNotification = userSelectedNotifications['notify.chatMessages']
  364. && !hasRead && !isReaction && !timestamp;
  365. dispatch(addMessage({
  366. displayName,
  367. hasRead,
  368. id,
  369. messageType: participant.local ? MESSAGE_TYPE_LOCAL : MESSAGE_TYPE_REMOTE,
  370. message,
  371. privateMessage,
  372. lobbyChat,
  373. recipient: getParticipantDisplayName(state, localParticipant.id),
  374. timestamp: millisecondsTimestamp,
  375. isReaction
  376. }));
  377. if (shouldShowNotification) {
  378. dispatch(showMessageNotification({
  379. title: displayName,
  380. description: message
  381. }, NOTIFICATION_TIMEOUT_TYPE.MEDIUM));
  382. }
  383. if (typeof APP !== 'undefined') {
  384. // Logic for web only:
  385. APP.API.notifyReceivedChatMessage({
  386. body: message,
  387. id,
  388. nick: displayName,
  389. privateMessage,
  390. ts: timestamp
  391. });
  392. if (!iAmRecorder) {
  393. dispatch(showToolbox(4000));
  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 }, recipientID, message, isLobbyPrivateMessage = false) {
  411. const state = getState();
  412. const localParticipant = getLocalParticipant(state);
  413. const displayName = getParticipantDisplayName(state, localParticipant.id);
  414. const { lobbyMessageRecipient } = state['features/chat'];
  415. dispatch(addMessage({
  416. displayName,
  417. hasRead: true,
  418. id: localParticipant.id,
  419. messageType: MESSAGE_TYPE_LOCAL,
  420. message,
  421. privateMessage: !isLobbyPrivateMessage,
  422. lobbyChat: isLobbyPrivateMessage,
  423. recipient: isLobbyPrivateMessage
  424. ? lobbyMessageRecipient && lobbyMessageRecipient.name
  425. : getParticipantDisplayName(getState, recipientID),
  426. timestamp: Date.now()
  427. }));
  428. }
  429. /**
  430. * Returns the ID of the participant who we may have wanted to send the message
  431. * that we're about to send.
  432. *
  433. * @param {Object} state - The Redux state.
  434. * @param {Object} action - The action being dispatched now.
  435. * @returns {string?}
  436. */
  437. function _shouldSendPrivateMessageTo(state, action): ?string {
  438. if (action.ignorePrivacy) {
  439. // Shortcut: this is only true, if we already displayed the notice, so no need to show it again.
  440. return undefined;
  441. }
  442. const { messages, privateMessageRecipient } = state['features/chat'];
  443. if (privateMessageRecipient) {
  444. // We're already sending a private message, no need to warn about privacy.
  445. return undefined;
  446. }
  447. if (!messages.length) {
  448. // No messages yet, no need to warn for privacy.
  449. return undefined;
  450. }
  451. // Platforms sort messages differently
  452. const lastMessage = navigator.product === 'ReactNative'
  453. ? messages[0] : messages[messages.length - 1];
  454. if (lastMessage.messageType === MESSAGE_TYPE_LOCAL) {
  455. // The sender is probably aware of any private messages as already sent
  456. // a message since then. Doesn't make sense to display the notice now.
  457. return undefined;
  458. }
  459. if (lastMessage.privateMessage) {
  460. // We show the notice if the last received message was private.
  461. return lastMessage.id;
  462. }
  463. // But messages may come rapidly, we want to protect our users from mis-sending a message
  464. // even when there was a reasonable recently received private message.
  465. const now = Date.now();
  466. const recentPrivateMessages = messages.filter(
  467. message =>
  468. message.messageType !== MESSAGE_TYPE_LOCAL
  469. && message.privateMessage
  470. && message.timestamp + PRIVACY_NOTICE_TIMEOUT > now);
  471. const recentPrivateMessage = navigator.product === 'ReactNative'
  472. ? recentPrivateMessages[0] : recentPrivateMessages[recentPrivateMessages.length - 1];
  473. if (recentPrivateMessage) {
  474. return recentPrivateMessage.id;
  475. }
  476. return undefined;
  477. }