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

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