Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

fix(api): match custom emoji reactions by id (#3857)

Hampus706040cfb708
diff --git a/fluxer_api/src/api/channel/repositories/MessageInteractionRepository.ts b/fluxer_api/src/api/channel/repositories/MessageInteractionRepository.ts
index 27473becd..4920540bb 100644
--- a/fluxer_api/src/api/channel/repositories/MessageInteractionRepository.ts
+++ b/fluxer_api/src/api/channel/repositories/MessageInteractionRepository.ts
@@ -52,6 +52,44 @@ const createFetchReactionUsersByEmojiQuery = (limit: number, hasAfter: boolean =
],
limit,
});
+const FETCH_FIRST_EMOJI_NAME_QUERY = MessageReactions.selectCql({
+ columns: ['emoji_name'],
+ where: [
+ MessageReactions.where.eq('channel_id'),
+ MessageReactions.where.eq('bucket'),
+ MessageReactions.where.eq('message_id'),
+ MessageReactions.where.eq('emoji_id'),
+ ],
+ limit: 1,
+});
+const FETCH_NEXT_EMOJI_NAME_QUERY = MessageReactions.selectCql({
+ columns: ['emoji_name'],
+ where: [
+ MessageReactions.where.eq('channel_id'),
+ MessageReactions.where.eq('bucket'),
+ MessageReactions.where.eq('message_id'),
+ MessageReactions.where.eq('emoji_id'),
+ MessageReactions.where.gt('emoji_name', 'after_emoji_name'),
+ ],
+ limit: 1,
+});
+const DELETE_REACTIONS_BY_EMOJI_ID_QUERY = MessageReactions.deleteCql({
+ where: [
+ MessageReactions.where.eq('channel_id'),
+ MessageReactions.where.eq('bucket'),
+ MessageReactions.where.eq('message_id'),
+ MessageReactions.where.eq('emoji_id'),
+ ],
+});
+const DELETE_REACTIONS_BY_EMOJI_QUERY = MessageReactions.deleteCql({
+ where: [
+ MessageReactions.where.eq('channel_id'),
+ MessageReactions.where.eq('bucket'),
+ MessageReactions.where.eq('message_id'),
+ MessageReactions.where.eq('emoji_id'),
+ MessageReactions.where.eq('emoji_name'),
+ ],
+});
const CHECK_USER_REACTION_EXISTS_QUERY = MessageReactions.selectCql({
columns: ['channel_id', 'bucket', 'message_id', 'user_id', 'emoji_id', 'emoji_name'],
where: [
@@ -64,6 +102,9 @@ const CHECK_USER_REACTION_EXISTS_QUERY = MessageReactions.selectCql({
],
limit: 1,
});
+const UNICODE_EMOJI_ID = createEmojiID(0n);
+
+export type ReactionEmojiKey = {id: EmojiID; name?: undefined} | {id?: undefined; name: string};
export class MessageInteractionRepository {
private messageRepository: MessageRepository;
@@ -130,35 +171,42 @@ export class MessageInteractionRepository {
async listReactionUsers(
channelId: ChannelID,
messageId: MessageID,
- emojiName: string,
+ emoji: ReactionEmojiKey,
limit: number = 25,
after?: UserID,
- emojiId?: EmojiID,
): Promise<Array<MessageReaction>> {
const bucket = BucketUtils.makeBucket(messageId);
- const normalizedEmojiId = emojiId ?? createEmojiID(0n);
- const hasAfter = !!after;
- const reactions = hasAfter
- ? await fetchMany<MessageReactionRow>(
- createFetchReactionUsersByEmojiQuery(limit, true).bind({
- channel_id: channelId,
- bucket,
- message_id: messageId,
- emoji_id: normalizedEmojiId,
- emoji_name: emojiName,
- after_user_id: after!,
- }),
- )
- : await fetchMany<MessageReactionRow>(
- createFetchReactionUsersByEmojiQuery(limit, false).bind({
- channel_id: channelId,
- bucket,
- message_id: messageId,
- emoji_id: normalizedEmojiId,
- emoji_name: emojiName,
- }),
- );
- return reactions.map((reaction) => new MessageReaction(reaction));
+ const emojiId = emoji.id ?? UNICODE_EMOJI_ID;
+ const names = await this.listStoredEmojiNames(channelId, bucket, messageId, emoji);
+ const pages = await Promise.all(
+ names.map((emojiName) =>
+ after
+ ? fetchMany<MessageReactionRow>(
+ createFetchReactionUsersByEmojiQuery(limit, true).bind({
+ channel_id: channelId,
+ bucket,
+ message_id: messageId,
+ emoji_id: emojiId,
+ emoji_name: emojiName,
+ after_user_id: after,
+ }),
+ )
+ : fetchMany<MessageReactionRow>(
+ createFetchReactionUsersByEmojiQuery(limit, false).bind({
+ channel_id: channelId,
+ bucket,
+ message_id: messageId,
+ emoji_id: emojiId,
+ emoji_name: emojiName,
+ }),
+ ),
+ ),
+ );
+ const byUser = new Map<UserID, MessageReactionRow>();
+ for (const row of pages.flat().sort((a, b) => Number(a.user_id - b.user_id))) {
+ if (!byUser.has(row.user_id)) byUser.set(row.user_id, row);
+ }
+ return [...byUser.values()].slice(0, limit).map((row) => new MessageReaction(row));
}
async addReaction(
@@ -170,13 +218,12 @@ export class MessageInteractionRepository {
emojiAnimated: boolean = false,
): Promise<MessageReaction> {
const bucket = BucketUtils.makeBucket(messageId);
- const normalizedEmojiId = emojiId ? emojiId : createEmojiID(0n);
const reactionData: MessageReactionRow = {
channel_id: channelId,
bucket,
message_id: messageId,
user_id: userId,
- emoji_id: normalizedEmojiId,
+ emoji_id: emojiId ?? UNICODE_EMOJI_ID,
emoji_name: emojiName,
emoji_animated: emojiAnimated,
created_at: new Date(),
@@ -190,21 +237,22 @@ export class MessageInteractionRepository {
channelId: ChannelID,
messageId: MessageID,
userId: UserID,
- emojiName: string,
- emojiId?: EmojiID,
+ emoji: ReactionEmojiKey,
): Promise<void> {
const bucket = BucketUtils.makeBucket(messageId);
- const normalizedEmojiId = emojiId ?? createEmojiID(0n);
- await deleteOneOrMany(
- MessageReactions.deleteByPk({
- channel_id: channelId,
- bucket,
- message_id: messageId,
- user_id: userId,
- emoji_id: normalizedEmojiId,
- emoji_name: emojiName,
- }),
- );
+ const names = await this.listStoredEmojiNames(channelId, bucket, messageId, emoji);
+ for (const emojiName of names) {
+ await deleteOneOrMany(
+ MessageReactions.deleteByPk({
+ channel_id: channelId,
+ bucket,
+ message_id: messageId,
+ user_id: userId,
+ emoji_id: emoji.id ?? UNICODE_EMOJI_ID,
+ emoji_name: emojiName,
+ }),
+ );
+ }
const hasReactions = await this.messageHasAnyReactions(channelId, messageId);
await this.setHasReaction(channelId, messageId, hasReactions);
}
@@ -227,50 +275,35 @@ export class MessageInteractionRepository {
await this.setHasReaction(channelId, messageId, hasReactions);
}
- async removeAllReactionsForEmoji(
- channelId: ChannelID,
- messageId: MessageID,
- emojiName: string,
- emojiId?: EmojiID,
- ): Promise<void> {
+ async removeAllReactionsForEmoji(channelId: ChannelID, messageId: MessageID, emoji: ReactionEmojiKey): Promise<void> {
const bucket = BucketUtils.makeBucket(messageId);
- const normalizedEmojiId = emojiId ?? createEmojiID(0n);
- const deleteQuery = MessageReactions.deleteCql({
- where: [
- MessageReactions.where.eq('channel_id'),
- MessageReactions.where.eq('bucket'),
- MessageReactions.where.eq('message_id'),
- MessageReactions.where.eq('emoji_id'),
- MessageReactions.where.eq('emoji_name'),
- ],
- });
- await deleteOneOrMany(deleteQuery, {
- channel_id: channelId,
- bucket,
- message_id: messageId,
- emoji_id: normalizedEmojiId,
- emoji_name: emojiName,
- });
+ if (emoji.id !== undefined) {
+ await deleteOneOrMany(DELETE_REACTIONS_BY_EMOJI_ID_QUERY, {
+ channel_id: channelId,
+ bucket,
+ message_id: messageId,
+ emoji_id: emoji.id,
+ });
+ } else {
+ await deleteOneOrMany(DELETE_REACTIONS_BY_EMOJI_QUERY, {
+ channel_id: channelId,
+ bucket,
+ message_id: messageId,
+ emoji_id: UNICODE_EMOJI_ID,
+ emoji_name: emoji.name,
+ });
+ }
const hasReactions = await this.messageHasAnyReactions(channelId, messageId);
await this.setHasReaction(channelId, messageId, hasReactions);
}
- async countReactionUsers(
- channelId: ChannelID,
- messageId: MessageID,
- emojiName: string,
- emojiId?: EmojiID,
- ): Promise<number> {
- const reactions = await this.listReactionUsers(channelId, messageId, emojiName, undefined, undefined, emojiId);
- return reactions.length;
- }
-
async countUniqueReactions(channelId: ChannelID, messageId: MessageID): Promise<number> {
const reactions = await this.listMessageReactions(channelId, messageId);
const uniqueEmojis = new Set<string>();
for (const reaction of reactions) {
- const emojiKey = `${reaction.emojiId}:${reaction.emojiName}`;
- uniqueEmojis.add(emojiKey);
+ uniqueEmojis.add(
+ reaction.emojiId === UNICODE_EMOJI_ID ? `unicode:${reaction.emojiName}` : `custom:${reaction.emojiId}`,
+ );
}
return uniqueEmojis.size;
}
@@ -279,20 +312,22 @@ export class MessageInteractionRepository {
channelId: ChannelID,
messageId: MessageID,
userId: UserID,
- emojiName: string,
- emojiId?: EmojiID,
+ emoji: ReactionEmojiKey,
): Promise<boolean> {
const bucket = BucketUtils.makeBucket(messageId);
- const normalizedEmojiId = emojiId ?? createEmojiID(0n);
- const reaction = await fetchOne<MessageReactionRow>(CHECK_USER_REACTION_EXISTS_QUERY, {
- channel_id: channelId,
- bucket,
- message_id: messageId,
- user_id: userId,
- emoji_id: normalizedEmojiId,
- emoji_name: emojiName,
- });
- return !!reaction;
+ const names = await this.listStoredEmojiNames(channelId, bucket, messageId, emoji);
+ for (const emojiName of names) {
+ const reaction = await fetchOne<MessageReactionRow>(CHECK_USER_REACTION_EXISTS_QUERY, {
+ channel_id: channelId,
+ bucket,
+ message_id: messageId,
+ user_id: userId,
+ emoji_id: emoji.id ?? UNICODE_EMOJI_ID,
+ emoji_name: emojiName,
+ });
+ if (reaction) return true;
+ }
+ return false;
}
async setHasReaction(channelId: ChannelID, messageId: MessageID, hasReaction: boolean): Promise<void> {
@@ -311,6 +346,26 @@ export class MessageInteractionRepository {
);
}
+ private async listStoredEmojiNames(
+ channelId: ChannelID,
+ bucket: number,
+ messageId: MessageID,
+ emoji: ReactionEmojiKey,
+ ): Promise<Array<string>> {
+ if (emoji.id === undefined) return [emoji.name];
+ const key = {channel_id: channelId, bucket, message_id: messageId, emoji_id: emoji.id};
+ const names: Array<string> = [];
+ let row = await fetchOne<Pick<MessageReactionRow, 'emoji_name'>>(FETCH_FIRST_EMOJI_NAME_QUERY, key);
+ while (row) {
+ names.push(row.emoji_name);
+ row = await fetchOne<Pick<MessageReactionRow, 'emoji_name'>>(FETCH_NEXT_EMOJI_NAME_QUERY, {
+ ...key,
+ after_emoji_name: row.emoji_name,
+ });
+ }
+ return names;
+ }
+
private async messageHasAnyReactions(channelId: ChannelID, messageId: MessageID): Promise<boolean> {
const bucket = BucketUtils.makeBucket(messageId);
const row = await fetchOne<Pick<MessageReactionRow, 'channel_id'>>(CHECK_MESSAGE_HAS_REACTIONS_QUERY, {
diff --git a/fluxer_api/src/api/channel/services/interaction/MessageReactionService.ts b/fluxer_api/src/api/channel/services/interaction/MessageReactionService.ts
index a753ec833..d87a41837 100644
--- a/fluxer_api/src/api/channel/services/interaction/MessageReactionService.ts
+++ b/fluxer_api/src/api/channel/services/interaction/MessageReactionService.ts
@@ -1,7 +1,8 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-import {createEmojiID, type MessageID, type UserID} from '@app/api/BrandedTypes';
+import {type ChannelID, createEmojiID, type MessageID, type UserID} from '@app/api/BrandedTypes';
import type {ChannelRepository} from '@app/api/channel/ChannelRepository';
+import type {ReactionEmojiKey} from '@app/api/channel/repositories/MessageInteractionRepository';
import type {AuthenticatedChannel} from '@app/api/channel/services/AuthenticatedChannel';
import {dispatchChannelEvent} from '@app/api/channel/services/ChannelGatewayDispatch';
import {ensureTextChannel, isOperationDisabled} from '@app/api/channel/services/message/MessageHelpers';
@@ -40,7 +41,15 @@ interface ParsedEmoji {
animated?: boolean;
}
-const REACTION_CUSTOM_EMOJI_REGEX = /^(.+):(\d+)$/;
+const UNICODE_EMOJI_ID = createEmojiID(0n);
+const REACTION_CUSTOM_EMOJI_REGEX = /^<?(?:a?:)?[^:<>]*:(\d+)>?$/;
+
+function toParsedEmoji(reaction: MessageReaction): ParsedEmoji {
+ if (reaction.emojiId === UNICODE_EMOJI_ID) {
+ return {name: reaction.emojiName};
+ }
+ return {id: reaction.emojiId.toString(), name: reaction.emojiName, animated: reaction.isEmojiAnimated};
+}
export class MessageReactionService {
private async assertReactionRemovalAllowed(authChannel: AuthenticatedChannel, messageId: MessageID): Promise<void> {
@@ -130,16 +139,12 @@ export class MessageReactionService {
const validatedLimit = Math.min(Math.max(requestedLimit, 1), limitCap);
const message = await this.channelRepository.messages.getMessage(channel.id, messageId);
if (!message) throw new UnknownMessageError();
- const parsedEmoji = this.parseEmojiWithoutValidation(emoji);
- const afterUserId = after;
- const fetchLimit = validatedLimit + 1;
const reactions = await this.channelRepository.messageInteractions.listReactionUsers(
channel.id,
messageId,
- parsedEmoji.name,
- fetchLimit,
- afterUserId,
- parsedEmoji.id ? createEmojiID(BigInt(parsedEmoji.id)) : undefined,
+ this.parseReactionEmojiKey(emoji),
+ validatedLimit + 1,
+ after,
);
const hasMore = reactions.length > validatedLimit;
const pageReactions = hasMore ? reactions.slice(0, validatedLimit) : reactions;
@@ -200,33 +205,31 @@ export class MessageReactionService {
key: 'max_reactions_per_message',
fallback: MAX_REACTIONS_PER_MESSAGE,
});
- const parsedEmojiBasic = this.parseEmojiWithoutValidation(emoji);
- const emojiId = parsedEmojiBasic.id ? createEmojiID(BigInt(parsedEmojiBasic.id)) : undefined;
+ const emojiKey = this.parseReactionEmojiKey(emoji);
const userReactionExists = await this.channelRepository.messageInteractions.checkUserReactionExists(
channel.id,
messageId,
userId,
- parsedEmojiBasic.name,
- emojiId,
+ emojiKey,
);
if (userReactionExists) {
return;
}
- const reactionCount = await this.channelRepository.messageInteractions.countReactionUsers(
+ const existingReactions = await this.channelRepository.messageInteractions.listReactionUsers(
channel.id,
messageId,
- parsedEmojiBasic.name,
- emojiId,
+ emojiKey,
);
+ const reactionCount = existingReactions.length;
if (reactionCount === 0 && guild) {
await checkPermission(Permissions.ADD_REACTIONS);
}
let parsedEmoji: ParsedEmoji;
if (reactionCount > 0) {
- parsedEmoji = parsedEmojiBasic;
+ parsedEmoji = toParsedEmoji(existingReactions[0]);
} else {
- parsedEmoji = await this.parseAndValidateEmoji({
- emoji,
+ parsedEmoji = await this.validateEmoji({
+ emojiKey,
guildId: channel.guildId?.toString() || undefined,
userId,
hasPermission: channel.guildId ? hasPermission : undefined,
@@ -249,7 +252,7 @@ export class MessageReactionService {
messageId,
userId,
parsedEmoji.name,
- emojiId,
+ emojiKey.id,
parsedEmoji.animated ?? false,
);
await this.dispatchMessageReactionAdd({
@@ -279,21 +282,16 @@ export class MessageReactionService {
const channel = authChannel.channel;
const {hasPermission} = authChannel;
await this.assertReactionRemovalAllowed(authChannel, messageId);
- const parsedEmoji = this.parseEmojiWithoutValidation(emoji);
+ const emojiKey = this.parseReactionEmojiKey(emoji);
const message = await this.channelRepository.messages.getMessage(channel.id, messageId);
if (!message) return;
const isRemovingOwnReaction = targetId === actorId;
if (!isRemovingOwnReaction) {
await this.assertCanModerateMessageReactions({channel, hasPermission});
}
- const emojiId = parsedEmoji.id ? createEmojiID(BigInt(parsedEmoji.id)) : undefined;
- await this.channelRepository.messageInteractions.removeReaction(
- channel.id,
- messageId,
- targetId,
- parsedEmoji.name,
- emojiId,
- );
+ const parsedEmoji = await this.findStoredEmoji(channel.id, messageId, emojiKey);
+ if (!parsedEmoji) return;
+ await this.channelRepository.messageInteractions.removeReaction(channel.id, messageId, targetId, emojiKey);
await this.dispatchMessageReactionRemove({
channel,
messageId,
@@ -315,17 +313,13 @@ export class MessageReactionService {
const channel = authChannel.channel;
const {hasPermission} = authChannel;
await this.assertReactionRemovalAllowed(authChannel, messageId);
- const parsedEmoji = this.parseEmojiWithoutValidation(emoji);
+ const emojiKey = this.parseReactionEmojiKey(emoji);
const message = await this.channelRepository.messages.getMessage(channel.id, messageId);
if (!message) return;
await this.assertCanModerateMessageReactions({channel, hasPermission});
- const emojiId = parsedEmoji.id ? createEmojiID(BigInt(parsedEmoji.id)) : undefined;
- await this.channelRepository.messageInteractions.removeAllReactionsForEmoji(
- channel.id,
- messageId,
- parsedEmoji.name,
- emojiId,
- );
+ const parsedEmoji = await this.findStoredEmoji(channel.id, messageId, emojiKey);
+ if (!parsedEmoji) return;
+ await this.channelRepository.messageInteractions.removeAllReactionsForEmoji(channel.id, messageId, emojiKey);
await this.dispatchMessageReactionRemoveAllForEmoji({
channel,
messageId,
@@ -366,43 +360,46 @@ export class MessageReactionService {
}
}
- private parseEmojiWithoutValidation(emoji: string): {
- name: string;
- id?: string;
- animated?: boolean;
- } {
+ private parseReactionEmojiKey(emoji: string): ReactionEmojiKey {
const decodedEmoji = decodeURIComponent(emoji);
const customEmojiMatch = decodedEmoji.match(REACTION_CUSTOM_EMOJI_REGEX);
if (customEmojiMatch) {
- const [, name, id] = customEmojiMatch;
- return {
- id,
- name: name || 'unknown',
- };
+ return {id: createEmojiID(BigInt(customEmojiMatch[1]))};
}
return {name: decodedEmoji};
}
- private async parseAndValidateEmoji({
- emoji,
+ private async findStoredEmoji(
+ channelId: ChannelID,
+ messageId: MessageID,
+ emojiKey: ReactionEmojiKey,
+ ): Promise<ParsedEmoji | null> {
+ const [reaction] = await this.channelRepository.messageInteractions.listReactionUsers(
+ channelId,
+ messageId,
+ emojiKey,
+ 1,
+ );
+ if (reaction) return toParsedEmoji(reaction);
+ return emojiKey.id === undefined ? {name: emojiKey.name} : null;
+ }
+
+ private async validateEmoji({
+ emojiKey,
guildId,
userId,
hasPermission,
}: {
- emoji: string;
+ emojiKey: ReactionEmojiKey;
guildId?: string | undefined;
userId?: UserID;
hasPermission?: (permission: bigint) => Promise<boolean>;
}): Promise<ParsedEmoji> {
- const decodedEmoji = decodeURIComponent(emoji);
- const customEmojiMatch = decodedEmoji.match(REACTION_CUSTOM_EMOJI_REGEX);
- if (customEmojiMatch) {
- const [, , id] = customEmojiMatch;
- const emojiIdBigInt = createEmojiID(BigInt(id));
+ if (emojiKey.id !== undefined) {
const hasGlobalExpressions = userId
? await checkUserGlobalExpressions(userId, this.userRepository, this.limitConfigService)
: 0;
- const emoji = await this.guildRepository.getEmojiById(emojiIdBigInt);
+ const emoji = await this.guildRepository.getEmojiById(emojiKey.id);
if (!emoji) {
throw InputValidationError.fromCode('emoji', ValidationErrorCodes.CUSTOM_EMOJI_NOT_FOUND);
}
@@ -420,15 +417,15 @@ export class MessageReactionService {
}
}
return {
- id,
+ id: emojiKey.id.toString(),
name: emoji.name,
animated: emoji.isAnimated,
};
}
- if (!isValidSingleUnicodeEmoji(decodedEmoji)) {
+ if (!isValidSingleUnicodeEmoji(emojiKey.name)) {
throw InputValidationError.fromCode('emoji', ValidationErrorCodes.NOT_A_VALID_UNICODE_EMOJI);
}
- return {name: decodedEmoji};
+ return {name: emojiKey.name};
}
private async dispatchMessageReactionAdd(params: {
diff --git a/fluxer_api/src/api/channel/tests/ReactionEmojiMatching.test.ts b/fluxer_api/src/api/channel/tests/ReactionEmojiMatching.test.ts
new file mode 100644
index 000000000..d0672a4f3
--- /dev/null
+++ b/fluxer_api/src/api/channel/tests/ReactionEmojiMatching.test.ts
@@ -0,0 +1,226 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import type {TestAccount} from '@app/api/auth/tests/AuthTestUtils';
+import {createChannelID, createEmojiID, createMessageID, createUserID} from '@app/api/BrandedTypes';
+import {sendChannelMessage, setupTestGuildWithMembers} from '@app/api/channel/tests/ChannelTestUtils';
+import {createEmoji, getPngDataUrl} from '@app/api/emoji/tests/EmojiTestUtils';
+import type {IGatewayService} from '@app/api/infrastructure/IGatewayService';
+import {getGatewayService} from '@app/api/middleware/ServiceRegistry';
+import {getChannelRepository} from '@app/api/middleware/ServiceSingletons';
+import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
+import {HTTP_STATUS} from '@app/api/test/TestConstants';
+import {createBuilder} from '@app/api/test/TestRequestBuilder';
+import type {MessageResponse} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';
+import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, type MockInstance, vi} from 'vitest';
+
+interface ReactionUsersPage {
+ items: Array<{id: string}>;
+}
+
+interface Setup {
+ owner: TestAccount;
+ guildId: string;
+ reactors: [TestAccount, TestAccount];
+ channelId: string;
+ messageId: string;
+ emoji: {id: string; name: string};
+}
+
+const CUSTOM_FORMS: Array<[string, (id: string) => string]> = [
+ ['coin:id', (id) => `coin:${id}`],
+ [':coin:id', (id) => `:coin:${id}`],
+ ['a:coin:id', (id) => `a:coin:${id}`],
+ ['<:coin:id>', (id) => `<:coin:${id}>`],
+ ['<a:coin:id>', (id) => `<a:coin:${id}>`],
+ [':id', (id) => `:${id}`],
+];
+
+describe('Reaction emoji matching', () => {
+ let harness: ApiTestHarness;
+ let dispatchGuild: MockInstance<IGatewayService['dispatchGuild']>;
+
+ beforeAll(async () => {
+ harness = await createApiTestHarness();
+ });
+
+ beforeEach(async () => {
+ await harness.reset();
+ dispatchGuild = vi.spyOn(getGatewayService(), 'dispatchGuild');
+ });
+
+ afterEach(() => {
+ dispatchGuild.mockRestore();
+ });
+
+ afterAll(async () => {
+ await harness?.shutdown();
+ });
+
+ async function setup(): Promise<Setup> {
+ const {owner, members, guild, systemChannel} = await setupTestGuildWithMembers(harness, 2);
+ const emoji = await createEmoji(harness, owner.token, guild.id, {name: 'coin', image: getPngDataUrl()});
+ const message = await sendChannelMessage(harness, owner.token, systemChannel.id, 'react to me');
+ return {
+ owner,
+ guildId: guild.id,
+ reactors: members as [TestAccount, TestAccount],
+ channelId: systemChannel.id,
+ messageId: message.id,
+ emoji: {id: emoji.id, name: emoji.name},
+ };
+ }
+
+ function reactionsPath(s: Setup, emoji: string): string {
+ return `/channels/${s.channelId}/messages/${s.messageId}/reactions/${encodeURIComponent(emoji)}`;
+ }
+
+ async function react(s: Setup, account: TestAccount, emoji: string): Promise<void> {
+ await createBuilder(harness, account.token)
+ .put(`${reactionsPath(s, emoji)}/@me`)
+ .body(null)
+ .expect(HTTP_STATUS.NO_CONTENT)
+ .execute();
+ }
+
+ async function remove(account: TestAccount, path: string): Promise<void> {
+ await createBuilder(harness, account.token).delete(path).expect(HTTP_STATUS.NO_CONTENT).execute();
+ }
+
+ async function messageReactions(s: Setup): Promise<MessageResponse['reactions']> {
+ const message = await createBuilder<MessageResponse>(harness, s.owner.token)
+ .get(`/channels/${s.channelId}/messages/${s.messageId}`)
+ .execute();
+ return message.reactions ?? [];
+ }
+
+ async function reactorIds(s: Setup, emoji: string): Promise<Array<string>> {
+ const page = await createBuilder<ReactionUsersPage>(harness, s.owner.token)
+ .get(`${reactionsPath(s, emoji)}/users`)
+ .execute();
+ return page.items.map((user) => user.id).sort();
+ }
+
+ function dispatchedEmoji(event: string): unknown {
+ const call = dispatchGuild.mock.calls.find(([params]) => params.event === event);
+ return (call?.[0].data as {emoji?: unknown} | undefined)?.emoji;
+ }
+
+ async function renameEmojiToBean(s: Setup): Promise<void> {
+ await createBuilder(harness, s.owner.token)
+ .patch(`/guilds/${s.guildId}/emojis/${s.emoji.id}`)
+ .body({name: 'bean'})
+ .execute();
+ }
+
+ it.each(CUSTOM_FORMS)('clears every reaction for a custom emoji requested as %s', async (_label, form) => {
+ const s = await setup();
+ const [first, second] = s.reactors;
+ await react(s, first, `coin:${s.emoji.id}`);
+ await react(s, second, `coin:${s.emoji.id}`);
+
+ await remove(s.owner, reactionsPath(s, form(s.emoji.id)));
+
+ expect(await messageReactions(s)).toEqual([]);
+ expect(await reactorIds(s, `coin:${s.emoji.id}`)).toEqual([]);
+ expect(dispatchedEmoji('MESSAGE_REACTION_REMOVE_EMOJI')).toEqual({id: s.emoji.id, name: 'coin', animated: false});
+ });
+
+ it.each(CUSTOM_FORMS)('removes one user reaction for a custom emoji requested as %s', async (_label, form) => {
+ const s = await setup();
+ const [first, second] = s.reactors;
+ const requested = form(s.emoji.id);
+ await react(s, first, `coin:${s.emoji.id}`);
+ await react(s, second, `coin:${s.emoji.id}`);
+
+ await remove(first, `${reactionsPath(s, requested)}/@me`);
+ expect(dispatchedEmoji('MESSAGE_REACTION_REMOVE')).toEqual({id: s.emoji.id, name: 'coin', animated: false});
+ await remove(s.owner, `${reactionsPath(s, requested)}/${second.userId}`);
+
+ expect(await messageReactions(s)).toEqual([]);
+ });
+
+ it.each(CUSTOM_FORMS)('lists and joins the existing custom emoji reaction requested as %s', async (_label, form) => {
+ const s = await setup();
+ const [first, second] = s.reactors;
+ const requested = form(s.emoji.id);
+ await react(s, first, `coin:${s.emoji.id}`);
+
+ await react(s, second, requested);
+ await react(s, second, requested);
+
+ expect(await messageReactions(s)).toEqual([{emoji: {id: s.emoji.id, name: 'coin'}, count: 2}]);
+ expect(await reactorIds(s, requested)).toEqual([first.userId, second.userId].sort());
+ expect(dispatchedEmoji('MESSAGE_REACTION_ADD')).toEqual({id: s.emoji.id, name: 'coin', animated: false});
+ });
+
+ it('names a new custom emoji reaction after the emoji, not the request', async () => {
+ const s = await setup();
+ const [first, second] = s.reactors;
+ await react(s, first, `:coin:${s.emoji.id}`);
+ await react(s, second, `coin:${s.emoji.id}`);
+
+ expect(await messageReactions(s)).toEqual([{emoji: {id: s.emoji.id, name: 'coin'}, count: 2}]);
+ });
+
+ it('keeps one reaction per custom emoji across a rename', async () => {
+ const s = await setup();
+ const [first, second] = s.reactors;
+ await react(s, first, `coin:${s.emoji.id}`);
+ await renameEmojiToBean(s);
+ await react(s, second, `bean:${s.emoji.id}`);
+
+ expect(await messageReactions(s)).toEqual([{emoji: {id: s.emoji.id, name: 'coin'}, count: 2}]);
+ await remove(s.owner, reactionsPath(s, `bean:${s.emoji.id}`));
+
+ expect(await messageReactions(s)).toEqual([]);
+ });
+
+ it('treats rows stored under an old emoji name as the same reaction', async () => {
+ const s = await setup();
+ const [first, second] = s.reactors;
+ await react(s, first, `coin:${s.emoji.id}`);
+ await getChannelRepository().messageInteractions.addReaction(
+ createChannelID(BigInt(s.channelId)),
+ createMessageID(BigInt(s.messageId)),
+ createUserID(BigInt(second.userId)),
+ 'bean',
+ createEmojiID(BigInt(s.emoji.id)),
+ );
+
+ expect(await messageReactions(s)).toEqual([{emoji: {id: s.emoji.id, name: 'bean'}, count: 2}]);
+ expect(await reactorIds(s, `coin:${s.emoji.id}`)).toEqual([first.userId, second.userId].sort());
+ await remove(second, `${reactionsPath(s, `coin:${s.emoji.id}`)}/@me`);
+ expect(await reactorIds(s, `coin:${s.emoji.id}`)).toEqual([first.userId]);
+ await react(s, second, `coin:${s.emoji.id}`);
+ await remove(s.owner, reactionsPath(s, `coin:${s.emoji.id}`));
+
+ expect(await messageReactions(s)).toEqual([]);
+ });
+
+ it.each([
+ ['with U+FE0F', '\u2764\uFE0F'],
+ ['with a skin tone', '\u{1F44D}\u{1F3FD}'],
+ ])('removes a unicode reaction %s', async (_label, emoji) => {
+ const s = await setup();
+ const [first, second] = s.reactors;
+ await react(s, first, emoji);
+ await react(s, second, emoji);
+
+ await remove(second, `${reactionsPath(s, emoji)}/@me`);
+ expect(await reactorIds(s, emoji)).toEqual([first.userId]);
+ await remove(s.owner, reactionsPath(s, emoji));
+
+ expect(await messageReactions(s)).toEqual([]);
+ });
+
+ it('keeps unicode reactions with and without U+FE0F apart', async () => {
+ const s = await setup();
+ const [first, second] = s.reactors;
+ await react(s, first, '\u2764\uFE0F');
+ await react(s, second, '\u2764');
+
+ await remove(s.owner, reactionsPath(s, '\u2764'));
+
+ expect(await messageReactions(s)).toEqual([{emoji: {id: null, name: '\u2764\uFE0F'}, count: 1}]);
+ });
+});
diff --git a/fluxer_api/src/api/test/mocks/RepositoryBackedMessageResponseDataService.ts b/fluxer_api/src/api/test/mocks/RepositoryBackedMessageResponseDataService.ts
index a56bc4f9f..e94765601 100644
--- a/fluxer_api/src/api/test/mocks/RepositoryBackedMessageResponseDataService.ts
+++ b/fluxer_api/src/api/test/mocks/RepositoryBackedMessageResponseDataService.ts
@@ -540,7 +540,7 @@ export class RepositoryBackedMessageResponseDataService extends MessageResponseD
>();
for (const reaction of reactions) {
const emojiId = reaction.emojiId.toString() === '0' ? null : reaction.emojiId.toString();
- const key = `${emojiId ?? ''}:${reaction.emojiName}`;
+ const key = emojiId ? `custom_${emojiId}` : `unicode_${reaction.emojiName}`;
const entry = byEmoji.get(key) ?? {
id: emojiId,
name: reaction.emojiName,