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

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