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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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 {
  13. getLocalParticipant,
  14. getParticipantById,
  15. getParticipantDisplayName
  16. } from '../base/participants';
  17. import { MiddlewareRegistry, StateListenerRegistry } from '../base/redux';
  18. import { playSound, registerSound, unregisterSound } from '../base/sounds';
  19. import { resetNbUnreadPollsMessages } from '../polls/actions';
  20. import { ADD_REACTION_MESSAGE } from '../reactions/actionTypes';
  21. import { pushReactions } from '../reactions/actions.any';
  22. import { ENDPOINT_REACTION_NAME } from '../reactions/constants';
  23. import { getReactionMessageFromBuffer, isReactionsEnabled } from '../reactions/functions.any';
  24. import { endpointMessageReceived } from '../subtitles';
  25. import {
  26. showToolbox
  27. } from '../toolbox/actions';
  28. import { ADD_MESSAGE, SEND_MESSAGE, OPEN_CHAT, CLOSE_CHAT, SET_IS_POLL_TAB_FOCUSED } from './actionTypes';
  29. import { addMessage, clearMessages } from './actions';
  30. import { closeChat } from './actions.any';
  31. import { ChatPrivacyDialog } from './components';
  32. import {
  33. INCOMING_MSG_SOUND_ID,
  34. MESSAGE_TYPE_ERROR,
  35. MESSAGE_TYPE_LOCAL,
  36. MESSAGE_TYPE_REMOTE
  37. } from './constants';
  38. import { getUnreadCount } from './functions';
  39. import { INCOMING_MSG_SOUND_FILE } from './sounds';
  40. declare var APP: Object;
  41. declare var interfaceConfig : Object;
  42. /**
  43. * Timeout for when to show the privacy notice after a private message was received.
  44. *
  45. * E.g. if this value is 20 secs (20000ms), then we show the privacy notice when sending a non private
  46. * message after we have received a private message in the last 20 seconds.
  47. */
  48. const PRIVACY_NOTICE_TIMEOUT = 20 * 1000;
  49. /**
  50. * Implements the middleware of the chat feature.
  51. *
  52. * @param {Store} store - The redux store.
  53. * @returns {Function}
  54. */
  55. MiddlewareRegistry.register(store => next => action => {
  56. const { dispatch, getState } = store;
  57. const localParticipant = getLocalParticipant(getState());
  58. let isOpen, unreadCount;
  59. switch (action.type) {
  60. case ADD_MESSAGE:
  61. unreadCount = getUnreadCount(getState());
  62. if (action.isReaction) {
  63. action.hasRead = false;
  64. } else {
  65. unreadCount = action.hasRead ? 0 : unreadCount + 1;
  66. }
  67. isOpen = getState()['features/chat'].isOpen;
  68. if (typeof APP !== 'undefined') {
  69. APP.API.notifyChatUpdated(unreadCount, isOpen);
  70. }
  71. break;
  72. case APP_WILL_MOUNT:
  73. dispatch(
  74. registerSound(INCOMING_MSG_SOUND_ID, INCOMING_MSG_SOUND_FILE));
  75. break;
  76. case APP_WILL_UNMOUNT:
  77. dispatch(unregisterSound(INCOMING_MSG_SOUND_ID));
  78. break;
  79. case CONFERENCE_JOINED:
  80. _addChatMsgListener(action.conference, store);
  81. break;
  82. case OPEN_CHAT:
  83. unreadCount = 0;
  84. if (typeof APP !== 'undefined') {
  85. APP.API.notifyChatUpdated(unreadCount, true);
  86. }
  87. break;
  88. case CLOSE_CHAT: {
  89. const isPollTabOpen = getState()['features/chat'].isPollsTabFocused;
  90. unreadCount = 0;
  91. if (typeof APP !== 'undefined') {
  92. APP.API.notifyChatUpdated(unreadCount, false);
  93. }
  94. if (isPollTabOpen) {
  95. dispatch(resetNbUnreadPollsMessages());
  96. }
  97. break;
  98. }
  99. case SET_IS_POLL_TAB_FOCUSED: {
  100. dispatch(resetNbUnreadPollsMessages());
  101. break;
  102. }
  103. case SEND_MESSAGE: {
  104. const state = store.getState();
  105. const { conference } = state['features/base/conference'];
  106. if (conference) {
  107. // There may be cases when we intend to send a private message but we forget to set the
  108. // recipient. This logic tries to mitigate this risk.
  109. const shouldSendPrivateMessageTo = _shouldSendPrivateMessageTo(state, action);
  110. if (shouldSendPrivateMessageTo) {
  111. dispatch(openDialog(ChatPrivacyDialog, {
  112. message: action.message,
  113. participantID: shouldSendPrivateMessageTo
  114. }));
  115. } else {
  116. // Sending the message if privacy notice doesn't need to be shown.
  117. const { privateMessageRecipient } = state['features/chat'];
  118. if (typeof APP !== 'undefined') {
  119. APP.API.notifySendingChatMessage(action.message, Boolean(privateMessageRecipient));
  120. }
  121. if (privateMessageRecipient) {
  122. conference.sendPrivateTextMessage(privateMessageRecipient.id, action.message);
  123. _persistSentPrivateMessage(store, privateMessageRecipient.id, action.message);
  124. } else {
  125. conference.sendTextMessage(action.message);
  126. }
  127. }
  128. }
  129. break;
  130. }
  131. case ADD_REACTION_MESSAGE: {
  132. _handleReceivedMessage(store, {
  133. id: localParticipant.id,
  134. message: action.message,
  135. privateMessage: false,
  136. timestamp: Date.now()
  137. }, false, true);
  138. }
  139. }
  140. return next(action);
  141. });
  142. /**
  143. * Set up state change listener to perform maintenance tasks when the conference
  144. * is left or failed, e.g. clear messages or close the chat modal if it's left
  145. * open.
  146. */
  147. StateListenerRegistry.register(
  148. state => getCurrentConference(state),
  149. (conference, { dispatch, getState }, previousConference) => {
  150. if (conference !== previousConference) {
  151. // conference changed, left or failed...
  152. if (getState()['features/chat'].isOpen) {
  153. // Closes the chat if it's left open.
  154. dispatch(closeChat());
  155. }
  156. // Clear chat messages.
  157. dispatch(clearMessages());
  158. }
  159. });
  160. StateListenerRegistry.register(
  161. state => state['features/chat'].isOpen,
  162. (isOpen, { dispatch }) => {
  163. if (typeof APP !== 'undefined' && isOpen) {
  164. dispatch(showToolbox());
  165. }
  166. }
  167. );
  168. /**
  169. * Registers listener for {@link JitsiConferenceEvents.MESSAGE_RECEIVED} that
  170. * will perform various chat related activities.
  171. *
  172. * @param {JitsiConference} conference - The conference instance on which the
  173. * new event listener will be registered.
  174. * @param {Object} store - The redux store object.
  175. * @private
  176. * @returns {void}
  177. */
  178. function _addChatMsgListener(conference, store) {
  179. if (store.getState()['features/base/config'].iAmRecorder) {
  180. // We don't register anything on web if we are in iAmRecorder mode
  181. return;
  182. }
  183. conference.on(
  184. JitsiConferenceEvents.MESSAGE_RECEIVED,
  185. (id, message, timestamp) => {
  186. _handleReceivedMessage(store, {
  187. id,
  188. message,
  189. privateMessage: false,
  190. timestamp
  191. });
  192. }
  193. );
  194. conference.on(
  195. JitsiConferenceEvents.PRIVATE_MESSAGE_RECEIVED,
  196. (id, message, timestamp) => {
  197. _handleReceivedMessage(store, {
  198. id,
  199. message,
  200. privateMessage: true,
  201. timestamp
  202. });
  203. }
  204. );
  205. conference.on(
  206. JitsiConferenceEvents.ENDPOINT_MESSAGE_RECEIVED,
  207. (...args) => {
  208. const state = store.getState();
  209. if (!isReactionsEnabled(state)) {
  210. return;
  211. }
  212. store.dispatch(endpointMessageReceived(...args));
  213. if (args && args.length >= 2) {
  214. const [ { _id }, eventData ] = args;
  215. if (eventData.name === ENDPOINT_REACTION_NAME) {
  216. store.dispatch(pushReactions(eventData.reactions));
  217. _handleReceivedMessage(store, {
  218. id: _id,
  219. message: getReactionMessageFromBuffer(eventData.reactions),
  220. privateMessage: false,
  221. timestamp: eventData.timestamp
  222. }, false, true);
  223. }
  224. }
  225. });
  226. conference.on(
  227. JitsiConferenceEvents.CONFERENCE_ERROR, (errorType, error) => {
  228. errorType === JitsiConferenceErrors.CHAT_ERROR && _handleChatError(store, error);
  229. });
  230. }
  231. /**
  232. * Handles a chat error received from the xmpp server.
  233. *
  234. * @param {Store} store - The Redux store.
  235. * @param {string} error - The error message.
  236. * @returns {void}
  237. */
  238. function _handleChatError({ dispatch }, error) {
  239. dispatch(addMessage({
  240. hasRead: true,
  241. messageType: MESSAGE_TYPE_ERROR,
  242. message: error,
  243. privateMessage: false,
  244. timestamp: Date.now()
  245. }));
  246. }
  247. /**
  248. * Function to handle an incoming chat message.
  249. *
  250. * @param {Store} store - The Redux store.
  251. * @param {Object} message - The message object.
  252. * @param {boolean} shouldPlaySound - Whether or not to play the incoming message sound.
  253. * @param {boolean} isReaction - Whether or not the message is a reaction message.
  254. * @returns {void}
  255. */
  256. function _handleReceivedMessage({ dispatch, getState },
  257. { id, message, privateMessage, timestamp },
  258. shouldPlaySound = true,
  259. isReaction = false
  260. ) {
  261. // Logic for all platforms:
  262. const state = getState();
  263. const { isOpen: isChatOpen } = state['features/chat'];
  264. const { iAmRecorder } = state['features/base/config'];
  265. const { soundsIncomingMessage: soundEnabled } = state['features/base/settings'];
  266. if (soundEnabled && shouldPlaySound && !isChatOpen) {
  267. dispatch(playSound(INCOMING_MSG_SOUND_ID));
  268. }
  269. // Provide a default for for the case when a message is being
  270. // backfilled for a participant that has left the conference.
  271. const participant = getParticipantById(state, id) || {};
  272. const localParticipant = getLocalParticipant(getState);
  273. const displayName = getParticipantDisplayName(state, id);
  274. const hasRead = participant.local || isChatOpen;
  275. const timestampToDate = timestamp ? new Date(timestamp) : new Date();
  276. const millisecondsTimestamp = timestampToDate.getTime();
  277. dispatch(addMessage({
  278. displayName,
  279. hasRead,
  280. id,
  281. messageType: participant.local ? MESSAGE_TYPE_LOCAL : MESSAGE_TYPE_REMOTE,
  282. message,
  283. privateMessage,
  284. recipient: getParticipantDisplayName(state, localParticipant.id),
  285. timestamp: millisecondsTimestamp,
  286. isReaction
  287. }));
  288. if (typeof APP !== 'undefined') {
  289. // Logic for web only:
  290. APP.API.notifyReceivedChatMessage({
  291. body: message,
  292. id,
  293. nick: displayName,
  294. privateMessage,
  295. ts: timestamp
  296. });
  297. if (!iAmRecorder) {
  298. dispatch(showToolbox(4000));
  299. }
  300. }
  301. }
  302. /**
  303. * Persists the sent private messages as if they were received over the muc.
  304. *
  305. * This is required as we rely on the fact that we receive all messages from the muc that we send
  306. * (as they are sent to everybody), but we don't receive the private messages we send to another participant.
  307. * But those messages should be in the store as well, otherwise they don't appear in the chat window.
  308. *
  309. * @param {Store} store - The Redux store.
  310. * @param {string} recipientID - The ID of the recipient the private message was sent to.
  311. * @param {string} message - The sent message.
  312. * @returns {void}
  313. */
  314. function _persistSentPrivateMessage({ dispatch, getState }, recipientID, message) {
  315. const localParticipant = getLocalParticipant(getState);
  316. const displayName = getParticipantDisplayName(getState, localParticipant.id);
  317. dispatch(addMessage({
  318. displayName,
  319. hasRead: true,
  320. id: localParticipant.id,
  321. messageType: MESSAGE_TYPE_LOCAL,
  322. message,
  323. privateMessage: true,
  324. recipient: getParticipantDisplayName(getState, recipientID),
  325. timestamp: Date.now()
  326. }));
  327. }
  328. /**
  329. * Returns the ID of the participant who we may have wanted to send the message
  330. * that we're about to send.
  331. *
  332. * @param {Object} state - The Redux state.
  333. * @param {Object} action - The action being dispatched now.
  334. * @returns {string?}
  335. */
  336. function _shouldSendPrivateMessageTo(state, action): ?string {
  337. if (action.ignorePrivacy) {
  338. // Shortcut: this is only true, if we already displayed the notice, so no need to show it again.
  339. return undefined;
  340. }
  341. const { messages, privateMessageRecipient } = state['features/chat'];
  342. if (privateMessageRecipient) {
  343. // We're already sending a private message, no need to warn about privacy.
  344. return undefined;
  345. }
  346. if (!messages.length) {
  347. // No messages yet, no need to warn for privacy.
  348. return undefined;
  349. }
  350. // Platforms sort messages differently
  351. const lastMessage = navigator.product === 'ReactNative'
  352. ? messages[0] : messages[messages.length - 1];
  353. if (lastMessage.messageType === MESSAGE_TYPE_LOCAL) {
  354. // The sender is probably aware of any private messages as already sent
  355. // a message since then. Doesn't make sense to display the notice now.
  356. return undefined;
  357. }
  358. if (lastMessage.privateMessage) {
  359. // We show the notice if the last received message was private.
  360. return lastMessage.id;
  361. }
  362. // But messages may come rapidly, we want to protect our users from mis-sending a message
  363. // even when there was a reasonable recently received private message.
  364. const now = Date.now();
  365. const recentPrivateMessages = messages.filter(
  366. message =>
  367. message.messageType !== MESSAGE_TYPE_LOCAL
  368. && message.privateMessage
  369. && message.timestamp + PRIVACY_NOTICE_TIMEOUT > now);
  370. const recentPrivateMessage = navigator.product === 'ReactNative'
  371. ? recentPrivateMessages[0] : recentPrivateMessages[recentPrivateMessages.length - 1];
  372. if (recentPrivateMessage) {
  373. return recentPrivateMessage.id;
  374. }
  375. return undefined;
  376. }