| | 1 | | using Cysharp.Threading.Tasks; |
| | 2 | | using System.Collections.Generic; |
| | 3 | | using System.Text; |
| | 4 | | using System.Text.RegularExpressions; |
| | 5 | | using System.Threading; |
| | 6 | |
|
| | 7 | | namespace DCL.ProfanityFiltering |
| | 8 | | { |
| | 9 | | public class RegexProfanityFilter : IProfanityFilter |
| | 10 | | { |
| | 11 | | private readonly IProfanityWordProvider wordProvider; |
| | 12 | | private Regex regex; |
| | 13 | |
|
| 19 | 14 | | public RegexProfanityFilter(IProfanityWordProvider wordProvider) |
| | 15 | | { |
| 19 | 16 | | this.wordProvider = wordProvider; |
| 19 | 17 | | } |
| | 18 | |
|
| | 19 | | public void Initialize() |
| | 20 | | { |
| 0 | 21 | | string explicitWords = ToRegex(wordProvider.GetExplicitWords()); |
| 0 | 22 | | string nonExplicitWords = ToRegex(wordProvider.GetNonExplicitWords()); |
| 0 | 23 | | regex = new Regex(@$"\b({explicitWords})\b|({nonExplicitWords})", RegexOptions.IgnoreCase); |
| 0 | 24 | | } |
| | 25 | |
|
| | 26 | | public void Dispose() |
| | 27 | | { |
| 0 | 28 | | } |
| | 29 | |
|
| | 30 | | public async UniTask<string> Filter(string message, CancellationToken cancellationToken) |
| | 31 | | { |
| 0 | 32 | | cancellationToken.ThrowIfCancellationRequested(); |
| 0 | 33 | | if (string.IsNullOrEmpty(message)) return message; |
| 0 | 34 | | return regex.Replace(message, |
| 0 | 35 | | match => new StringBuilder().Append('*', match.Value.Length).ToString()); |
| 0 | 36 | | } |
| | 37 | |
|
| 0 | 38 | | private string ToRegex(IEnumerable<string> words) => string.Join("|", words); |
| | 39 | | } |
| | 40 | | } |