A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
// SPDX-License-Identifier: AGPL-3.0-or-later
import {createStickerID, type GuildID, type StickerID, type UserID} from '@app/api/BrandedTypes';
import {getContentMessage} from '@app/api/content_i18n/ContentI18n';
import {mapGuildStickersWithUsersToResponse, mapGuildStickerToResponse} from '@app/api/guild/GuildModel';
import type {GuildRepository} from '@app/api/guild/repositories/GuildRepository';
import type {ContentHelpers} from '@app/api/guild/services/content/ContentHelpers';
import type {ExpressionAssetPurger} from '@app/api/guild/services/content/ExpressionAssetPurger';
import {getLocalizedBulkCreateError, resolveGuildLimit} from '@app/api/guild/services/content/ExpressionHelpers';
import type {AvatarService} from '@app/api/infrastructure/AvatarService';
import {contentModerationService} from '@app/api/infrastructure/ContentModerationService';
import type {IGatewayService} from '@app/api/infrastructure/IGatewayService';
import type {ISnowflakeService} from '@app/api/infrastructure/ISnowflakeService';
import type {UserCacheService} from '@app/api/infrastructure/UserCacheService';
import type {LimitConfigService} from '@app/api/limits/LimitConfigService';
import type {RequestCache} from '@app/api/middleware/RequestCacheMiddleware';
import type {GuildSticker} from '@app/api/models/GuildSticker';
import type {User} from '@app/api/models/User';
import {serializeStickerForAudit} from '@app/api/utils/AuditSerializationUtils';
import {AuditLogActionType} from '@fluxer/constants/src/AuditLogActionType';
import {Permissions} from '@fluxer/constants/src/ChannelConstants';
import {GuildFeatures} from '@fluxer/constants/src/GuildConstants';
import {MAX_GUILD_EXPRESSION_SLOTS_UNLIMITED, MAX_GUILD_STICKERS} from '@fluxer/constants/src/LimitConstants';
import {MissingAccessError} from '@fluxer/errors/src/domains/core/MissingAccessError';
import {MaxGuildStickersStaticError} from '@fluxer/errors/src/domains/guild/MaxGuildStickersStaticError';
import {UnknownGuildStickerError} from '@fluxer/errors/src/domains/guild/UnknownGuildStickerError';
import type {
GuildStickerResponse,
GuildStickerWithUserResponse,
} from '@fluxer/schema/src/domains/guild/GuildEmojiSchemas';
export class StickerService {
constructor(
private readonly guildRepository: GuildRepository,
private readonly userCacheService: UserCacheService,
private readonly gatewayService: IGatewayService,
private readonly avatarService: AvatarService,
private readonly snowflakeService: ISnowflakeService,
private readonly contentHelpers: ContentHelpers,
private readonly assetPurger: ExpressionAssetPurger,
private readonly limitConfigService: LimitConfigService,
) {}
async getStickers(params: {
userId: UserID;
guildId: GuildID;
requestCache: RequestCache;
}): Promise<Array<GuildStickerWithUserResponse>> {
const {userId, guildId, requestCache} = params;
await this.gatewayService.getGuildData({userId, guildId});
const stickers = await this.guildRepository.listStickers(guildId);
return await mapGuildStickersWithUsersToResponse(stickers, this.userCacheService, requestCache);
}
async createSticker(
params: {
user: User;
guildId: GuildID;
name: string;
description?: string | null;
tags: Array<string>;
image: string;
},
auditLogReason?: string | null,
): Promise<GuildStickerResponse> {
const {user, guildId, name, description, tags, image} = params;
const stickerModCtx = {
userId: user.id,
guildId,
channelId: null,
messageId: null,
surface: 'sticker' as const,
};
contentModerationService.scanText(name, stickerModCtx);
contentModerationService.scanText(description, stickerModCtx);
contentModerationService.scanText(tags.join(' '), stickerModCtx);
const {allStickers, guildFeatures, maxStickers} = await this.loadStickerSlots(user.id, guildId);
if (allStickers.length >= maxStickers) {
throw new MaxGuildStickersStaticError(maxStickers);
}
const {animated, imageBuffer} = await this.avatarService.processSticker({
errorPath: 'image',
base64Image: image,
guildFeatures,
});
const stickerId = createStickerID(await this.snowflakeService.generate());
await this.avatarService.uploadSticker({prefix: 'stickers', stickerId, imageBuffer});
const sticker = await this.guildRepository.upsertSticker({
guild_id: guildId,
sticker_id: stickerId,
name,
description: description ?? null,
animated,
tags,
creator_id: user.id,
version: 1,
});
return this.finishStickerCreate(guildId, user, allStickers, sticker, auditLogReason);
}
async cloneSticker(
params: {
user: User;
guildId: GuildID;
sourceStickerId: StickerID;
},
auditLogReason?: string | null,
): Promise<GuildStickerResponse> {
const {user, guildId, sourceStickerId} = params;
const sourceSticker = await this.guildRepository.getStickerById(sourceStickerId);
if (!sourceSticker) throw new UnknownGuildStickerError();
const sourceGuild = await this.guildRepository.findUnique(sourceSticker.guildId);
if (!sourceGuild?.features.has(GuildFeatures.CLONE_STICKER_ENABLED)) {
throw new MissingAccessError();
}
const {allStickers, maxStickers} = await this.loadStickerSlots(user.id, guildId);
if (allStickers.length >= maxStickers) {
throw new MaxGuildStickersStaticError(maxStickers);
}
const stickerId = createStickerID(await this.snowflakeService.generate());
await this.avatarService.cloneStickerImage({sourceStickerId, stickerId});
const sticker = await this.guildRepository.upsertSticker({
guild_id: guildId,
sticker_id: stickerId,
name: sourceSticker.name,
description: sourceSticker.description,
animated: sourceSticker.animated,
tags: sourceSticker.tags,
creator_id: user.id,
version: 1,
});
return this.finishStickerCreate(guildId, user, allStickers, sticker, auditLogReason);
}
async bulkCreateStickers(
params: {
user: User;
guildId: GuildID;
stickers: Array<{
name: string;
description?: string | null;
tags: Array<string>;
image: string;
}>;
},
auditLogReason?: string | null,
): Promise<{
success: Array<GuildStickerResponse>;
failed: Array<{
name: string;
error: string;
}>;
}> {
const {user, guildId, stickers} = params;
const {allStickers, guildFeatures, maxStickers} = await this.loadStickerSlots(user.id, guildId);
let stickerCount = allStickers.length;
const success: Array<GuildStickerResponse> = [];
const failed: Array<{
name: string;
error: string;
}> = [];
const newStickers: Array<GuildSticker> = [];
for (const stickerData of stickers) {
try {
if (stickerCount >= maxStickers) {
failed.push({
name: stickerData.name,
error: getContentMessage('guild.bulk_create.sticker_limit', user.locale, {
limit: Math.floor(maxStickers),
}),
});
continue;
}
const bulkStickerModCtx = {
userId: user.id,
guildId,
channelId: null,
messageId: null,
surface: 'sticker' as const,
};
contentModerationService.scanText(stickerData.name, bulkStickerModCtx);
contentModerationService.scanText(stickerData.description, bulkStickerModCtx);
contentModerationService.scanText(stickerData.tags.join(' '), bulkStickerModCtx);
const {animated, imageBuffer} = await this.avatarService.processSticker({
errorPath: `stickers[${success.length + failed.length}].image`,
base64Image: stickerData.image,
guildFeatures,
});
const stickerId = createStickerID(await this.snowflakeService.generate());
await this.avatarService.uploadSticker({prefix: 'stickers', stickerId, imageBuffer});
const sticker = await this.guildRepository.upsertSticker({
guild_id: guildId,
sticker_id: stickerId,
name: stickerData.name,
description: stickerData.description ?? null,
tags: stickerData.tags,
animated,
creator_id: user.id,
version: 1,
});
stickerCount++;
newStickers.push(sticker);
success.push(mapGuildStickerToResponse(sticker));
} catch (error) {
failed.push({name: stickerData.name, error: getLocalizedBulkCreateError(error, user.locale)});
}
}
if (newStickers.length > 0) {
const updatedStickers = [...allStickers, ...newStickers];
await this.dispatchGuildStickersUpdate({guildId, stickers: updatedStickers});
await Promise.all(newStickers.map((sticker) => this.recordStickerCreate(guildId, user, sticker, auditLogReason)));
}
return {success, failed};
}
async updateSticker(
params: {
userId: UserID;
guildId: GuildID;
stickerId: StickerID;
name: string;
description?: string | null;
tags: Array<string>;
},
auditLogReason?: string | null,
): Promise<GuildStickerResponse> {
const {userId, guildId, stickerId, name, description, tags} = params;
const stickerModCtx = {
userId,
guildId,
channelId: null,
messageId: null,
surface: 'sticker' as const,
};
contentModerationService.scanText(name, stickerModCtx);
contentModerationService.scanText(description, stickerModCtx);
contentModerationService.scanText(tags.join(' '), stickerModCtx);
const allStickers = await this.guildRepository.listStickers(guildId);
const sticker = allStickers.find((e) => e.id === stickerId);
if (!sticker) throw new UnknownGuildStickerError();
await this.contentHelpers.checkModifyExpressionPermission({userId, guildId, creatorId: sticker.creatorId});
const previousSnapshot = serializeStickerForAudit(sticker);
const updatedSticker = await this.guildRepository.upsertSticker({
...sticker.toRow(),
name,
description: description ?? null,
tags,
});
const updatedStickers = allStickers.map((e) => (e.id === stickerId ? updatedSticker : e));
await this.dispatchGuildStickersUpdate({guildId, stickers: updatedStickers});
await this.contentHelpers.guildAuditLogService.record({
guildId,
userId,
action: AuditLogActionType.STICKER_UPDATE,
targetId: stickerId,
auditLogReason: auditLogReason ?? null,
changes: this.contentHelpers.guildAuditLogService.computeChanges(
previousSnapshot,
serializeStickerForAudit(updatedSticker),
),
});
return mapGuildStickerToResponse(updatedSticker);
}
async deleteSticker(
params: {
userId: UserID;
guildId: GuildID;
stickerId: StickerID;
purge?: boolean;
},
auditLogReason?: string | null,
): Promise<void> {
const {userId, guildId, stickerId, purge = false} = params;
const guildData = await this.gatewayService.getGuildData({userId, guildId});
if (purge && !guildData.features.includes(GuildFeatures.EXPRESSION_PURGE_ALLOWED)) {
throw new MissingAccessError();
}
const allStickers = await this.guildRepository.listStickers(guildId);
const sticker = allStickers.find((e) => e.id === stickerId);
if (!sticker) throw new UnknownGuildStickerError();
await this.contentHelpers.checkModifyExpressionPermission({userId, guildId, creatorId: sticker.creatorId});
const previousSnapshot = serializeStickerForAudit(sticker);
await this.guildRepository.deleteSticker(guildId, stickerId);
const updatedStickers = allStickers.filter((e) => e.id !== stickerId);
await this.dispatchGuildStickersUpdate({guildId, stickers: updatedStickers});
if (purge) {
await this.assetPurger.purgeSticker(sticker.id.toString());
}
await this.contentHelpers.guildAuditLogService.record({
guildId,
userId,
action: AuditLogActionType.STICKER_DELETE,
targetId: stickerId,
auditLogReason: auditLogReason ?? null,
changes: this.contentHelpers.guildAuditLogService.computeChanges(previousSnapshot, null),
});
}
private async loadStickerSlots(
userId: UserID,
guildId: GuildID,
): Promise<{allStickers: Array<GuildSticker>; guildFeatures: Array<string>; maxStickers: number}> {
const guildData = await this.gatewayService.getGuildData({userId, guildId});
await this.contentHelpers.checkPermission({userId, guildId, permission: Permissions.CREATE_EXPRESSIONS});
const allStickers = await this.guildRepository.listStickers(guildId);
const guildFeatures = guildData.features;
const maxStickers = guildFeatures.includes(GuildFeatures.UNLIMITED_STICKERS)
? MAX_GUILD_EXPRESSION_SLOTS_UNLIMITED
: resolveGuildLimit(this.limitConfigService, 'max_guild_stickers', MAX_GUILD_STICKERS, guildFeatures);
return {allStickers, guildFeatures, maxStickers};
}
private async finishStickerCreate(
guildId: GuildID,
user: User,
allStickers: Array<GuildSticker>,
sticker: GuildSticker,
auditLogReason?: string | null,
): Promise<GuildStickerResponse> {
await this.dispatchGuildStickersUpdate({guildId, stickers: [...allStickers, sticker]});
await this.recordStickerCreate(guildId, user, sticker, auditLogReason);
return mapGuildStickerToResponse(sticker);
}
private async recordStickerCreate(
guildId: GuildID,
user: User,
sticker: GuildSticker,
auditLogReason?: string | null,
): Promise<void> {
await this.contentHelpers.guildAuditLogService.record({
guildId,
userId: user.id,
action: AuditLogActionType.STICKER_CREATE,
targetId: sticker.id,
auditLogReason: auditLogReason ?? null,
changes: this.contentHelpers.guildAuditLogService.computeChanges(null, serializeStickerForAudit(sticker)),
});
}
private async dispatchGuildStickersUpdate(params: {guildId: GuildID; stickers: Array<GuildSticker>}): Promise<void> {
const {guildId, stickers} = params;
await this.gatewayService.dispatchGuild({
guildId,
event: 'GUILD_STICKERS_UPDATE',
data: {stickers: stickers.map(mapGuildStickerToResponse)},
});
}
}