import { Injectable, Logger, OnModuleInit } from '@nestjs/common'; import { PrismaService } from '../../../database/prisma.service'; export interface SensitiveCheckResult { hasSensitive: boolean; hasForbidden: boolean; words: string[]; wordTypes: Array<{ word: string; type: string; level: number }>; } /** * 敏感词服务 - 违禁词/敏感词检测 */ @Injectable() export class SensitiveService implements OnModuleInit { private readonly logger = new Logger(SensitiveService.name); // 内存缓存敏感词 private sensitiveWords: Map = new Map(); private initialized = false; constructor(private readonly prisma: PrismaService) {} async onModuleInit(): Promise { await this.loadWords(); } /** * 加载敏感词到内存 */ private async loadWords(): Promise { try { const words = await this.prisma.sensitiveWord.findMany(); this.sensitiveWords.clear(); for (const word of words) { this.sensitiveWords.set(word.word, { type: word.type as 'FORBIDDEN' | 'SENSITIVE', level: word.level, }); } this.initialized = true; this.logger.log(`已加载 ${this.sensitiveWords.size} 个敏感词`); } catch (error) { this.logger.error('加载敏感词失败:', error); } } /** * 检测文本中的敏感词 */ async checkText(text: string): Promise { if (!this.initialized) { await this.loadWords(); } const foundWords: Array<{ word: string; type: string; level: number }> = []; const textLower = text.toLowerCase(); for (const [word, info] of this.sensitiveWords) { if (textLower.includes(word.toLowerCase())) { foundWords.push({ word, type: info.type, level: info.level, }); } } const hasForbidden = foundWords.some((w) => w.type === 'FORBIDDEN'); const hasSensitive = foundWords.length > 0; return { hasSensitive, hasForbidden, words: foundWords.map((w) => w.word), wordTypes: foundWords, }; } /** * 过滤敏感词(替换为*) */ async filterText(text: string, replacement = '***'): Promise { const checkResult = await this.checkText(text); let filtered = text; for (const word of checkResult.words) { const regex = new RegExp(word, 'gi'); filtered = filtered.replace(regex, replacement); } return filtered; } /** * 添加敏感词 */ async addWord(word: string, type: 'FORBIDDEN' | 'SENSITIVE', level = 1, category?: string): Promise { await this.prisma.sensitiveWord.create({ data: { word, type, level, category, }, }); // 更新内存缓存 this.sensitiveWords.set(word, { type, level }); this.logger.debug(`添加敏感词: ${word} (${type})`); } /** * 删除敏感词 */ async removeWord(word: string): Promise { await this.prisma.sensitiveWord.delete({ where: { word }, }); this.sensitiveWords.delete(word); this.logger.debug(`删除敏感词: ${word}`); } /** * 批量添加敏感词 */ async addWords(words: Array<{ word: string; type: 'FORBIDDEN' | 'SENSITIVE'; level?: number }>): Promise { let added = 0; for (const item of words) { try { await this.addWord(item.word, item.type, item.level || 1); added++; } catch { // 忽略重复等错误 } } return added; } /** * 重新加载敏感词 */ async reload(): Promise { await this.loadWords(); } /** * 获取所有敏感词 */ getAllWords(): Array<{ word: string; type: string; level: number }> { const result: Array<{ word: string; type: string; level: number }> = []; for (const [word, info] of this.sensitiveWords) { result.push({ word, type: info.type, level: info.level, }); } return result; } }