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

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