File size: 4,102 Bytes
d162abc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
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<string, { type: 'FORBIDDEN' | 'SENSITIVE'; level: number }> = new Map();
  private initialized = false;

  constructor(private readonly prisma: PrismaService) {}

  async onModuleInit(): Promise<void> {
    await this.loadWords();
  }

  /**
   * 加载敏感词到内存
   */
  private async loadWords(): Promise<void> {
    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<SensitiveCheckResult> {
    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<string> {
    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<void> {
    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<void> {
    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<number> {
    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<void> {
    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;
  }
}