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

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