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

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