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 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. // @flow
  2. import { batch } from 'react-redux';
  3. import { ENDPOINT_REACTION_NAME } from '../../../modules/API/constants';
  4. import { APP_WILL_MOUNT, APP_WILL_UNMOUNT } from '../base/app';
  5. import {
  6. CONFERENCE_JOINED,
  7. getCurrentConference
  8. } from '../base/conference';
  9. import { openDialog } from '../base/dialog';
  10. import {
  11. JitsiConferenceErrors,
  12. JitsiConferenceEvents
  13. } from '../base/lib-jitsi-meet';
  14. import { setActiveModalId } from '../base/modal';
  15. import {
  16. getLocalParticipant,
  17. getParticipantById,
  18. getParticipantDisplayName
  19. } from '../base/participants';
  20. import { MiddlewareRegistry, StateListenerRegistry } from '../base/redux';
  21. import { playSound, registerSound, unregisterSound } from '../base/sounds';
  22. import { openDisplayNamePrompt } from '../display-name';
  23. import { resetNbUnreadPollsMessages } from '../polls/actions';
  24. import { ADD_REACTION_MESSAGE } from '../reactions/actionTypes';
  25. import { pushReactions } from '../reactions/actions.any';
  26. import { getReactionMessageFromBuffer } from '../reactions/functions.any';
  27. import { endpointMessageReceived } from '../subtitles';
  28. import { showToolbox } from '../toolbox/actions';
  29. import {
  30. hideToolbox,
  31. setToolboxTimeout,
  32. setToolboxVisible
  33. } from '../toolbox/actions.web';
  34. import { ADD_MESSAGE, SEND_MESSAGE, OPEN_CHAT, CLOSE_CHAT, SET_IS_POLL_TAB_FOCUSED } from './actionTypes';
  35. import { addMessage, clearMessages } from './actions';
  36. import { closeChat } from './actions.any';
  37. import { ChatPrivacyDialog } from './components';
  38. import {
  39. CHAT_VIEW_MODAL_ID,
  40. INCOMING_MSG_SOUND_ID,
  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. declare var APP: Object;
  48. declare var interfaceConfig : Object;
  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 = action.hasRead ? 0 : getUnreadCount(getState()) + 1;
  69. isOpen = getState()['features/chat'].isOpen;
  70. if (typeof APP !== 'undefined') {
  71. APP.API.notifyChatUpdated(unreadCount, isOpen);
  72. }
  73. break;
  74. case APP_WILL_MOUNT:
  75. dispatch(
  76. registerSound(INCOMING_MSG_SOUND_ID, INCOMING_MSG_SOUND_FILE));
  77. break;
  78. case APP_WILL_UNMOUNT:
  79. dispatch(unregisterSound(INCOMING_MSG_SOUND_ID));
  80. break;
  81. case CONFERENCE_JOINED:
  82. _addChatMsgListener(action.conference, store);
  83. break;
  84. case OPEN_CHAT:
  85. if (navigator.product === 'ReactNative') {
  86. if (localParticipant.name) {
  87. dispatch(setActiveModalId(CHAT_VIEW_MODAL_ID));
  88. } else {
  89. dispatch(openDisplayNamePrompt(() => {
  90. dispatch(setActiveModalId(CHAT_VIEW_MODAL_ID));
  91. }));
  92. }
  93. } else {
  94. dispatch(setActiveModalId(CHAT_VIEW_MODAL_ID));
  95. }
  96. unreadCount = 0;
  97. if (typeof APP !== 'undefined') {
  98. APP.API.notifyChatUpdated(unreadCount, true);
  99. }
  100. break;
  101. case CLOSE_CHAT: {
  102. const isPollTabOpen = getState()['features/chat'].isPollsTabFocused;
  103. unreadCount = 0;
  104. if (typeof APP !== 'undefined') {
  105. APP.API.notifyChatUpdated(unreadCount, false);
  106. }
  107. if (isPollTabOpen) {
  108. dispatch(resetNbUnreadPollsMessages());
  109. }
  110. dispatch(setActiveModalId());
  111. break;
  112. }
  113. case SET_IS_POLL_TAB_FOCUSED: {
  114. dispatch(resetNbUnreadPollsMessages());
  115. break;
  116. }
  117. case SEND_MESSAGE: {
  118. const state = store.getState();
  119. const { conference } = state['features/base/conference'];
  120. if (conference) {
  121. // There may be cases when we intend to send a private message but we forget to set the
  122. // recipient. This logic tries to mitigate this risk.
  123. const shouldSendPrivateMessageTo = _shouldSendPrivateMessageTo(state, action);
  124. if (shouldSendPrivateMessageTo) {
  125. dispatch(openDialog(ChatPrivacyDialog, {
  126. message: action.message,
  127. participantID: shouldSendPrivateMessageTo
  128. }));
  129. } else {
  130. // Sending the message if privacy notice doesn't need to be shown.
  131. const { privateMessageRecipient } = state['features/chat'];
  132. if (typeof APP !== 'undefined') {
  133. APP.API.notifySendingChatMessage(action.message, Boolean(privateMessageRecipient));
  134. }
  135. 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. _handleReceivedMessage(store, {
  147. id: localParticipant.id,
  148. message: action.message,
  149. privateMessage: false,
  150. timestamp: Date.now()
  151. }, false);
  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. _handleReceivedMessage(store, {
  201. id,
  202. message,
  203. privateMessage: false,
  204. timestamp
  205. });
  206. }
  207. );
  208. conference.on(
  209. JitsiConferenceEvents.PRIVATE_MESSAGE_RECEIVED,
  210. (id, message, timestamp) => {
  211. _handleReceivedMessage(store, {
  212. id,
  213. message,
  214. privateMessage: true,
  215. timestamp
  216. });
  217. }
  218. );
  219. conference.on(
  220. JitsiConferenceEvents.ENDPOINT_MESSAGE_RECEIVED,
  221. (...args) => {
  222. store.dispatch(endpointMessageReceived(...args));
  223. if (args && args.length >= 2) {
  224. const [ { _id }, eventData ] = args;
  225. if (eventData.name === ENDPOINT_REACTION_NAME) {
  226. batch(() => {
  227. store.dispatch(setToolboxVisible(true));
  228. store.dispatch(setToolboxTimeout(
  229. () => store.dispatch(hideToolbox()),
  230. 5000)
  231. );
  232. store.dispatch(pushReactions(eventData.reactions));
  233. });
  234. _handleReceivedMessage(store, {
  235. id: _id,
  236. message: getReactionMessageFromBuffer(eventData.reactions),
  237. privateMessage: false,
  238. timestamp: eventData.timestamp
  239. }, false);
  240. }
  241. }
  242. });
  243. conference.on(
  244. JitsiConferenceEvents.CONFERENCE_ERROR, (errorType, error) => {
  245. errorType === JitsiConferenceErrors.CHAT_ERROR && _handleChatError(store, error);
  246. });
  247. }
  248. /**
  249. * Handles a chat error received from the xmpp server.
  250. *
  251. * @param {Store} store - The Redux store.
  252. * @param {string} error - The error message.
  253. * @returns {void}
  254. */
  255. function _handleChatError({ dispatch }, error) {
  256. dispatch(addMessage({
  257. hasRead: true,
  258. messageType: MESSAGE_TYPE_ERROR,
  259. message: error,
  260. privateMessage: false,
  261. timestamp: Date.now()
  262. }));
  263. }
  264. /**
  265. * Function to handle an incoming chat message.
  266. *
  267. * @param {Store} store - The Redux store.
  268. * @param {Object} message - The message object.
  269. * @param {boolean} shouldPlaySound - Whether or not to play the incoming message sound.
  270. * @returns {void}
  271. */
  272. function _handleReceivedMessage({ dispatch, getState },
  273. { id, message, privateMessage, timestamp },
  274. shouldPlaySound = true
  275. ) {
  276. // Logic for all platforms:
  277. const state = getState();
  278. const { isOpen: isChatOpen } = state['features/chat'];
  279. const { disableIncomingMessageSound } = state['features/base/config'];
  280. const { soundsIncomingMessage: soundEnabled } = state['features/base/settings'];
  281. if (!disableIncomingMessageSound && soundEnabled && shouldPlaySound && !isChatOpen) {
  282. dispatch(playSound(INCOMING_MSG_SOUND_ID));
  283. }
  284. // Provide a default for for the case when a message is being
  285. // backfilled for a participant that has left the conference.
  286. const participant = getParticipantById(state, id) || {};
  287. const localParticipant = getLocalParticipant(getState);
  288. const displayName = getParticipantDisplayName(state, id);
  289. const hasRead = participant.local || isChatOpen;
  290. const timestampToDate = timestamp ? new Date(timestamp) : new Date();
  291. const millisecondsTimestamp = timestampToDate.getTime();
  292. dispatch(addMessage({
  293. displayName,
  294. hasRead,
  295. id,
  296. messageType: participant.local ? MESSAGE_TYPE_LOCAL : MESSAGE_TYPE_REMOTE,
  297. message,
  298. privateMessage,
  299. recipient: getParticipantDisplayName(state, localParticipant.id),
  300. timestamp: millisecondsTimestamp
  301. }));
  302. if (typeof APP !== 'undefined') {
  303. // Logic for web only:
  304. APP.API.notifyReceivedChatMessage({
  305. body: message,
  306. id,
  307. nick: displayName,
  308. privateMessage,
  309. ts: timestamp
  310. });
  311. dispatch(showToolbox(4000));
  312. }
  313. }
  314. /**
  315. * Persists the sent private messages as if they were received over the muc.
  316. *
  317. * This is required as we rely on the fact that we receive all messages from the muc that we send
  318. * (as they are sent to everybody), but we don't receive the private messages we send to another participant.
  319. * But those messages should be in the store as well, otherwise they don't appear in the chat window.
  320. *
  321. * @param {Store} store - The Redux store.
  322. * @param {string} recipientID - The ID of the recipient the private message was sent to.
  323. * @param {string} message - The sent message.
  324. * @returns {void}
  325. */
  326. function _persistSentPrivateMessage({ dispatch, getState }, recipientID, message) {
  327. const localParticipant = getLocalParticipant(getState);
  328. const displayName = getParticipantDisplayName(getState, localParticipant.id);
  329. dispatch(addMessage({
  330. displayName,
  331. hasRead: true,
  332. id: localParticipant.id,
  333. messageType: MESSAGE_TYPE_LOCAL,
  334. message,
  335. privateMessage: true,
  336. recipient: getParticipantDisplayName(getState, recipientID),
  337. timestamp: Date.now()
  338. }));
  339. }
  340. /**
  341. * Returns the ID of the participant who we may have wanted to send the message
  342. * that we're about to send.
  343. *
  344. * @param {Object} state - The Redux state.
  345. * @param {Object} action - The action being dispatched now.
  346. * @returns {string?}
  347. */
  348. function _shouldSendPrivateMessageTo(state, action): ?string {
  349. if (action.ignorePrivacy) {
  350. // Shortcut: this is only true, if we already displayed the notice, so no need to show it again.
  351. return undefined;
  352. }
  353. const { messages, privateMessageRecipient } = state['features/chat'];
  354. if (privateMessageRecipient) {
  355. // We're already sending a private message, no need to warn about privacy.
  356. return undefined;
  357. }
  358. if (!messages.length) {
  359. // No messages yet, no need to warn for privacy.
  360. return undefined;
  361. }
  362. // Platforms sort messages differently
  363. const lastMessage = navigator.product === 'ReactNative'
  364. ? messages[0] : messages[messages.length - 1];
  365. if (lastMessage.messageType === MESSAGE_TYPE_LOCAL) {
  366. // The sender is probably aware of any private messages as already sent
  367. // a message since then. Doesn't make sense to display the notice now.
  368. return undefined;
  369. }
  370. if (lastMessage.privateMessage) {
  371. // We show the notice if the last received message was private.
  372. return lastMessage.id;
  373. }
  374. // But messages may come rapidly, we want to protect our users from mis-sending a message
  375. // even when there was a reasonable recently received private message.
  376. const now = Date.now();
  377. const recentPrivateMessages = messages.filter(
  378. message =>
  379. message.messageType !== MESSAGE_TYPE_LOCAL
  380. && message.privateMessage
  381. && message.timestamp + PRIVACY_NOTICE_TIMEOUT > now);
  382. const recentPrivateMessage = navigator.product === 'ReactNative'
  383. ? recentPrivateMessages[0] : recentPrivateMessages[recentPrivateMessages.length - 1];
  384. if (recentPrivateMessage) {
  385. return recentPrivateMessage.id;
  386. }
  387. return undefined;
  388. }