feat: add notice model, rules and service

This commit is contained in:
2026-11-13 18:10:41 +01:00
parent f15253b976
commit 41d1978d34
11 changed files with 658 additions and 0 deletions
@@ -0,0 +1,17 @@
namespace Jellyfin.Plugin.Herald.Notices;
/// <summary>
/// How a user responded to a notice.
/// </summary>
public enum AckAction
{
/// <summary>
/// The user closed the notice.
/// </summary>
Dismissed = 0,
/// <summary>
/// The user explicitly accepted the notice.
/// </summary>
Accepted = 1
}
@@ -0,0 +1,29 @@
using System;
namespace Jellyfin.Plugin.Herald.Notices;
/// <summary>
/// One row of the acknowledgement report.
/// </summary>
public class AckEntry
{
/// <summary>
/// Gets or sets the user id.
/// </summary>
public Guid UserId { get; set; }
/// <summary>
/// Gets or sets the user name. <c>null</c> if the user no longer exists.
/// </summary>
public string? UserName { get; set; }
/// <summary>
/// Gets or sets the response. <c>null</c> for users who have not responded.
/// </summary>
public AckAction? Action { get; set; }
/// <summary>
/// Gets or sets the response time (UTC). <c>null</c> for users who have not responded.
/// </summary>
public DateTime? Timestamp { get; set; }
}
@@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
namespace Jellyfin.Plugin.Herald.Notices;
/// <summary>
/// Who responded to the current revision of a notice and who has not yet.
/// </summary>
public class AckReport
{
/// <summary>
/// Gets or sets the notice id.
/// </summary>
public Guid NoticeId { get; set; }
/// <summary>
/// Gets or sets the revision the report covers.
/// </summary>
public int Revision { get; set; }
/// <summary>
/// Gets or sets the users who responded, oldest response first.
/// </summary>
public IReadOnlyList<AckEntry> Responses { get; set; } = [];
/// <summary>
/// Gets or sets the addressed users who have not responded.
/// </summary>
public IReadOnlyList<AckEntry> Pending { get; set; } = [];
}
@@ -0,0 +1,27 @@
namespace Jellyfin.Plugin.Herald.Notices;
/// <summary>
/// Outcome of an acknowledgement attempt.
/// </summary>
public enum AckResult
{
/// <summary>
/// The acknowledgement was stored (or already existed).
/// </summary>
Ok,
/// <summary>
/// The notice does not exist, is disabled or is not addressed to the user.
/// </summary>
NotFound,
/// <summary>
/// The acknowledged revision is not the current one.
/// </summary>
RevisionMismatch,
/// <summary>
/// The notice must be accepted and cannot be dismissed.
/// </summary>
AcceptRequired
}
@@ -0,0 +1,57 @@
using System;
using System.Collections.Generic;
namespace Jellyfin.Plugin.Herald.Notices;
/// <summary>
/// Persistence for notices and acknowledgements.
/// </summary>
public interface INoticeStore
{
/// <summary>
/// Gets all notices, oldest first.
/// </summary>
/// <returns>The notices.</returns>
IReadOnlyList<Notice> GetNotices();
/// <summary>
/// Gets a single notice.
/// </summary>
/// <param name="id">The notice id.</param>
/// <returns>The notice, or <c>null</c>.</returns>
Notice? GetNotice(Guid id);
/// <summary>
/// Inserts or replaces a notice.
/// </summary>
/// <param name="notice">The notice.</param>
void SaveNotice(Notice notice);
/// <summary>
/// Deletes a notice together with its acknowledgements.
/// </summary>
/// <param name="id">The notice id.</param>
/// <returns><c>true</c> if a notice was deleted.</returns>
bool DeleteNotice(Guid id);
/// <summary>
/// Gets every acknowledgement of a user.
/// </summary>
/// <param name="userId">The user id.</param>
/// <returns>The acknowledgements.</returns>
IReadOnlyList<NoticeAck> GetAcksByUser(Guid userId);
/// <summary>
/// Gets the acknowledgements for one revision of a notice, oldest first.
/// </summary>
/// <param name="noticeId">The notice id.</param>
/// <param name="revision">The revision.</param>
/// <returns>The acknowledgements.</returns>
IReadOnlyList<NoticeAck> GetAcks(Guid noticeId, int revision);
/// <summary>
/// Stores an acknowledgement. An existing one for the same notice, revision and user is kept.
/// </summary>
/// <param name="ack">The acknowledgement.</param>
void AddAck(NoticeAck ack);
}
+54
View File
@@ -0,0 +1,54 @@
using System;
namespace Jellyfin.Plugin.Herald.Notices;
/// <summary>
/// A message shown once to each addressed user.
/// </summary>
public class Notice
{
/// <summary>
/// Gets or sets the id.
/// </summary>
public Guid Id { get; set; }
/// <summary>
/// Gets or sets the title.
/// </summary>
public string Title { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the body: plain text or the supported Markdown subset.
/// </summary>
public string Body { get; set; } = string.Empty;
/// <summary>
/// Gets or sets a value indicating whether users have to accept the notice.
/// </summary>
public bool RequireAccept { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the notice is shown at all.
/// </summary>
public bool Enabled { get; set; } = true;
/// <summary>
/// Gets or sets the addressed users.
/// </summary>
public NoticeTarget Target { get; set; } = new();
/// <summary>
/// Gets or sets the revision. Acknowledgements only count for the current revision.
/// </summary>
public int Revision { get; set; } = 1;
/// <summary>
/// Gets or sets the creation time (UTC).
/// </summary>
public DateTime CreatedAt { get; set; }
/// <summary>
/// Gets or sets the time of the last change (UTC).
/// </summary>
public DateTime UpdatedAt { get; set; }
}
@@ -0,0 +1,34 @@
using System;
namespace Jellyfin.Plugin.Herald.Notices;
/// <summary>
/// A user's response to one revision of a notice.
/// </summary>
public class NoticeAck
{
/// <summary>
/// Gets or sets the notice id.
/// </summary>
public Guid NoticeId { get; set; }
/// <summary>
/// Gets or sets the acknowledged revision.
/// </summary>
public int Revision { get; set; }
/// <summary>
/// Gets or sets the user id.
/// </summary>
public Guid UserId { get; set; }
/// <summary>
/// Gets or sets the response.
/// </summary>
public AckAction Action { get; set; }
/// <summary>
/// Gets or sets the response time (UTC).
/// </summary>
public DateTime Timestamp { get; set; }
}
@@ -0,0 +1,32 @@
namespace Jellyfin.Plugin.Herald.Notices;
/// <summary>
/// The editable part of a notice, as sent by the admin UI.
/// </summary>
public class NoticeDraft
{
/// <summary>
/// Gets or sets the title.
/// </summary>
public string? Title { get; set; }
/// <summary>
/// Gets or sets the body.
/// </summary>
public string? Body { get; set; }
/// <summary>
/// Gets or sets a value indicating whether users have to accept the notice.
/// </summary>
public bool RequireAccept { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the notice is shown.
/// </summary>
public bool Enabled { get; set; } = true;
/// <summary>
/// Gets or sets the addressed users. Defaults to all users.
/// </summary>
public NoticeTarget? Target { get; set; }
}
@@ -0,0 +1,134 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace Jellyfin.Plugin.Herald.Notices;
/// <summary>
/// The decisions around who sees a notice and which responses are allowed.
/// </summary>
public static class NoticeRules
{
/// <summary>
/// Maximum title length.
/// </summary>
public const int MaxTitleLength = 200;
/// <summary>
/// Maximum body length.
/// </summary>
public const int MaxBodyLength = 20000;
/// <summary>
/// Checks whether a notice is addressed to a user.
/// </summary>
/// <param name="notice">The notice.</param>
/// <param name="userId">The user id.</param>
/// <returns><c>true</c> if the user is addressed.</returns>
public static bool IsTargeted(Notice notice, Guid userId)
{
ArgumentNullException.ThrowIfNull(notice);
return notice.Target.AllUsers || notice.Target.UserIds.Contains(userId);
}
/// <summary>
/// Checks whether a notice still has to be shown to a user.
/// </summary>
/// <param name="notice">The notice.</param>
/// <param name="userId">The user id.</param>
/// <param name="userAcks">The acknowledgements of that user.</param>
/// <returns><c>true</c> if the notice is pending.</returns>
public static bool IsPending(Notice notice, Guid userId, IEnumerable<NoticeAck> 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);
}
/// <summary>
/// Selects the notices a user still has to see, oldest first.
/// </summary>
/// <param name="notices">All notices.</param>
/// <param name="userId">The user id.</param>
/// <param name="userAcks">The acknowledgements of that user.</param>
/// <returns>The pending notices.</returns>
public static IReadOnlyList<Notice> SelectPending(IEnumerable<Notice> notices, Guid userId, IReadOnlyCollection<NoticeAck> userAcks)
{
ArgumentNullException.ThrowIfNull(notices);
return notices
.Where(n => IsPending(n, userId, userAcks))
.OrderBy(n => n.CreatedAt)
.ThenBy(n => n.Id)
.ToList();
}
/// <summary>
/// Validates a response to a notice.
/// </summary>
/// <param name="notice">The notice, or <c>null</c> if it does not exist.</param>
/// <param name="userId">The responding user.</param>
/// <param name="revision">The revision the user saw.</param>
/// <param name="action">The response.</param>
/// <returns>The validation outcome.</returns>
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;
}
/// <summary>
/// Validates the editable fields of a notice.
/// </summary>
/// <param name="draft">The draft.</param>
/// <returns>An error message, or <c>null</c> if the draft is valid.</returns>
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;
}
}
@@ -0,0 +1,224 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Logging;
namespace Jellyfin.Plugin.Herald.Notices;
/// <summary>
/// Notice operations used by the API.
/// </summary>
public class NoticeService
{
private readonly INoticeStore _store;
private readonly TimeProvider _timeProvider;
private readonly ILogger<NoticeService> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="NoticeService"/> class.
/// </summary>
/// <param name="store">The notice store.</param>
/// <param name="timeProvider">The time provider.</param>
/// <param name="logger">The logger.</param>
public NoticeService(INoticeStore store, TimeProvider timeProvider, ILogger<NoticeService> logger)
{
_store = store;
_timeProvider = timeProvider;
_logger = logger;
}
/// <summary>
/// Gets all notices, oldest first.
/// </summary>
/// <returns>The notices.</returns>
public IReadOnlyList<Notice> GetAll() => _store.GetNotices();
/// <summary>
/// Gets a single notice.
/// </summary>
/// <param name="id">The notice id.</param>
/// <returns>The notice, or <c>null</c>.</returns>
public Notice? Get(Guid id) => _store.GetNotice(id);
/// <summary>
/// Gets the notices a user still has to see, oldest first.
/// </summary>
/// <param name="userId">The user id.</param>
/// <returns>The pending notices.</returns>
public IReadOnlyList<Notice> GetPending(Guid userId)
{
return NoticeRules.SelectPending(_store.GetNotices(), userId, _store.GetAcksByUser(userId));
}
/// <summary>
/// Records a user's response to a notice.
/// </summary>
/// <param name="userId">The responding user.</param>
/// <param name="noticeId">The notice id.</param>
/// <param name="revision">The revision the user saw.</param>
/// <param name="action">The response.</param>
/// <returns>The outcome.</returns>
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;
}
/// <summary>
/// Creates a notice from a validated draft.
/// </summary>
/// <param name="draft">The draft.</param>
/// <returns>The created notice.</returns>
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;
}
/// <summary>
/// Updates a notice from a validated draft. The revision is left alone.
/// </summary>
/// <param name="id">The notice id.</param>
/// <param name="draft">The draft.</param>
/// <returns>The updated notice, or <c>null</c> if it does not exist.</returns>
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;
}
/// <summary>
/// Bumps the revision so the notice is shown to everyone again.
/// </summary>
/// <param name="id">The notice id.</param>
/// <returns>The updated notice, or <c>null</c> if it does not exist.</returns>
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;
}
/// <summary>
/// Deletes a notice and its acknowledgements.
/// </summary>
/// <param name="id">The notice id.</param>
/// <returns><c>true</c> if the notice existed.</returns>
public bool Delete(Guid id)
{
var deleted = _store.DeleteNotice(id);
if (deleted)
{
_logger.LogInformation("Deleted notice {NoticeId}", id);
}
return deleted;
}
/// <summary>
/// Builds the acknowledgement report for the current revision of a notice.
/// </summary>
/// <param name="id">The notice id.</param>
/// <param name="userNames">All existing users by id.</param>
/// <returns>The report, or <c>null</c> if the notice does not exist.</returns>
public AckReport? GetAckReport(Guid id, IReadOnlyDictionary<Guid, string> 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;
}
@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
namespace Jellyfin.Plugin.Herald.Notices;
/// <summary>
/// Who a notice is addressed to.
/// </summary>
public class NoticeTarget
{
/// <summary>
/// Gets or sets a value indicating whether every user is addressed.
/// </summary>
public bool AllUsers { get; set; } = true;
/// <summary>
/// Gets or sets the addressed users. Ignored when <see cref="AllUsers"/> is set.
/// </summary>
public IReadOnlyList<Guid> UserIds { get; set; } = [];
}