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

middleware.js 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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 { NOTIFICATION_TIMEOUT_TYPE, showMessageNotification } from '../notifications';
  20. import { resetNbUnreadPollsMessages } from '../polls/actions';
  21. import { ADD_REACTION_MESSAGE } from '../reactions/actionTypes';
  22. import { pushReactions } from '../reactions/actions.any';
  23. import { ENDPOINT_REACTION_NAME } from '../reactions/constants';
  24. import { getReactionMessageFromBuffer, isReactionsEnabled } from '../reactions/functions.any';
  25. import { endpointMessageReceived } from '../subtitles';
  26. import {
  27. showToolbox
  28. } from '../toolbox/actions';
  29. import { ADD_MESSAGE, SEND_MESSAGE, OPEN_CHAT, CLOSE_CHAT, SET_IS_POLL_TAB_FOCUSED } from './actionTypes';
  30. import { addMessage, clearMessages } from './actions';
  31. import { closeChat } from './actions.any';
  32. import { ChatPrivacyDialog } from './components';
  33. import {
  34. INCOMING_MSG_SOUND_ID,
  35. MESSAGE_TYPE_ERROR,
  36. MESSAGE_TYPE_LOCAL,
  37. MESSAGE_TYPE_REMOTE
  38. } from './constants';
  39. import { getUnreadCount } from './functions';
  40. import { INCOMING_MSG_SOUND_FILE } from './sounds';
  41. declare var APP: Object;
  42. declare var interfaceConfig : Object;
  43. /**
  44. * Timeout for when to show the privacy notice after a private message was received.
  45. *
  46. * E.g. If this value is 20 secs (20000ms), then we show the privacy notice when sending a non private
  47. * message after we have received a private message in the last 20 seconds.
  48. */
  49. const PRIVACY_NOTICE_TIMEOUT = 20 * 1000;
  50. /**
  51. * Implements the middleware of the chat feature.
  52. *
  53. * @param {Store} store - The redux store.
  54. * @returns {Function}
  55. */
  56. MiddlewareRegistry.register(store => next => action => {
  57. const { dispatch, getState } = store;
  58. const localParticipant = getLocalParticipant(getState());
  59. let isOpen, unreadCount;
  60. switch (action.type) {
  61. case ADD_MESSAGE:
  62. unreadCount = getUnreadCount(getState());
  63. if (action.isReaction) {
  64. action.hasRead = false;
  65. } else {
  66. unreadCount = action.hasRead ? 0 : unreadCount + 1;
  67. }
  68. isOpen = getState()['features/chat'].isOpen;
  69. if (typeof APP !== 'undefined') {
  70. APP.API.notifyChatUpdated(unreadCount, isOpen);
  71. }
  72. break;
  73. case APP_WILL_MOUNT:
  74. dispatch(
  75. registerSound(INCOMING_MSG_SOUND_ID, INCOMING_MSG_SOUND_FILE));
  76. break;
  77. case APP_WILL_UNMOUNT:
  78. dispatch(unregisterSound(INCOMING_MSG_SOUND_ID));
  79. break;
  80. case CONFERENCE_JOINED:
  81. _addChatMsgListener(action.conference, store);
  82. break;
  83. case OPEN_CHAT:
  84. unreadCount = 0;
  85. if (typeof APP !== 'undefined') {
  86. APP.API.notifyChatUpdated(unreadCount, true);
  87. }
  88. break;
  89. case CLOSE_CHAT: {
  90. const isPollTabOpen = getState()['features/chat'].isPollsTabFocused;
  91. unreadCount = 0;
  92. if (typeof APP !== 'undefined') {
  93. APP.API.notifyChatUpdated(unreadCount, false);
  94. }
  95. if (isPollTabOpen) {
  96. dispatch(resetNbUnreadPollsMessages());
  97. }
  98. break;
  99. }
  100. case SET_IS_POLL_TAB_FOCUSED: {
  101. dispatch(resetNbUnreadPollsMessages());
  102. break;
  103. }
  104. case SEND_MESSAGE: {
  105. const state = store.getState();
  106. const { conference } = state['features/base/conference'];
  107. if (conference) {
  108. // There may be cases when we intend to send a private message but we forget to set the
  109. // recipient. This logic tries to mitigate this risk.
  110. const shouldSendPrivateMessageTo = _shouldSendPrivateMessageTo(state, action);
  111. if (shouldSendPrivateMessageTo) {
  112. dispatch(openDialog(ChatPrivacyDialog, {
  113. message: action.message,
  114. participantID: shouldSendPrivateMessageTo
  115. }));
  116. } else {
  117. // Sending the message if privacy notice doesn't need to be shown.
  118. const { privateMessageRecipient } = state['features/chat'];
  119. if (typeof APP !== 'undefined') {
  120. APP.API.notifySendingChatMessage(action.message, Boolean(privateMessageRecipient));
  121. }
  122. if (privateMessageRecipient) {
  123. conference.sendPrivateTextMessage(privateMessageRecipient.id, action.message);
  124. _persistSentPrivateMessage(store, privateMessageRecipient.id, action.message);
  125. } else {
  126. conference.sendTextMessage(action.message);
  127. }
  128. }
  129. }
  130. break;
  131. }
  132. case ADD_REACTION_MESSAGE: {
  133. _handleReceivedMessage(store, {
  134. id: localParticipant.id,
  135. message: action.message,
  136. privateMessage: false,
  137. timestamp: Date.now()
  138. }, false, true);
  139. }
  140. }
  141. return next(action);
  142. });
  143. /**
  144. * Set up state change listener to perform maintenance tasks when the conference
  145. * is left or failed, e.g. Clear messages or close the chat modal if it's left
  146. * open.
  147. */
  148. StateListenerRegistry.register(
  149. state => getCurrentConference(state),
  150. (conference, { dispatch, getState }, previousConference) => {
  151. if (conference !== previousConference) {
  152. // conference changed, left or failed...
  153. if (getState()['features/chat'].isOpen) {
  154. // Closes the chat if it's left open.
  155. dispatch(closeChat());
  156. }
  157. // Clear chat messages.
  158. dispatch(clearMessages());
  159. }
  160. });
  161. StateListenerRegistry.register(
  162. state => state['features/chat'].isOpen,
  163. (isOpen, { dispatch }) => {
  164. if (typeof APP !== 'undefined' && isOpen) {
  165. dispatch(showToolbox());
  166. }
  167. }
  168. );
  169. /**
  170. * Registers listener for {@link JitsiConferenceEvents.MESSAGE_RECEIVED} that
  171. * will perform various chat related activities.
  172. *
  173. * @param {JitsiConference} conference - The conference instance on which the
  174. * new event listener will be registered.
  175. * @param {Object} store - The redux store object.
  176. * @private
  177. * @returns {void}
  178. */
  179. function _addChatMsgListener(conference, store) {
  180. if (store.getState()['features/base/config'].iAmRecorder) {
  181. // We don't register anything on web if we are in iAmRecorder mode
  182. return;
  183. }
  184. conference.on(
  185. JitsiConferenceEvents.MESSAGE_RECEIVED,
  186. (id, message, timestamp) => {
  187. _handleReceivedMessage(store, {
  188. id,
  189. message,
  190. privateMessage: false,
  191. timestamp
  192. });
  193. }
  194. );
  195. conference.on(
  196. JitsiConferenceEvents.PRIVATE_MESSAGE_RECEIVED,
  197. (id, message, timestamp) => {
  198. _handleReceivedMessage(store, {
  199. id,
  200. message,
  201. privateMessage: true,
  202. timestamp
  203. });
  204. }
  205. );
  206. conference.on(
  207. JitsiConferenceEvents.ENDPOINT_MESSAGE_RECEIVED,
  208. (...args) => {
  209. const state = store.getState();
  210. if (!isReactionsEnabled(state)) {
  211. return;
  212. }
  213. store.dispatch(endpointMessageReceived(...args));
  214. if (args && args.length >= 2) {
  215. const [ { _id }, eventData ] = args;
  216. if (eventData.name === ENDPOINT_REACTION_NAME) {
  217. store.dispatch(pushReactions(eventData.reactions));
  218. _handleReceivedMessage(store, {
  219. id: _id,
  220. message: getReactionMessageFromBuffer(eventData.reactions),
  221. privateMessage: false,
  222. timestamp: eventData.timestamp
  223. }, false, true);
  224. }
  225. }
  226. });
  227. conference.on(
  228. JitsiConferenceEvents.CONFERENCE_ERROR, (errorType, error) => {
  229. errorType === JitsiConferenceErrors.CHAT_ERROR && _handleChatError(store, error);
  230. });
  231. }
  232. /**
  233. * Handles a chat error received from the xmpp server.
  234. *
  235. * @param {Store} store - The Redux store.
  236. * @param {string} error - The error message.
  237. * @returns {void}
  238. */
  239. function _handleChatError({ dispatch }, error) {
  240. dispatch(addMessage({
  241. hasRead: true,
  242. messageType: MESSAGE_TYPE_ERROR,
  243. message: error,
  244. privateMessage: false,
  245. timestamp: Date.now()
  246. }));
  247. }
  248. /**
  249. * Function to handle an incoming chat message.
  250. *
  251. * @param {Store} store - The Redux store.
  252. * @param {Object} message - The message object.
  253. * @param {boolean} shouldPlaySound - Whether or not to play the incoming message sound.
  254. * @param {boolean} isReaction - Whether or not the message is a reaction message.
  255. * @returns {void}
  256. */
  257. function _handleReceivedMessage({ dispatch, getState },
  258. { id, message, privateMessage, timestamp },
  259. shouldPlaySound = true,
  260. isReaction = false
  261. ) {
  262. // Logic for all platforms:
  263. const state = getState();
  264. const { isOpen: isChatOpen } = state['features/chat'];
  265. const { iAmRecorder } = state['features/base/config'];
  266. const { soundsIncomingMessage: soundEnabled, userSelectedNotifications } = state['features/base/settings'];
  267. if (soundEnabled && shouldPlaySound && !isChatOpen) {
  268. dispatch(playSound(INCOMING_MSG_SOUND_ID));
  269. }
  270. // Provide a default for for the case when a message is being
  271. // backfilled for a participant that has left the conference.
  272. const participant = getParticipantById(state, id) || {};
  273. const localParticipant = getLocalParticipant(getState);
  274. const displayName = getParticipantDisplayName(state, id);
  275. const hasRead = participant.local || isChatOpen;
  276. const timestampToDate = timestamp ? new Date(timestamp) : new Date();
  277. const millisecondsTimestamp = timestampToDate.getTime();
  278. const shouldShowNotification = userSelectedNotifications['notify.chatMessages'] && !hasRead && !isReaction;
  279. dispatch(addMessage({
  280. displayName,
  281. hasRead,
  282. id,
  283. messageType: participant.local ? MESSAGE_TYPE_LOCAL : MESSAGE_TYPE_REMOTE,
  284. message,
  285. privateMessage,
  286. recipient: getParticipantDisplayName(state, localParticipant.id),
  287. timestamp: millisecondsTimestamp,
  288. isReaction
  289. }));
  290. if (shouldShowNotification) {
  291. dispatch(showMessageNotification({
  292. title: displayName,
  293. description: message
  294. }, NOTIFICATION_TIMEOUT_TYPE.MEDIUM));
  295. }
  296. if (typeof APP !== 'undefined') {
  297. // Logic for web only:
  298. APP.API.notifyReceivedChatMessage({
  299. body: message,
  300. id,
  301. nick: displayName,
  302. privateMessage,
  303. ts: timestamp
  304. });
  305. if (!iAmRecorder) {
  306. dispatch(showToolbox(4000));
  307. }
  308. }
  309. }
  310. /**
  311. * Persists the sent private messages as if they were received over the muc.
  312. *
  313. * This is required as we rely on the fact that we receive all messages from the muc that we send
  314. * (as they are sent to everybody), but we don't receive the private messages we send to another participant.
  315. * But those messages should be in the store as well, otherwise they don't appear in the chat window.
  316. *
  317. * @param {Store} store - The Redux store.
  318. * @param {string} recipientID - The ID of the recipient the private message was sent to.
  319. * @param {string} message - The sent message.
  320. * @returns {void}
  321. */
  322. function _persistSentPrivateMessage({ dispatch, getState }, recipientID, message) {
  323. const localParticipant = getLocalParticipant(getState);
  324. const displayName = getParticipantDisplayName(getState, localParticipant.id);
  325. dispatch(addMessage({
  326. displayName,
  327. hasRead: true,
  328. id: localParticipant.id,
  329. messageType: MESSAGE_TYPE_LOCAL,
  330. message,
  331. privateMessage: true,
  332. recipient: getParticipantDisplayName(getState, recipientID),
  333. timestamp: Date.now()
  334. }));
  335. }
  336. /**
  337. * Returns the ID of the participant who we may have wanted to send the message
  338. * that we're about to send.
  339. *
  340. * @param {Object} state - The Redux state.
  341. * @param {Object} action - The action being dispatched now.
  342. * @returns {string?}
  343. */
  344. function _shouldSendPrivateMessageTo(state, action): ?string {
  345. if (action.ignorePrivacy) {
  346. // Shortcut: this is only true, if we already displayed the notice, so no need to show it again.
  347. return undefined;
  348. }
  349. const { messages, privateMessageRecipient } = state['features/chat'];
  350. if (privateMessageRecipient) {
  351. // We're already sending a private message, no need to warn about privacy.
  352. return undefined;
  353. }
  354. if (!messages.length) {
  355. // No messages yet, no need to warn for privacy.
  356. return undefined;
  357. }
  358. // Platforms sort messages differently
  359. const lastMessage = navigator.product === 'ReactNative'
  360. ? messages[0] : messages[messages.length - 1];
  361. if (lastMessage.messageType === MESSAGE_TYPE_LOCAL) {
  362. // The sender is probably aware of any private messages as already sent
  363. // a message since then. Doesn't make sense to display the notice now.
  364. return undefined;
  365. }
  366. if (lastMessage.privateMessage) {
  367. // We show the notice if the last received message was private.
  368. return lastMessage.id;
  369. }
  370. // But messages may come rapidly, we want to protect our users from mis-sending a message
  371. // even when there was a reasonable recently received private message.
  372. const now = Date.now();
  373. const recentPrivateMessages = messages.filter(
  374. message =>
  375. message.messageType !== MESSAGE_TYPE_LOCAL
  376. && message.privateMessage
  377. && message.timestamp + PRIVACY_NOTICE_TIMEOUT > now);
  378. const recentPrivateMessage = navigator.product === 'ReactNative'
  379. ? recentPrivateMessages[0] : recentPrivateMessages[recentPrivateMessages.length - 1];
  380. if (recentPrivateMessage) {
  381. return recentPrivateMessage.id;
  382. }
  383. return undefined;
  384. }