Skip to content

Jitsi Meet - Secure, Simple and Scalable Video Conferences that you use as a standalone app or embed in your web application.

fix(chat): follow-ups for deleted and moderated messages (#18007)

Дамян Минков74ff29203617
diff --git a/react/features/chat/components/native/ChatMessage.tsx b/react/features/chat/components/native/ChatMessage.tsx
index a9587b169b..7877adccd7 100644
--- a/react/features/chat/components/native/ChatMessage.tsx
+++ b/react/features/chat/components/native/ChatMessage.tsx
@@ -81,10 +81,11 @@ class ChatMessage extends Component<IChatMessageProps> {
messageBubbleStyle.push(styles.activeMatchMessageBubble);
}
- const messageText = message.isDeleted
- ? this.props.t(localMessage ? 'chat.deletedMessageByMe' : 'chat.deletedMessage')
- : message.isModerated
- ? this.props.t('chat.moderatedMessage')
+ // A moderation is shown over a retraction, as its reason is shown as well.
+ const messageText = message.isModerated
+ ? this.props.t('chat.moderatedMessage')
+ : message.isDeleted
+ ? this.props.t(localMessage ? 'chat.deletedMessageByMe' : 'chat.deletedMessage')
: getMessageText(this.props.message);
return (
@@ -99,6 +100,7 @@ class ChatMessage extends Component<IChatMessageProps> {
{ gifEnabled && isGifMessage(messageText)
? <GifMessage message = { messageText } />
: this._renderMessageTextComponent(messageText) }
+ { this._renderModerationReason() }
{ this._renderPrivateNotice() }
</View>
{ !message.isDeleted && !message.isModerated && this._renderPrivateReplyButton() }
@@ -230,6 +232,25 @@ class ChatMessage extends Component<IChatMessageProps> {
);
}
+ /**
+ * Renders the reason a moderator gave for removing the message, if any.
+ *
+ * @returns {React.ReactElement<*> | null}
+ */
+ _renderModerationReason() {
+ const { message, t } = this.props;
+
+ if (!message.isModerated || !message.moderationReason) {
+ return null;
+ }
+
+ return (
+ <Text style = { styles.privateNotice }>
+ { t('chat.moderationReason', { reason: message.moderationReason }) }
+ </Text>
+ );
+ }
+
/**
* Renders the private reply button, if necessary.
*
@@ -286,7 +307,8 @@ function _mapStateToProps(state: IReduxState, { message }: IChatMessageProps) {
return {
canReply: getCanReplyToMessage(state, message),
gifEnabled: isGifEnabled(state),
- highlightQuery: getChatSearchQuery(state),
+ // A deleted or moderated message shows a placeholder, which is not searched, so do not highlight it.
+ highlightQuery: message.isDeleted || message.isModerated ? '' : getChatSearchQuery(state),
isActiveMatch: Boolean(activeMatch && activeMatch.messageId === message.messageId),
knocking: state['features/lobby'].knocking
};
diff --git a/react/features/chat/components/web/ChatHeader.tsx b/react/features/chat/components/web/ChatHeader.tsx
index 694fc9f8ed..7773328181 100644
--- a/react/features/chat/components/web/ChatHeader.tsx
+++ b/react/features/chat/components/web/ChatHeader.tsx
@@ -211,14 +211,6 @@ function ChatHeader({ className, isCCTabEnabled, isPollsEnabled, onCancel: onCan
};
}, []);
- // Keep matchIndex in bounds whenever the match set shrinks (new query, or a message
- // disappearing) so `matches[matchIndex]` never reads undefined downstream.
- useEffect(() => {
- if (matchIndex >= matches.length && matches.length > 0) {
- dispatch(setChatSearchMatchIndex(0));
- }
- }, [ matches.length, matchIndex, dispatch ]);
-
// Close the search bar if the user switches away from the Chat tab (e.g. to Polls/CC/
// File sharing) without closing the whole panel — search only makes sense on the Chat tab.
useEffect(() => {
diff --git a/react/features/chat/components/web/ChatMessage.tsx b/react/features/chat/components/web/ChatMessage.tsx
index 664729f356..5fa43db22c 100644
--- a/react/features/chat/components/web/ChatMessage.tsx
+++ b/react/features/chat/components/web/ChatMessage.tsx
@@ -453,16 +453,20 @@ const ChatMessage = ({
);
}, [ message?.reactions, isHovered, isReactionsOpen ]);
- const messageText = message.isDeleted
- ? (
- message.messageType === MESSAGE_TYPE_LOCAL
- ? t<string>('chat.deletedMessageByMe')
- : t<string>('chat.deletedMessage')
- )
- : message.isModerated
- ? t('chat.moderatedMessage')
+ // A moderation is shown over a retraction, as its reason is shown as well.
+ const messageText = message.isModerated
+ ? t('chat.moderatedMessage')
+ : message.isDeleted
+ ? (
+ message.messageType === MESSAGE_TYPE_LOCAL
+ ? t<string>('chat.deletedMessageByMe')
+ : t<string>('chat.deletedMessage')
+ )
: getMessageText(message);
+ // A removed file message shows the text placeholder instead of the file.
+ const showFile = !message.isDeleted && !message.isModerated && isFileMessage(message);
+
const canEdit = message.messageType === MESSAGE_TYPE_LOCAL
&& !message.lobbyChat
&& !message.isReaction
@@ -479,7 +483,7 @@ const ChatMessage = ({
<div className = { classes.sideBySideContainer }>
{!shouldDisplayMenuOnRight && (
<div className = { classes.optionsButtonContainer }>
- {isHovered && !message.isModerated && <MessageMenu
+ {isHovered && !message.isDeleted && !message.isModerated && <MessageMenu
canEdit = { canEdit }
displayName = { message.displayName }
enablePrivateChat = { Boolean(enablePrivateChat) }
@@ -499,15 +503,15 @@ const ChatMessage = ({
className,
message.privateMessage && 'privatemessage',
message.lobbyChat && !knocking && 'lobbymessage',
- isFileMessage(message) && 'file',
+ showFile && 'file',
isActiveSearchMatch && classes.searchMatchActive
) }
ref = { messageRef }>
<div className = { classes.replyWrapper }>
<div className = { cx('messagecontent', classes.messageContent) }>
{showDisplayName && _renderDisplayName()}
- <div className = { cx('usermessage', classes.userMessage, message.isDeleted && message.isModerated && classes.deletedMessage) }>
- {!message.isModerated && isFileMessage(message) ? (
+ <div className = { cx('usermessage', classes.userMessage, (message.isDeleted || message.isModerated) && classes.deletedMessage) }>
+ {showFile ? (
<FileMessage
message = { message }
screenReaderHelpText = { message.messageType === MESSAGE_TYPE_LOCAL
@@ -544,7 +548,7 @@ const ChatMessage = ({
</>
)}
</div>
- {message.isEdited && (
+ {message.isEdited && !message.isDeleted && !message.isModerated && (
<div className = { classes.editedLabel }>
{t('chat.edited', '(edited)')}
</div>
@@ -619,7 +623,8 @@ function _mapStateToProps(state: IReduxState, { message }: IProps) {
shouldDisplayMenuOnRight,
enablePrivateChat,
isActiveSearchMatch,
- searchQuery: getChatSearchQuery(state),
+ // A deleted or moderated message shows a placeholder, which is not searched, so do not highlight it.
+ searchQuery: message.isDeleted || message.isModerated ? '' : getChatSearchQuery(state),
knocking,
state
};
diff --git a/react/features/chat/constants.ts b/react/features/chat/constants.ts
index fb9242e374..21cae0fe5e 100644
--- a/react/features/chat/constants.ts
+++ b/react/features/chat/constants.ts
@@ -79,6 +79,6 @@ export const MODERATE_CHAT_MESSAGE = 'MODERATE_CHAT_MESSAGE';
/**
- * Maximum number of pending edits are allowed.
+ * Maximum number of pending edits, or pending moderations, kept for messages that have not arrived yet.
*/
-export const MAX_PENDING_EDITS = 200;
+export const MAX_PENDING_ENTRIES = 200;
diff --git a/react/features/chat/functions.ts b/react/features/chat/functions.ts
index a0083fdc63..3450dfcd3e 100644
--- a/react/features/chat/functions.ts
+++ b/react/features/chat/functions.ts
@@ -21,8 +21,8 @@ import { isCCTabEnabled } from '../subtitles/functions.any';
import { VIDEO_SPACE_MIN_SIZE } from '../video-layout/constants';
import { IVisitorChatParticipant } from '../visitors/types';
-import { ChatTabs, MAX_PENDING_EDITS, MESSAGE_TYPE_ERROR, MESSAGE_TYPE_LOCAL, TIMESTAMP_FORMAT } from './constants';
-import { IMessage, IPendingEdit, IPendingEditsMap } from './types';
+import { ChatTabs, MAX_PENDING_ENTRIES, MESSAGE_TYPE_ERROR, MESSAGE_TYPE_LOCAL, TIMESTAMP_FORMAT } from './constants';
+import { IMessage, IPendingMap } from './types';
/**
* An ASCII emoticon regexp array to find and replace old-style ASCII
@@ -427,22 +427,23 @@ export function isFileMessage(message: IMessage): boolean {
}
/**
- * Inserts a pending edit into the map, evicting the oldest entry if the cap is exceeded.
+ * Inserts a pending entry (an edit or a moderation for a message that has not arrived yet) into
+ * the map, evicting the oldest entry if the cap is exceeded.
*
- * @param {IPendingEditsMap} pendingEdits - The current pending edits map.
- * @param {string} messageId - The id of the message the edit targets.
- * @param {IPendingEdit} edit - The pending edit to insert.
- * @returns {IPendingEditsMap} The updated pending edits map.
+ * @param {Object} pendingEntries - The current pending entries map.
+ * @param {string} messageId - The id of the message the entry targets.
+ * @param {Object} entry - The pending entry to insert.
+ * @returns {Object} The updated pending entries map.
*/
-export function addPendingEdit(
- pendingEdits: IPendingEditsMap,
+export function addPendingEntry<T>(
+ pendingEntries: IPendingMap<T>,
messageId: string,
- edit: IPendingEdit
-): IPendingEditsMap {
- const next = { ...pendingEdits, [messageId]: edit };
+ entry: T
+): IPendingMap<T> {
+ const next = { ...pendingEntries, [messageId]: entry };
const keys = Object.keys(next);
- if (keys.length > MAX_PENDING_EDITS) {
+ if (keys.length > MAX_PENDING_ENTRIES) {
// Object key order is insertion order for string keys in JS, so the first key is the oldest.
delete next[keys[0]];
}
@@ -498,13 +499,18 @@ export const getChatSearchMatches = createSelector(
);
/**
- * Returns the index of the currently focused search match.
+ * Returns the index of the currently focused search match. The stored index is kept within the
+ * current matches, as the matches can shrink while the search is open, e.g. when the focused
+ * match is deleted or moderated.
*
* @param {IReduxState} state - The redux state.
* @returns {number}
*/
export function getChatSearchMatchIndex(state: IReduxState): number {
- return state['features/chat'].searchMatchIndex || 0;
+ const index = state['features/chat'].searchMatchIndex || 0;
+ const { length } = getChatSearchMatches(state);
+
+ return length ? Math.min(index, length - 1) : 0;
}
/**
diff --git a/react/features/chat/middleware.ts b/react/features/chat/middleware.ts
index 2cbc693d74..333a1b959f 100644
--- a/react/features/chat/middleware.ts
+++ b/react/features/chat/middleware.ts
@@ -752,16 +752,12 @@ function _onReactionReceived(store: IStore, { participantId, reactionList, messa
* @returns {void}
*/
function _onMessageModerated(store: IStore, messageId: string, reason?: string) {
- const { messages } = store.getState()['features/chat'];
-
- const originalMessage = messages.find(
- message => message.messageId === messageId
- );
-
- if (!originalMessage) {
+ if (typeof messageId !== 'string' || !messageId) {
return;
}
+ // The message may not have arrived yet, in which case the reducer keeps the moderation
+ // and applies it once the message arrives.
store.dispatch(moderateMessage(messageId, reason));
}
@@ -963,6 +959,11 @@ function _handleReceivedMessage({ dispatch, getState }: IStore,
dispatch(addMessage(newMessage));
+ // A message moderated before it arrived is added as removed (see the reducer), so its text must
+ // not reach the notification or the external API either.
+ const { pendingModerations } = state['features/chat'];
+ const isModerated = Boolean(messageId && Object.prototype.hasOwnProperty.call(pendingModerations, messageId));
+
let notificationDisplayName = _displayName;
// source can be 'token' or 'guest'. When it is 'guest', we append a guest indicator
@@ -974,7 +975,7 @@ function _handleReceivedMessage({ dispatch, getState }: IStore,
notificationDisplayName = `${_displayName} ${getDisplayNameSuffix(newMessage)}`;
}
- if (shouldShowNotification) {
+ if (shouldShowNotification && !isModerated) {
dispatch(showMessageNotification({
title: notificationDisplayName,
description: message,
@@ -987,7 +988,7 @@ function _handleReceivedMessage({ dispatch, getState }: IStore,
// Logic for web only:
APP.API.notifyReceivedChatMessage({
- body: message,
+ body: isModerated ? i18next.t('chat.moderatedMessage') : message,
from: participantId,
nick: notificationDisplayName,
privateMessage,
diff --git a/react/features/chat/reducer.ts b/react/features/chat/reducer.ts
index 5e466c4be5..62796cbeaf 100644
--- a/react/features/chat/reducer.ts
+++ b/react/features/chat/reducer.ts
@@ -28,8 +28,8 @@ import {
SET_USER_CHAT_WIDTH
} from './actionTypes';
import { CHAT_SIZE, ChatTabs } from './constants';
-import { addPendingEdit } from './functions';
-import { IMessage, IPendingEditsMap } from './types';
+import { addPendingEntry } from './functions';
+import { IMessage, IPendingEditsMap, IPendingModerationsMap } from './types';
const DEFAULT_STATE = {
groupChatWithPermissions: false,
@@ -39,6 +39,7 @@ const DEFAULT_STATE = {
messages: [],
notifyPrivateRecipientsChangedTimestamp: undefined,
pendingEdits: {},
+ pendingModerations: {},
reactions: {},
unreadMessagesCount: 0,
unreadFilesCount: 0,
@@ -70,6 +71,7 @@ export interface IChatState {
messages: IMessage[];
notifyPrivateRecipientsChangedTimestamp?: number;
pendingEdits: IPendingEditsMap;
+ pendingModerations: IPendingModerationsMap;
privateChatWithPermissions: boolean;
privateMessageRecipient?: IParticipant | IVisitorChatParticipant;
searchMatchIndex: number;
@@ -108,7 +110,14 @@ ReducerRegistry.register<IChatState>('features/chat', (state = DEFAULT_STATE, ac
timestamp: action.timestamp
};
- const pendingEdit = action.messageId ? state.pendingEdits[action.messageId] : undefined;
+ // The message id is chosen by the sender, so only look up entries the maps hold themselves:
+ // an id such as '__proto__' must not resolve to an inherited value.
+ const pendingEdit = action.messageId
+ && Object.prototype.hasOwnProperty.call(state.pendingEdits, action.messageId)
+ ? state.pendingEdits[action.messageId] : undefined;
+ const pendingModeration = action.messageId
+ && Object.prototype.hasOwnProperty.call(state.pendingModerations, action.messageId)
+ ? state.pendingModerations[action.messageId] : undefined;
// only apply a cached pending edit if its claimed author matches
// the author of the message that actually arrived. Prevents a forged/mismatched
@@ -116,7 +125,7 @@ ReducerRegistry.register<IChatState>('features/chat', (state = DEFAULT_STATE, ac
// someone else's message once it shows up.
const pendingEditValid = pendingEdit?.participantId === action.participantId;
- const finalMessage = pendingEdit && pendingEditValid
+ let finalMessage = pendingEdit && pendingEditValid
? {
...newMessage,
message: pendingEdit.message,
@@ -125,6 +134,19 @@ ReducerRegistry.register<IChatState>('features/chat', (state = DEFAULT_STATE, ac
}
: newMessage;
+ // The message was moderated before it arrived (e.g. a moderator brought a late joiner up to
+ // date before the room history was received), so it arrives already removed. The pending
+ // moderation is kept rather than consumed, like in MODERATE_MESSAGE: message ids are chosen
+ // by the sender, so several messages may arrive with the same id, and moderating twice is harmless.
+ if (pendingModeration) {
+ finalMessage = {
+ ...finalMessage,
+ message: '',
+ isModerated: true,
+ moderationReason: pendingModeration.reason
+ };
+ }
+
// React native, unlike web, needs a reverse sorted message list.
const messages = navigator.product === 'ReactNative'
? [
@@ -156,7 +178,8 @@ ReducerRegistry.register<IChatState>('features/chat', (state = DEFAULT_STATE, ac
const { participantId, reactionList, messageId } = action;
const messages = state.messages.map(message => {
- if (messageId === message.messageId) {
+ // A deleted or moderated message is shown as a placeholder, so it does not take reactions.
+ if (messageId === message.messageId && !message.isDeleted && !message.isModerated) {
const newReactions = new Map(message.reactions);
reactionList.forEach((reaction: string) => {
@@ -181,6 +204,7 @@ ReducerRegistry.register<IChatState>('features/chat', (state = DEFAULT_STATE, ac
return {
...state,
+ lastReadMessage: _getLastReadMessage(state, messages),
messages
};
}
@@ -235,7 +259,7 @@ ReducerRegistry.register<IChatState>('features/chat', (state = DEFAULT_STATE, ac
if (!messageExists) {
return {
...state,
- pendingEdits: addPendingEdit(state.pendingEdits, newMessage.messageId, {
+ pendingEdits: addPendingEntry(state.pendingEdits, newMessage.messageId, {
message: newMessage.message,
editedAt: newMessage.editedAt,
participantId: newMessage.participantId
@@ -249,13 +273,18 @@ ReducerRegistry.register<IChatState>('features/chat', (state = DEFAULT_STATE, ac
return {
...state,
+ lastReadMessage: _getLastReadMessage(state, messages),
messages
};
}
case MODERATE_MESSAGE: {
+ let messageExists = false;
+
const messages = state.messages.map(message => {
if (message.messageId === action.messageId) {
+ messageExists = true;
+
// Clear the text, like RETRACT_MESSAGE does, so the removed content
// does not stay in the state while the UI shows a placeholder.
return {
@@ -269,15 +298,35 @@ ReducerRegistry.register<IChatState>('features/chat', (state = DEFAULT_STATE, ac
return message;
});
+ // Cache the moderation whether or not the message has arrived yet: it is applied to the
+ // message once it does, and, as message ids are chosen by the sender, also to any later
+ // message that arrives with the same id.
+ const pendingModerations = addPendingEntry(state.pendingModerations, action.messageId, {
+ reason: action.reason
+ });
+
+ if (!messageExists) {
+ return {
+ ...state,
+ pendingModerations
+ };
+ }
+
return {
...state,
- messages
+ lastReadMessage: _getLastReadMessage(state, messages),
+ messages,
+ pendingModerations
};
}
case RETRACT_MESSAGE: {
+ let retracted = false;
+
const messages = state.messages.map(message => {
if (message.messageId === action.messageId && message.participantId === action.retractedBy) {
+ retracted = true;
+
return {
...message,
message: '',
@@ -289,8 +338,13 @@ ReducerRegistry.register<IChatState>('features/chat', (state = DEFAULT_STATE, ac
return message;
});
+ if (!retracted) {
+ return state;
+ }
+
return {
...state,
+ lastReadMessage: _getLastReadMessage(state, messages),
messages
};
}
@@ -355,20 +409,20 @@ ReducerRegistry.register<IChatState>('features/chat', (state = DEFAULT_STATE, ac
privateMessageRecipient: undefined
};
- case REMOVE_LOBBY_CHAT_PARTICIPANT:
+ case REMOVE_LOBBY_CHAT_PARTICIPANT: {
+ const messages = action.removeLobbyChatMessages
+ ? state.messages.filter(m => !m.lobbyChat)
+ : state.messages;
+
return {
...state,
- messages: state.messages.filter(m => {
- if (action.removeLobbyChatMessages) {
- return !m.lobbyChat;
- }
-
- return true;
- }),
+ lastReadMessage: _getLastReadMessageAfterRemoval(state, messages),
+ messages,
isOpen: state.isOpen && state.isLobbyChatActive ? false : state.isOpen,
isLobbyChatActive: false,
lobbyMessageRecipient: undefined
};
+ }
case UPDATE_CONFERENCE_METADATA: {
const { metadata } = action;
@@ -444,3 +498,60 @@ ReducerRegistry.register<IChatState>('features/chat', (state = DEFAULT_STATE, ac
return state;
});
+
+/**
+ * Returns the last read message to keep in the state once some of the messages were replaced by
+ * updated copies. The last read message is compared by reference, thus it has to point to the
+ * updated copy, or it would not be found in the new list anymore and would keep the old content.
+ *
+ * @param {IChatState} state - The current chat state.
+ * @param {IMessage[]} messages - The new list of messages, mapped one to one from the current one.
+ * @returns {IMessage|undefined}
+ */
+function _getLastReadMessage(state: IChatState, messages: IMessage[]): IMessage | undefined {
+ const { lastReadMessage } = state;
+
+ if (!lastReadMessage) {
+ return lastReadMessage;
+ }
+
+ const index = state.messages.indexOf(lastReadMessage);
+
+ return index === -1 ? lastReadMessage : messages[index];
+}
+
+/**
+ * Returns the last read message to keep in the state once some of the messages were removed.
+ * If the last read message itself was removed, the closest older message that is kept becomes the
+ * last read one, so the messages that were already read are not counted as unread again.
+ *
+ * @param {IChatState} state - The current chat state.
+ * @param {IMessage[]} messages - The new list of messages, a subset of the current one.
+ * @returns {IMessage|undefined}
+ */
+function _getLastReadMessageAfterRemoval(state: IChatState, messages: IMessage[]): IMessage | undefined {
+ const { lastReadMessage } = state;
+
+ if (!lastReadMessage || messages === state.messages) {
+ return lastReadMessage;
+ }
+
+ const index = state.messages.indexOf(lastReadMessage);
+
+ if (index === -1) {
+ return lastReadMessage;
+ }
+
+ const kept = new Set(messages);
+
+ // React native stores the messages in a reversed order, so the older ones come after.
+ const step = navigator.product === 'ReactNative' ? 1 : -1;
+
+ for (let i = index; i >= 0 && i < state.messages.length; i += step) {
+ if (kept.has(state.messages[i])) {
+ return state.messages[i];
+ }
+ }
+
+ return undefined;
+}
diff --git a/react/features/chat/types.ts b/react/features/chat/types.ts
index 3d7bed123a..4d2076eaa2 100644
--- a/react/features/chat/types.ts
+++ b/react/features/chat/types.ts
@@ -127,8 +127,25 @@ export interface IPendingEdit {
}
/**
- * The shape of the pendingEdits map in Redux state.
+ * The shape of a single cached pending moderation, keyed by messageId in Redux state.
+ */
+export interface IPendingModeration {
+ reason?: string;
+}
+
+/**
+ * The shape of a map of entries cached for messages that have not arrived yet.
*/
-export interface IPendingEditsMap {
- [messageId: string]: IPendingEdit;
+export interface IPendingMap<T> {
+ [messageId: string]: T;
}
+
+/**
+ * The shape of the pendingEdits map in Redux state.
+ */
+export type IPendingEditsMap = IPendingMap<IPendingEdit>;
+
+/**
+ * The shape of the pendingModerations map in Redux state.
+ */
+export type IPendingModerationsMap = IPendingMap<IPendingModeration>;