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

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