[MM-55143] Disallow reacting with an emoji that does not exist, limit the total number of unique reactions per post (#25331)

* [MM-55143] Disallow reacting with an emoji that does not exist

* WIP for server limit on emoji reactions

* WIP

* Implement default limit of 25 unique emoji reactions

* Add modal for reaction limit

* Fix test

* PR feedback

* Fix i18n

* Update admin string

* Merge'd

* Fixing some issues, check limits correctly based on other users reactions

* Fix typos

* Fix lint/test

* Add tests, fix other tests

---------

Co-authored-by: Mattermost Build <build@mattermost.com>
Этот коммит содержится в:
Devin Binnie
2023-11-27 09:11:04 -05:00
коммит произвёл GitHub
родитель 0a38042d58
Коммит eaa5cce3ce
24 изменённых файлов: 652 добавлений и 29 удалений

Просмотреть файл

@@ -50,7 +50,13 @@ jest.mock('utils/user_agent', () => ({
isDesktopApp: jest.fn().mockReturnValue(false),
}));
const mockMakeGetIsReactionAlreadyAddedToPost = jest.spyOn(PostUtils, 'makeGetIsReactionAlreadyAddedToPost');
jest.mock('utils/post_utils', () => ({
makeGetUniqueEmojiNameReactionsForPost: jest.fn(),
makeGetIsReactionAlreadyAddedToPost: jest.fn(),
}));
const mockMakeGetIsReactionAlreadyAddedToPost = PostUtils.makeGetIsReactionAlreadyAddedToPost as unknown as jest.Mock<() => boolean>;
const mockMakeGetUniqueEmojiNameReactionsForPost = PostUtils.makeGetUniqueEmojiNameReactionsForPost as unknown as jest.Mock<() => string[]>;
const POST_CREATED_TIME = Date.now();
@@ -515,14 +521,40 @@ describe('Actions.Posts', () => {
});
});
test('addReaction', async () => {
const testStore = mockStore(initialState);
describe('addReaction', () => {
mockMakeGetUniqueEmojiNameReactionsForPost.mockReturnValue(() => []);
await testStore.dispatch(Actions.addReaction('post_id_1', 'emoji_name_1'));
expect(testStore.getActions()).toEqual([
{args: ['post_id_1', 'emoji_name_1'], type: 'MOCK_ADD_REACTION'},
{args: ['emoji_name_1'], type: 'MOCK_ADD_RECENT_EMOJI'},
]);
test('should add reaction', async () => {
const testStore = mockStore(initialState);
await testStore.dispatch(Actions.addReaction('post_id_1', 'emoji_name_1'));
expect(testStore.getActions()).toEqual([
{args: ['post_id_1', 'emoji_name_1'], type: 'MOCK_ADD_REACTION'},
{args: ['emoji_name_1'], type: 'MOCK_ADD_RECENT_EMOJI'},
]);
});
test('should not add reaction if we are over the limit', async () => {
mockMakeGetUniqueEmojiNameReactionsForPost.mockReturnValue(() => ['another_emoji']);
const testStore = mockStore({
...initialState,
entities: {
...initialState.entities,
general: {
...initialState.entities.general,
config: {
...initialState.entities.general.config,
UniqueEmojiReactionLimitPerPost: '1',
},
},
},
});
await testStore.dispatch(Actions.addReaction('post_id_1', 'emoji_name_1'));
expect(testStore.getActions()).not.toEqual([
{args: ['post_id_1', 'emoji_name_1'], type: 'MOCK_ADD_REACTION'},
{args: ['emoji_name_1'], type: 'MOCK_ADD_RECENT_EMOJI'},
]);
});
});
test('flagPost', async () => {

Просмотреть файл

@@ -10,10 +10,11 @@ import {getMyChannelMember} from 'mattermost-redux/actions/channels';
import * as PostActions from 'mattermost-redux/actions/posts';
import * as ThreadActions from 'mattermost-redux/actions/threads';
import {getChannel, getMyChannelMember as getMyChannelMemberSelector} from 'mattermost-redux/selectors/entities/channels';
import {getConfig} from 'mattermost-redux/selectors/entities/general';
import * as PostSelectors from 'mattermost-redux/selectors/entities/posts';
import {isCollapsedThreadsEnabled} from 'mattermost-redux/selectors/entities/preferences';
import {getCurrentTeamId} from 'mattermost-redux/selectors/entities/teams';
import {getCurrentUserId} from 'mattermost-redux/selectors/entities/users';
import {getCurrentUserId, isCurrentUserSystemAdmin} from 'mattermost-redux/selectors/entities/users';
import type {DispatchFunc, GetStateFunc} from 'mattermost-redux/types/actions';
import {canEditPost, comparePosts} from 'mattermost-redux/utils/post_utils';
@@ -21,20 +22,24 @@ import {addRecentEmoji, addRecentEmojis} from 'actions/emoji_actions';
import * as StorageActions from 'actions/storage';
import {loadNewDMIfNeeded, loadNewGMIfNeeded} from 'actions/user_actions';
import {removeDraft} from 'actions/views/drafts';
import {closeModal, openModal} from 'actions/views/modals';
import * as RhsActions from 'actions/views/rhs';
import {manuallyMarkThreadAsUnread} from 'actions/views/threads';
import {isEmbedVisible, isInlineImageVisible} from 'selectors/posts';
import {getSelectedPostId, getSelectedPostCardId, getRhsState} from 'selectors/rhs';
import {getGlobalItem} from 'selectors/storage';
import ReactionLimitReachedModal from 'components/reaction_limit_reached_modal';
import {
ActionTypes,
Constants,
ModalIdentifiers,
RHSStates,
StoragePrefixes,
} from 'utils/constants';
import {matchEmoticons} from 'utils/emoticons';
import {makeGetIsReactionAlreadyAddedToPost} from 'utils/post_utils';
import {makeGetIsReactionAlreadyAddedToPost, makeGetUniqueEmojiNameReactionsForPost} from 'utils/post_utils';
import * as UserAgent from 'utils/user_agent';
import type {GlobalState} from 'types/store';
@@ -172,7 +177,25 @@ export function toggleReaction(postId: string, emojiName: string) {
}
export function addReaction(postId: string, emojiName: string) {
return (dispatch: DispatchFunc) => {
const getUniqueEmojiNameReactionsForPost = makeGetUniqueEmojiNameReactionsForPost();
return (dispatch: DispatchFunc, getState: GetStateFunc) => {
const state = getState() as GlobalState;
const config = getConfig(state);
const uniqueEmojiNames = getUniqueEmojiNameReactionsForPost(state, postId) ?? [];
// If we're adding a new reaction but we're already at or over the limit, stop
if (uniqueEmojiNames.length >= Number(config.UniqueEmojiReactionLimitPerPost) && !uniqueEmojiNames.some((name) => name === emojiName)) {
dispatch(openModal({
modalId: ModalIdentifiers.REACTION_LIMIT_REACHED,
dialogType: ReactionLimitReachedModal,
dialogProps: {
isAdmin: isCurrentUserSystemAdmin(state),
onExited: () => closeModal(ModalIdentifiers.REACTION_LIMIT_REACHED),
},
}));
return {data: false};
}
dispatch(PostActions.addReaction(postId, emojiName));
dispatch(addRecentEmoji(emojiName));
return {data: true};

Просмотреть файл

@@ -236,6 +236,7 @@ export const it = {
export const validators = {
isRequired: (text: string, textDefault: string) => (value: string) => new ValidationResult(Boolean(value), text, textDefault),
minValue: (min: number, text: string, textDefault: string) => (value: number) => new ValidationResult((value >= min), text, textDefault),
maxValue: (max: number, text: string, textDefault: string) => (value: number) => new ValidationResult((value <= max), text, textDefault),
};
const usesLegacyOauth = (config: DeepPartial<AdminConfig>, state: any, license?: ClientLicense, enterpriseReady?: boolean, consoleAccess?: ConsoleAccess, cloud?: CloudState) => {
@@ -3167,6 +3168,36 @@ const AdminDefinition: AdminDefinitionType = {
help_text_default: 'When enabled, users message drafts will sync with the server so they can be accessed from any device. Users may opt out of this behaviour in Account settings.',
help_text_markdown: false,
},
{
type: 'number',
key: 'ServiceSettings.UniqueEmojiReactionLimitPerPost',
label: t('admin.customization.uniqueEmojiReactionLimitPerPost'),
label_default: 'Unique Emoji Reaction Limit:',
placeholder: t('admin.customization.uniqueEmojiReactionLimitPerPostPlaceholder'),
placeholder_default: 'E.g.: 25',
help_text: t('admin.customization.uniqueEmojiReactionLimitPerPostDesc'),
help_text_default: 'The number of unique emoji reactions that can be added to a post. Increasing this limit could lead to poor client performance. Maximum is 500.',
help_text_markdown: false,
validate: (value) => {
const maxResult = validators.maxValue(
500,
t('admin.customization.uniqueEmojiReactionLimitPerPost.maxValue'),
'Cannot increase the limit to a value above 500.',
)(value);
if (!maxResult.isValid()) {
return maxResult;
}
const minResult = validators.minValue(0,
t('admin.customization.uniqueEmojiReactionLimitPerPost.minValue'),
'Cannot decrease the limit below 0.',
)(value);
if (!minResult.isValid()) {
return minResult;
}
return new ValidationResult(true, '', '');
},
},
],
},
},

Просмотреть файл

@@ -0,0 +1,63 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import React from 'react';
import {FormattedMessage} from 'react-intl';
import {Link} from 'react-router-dom';
import {GenericModal} from '@mattermost/components';
import ExternalLink from 'components/external_link';
export default function ReactionLimitReachedModal(props: {isAdmin: boolean; onExited: () => void}) {
const body = props.isAdmin ? (
<FormattedMessage
id='reaction_limit_reached_modal.body.admin'
defaultMessage="Oops! It looks like we've hit a ceiling on emoji reactions for this message. We've <link>set a limit</link> to keep things running smoothly on your server. As a system administrator, you can adjust this limit from the <linkAdmin>system console</linkAdmin>."
values={{
link: (msg: React.ReactNode) => (
<ExternalLink
href='https://mattermost.com/pl/configure-unique-emoji-reaction-limit'
>
{msg}
</ExternalLink>
),
linkAdmin: (msg: React.ReactNode) => (
<Link
onClick={props.onExited}
to='/admin_console'
>
{msg}
</Link>
),
}}
/>
) : (
<FormattedMessage
id='reaction_limit_reached_modal.body'
defaultMessage="Oops! It looks like we've hit a ceiling on emoji reactions for this message. Please contact your system administrator for any adjustments to this limit."
/>
);
return (
<GenericModal
modalHeaderText={
<FormattedMessage
id='reaction_limit_reached_modal.title'
defaultMessage="You've reached the reaction limit"
/>
}
compassDesign={true}
confirmButtonText={
<FormattedMessage
id='generic.okay'
defaultMessage='Okay'
/>
}
onExited={props.onExited}
handleConfirm={props.onExited}
>
{body}
</GenericModal>
);
}

Просмотреть файл

@@ -672,6 +672,11 @@
"admin.customization.restrictLinkPreviewsDesc": "Link previews and image link previews will not be shown for the above list of comma-separated domains.",
"admin.customization.restrictLinkPreviewsExample": "E.g.: \"internal.mycompany.com, images.example.com\"",
"admin.customization.restrictLinkPreviewsTitle": "Disable website link previews from these domains:",
"admin.customization.uniqueEmojiReactionLimitPerPost": "Unique Emoji Reaction Limit:",
"admin.customization.uniqueEmojiReactionLimitPerPost.maxValue": "Cannot increase the limit to a value above 500.",
"admin.customization.uniqueEmojiReactionLimitPerPost.minValue": "Cannot decrease the limit below 0.",
"admin.customization.uniqueEmojiReactionLimitPerPostDesc": "The number of unique emoji reactions that can be added to a post. Increasing this limit could lead to poor client performance. Maximum is 500.",
"admin.customization.uniqueEmojiReactionLimitPerPostPlaceholder": "E.g.: 25",
"admin.data_grid.empty": "No items found",
"admin.data_grid.loading": "Loading",
"admin.data_grid.paginatorCount": "{startCount, number} - {endCount, number} of {total, number}",
@@ -4567,6 +4572,9 @@
"quick_switch_modal.help_no_team": "Type to find a channel. Use **UP/DOWN** to browse, **ENTER** to select, **ESC** to dismiss.",
"quick_switch_modal.input": "quick switch input",
"quick_switch_modal.switchChannels": "Find Channels",
"reaction_limit_reached_modal.body": "Oops! It looks like we've hit a ceiling on emoji reactions for this message. Please contact your system administrator for any adjustments to this limit.",
"reaction_limit_reached_modal.body.admin": "Oops! It looks like we've hit a ceiling on emoji reactions for this message. We've <link>set a limit</link> to keep things running smoothly on your server. As a system administrator, you can adjust this limit from the <linkAdmin>system console</linkAdmin>.",
"reaction_limit_reached_modal.title": "You've reached the reaction limit",
"reaction_list.addReactionTooltip": "Add a reaction",
"reaction.add.ariaLabel": "Add a reaction",
"reaction.clickToAdd": "(click to add)",

Просмотреть файл

@@ -449,6 +449,7 @@ export const ModalIdentifiers = {
IP_FILTERING_ADD_EDIT_MODAL: 'ip_filtering_add_edit_modal',
IP_FILTERING_DELETE_CONFIRMATION_MODAL: 'ip_filtering_delete_confirmation_modal',
IP_FILTERING_SAVE_CONFIRMATION_MODAL: 'ip_filtering_save_confirmation_modal',
REACTION_LIMIT_REACHED: 'reaction_limit_reached',
};
export const UserStatuses = {

Просмотреть файл

@@ -1353,3 +1353,43 @@ describe('makeGetIsReactionAlreadyAddedToPost', () => {
expect(getIsReactionAlreadyAddedToPost(baseState, 'post_id_1', 'smile')).toBeTruthy();
});
});
describe('makeGetUniqueEmojiNameReactionsForPost', () => {
const baseState = {
entities: {
posts: {
reactions: {
post_id_1: {
user_1_post_id_1_smile: {
emoji_name: 'smile',
post_id: 'post_id_1',
},
user_2_post_id_1_smile: {
emoji_name: 'smile',
post_id: 'post_id_1',
},
user_3_post_id_1_smile: {
emoji_name: 'smile',
post_id: 'post_id_1',
},
user_1_post_id_1_cry: {
emoji_name: 'cry',
post_id: 'post_id_1',
},
},
},
},
general: {
config: {},
},
emojis: {},
},
} as unknown as GlobalState;
test('should only return names of unique reactions', () => {
const getUniqueEmojiNameReactionsForPost = PostUtils.makeGetUniqueEmojiNameReactionsForPost();
expect(getUniqueEmojiNameReactionsForPost(baseState, 'post_id_1')).toEqual(['smile', 'cry']);
});
});

Просмотреть файл

@@ -710,6 +710,31 @@ export function makeGetUniqueReactionsToPost(): (state: GlobalState, postId: Pos
);
}
export function makeGetUniqueEmojiNameReactionsForPost(): (state: GlobalState, postId: Post['id']) => string[] | undefined | null {
const getReactionsForPost = makeGetReactionsForPost();
return createSelector(
'makeGetUniqueEmojiReactionsForPost',
(state: GlobalState, postId: string) => getReactionsForPost(state, postId),
getEmojiMap,
(reactions, emojiMap) => {
if (!reactions) {
return null;
}
const emojiNames: string[] = [];
Object.values(reactions).forEach((reaction) => {
if (emojiMap.get(reaction.emoji_name) && !emojiNames.includes(reaction.emoji_name)) {
emojiNames.push(reaction.emoji_name);
}
});
return emojiNames;
},
);
}
export function makeGetIsReactionAlreadyAddedToPost(): (state: GlobalState, postId: Post['id'], emojiName: string) => boolean {
const getUniqueReactionsToPost = makeGetUniqueReactionsToPost();

Просмотреть файл

@@ -200,6 +200,7 @@ export type ClientConfig = {
AllowPersistentNotificationsForGuests: string;
DelayChannelAutocomplete: 'true' | 'false';
ServiceEnvironment: string;
UniqueEmojiReactionLimitPerPost: string;
};
export type License = {
@@ -378,6 +379,7 @@ export type ServiceSettings = {
PersistentNotificationIntervalMinutes: number;
PersistentNotificationMaxCount: number;
PersistentNotificationMaxRecipients: number;
UniqueEmojiReactionLimitPerPost: number;
RefreshPostStatsRunTime: string;
};