| | | 1 | | using System.Text; |
| | | 2 | | |
| | | 3 | | namespace TeleFlow.Telegram.Formatting; |
| | | 4 | | |
| | | 5 | | /// <summary> |
| | | 6 | | /// Encodes dynamic values for Telegram HTML text and interpolation boundaries in one pass. |
| | | 7 | | /// Text rendering preserves quotes, while general interpolation also prevents values from leaving quoted attributes. |
| | | 8 | | /// </summary> |
| | | 9 | | internal static class TelegramHtmlEscaper |
| | | 10 | | { |
| | | 11 | | public static string EscapeText(string value) |
| | | 12 | | { |
| | 15 | 13 | | return Escape(value, escapeQuotes: false); |
| | | 14 | | } |
| | | 15 | | |
| | | 16 | | public static string EscapeInterpolation(string value) |
| | | 17 | | { |
| | 8 | 18 | | return Escape(value, escapeQuotes: true); |
| | | 19 | | } |
| | | 20 | | |
| | | 21 | | private static string Escape(string value, bool escapeQuotes) |
| | | 22 | | { |
| | 23 | 23 | | var firstSpecialCharacter = FindFirstSpecialCharacter(value, escapeQuotes); |
| | | 24 | | |
| | 23 | 25 | | if (firstSpecialCharacter < 0) |
| | | 26 | | { |
| | 14 | 27 | | return value; |
| | | 28 | | } |
| | | 29 | | |
| | 9 | 30 | | var builder = new StringBuilder(value.Length + 16); |
| | 9 | 31 | | builder.Append(value.AsSpan(0, firstSpecialCharacter)); |
| | | 32 | | |
| | 178 | 33 | | for (var index = firstSpecialCharacter; index < value.Length; index++) |
| | | 34 | | { |
| | 80 | 35 | | var replacement = value[index] switch |
| | 80 | 36 | | { |
| | 6 | 37 | | '&' => "&", |
| | 4 | 38 | | '<' => "<", |
| | 2 | 39 | | '>' => ">", |
| | 4 | 40 | | '"' when escapeQuotes => """, |
| | 2 | 41 | | '\'' when escapeQuotes => "'", |
| | 65 | 42 | | _ => null |
| | 80 | 43 | | }; |
| | | 44 | | |
| | 80 | 45 | | if (replacement is null) |
| | | 46 | | { |
| | 65 | 47 | | builder.Append(value[index]); |
| | | 48 | | } |
| | | 49 | | else |
| | | 50 | | { |
| | 15 | 51 | | builder.Append(replacement); |
| | | 52 | | } |
| | | 53 | | } |
| | | 54 | | |
| | 9 | 55 | | return builder.ToString(); |
| | | 56 | | } |
| | | 57 | | |
| | | 58 | | private static int FindFirstSpecialCharacter(string value, bool escapeQuotes) |
| | | 59 | | { |
| | 312 | 60 | | for (var index = 0; index < value.Length; index++) |
| | | 61 | | { |
| | 142 | 62 | | if (value[index] is '&' or '<' or '>' || |
| | 142 | 63 | | escapeQuotes && (value[index] is '"' or '\'')) |
| | | 64 | | { |
| | 9 | 65 | | return index; |
| | | 66 | | } |
| | | 67 | | } |
| | | 68 | | |
| | 14 | 69 | | return -1; |
| | | 70 | | } |
| | | 71 | | } |