Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

middleware.js 17KB

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