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 12KB

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