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

middleware.js 12KB

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