Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

middleware.js 14KB

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