Files

226 lines
7.3 KiB
C#

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.AcceptDelaySeconds = draft.RequireAccept ? draft.AcceptDelaySeconds : 0;
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;
}