您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

middleware.js 11KB

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