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

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