using System; using System.Collections.Generic; using System.Linq; namespace Jellyfin.Plugin.Herald.Notices; /// /// The decisions around who sees a notice and which responses are allowed. /// public static class NoticeRules { /// /// Maximum title length. /// public const int MaxTitleLength = 200; /// /// Maximum body length. /// public const int MaxBodyLength = 20000; /// /// Checks whether a notice is addressed to a user. /// /// The notice. /// The user id. /// true if the user is addressed. public static bool IsTargeted(Notice notice, Guid userId) { ArgumentNullException.ThrowIfNull(notice); return notice.Target.AllUsers || notice.Target.UserIds.Contains(userId); } /// /// Checks whether a notice still has to be shown to a user. /// /// The notice. /// The user id. /// The acknowledgements of that user. /// true if the notice is pending. public static bool IsPending(Notice notice, Guid userId, IEnumerable userAcks) { ArgumentNullException.ThrowIfNull(notice); ArgumentNullException.ThrowIfNull(userAcks); if (!notice.Enabled || !IsTargeted(notice, userId)) { return false; } return !userAcks.Any(a => a.UserId == userId && a.NoticeId == notice.Id && a.Revision == notice.Revision); } /// /// Selects the notices a user still has to see, oldest first. /// /// All notices. /// The user id. /// The acknowledgements of that user. /// The pending notices. public static IReadOnlyList SelectPending(IEnumerable notices, Guid userId, IReadOnlyCollection userAcks) { ArgumentNullException.ThrowIfNull(notices); return notices .Where(n => IsPending(n, userId, userAcks)) .OrderBy(n => n.CreatedAt) .ThenBy(n => n.Id) .ToList(); } /// /// Validates a response to a notice. /// /// The notice, or null if it does not exist. /// The responding user. /// The revision the user saw. /// The response. /// The validation outcome. public static AckResult ValidateAck(Notice? notice, Guid userId, int revision, AckAction action) { if (notice is null || !notice.Enabled || !IsTargeted(notice, userId)) { return AckResult.NotFound; } if (revision != notice.Revision) { return AckResult.RevisionMismatch; } if (notice.RequireAccept && action != AckAction.Accepted) { return AckResult.AcceptRequired; } return AckResult.Ok; } /// /// Validates the editable fields of a notice. /// /// The draft. /// An error message, or null if the draft is valid. public static string? ValidateDraft(NoticeDraft? draft) { if (draft is null) { return "A notice is required."; } if (string.IsNullOrWhiteSpace(draft.Title)) { return "Title is required."; } if (draft.Title.Trim().Length > MaxTitleLength) { return "Title is too long."; } if ((draft.Body?.Length ?? 0) > MaxBodyLength) { return "Body is too long."; } if (draft.Target is { AllUsers: false } target && (target.UserIds is null || target.UserIds.Count == 0)) { return "Select at least one user or address all users."; } return null; } }