| | | 1 | | namespace TeleFlow.Annotations; |
| | | 2 | | /// <summary> |
| | | 3 | | /// Restricts a handler or handler class to specific Telegram chat usernames. |
| | | 4 | | /// </summary> |
| | | 5 | | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] |
| | | 6 | | public sealed class ChatUsernameAttribute : TeleFlowAttribute |
| | | 7 | | { |
| | | 8 | | /// <summary> |
| | | 9 | | /// Creates a chat username filter. |
| | | 10 | | /// </summary> |
| | | 11 | | /// <param name="usernames">Telegram chat usernames allowed to match, with or without leading <c>@</c>.</param> |
| | 8 | 12 | | public ChatUsernameAttribute(params string[] usernames) |
| | | 13 | | { |
| | 8 | 14 | | ArgumentNullException.ThrowIfNull(usernames); |
| | | 15 | | |
| | 8 | 16 | | var canonicalUsernames = usernames |
| | 8 | 17 | | .Select(CanonicalizeUsername) |
| | 8 | 18 | | .ToArray(); |
| | | 19 | | |
| | 8 | 20 | | if (canonicalUsernames.Length == 0) |
| | | 21 | | { |
| | 0 | 22 | | throw new ArgumentException("At least one Telegram chat username must be specified.", nameof(usernames)); |
| | | 23 | | } |
| | | 24 | | |
| | 16 | 25 | | if (canonicalUsernames.Any(static username => username.Length == 0)) |
| | | 26 | | { |
| | 0 | 27 | | throw new ArgumentException("Telegram chat usernames must not be empty.", nameof(usernames)); |
| | | 28 | | } |
| | | 29 | | |
| | | 30 | | Usernames = canonicalUsernames; |
| | 8 | 31 | | } |
| | | 32 | | |
| | | 33 | | /// <summary> |
| | | 34 | | /// Canonical Telegram chat usernames allowed to match, without leading <c>@</c>. |
| | | 35 | | /// </summary> |
| | | 36 | | public IReadOnlyList<string> Usernames { get; } |
| | | 37 | | |
| | | 38 | | private static string CanonicalizeUsername(string? username) |
| | | 39 | | { |
| | 8 | 40 | | if (username is null) |
| | | 41 | | { |
| | 0 | 42 | | return string.Empty; |
| | | 43 | | } |
| | | 44 | | |
| | 8 | 45 | | var value = username.Trim(); |
| | 8 | 46 | | return value.StartsWith('@') ? value[1..] : value; |
| | | 47 | | } |
| | | 48 | | } |