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

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