From 873b48e2f88c95b780cbea46fd5e36795ce80cf9 Mon Sep 17 00:00:00 2001 From: Laura Hausmann Date: Wed, 8 Jan 2025 12:16:22 +0100 Subject: [PATCH] [backend/core] Add CollapseWhitespace rewrite policy (ISH-625) --- .../CollapseWhitespaceRewritePolicy.cs | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Iceshrimp.Backend/Core/Policies/CollapseWhitespaceRewritePolicy.cs diff --git a/Iceshrimp.Backend/Core/Policies/CollapseWhitespaceRewritePolicy.cs b/Iceshrimp.Backend/Core/Policies/CollapseWhitespaceRewritePolicy.cs new file mode 100644 index 00000000..ddf36bbd --- /dev/null +++ b/Iceshrimp.Backend/Core/Policies/CollapseWhitespaceRewritePolicy.cs @@ -0,0 +1,51 @@ +using System.Text.RegularExpressions; +using Iceshrimp.Backend.Core.Database.Tables; +using Iceshrimp.Backend.Core.Federation.ActivityStreams.Types; +using Iceshrimp.Backend.Core.Services; +using Iceshrimp.MfmSharp; + +namespace Iceshrimp.Backend.Core.Policies; + +public partial class CollapseWhitespaceRewritePolicy( + bool enabled, + int priority +) : IRewritePolicy +{ + public string Name => nameof(CollapseWhitespaceRewritePolicy); + public bool Enabled => enabled; + public int Priority => priority; + public IRewritePolicy.HookLocationEnum HookLocation => IRewritePolicy.HookLocationEnum.PostLogic; + + [GeneratedRegex(" +")] private static partial Regex WhitespaceRegex { get; } + + public void Apply(NoteService.NoteCreationData data) + { + if (data.Text == null || !IsApplicable(data)) return; + data.Text = WhitespaceRegex.Replace(data.Text, " "); + data.ParsedText = MfmParser.Parse(data.Text); + } + + public void Apply(NoteService.NoteUpdateData data) + { + if (data.Text == null || !IsApplicable(data)) return; + data.Text = WhitespaceRegex.Replace(data.Text, " "); + data.ParsedText = MfmParser.Parse(data.Text); + } + + public void Apply(ASNote note, User actor) { } + + private static bool IsApplicable(NoteService.NoteCreationData data) + => data.Text != null && data.Text.Contains(" ") && !data.Text.Contains("$["); + + private static bool IsApplicable(NoteService.NoteUpdateData data) + => data.Text != null && data.Text.Contains(" ") && !data.Text.Contains("$["); +} + +public class CollapseWhitespaceRewritePolicyConfiguration : IPolicyConfiguration +{ + public CollapseWhitespaceRewritePolicy Apply() => new(Enabled, Priority); + IPolicy IPolicyConfiguration. Apply() => Apply(); + + public bool Enabled { get; set; } + public int Priority { get; set; } +}