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;
}