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

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