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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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 interfaceConfig === 'object' && interfaceConfig.filmStripOnly)
  135. || (typeof APP !== 'undefined' && !isButtonEnabled('chat'))
  136. || store.getState()['features/base/config'].iAmRecorder) {
  137. // We don't register anything on web if we're in filmStripOnly mode, or
  138. // the chat button is not enabled in interfaceConfig.
  139. // or we are in iAmRecorder mode
  140. return;
  141. }
  142. conference.on(
  143. JitsiConferenceEvents.MESSAGE_RECEIVED,
  144. (id, message, timestamp, nick) => {
  145. _handleReceivedMessage(store, {
  146. id,
  147. message,
  148. nick,
  149. privateMessage: false,
  150. timestamp
  151. });
  152. }
  153. );
  154. conference.on(
  155. JitsiConferenceEvents.PRIVATE_MESSAGE_RECEIVED,
  156. (id, message, timestamp) => {
  157. _handleReceivedMessage(store, {
  158. id,
  159. message,
  160. privateMessage: true,
  161. timestamp,
  162. nick: undefined
  163. });
  164. }
  165. );
  166. conference.on(
  167. JitsiConferenceEvents.CONFERENCE_ERROR, (errorType, error) => {
  168. errorType === JitsiConferenceErrors.CHAT_ERROR && _handleChatError(store, error);
  169. });
  170. }
  171. /**
  172. * Handles a chat error received from the xmpp server.
  173. *
  174. * @param {Store} store - The Redux store.
  175. * @param {string} error - The error message.
  176. * @returns {void}
  177. */
  178. function _handleChatError({ dispatch }, error) {
  179. dispatch(addMessage({
  180. hasRead: true,
  181. messageType: MESSAGE_TYPE_ERROR,
  182. message: error,
  183. privateMessage: false,
  184. timestamp: Date.now()
  185. }));
  186. }
  187. /**
  188. * Function to handle an incoming chat message.
  189. *
  190. * @param {Store} store - The Redux store.
  191. * @param {Object} message - The message object.
  192. * @returns {void}
  193. */
  194. function _handleReceivedMessage({ dispatch, getState }, { id, message, nick, privateMessage, timestamp }) {
  195. // Logic for all platforms:
  196. const state = getState();
  197. const { isOpen: isChatOpen } = state['features/chat'];
  198. if (!isChatOpen) {
  199. dispatch(playSound(INCOMING_MSG_SOUND_ID));
  200. }
  201. // Provide a default for for the case when a message is being
  202. // backfilled for a participant that has left the conference.
  203. const participant = getParticipantById(state, id) || {};
  204. const localParticipant = getLocalParticipant(getState);
  205. const displayName = participant.name || nick || getParticipantDisplayName(state, id);
  206. const hasRead = participant.local || isChatOpen;
  207. const timestampToDate = timestamp
  208. ? new Date(timestamp) : new Date();
  209. const millisecondsTimestamp = timestampToDate.getTime();
  210. dispatch(addMessage({
  211. displayName,
  212. hasRead,
  213. id,
  214. messageType: participant.local ? MESSAGE_TYPE_LOCAL : MESSAGE_TYPE_REMOTE,
  215. message,
  216. privateMessage,
  217. recipient: getParticipantDisplayName(state, localParticipant.id),
  218. timestamp: millisecondsTimestamp
  219. }));
  220. if (typeof APP !== 'undefined') {
  221. // Logic for web only:
  222. APP.API.notifyReceivedChatMessage({
  223. body: message,
  224. id,
  225. nick: displayName,
  226. ts: timestamp
  227. });
  228. dispatch(showToolbox(4000));
  229. }
  230. }
  231. /**
  232. * Focuses the chat text field on web after the message recipient was updated, if needed.
  233. *
  234. * @returns {void}
  235. */
  236. function _maybeFocusField() {
  237. if (navigator.product !== 'ReactNative') {
  238. const textField = document.getElementById('usermsg');
  239. textField && textField.focus();
  240. }
  241. }
  242. /**
  243. * Persists the sent private messages as if they were received over the muc.
  244. *
  245. * This is required as we rely on the fact that we receive all messages from the muc that we send
  246. * (as they are sent to everybody), but we don't receive the private messages we send to another participant.
  247. * But those messages should be in the store as well, otherwise they don't appear in the chat window.
  248. *
  249. * @param {Store} store - The Redux store.
  250. * @param {string} recipientID - The ID of the recipient the private message was sent to.
  251. * @param {string} message - The sent message.
  252. * @returns {void}
  253. */
  254. function _persistSentPrivateMessage({ dispatch, getState }, recipientID, message) {
  255. const localParticipant = getLocalParticipant(getState);
  256. const displayName = getParticipantDisplayName(getState, localParticipant.id);
  257. dispatch(addMessage({
  258. displayName,
  259. hasRead: true,
  260. id: localParticipant.id,
  261. messageType: MESSAGE_TYPE_LOCAL,
  262. message,
  263. privateMessage: true,
  264. recipient: getParticipantDisplayName(getState, recipientID),
  265. timestamp: Date.now()
  266. }));
  267. }
  268. /**
  269. * Returns the ID of the participant who we may have wanted to send the message
  270. * that we're about to send.
  271. *
  272. * @param {Object} state - The Redux state.
  273. * @param {Object} action - The action being dispatched now.
  274. * @returns {string?}
  275. */
  276. function _shouldSendPrivateMessageTo(state, action): ?string {
  277. if (action.ignorePrivacy) {
  278. // Shortcut: this is only true, if we already displayed the notice, so no need to show it again.
  279. return undefined;
  280. }
  281. const { messages, privateMessageRecipient } = state['features/chat'];
  282. if (privateMessageRecipient) {
  283. // We're already sending a private message, no need to warn about privacy.
  284. return undefined;
  285. }
  286. if (!messages.length) {
  287. // No messages yet, no need to warn for privacy.
  288. return undefined;
  289. }
  290. // Platforms sort messages differently
  291. const lastMessage = navigator.product === 'ReactNative'
  292. ? messages[0] : messages[messages.length - 1];
  293. if (lastMessage.messageType === MESSAGE_TYPE_LOCAL) {
  294. // The sender is probably aware of any private messages as already sent
  295. // a message since then. Doesn't make sense to display the notice now.
  296. return undefined;
  297. }
  298. if (lastMessage.privateMessage) {
  299. // We show the notice if the last received message was private.
  300. return lastMessage.id;
  301. }
  302. // But messages may come rapidly, we want to protect our users from mis-sending a message
  303. // even when there was a reasonable recently received private message.
  304. const now = Date.now();
  305. const recentPrivateMessages = messages.filter(
  306. message =>
  307. message.messageType !== MESSAGE_TYPE_LOCAL
  308. && message.privateMessage
  309. && message.timestamp + PRIVACY_NOTICE_TIMEOUT > now);
  310. const recentPrivateMessage = navigator.product === 'ReactNative'
  311. ? recentPrivateMessages[0] : recentPrivateMessages[recentPrivateMessages.length - 1];
  312. if (recentPrivateMessage) {
  313. return recentPrivateMessage.id;
  314. }
  315. return undefined;
  316. }