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

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