ChatCensor.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using System.Linq;
  2. namespace Content.Shared.Chat.V2.Moderation;
  3. public interface IChatCensor
  4. {
  5. public bool Censor(string input, out string output, char replaceWith = '*');
  6. }
  7. public sealed class CompoundChatCensor(IEnumerable<IChatCensor> censors) : IChatCensor
  8. {
  9. public bool Censor(string input, out string output, char replaceWith = '*')
  10. {
  11. var censored = false;
  12. foreach (var censor in censors)
  13. {
  14. if (censor.Censor(input, out output, replaceWith))
  15. {
  16. censored = true;
  17. }
  18. }
  19. output = input;
  20. return censored;
  21. }
  22. }
  23. public sealed class ChatCensorFactory
  24. {
  25. private List<IChatCensor> _censors = new();
  26. public void With(IChatCensor censor)
  27. {
  28. _censors.Add(censor);
  29. }
  30. /// <summary>
  31. /// Builds a ChatCensor that combines all the censors that have been added to this.
  32. /// </summary>
  33. public IChatCensor Build()
  34. {
  35. return new CompoundChatCensor(_censors.ToArray());
  36. }
  37. /// <summary>
  38. /// Resets the build state to zero, allowing for different rules to be provided to the next censor(s) built.
  39. /// </summary>
  40. /// <returns>True if the builder had any setup prior to the reset.</returns>
  41. public bool Reset()
  42. {
  43. var notEmpty = _censors.Count > 0;
  44. _censors = new List<IChatCensor>();
  45. return notEmpty;
  46. }
  47. }