diff --git a/Jellyfin.Plugin.Herald/Notices/AckAction.cs b/Jellyfin.Plugin.Herald/Notices/AckAction.cs new file mode 100644 index 0000000..88c73e2 --- /dev/null +++ b/Jellyfin.Plugin.Herald/Notices/AckAction.cs @@ -0,0 +1,17 @@ +namespace Jellyfin.Plugin.Herald.Notices; + +/// +/// How a user responded to a notice. +/// +public enum AckAction +{ + /// + /// The user closed the notice. + /// + Dismissed = 0, + + /// + /// The user explicitly accepted the notice. + /// + Accepted = 1 +} diff --git a/Jellyfin.Plugin.Herald/Notices/AckEntry.cs b/Jellyfin.Plugin.Herald/Notices/AckEntry.cs new file mode 100644 index 0000000..6654bb5 --- /dev/null +++ b/Jellyfin.Plugin.Herald/Notices/AckEntry.cs @@ -0,0 +1,29 @@ +using System; + +namespace Jellyfin.Plugin.Herald.Notices; + +/// +/// One row of the acknowledgement report. +/// +public class AckEntry +{ + /// + /// Gets or sets the user id. + /// + public Guid UserId { get; set; } + + /// + /// Gets or sets the user name. null if the user no longer exists. + /// + public string? UserName { get; set; } + + /// + /// Gets or sets the response. null for users who have not responded. + /// + public AckAction? Action { get; set; } + + /// + /// Gets or sets the response time (UTC). null for users who have not responded. + /// + public DateTime? Timestamp { get; set; } +} diff --git a/Jellyfin.Plugin.Herald/Notices/AckReport.cs b/Jellyfin.Plugin.Herald/Notices/AckReport.cs new file mode 100644 index 0000000..5060b5d --- /dev/null +++ b/Jellyfin.Plugin.Herald/Notices/AckReport.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; + +namespace Jellyfin.Plugin.Herald.Notices; + +/// +/// Who responded to the current revision of a notice and who has not yet. +/// +public class AckReport +{ + /// + /// Gets or sets the notice id. + /// + public Guid NoticeId { get; set; } + + /// + /// Gets or sets the revision the report covers. + /// + public int Revision { get; set; } + + /// + /// Gets or sets the users who responded, oldest response first. + /// + public IReadOnlyList Responses { get; set; } = []; + + /// + /// Gets or sets the addressed users who have not responded. + /// + public IReadOnlyList Pending { get; set; } = []; +} diff --git a/Jellyfin.Plugin.Herald/Notices/AckResult.cs b/Jellyfin.Plugin.Herald/Notices/AckResult.cs new file mode 100644 index 0000000..c9add12 --- /dev/null +++ b/Jellyfin.Plugin.Herald/Notices/AckResult.cs @@ -0,0 +1,27 @@ +namespace Jellyfin.Plugin.Herald.Notices; + +/// +/// Outcome of an acknowledgement attempt. +/// +public enum AckResult +{ + /// + /// The acknowledgement was stored (or already existed). + /// + Ok, + + /// + /// The notice does not exist, is disabled or is not addressed to the user. + /// + NotFound, + + /// + /// The acknowledged revision is not the current one. + /// + RevisionMismatch, + + /// + /// The notice must be accepted and cannot be dismissed. + /// + AcceptRequired +} diff --git a/Jellyfin.Plugin.Herald/Notices/INoticeStore.cs b/Jellyfin.Plugin.Herald/Notices/INoticeStore.cs new file mode 100644 index 0000000..ff959f6 --- /dev/null +++ b/Jellyfin.Plugin.Herald/Notices/INoticeStore.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; + +namespace Jellyfin.Plugin.Herald.Notices; + +/// +/// Persistence for notices and acknowledgements. +/// +public interface INoticeStore +{ + /// + /// Gets all notices, oldest first. + /// + /// The notices. + IReadOnlyList GetNotices(); + + /// + /// Gets a single notice. + /// + /// The notice id. + /// The notice, or null. + Notice? GetNotice(Guid id); + + /// + /// Inserts or replaces a notice. + /// + /// The notice. + void SaveNotice(Notice notice); + + /// + /// Deletes a notice together with its acknowledgements. + /// + /// The notice id. + /// true if a notice was deleted. + bool DeleteNotice(Guid id); + + /// + /// Gets every acknowledgement of a user. + /// + /// The user id. + /// The acknowledgements. + IReadOnlyList GetAcksByUser(Guid userId); + + /// + /// Gets the acknowledgements for one revision of a notice, oldest first. + /// + /// The notice id. + /// The revision. + /// The acknowledgements. + IReadOnlyList GetAcks(Guid noticeId, int revision); + + /// + /// Stores an acknowledgement. An existing one for the same notice, revision and user is kept. + /// + /// The acknowledgement. + void AddAck(NoticeAck ack); +} diff --git a/Jellyfin.Plugin.Herald/Notices/Notice.cs b/Jellyfin.Plugin.Herald/Notices/Notice.cs new file mode 100644 index 0000000..e3089d0 --- /dev/null +++ b/Jellyfin.Plugin.Herald/Notices/Notice.cs @@ -0,0 +1,54 @@ +using System; + +namespace Jellyfin.Plugin.Herald.Notices; + +/// +/// A message shown once to each addressed user. +/// +public class Notice +{ + /// + /// Gets or sets the id. + /// + public Guid Id { get; set; } + + /// + /// Gets or sets the title. + /// + public string Title { get; set; } = string.Empty; + + /// + /// Gets or sets the body: plain text or the supported Markdown subset. + /// + public string Body { get; set; } = string.Empty; + + /// + /// Gets or sets a value indicating whether users have to accept the notice. + /// + public bool RequireAccept { get; set; } + + /// + /// Gets or sets a value indicating whether the notice is shown at all. + /// + public bool Enabled { get; set; } = true; + + /// + /// Gets or sets the addressed users. + /// + public NoticeTarget Target { get; set; } = new(); + + /// + /// Gets or sets the revision. Acknowledgements only count for the current revision. + /// + public int Revision { get; set; } = 1; + + /// + /// Gets or sets the creation time (UTC). + /// + public DateTime CreatedAt { get; set; } + + /// + /// Gets or sets the time of the last change (UTC). + /// + public DateTime UpdatedAt { get; set; } +} diff --git a/Jellyfin.Plugin.Herald/Notices/NoticeAck.cs b/Jellyfin.Plugin.Herald/Notices/NoticeAck.cs new file mode 100644 index 0000000..6aaf7cb --- /dev/null +++ b/Jellyfin.Plugin.Herald/Notices/NoticeAck.cs @@ -0,0 +1,34 @@ +using System; + +namespace Jellyfin.Plugin.Herald.Notices; + +/// +/// A user's response to one revision of a notice. +/// +public class NoticeAck +{ + /// + /// Gets or sets the notice id. + /// + public Guid NoticeId { get; set; } + + /// + /// Gets or sets the acknowledged revision. + /// + public int Revision { get; set; } + + /// + /// Gets or sets the user id. + /// + public Guid UserId { get; set; } + + /// + /// Gets or sets the response. + /// + public AckAction Action { get; set; } + + /// + /// Gets or sets the response time (UTC). + /// + public DateTime Timestamp { get; set; } +} diff --git a/Jellyfin.Plugin.Herald/Notices/NoticeDraft.cs b/Jellyfin.Plugin.Herald/Notices/NoticeDraft.cs new file mode 100644 index 0000000..ee7d7cc --- /dev/null +++ b/Jellyfin.Plugin.Herald/Notices/NoticeDraft.cs @@ -0,0 +1,32 @@ +namespace Jellyfin.Plugin.Herald.Notices; + +/// +/// The editable part of a notice, as sent by the admin UI. +/// +public class NoticeDraft +{ + /// + /// Gets or sets the title. + /// + public string? Title { get; set; } + + /// + /// Gets or sets the body. + /// + public string? Body { get; set; } + + /// + /// Gets or sets a value indicating whether users have to accept the notice. + /// + public bool RequireAccept { get; set; } + + /// + /// Gets or sets a value indicating whether the notice is shown. + /// + public bool Enabled { get; set; } = true; + + /// + /// Gets or sets the addressed users. Defaults to all users. + /// + public NoticeTarget? Target { get; set; } +} diff --git a/Jellyfin.Plugin.Herald/Notices/NoticeRules.cs b/Jellyfin.Plugin.Herald/Notices/NoticeRules.cs new file mode 100644 index 0000000..6837e3b --- /dev/null +++ b/Jellyfin.Plugin.Herald/Notices/NoticeRules.cs @@ -0,0 +1,134 @@ +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; + } +} diff --git a/Jellyfin.Plugin.Herald/Notices/NoticeService.cs b/Jellyfin.Plugin.Herald/Notices/NoticeService.cs new file mode 100644 index 0000000..2064ffd --- /dev/null +++ b/Jellyfin.Plugin.Herald/Notices/NoticeService.cs @@ -0,0 +1,224 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Microsoft.Extensions.Logging; + +namespace Jellyfin.Plugin.Herald.Notices; + +/// +/// Notice operations used by the API. +/// +public class NoticeService +{ + private readonly INoticeStore _store; + private readonly TimeProvider _timeProvider; + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + /// The notice store. + /// The time provider. + /// The logger. + public NoticeService(INoticeStore store, TimeProvider timeProvider, ILogger logger) + { + _store = store; + _timeProvider = timeProvider; + _logger = logger; + } + + /// + /// Gets all notices, oldest first. + /// + /// The notices. + public IReadOnlyList GetAll() => _store.GetNotices(); + + /// + /// Gets a single notice. + /// + /// The notice id. + /// The notice, or null. + public Notice? Get(Guid id) => _store.GetNotice(id); + + /// + /// Gets the notices a user still has to see, oldest first. + /// + /// The user id. + /// The pending notices. + public IReadOnlyList GetPending(Guid userId) + { + return NoticeRules.SelectPending(_store.GetNotices(), userId, _store.GetAcksByUser(userId)); + } + + /// + /// Records a user's response to a notice. + /// + /// The responding user. + /// The notice id. + /// The revision the user saw. + /// The response. + /// The outcome. + public AckResult Acknowledge(Guid userId, Guid noticeId, int revision, AckAction action) + { + var notice = _store.GetNotice(noticeId); + var result = NoticeRules.ValidateAck(notice, userId, revision, action); + if (result != AckResult.Ok) + { + return result; + } + + _store.AddAck(new NoticeAck + { + NoticeId = noticeId, + Revision = revision, + UserId = userId, + Action = action, + Timestamp = UtcNow() + }); + + _logger.LogDebug("User {UserId} responded {Action} to notice {NoticeId} (revision {Revision})", userId, action, noticeId, revision); + return AckResult.Ok; + } + + /// + /// Creates a notice from a validated draft. + /// + /// The draft. + /// The created notice. + public Notice Create(NoticeDraft draft) + { + ArgumentNullException.ThrowIfNull(draft); + + var now = UtcNow(); + var notice = new Notice + { + Id = Guid.NewGuid(), + Revision = 1, + CreatedAt = now, + UpdatedAt = now + }; + Apply(notice, draft); + _store.SaveNotice(notice); + + _logger.LogInformation("Created notice \"{Title}\" ({NoticeId})", notice.Title, notice.Id); + return notice; + } + + /// + /// Updates a notice from a validated draft. The revision is left alone. + /// + /// The notice id. + /// The draft. + /// The updated notice, or null if it does not exist. + public Notice? Update(Guid id, NoticeDraft draft) + { + ArgumentNullException.ThrowIfNull(draft); + + var notice = _store.GetNotice(id); + if (notice is null) + { + return null; + } + + Apply(notice, draft); + notice.UpdatedAt = UtcNow(); + _store.SaveNotice(notice); + + _logger.LogInformation("Updated notice \"{Title}\" ({NoticeId})", notice.Title, notice.Id); + return notice; + } + + /// + /// Bumps the revision so the notice is shown to everyone again. + /// + /// The notice id. + /// The updated notice, or null if it does not exist. + public Notice? Reshow(Guid id) + { + var notice = _store.GetNotice(id); + if (notice is null) + { + return null; + } + + notice.Revision++; + notice.UpdatedAt = UtcNow(); + _store.SaveNotice(notice); + + _logger.LogInformation("Notice \"{Title}\" ({NoticeId}) is shown again, now at revision {Revision}", notice.Title, notice.Id, notice.Revision); + return notice; + } + + /// + /// Deletes a notice and its acknowledgements. + /// + /// The notice id. + /// true if the notice existed. + public bool Delete(Guid id) + { + var deleted = _store.DeleteNotice(id); + if (deleted) + { + _logger.LogInformation("Deleted notice {NoticeId}", id); + } + + return deleted; + } + + /// + /// Builds the acknowledgement report for the current revision of a notice. + /// + /// The notice id. + /// All existing users by id. + /// The report, or null if the notice does not exist. + public AckReport? GetAckReport(Guid id, IReadOnlyDictionary userNames) + { + ArgumentNullException.ThrowIfNull(userNames); + + var notice = _store.GetNotice(id); + if (notice is null) + { + return null; + } + + var acks = _store.GetAcks(id, notice.Revision); + var responded = acks.Select(a => a.UserId).ToHashSet(); + + return new AckReport + { + NoticeId = notice.Id, + Revision = notice.Revision, + Responses = acks + .Select(a => new AckEntry + { + UserId = a.UserId, + UserName = userNames.GetValueOrDefault(a.UserId), + Action = a.Action, + Timestamp = a.Timestamp + }) + .ToList(), + Pending = userNames + .Where(u => NoticeRules.IsTargeted(notice, u.Key) && !responded.Contains(u.Key)) + .OrderBy(u => u.Value, StringComparer.OrdinalIgnoreCase) + .Select(u => new AckEntry { UserId = u.Key, UserName = u.Value }) + .ToList() + }; + } + + private static void Apply(Notice notice, NoticeDraft draft) + { + notice.Title = (draft.Title ?? string.Empty).Trim(); + notice.Body = (draft.Body ?? string.Empty).Replace("\r\n", "\n", StringComparison.Ordinal).Trim(); + notice.RequireAccept = draft.RequireAccept; + notice.Enabled = draft.Enabled; + + var allUsers = draft.Target?.AllUsers ?? true; + notice.Target = new NoticeTarget + { + AllUsers = allUsers, + UserIds = allUsers ? [] : (draft.Target?.UserIds ?? []).Distinct().ToList() + }; + } + + private DateTime UtcNow() => _timeProvider.GetUtcNow().UtcDateTime; +} diff --git a/Jellyfin.Plugin.Herald/Notices/NoticeTarget.cs b/Jellyfin.Plugin.Herald/Notices/NoticeTarget.cs new file mode 100644 index 0000000..0344e69 --- /dev/null +++ b/Jellyfin.Plugin.Herald/Notices/NoticeTarget.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; + +namespace Jellyfin.Plugin.Herald.Notices; + +/// +/// Who a notice is addressed to. +/// +public class NoticeTarget +{ + /// + /// Gets or sets a value indicating whether every user is addressed. + /// + public bool AllUsers { get; set; } = true; + + /// + /// Gets or sets the addressed users. Ignored when is set. + /// + public IReadOnlyList UserIds { get; set; } = []; +}