test: cover watch-time tracking, notices and storage
This commit is contained in:
@@ -0,0 +1,47 @@
|
|||||||
|
using Jellyfin.Plugin.Herald.Injection;
|
||||||
|
|
||||||
|
namespace Jellyfin.Plugin.Herald.Tests;
|
||||||
|
|
||||||
|
public class IndexHtmlTransformerTests
|
||||||
|
{
|
||||||
|
private const string Page = "<html><head></head><body><div id=\"reactRoot\"></div></body></html>";
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Inject_AddsTheScriptBeforeTheClosingBodyTag()
|
||||||
|
{
|
||||||
|
var result = IndexHtmlTransformer.Inject(Page);
|
||||||
|
|
||||||
|
Assert.EndsWith(IndexHtmlTransformer.ScriptTag + "</body></html>", result, StringComparison.Ordinal);
|
||||||
|
Assert.Contains("src=\"../Herald/client.js?v=", result, StringComparison.Ordinal);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Inject_IsIdempotent()
|
||||||
|
{
|
||||||
|
var once = IndexHtmlTransformer.Inject(Page);
|
||||||
|
|
||||||
|
Assert.Equal(once, IndexHtmlTransformer.Inject(once));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Inject_LeavesContentWithoutABodyTagAlone()
|
||||||
|
{
|
||||||
|
const string Script = "(self.webpackChunk=self.webpackChunk||[]).push([[17244],{}]);";
|
||||||
|
|
||||||
|
Assert.Equal(Script, IndexHtmlTransformer.Inject(Script));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Transform_HandlesAnEmptyPayload()
|
||||||
|
{
|
||||||
|
Assert.Equal(string.Empty, IndexHtmlTransformer.Transform(new IndexHtmlPayload()));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Transform_InjectsIntoThePayloadContents()
|
||||||
|
{
|
||||||
|
var result = IndexHtmlTransformer.Transform(new IndexHtmlPayload { Contents = Page });
|
||||||
|
|
||||||
|
Assert.Contains(IndexHtmlTransformer.Marker, result, StringComparison.Ordinal);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>$(JellyfinTargetFramework)</TargetFramework>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
|
||||||
|
<IsPackable>false</IsPackable>
|
||||||
|
<IsTestProject>true</IsTestProject>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
|
||||||
|
<PackageReference Include="xunit" Version="2.9.3" />
|
||||||
|
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4" PrivateAssets="All" />
|
||||||
|
<!-- The plugin leaves these to the Jellyfin host; the tests have to bring them along. -->
|
||||||
|
<PackageReference Include="Jellyfin.Controller" Version="$(JellyfinVersion)" />
|
||||||
|
<PackageReference Include="Microsoft.Data.Sqlite" Version="$(JellyfinSqliteVersion)" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\Jellyfin.Plugin.Herald\Jellyfin.Plugin.Herald.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<Using Include="Xunit" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
namespace Jellyfin.Plugin.Herald.Tests;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A clock the tests move by hand.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class ManualTimeProvider : TimeProvider
|
||||||
|
{
|
||||||
|
private DateTimeOffset _now;
|
||||||
|
|
||||||
|
public ManualTimeProvider(DateTimeOffset now, TimeZoneInfo? zone = null)
|
||||||
|
{
|
||||||
|
_now = now;
|
||||||
|
LocalTimeZone = zone ?? TimeZoneInfo.Utc;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override TimeZoneInfo LocalTimeZone { get; }
|
||||||
|
|
||||||
|
public override DateTimeOffset GetUtcNow() => _now;
|
||||||
|
|
||||||
|
public void Advance(TimeSpan by) => _now += by;
|
||||||
|
|
||||||
|
public void Set(DateTimeOffset now) => _now = now;
|
||||||
|
}
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
using Jellyfin.Plugin.Herald.Notices;
|
||||||
|
|
||||||
|
namespace Jellyfin.Plugin.Herald.Tests;
|
||||||
|
|
||||||
|
public class NoticeRulesTests
|
||||||
|
{
|
||||||
|
private static readonly Guid _alice = Guid.NewGuid();
|
||||||
|
private static readonly Guid _bob = Guid.NewGuid();
|
||||||
|
|
||||||
|
private static Notice Notice(Action<Notice>? configure = null)
|
||||||
|
{
|
||||||
|
var notice = new Notice
|
||||||
|
{
|
||||||
|
Id = Guid.NewGuid(),
|
||||||
|
Title = "Maintenance",
|
||||||
|
Body = "Saturday night.",
|
||||||
|
CreatedAt = new DateTime(2026, 3, 1, 0, 0, 0, DateTimeKind.Utc)
|
||||||
|
};
|
||||||
|
configure?.Invoke(notice);
|
||||||
|
return notice;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static NoticeAck Ack(Notice notice, Guid userId, int? revision = null) => new()
|
||||||
|
{
|
||||||
|
NoticeId = notice.Id,
|
||||||
|
UserId = userId,
|
||||||
|
Revision = revision ?? notice.Revision,
|
||||||
|
Action = AckAction.Dismissed
|
||||||
|
};
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Pending_WhenNeverAcknowledged()
|
||||||
|
{
|
||||||
|
Assert.True(NoticeRules.IsPending(Notice(), _alice, []));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void NotPending_AfterAcknowledgingCurrentRevision()
|
||||||
|
{
|
||||||
|
var notice = Notice();
|
||||||
|
|
||||||
|
Assert.False(NoticeRules.IsPending(notice, _alice, [Ack(notice, _alice)]));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Pending_AgainAfterRevisionBump()
|
||||||
|
{
|
||||||
|
var notice = Notice();
|
||||||
|
var ack = Ack(notice, _alice);
|
||||||
|
notice.Revision++;
|
||||||
|
|
||||||
|
Assert.True(NoticeRules.IsPending(notice, _alice, [ack]));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Pending_IgnoresOtherUsersAndOtherNotices()
|
||||||
|
{
|
||||||
|
var notice = Notice();
|
||||||
|
var other = Notice();
|
||||||
|
|
||||||
|
Assert.True(NoticeRules.IsPending(notice, _alice, [Ack(notice, _bob), Ack(other, _alice)]));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void NotPending_WhenDisabled()
|
||||||
|
{
|
||||||
|
Assert.False(NoticeRules.IsPending(Notice(n => n.Enabled = false), _alice, []));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Targeting_OnlyListedUsersSeeTheNotice()
|
||||||
|
{
|
||||||
|
var notice = Notice(n => n.Target = new NoticeTarget { AllUsers = false, UserIds = [_alice] });
|
||||||
|
|
||||||
|
Assert.True(NoticeRules.IsPending(notice, _alice, []));
|
||||||
|
Assert.False(NoticeRules.IsPending(notice, _bob, []));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Targeting_AllUsersWinsOverALeftoverList()
|
||||||
|
{
|
||||||
|
var notice = Notice(n => n.Target = new NoticeTarget { AllUsers = true, UserIds = [_alice] });
|
||||||
|
|
||||||
|
Assert.True(NoticeRules.IsPending(notice, _bob, []));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void SelectPending_ReturnsOldestFirst()
|
||||||
|
{
|
||||||
|
var newest = Notice(n => n.CreatedAt = new DateTime(2026, 3, 3, 0, 0, 0, DateTimeKind.Utc));
|
||||||
|
var oldest = Notice(n => n.CreatedAt = new DateTime(2026, 3, 1, 0, 0, 0, DateTimeKind.Utc));
|
||||||
|
var middle = Notice(n => n.CreatedAt = new DateTime(2026, 3, 2, 0, 0, 0, DateTimeKind.Utc));
|
||||||
|
var done = Notice();
|
||||||
|
|
||||||
|
var pending = NoticeRules.SelectPending([newest, oldest, done, middle], _alice, [Ack(done, _alice)]);
|
||||||
|
|
||||||
|
Assert.Equal([oldest.Id, middle.Id, newest.Id], pending.Select(n => n.Id));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Ack_DismissIsRejectedWhenAcceptIsRequired()
|
||||||
|
{
|
||||||
|
var notice = Notice(n => n.RequireAccept = true);
|
||||||
|
|
||||||
|
Assert.Equal(AckResult.AcceptRequired, NoticeRules.ValidateAck(notice, _alice, notice.Revision, AckAction.Dismissed));
|
||||||
|
Assert.Equal(AckResult.Ok, NoticeRules.ValidateAck(notice, _alice, notice.Revision, AckAction.Accepted));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Ack_BothActionsAreFineWithoutRequireAccept()
|
||||||
|
{
|
||||||
|
var notice = Notice();
|
||||||
|
|
||||||
|
Assert.Equal(AckResult.Ok, NoticeRules.ValidateAck(notice, _alice, notice.Revision, AckAction.Dismissed));
|
||||||
|
Assert.Equal(AckResult.Ok, NoticeRules.ValidateAck(notice, _alice, notice.Revision, AckAction.Accepted));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Ack_OutdatedRevisionIsRejected()
|
||||||
|
{
|
||||||
|
var notice = Notice(n => n.Revision = 3);
|
||||||
|
|
||||||
|
Assert.Equal(AckResult.RevisionMismatch, NoticeRules.ValidateAck(notice, _alice, 2, AckAction.Accepted));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Ack_UnknownDisabledOrUntargetedNoticeIsNotFound()
|
||||||
|
{
|
||||||
|
var disabled = Notice(n => n.Enabled = false);
|
||||||
|
var notForBob = Notice(n => n.Target = new NoticeTarget { AllUsers = false, UserIds = [_alice] });
|
||||||
|
|
||||||
|
Assert.Equal(AckResult.NotFound, NoticeRules.ValidateAck(null, _alice, 1, AckAction.Accepted));
|
||||||
|
Assert.Equal(AckResult.NotFound, NoticeRules.ValidateAck(disabled, _alice, 1, AckAction.Accepted));
|
||||||
|
Assert.Equal(AckResult.NotFound, NoticeRules.ValidateAck(notForBob, _bob, 1, AckAction.Accepted));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(null)]
|
||||||
|
[InlineData("")]
|
||||||
|
[InlineData(" ")]
|
||||||
|
public void Draft_NeedsATitle(string? title)
|
||||||
|
{
|
||||||
|
Assert.NotNull(NoticeRules.ValidateDraft(new NoticeDraft { Title = title }));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Draft_SelectedUsersNeedAtLeastOneUser()
|
||||||
|
{
|
||||||
|
var draft = new NoticeDraft { Title = "Hi", Target = new NoticeTarget { AllUsers = false } };
|
||||||
|
|
||||||
|
Assert.NotNull(NoticeRules.ValidateDraft(draft));
|
||||||
|
Assert.Null(NoticeRules.ValidateDraft(new NoticeDraft { Title = "Hi" }));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,201 @@
|
|||||||
|
using Jellyfin.Plugin.Herald.Notices;
|
||||||
|
using Jellyfin.Plugin.Herald.Storage;
|
||||||
|
using Microsoft.Extensions.Logging.Abstractions;
|
||||||
|
|
||||||
|
namespace Jellyfin.Plugin.Herald.Tests;
|
||||||
|
|
||||||
|
public sealed class NoticeServiceTests : IDisposable
|
||||||
|
{
|
||||||
|
private static readonly Guid _alice = Guid.NewGuid();
|
||||||
|
private static readonly Guid _bob = Guid.NewGuid();
|
||||||
|
private static readonly Dictionary<Guid, string> _userNames = new() { [_alice] = "alice", [_bob] = "bob" };
|
||||||
|
|
||||||
|
private readonly TempDatabase _temp = new();
|
||||||
|
private readonly ManualTimeProvider _clock = new(new DateTimeOffset(2026, 3, 10, 12, 0, 0, TimeSpan.Zero));
|
||||||
|
private readonly NoticeService _service;
|
||||||
|
|
||||||
|
public NoticeServiceTests()
|
||||||
|
{
|
||||||
|
_service = new NoticeService(new SqliteNoticeStore(_temp.Database), _clock, NullLogger<NoticeService>.Instance);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose() => _temp.Dispose();
|
||||||
|
|
||||||
|
private Notice Create(string title, Action<NoticeDraft>? configure = null)
|
||||||
|
{
|
||||||
|
var draft = new NoticeDraft { Title = title, Body = "Body" };
|
||||||
|
configure?.Invoke(draft);
|
||||||
|
var notice = _service.Create(draft);
|
||||||
|
_clock.Advance(TimeSpan.FromMinutes(1));
|
||||||
|
return notice;
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Create_RoundTripsThroughTheDatabase()
|
||||||
|
{
|
||||||
|
var created = Create(" Hello ", d =>
|
||||||
|
{
|
||||||
|
d.Body = "Line one\r\nLine two";
|
||||||
|
d.RequireAccept = true;
|
||||||
|
d.Target = new NoticeTarget { AllUsers = false, UserIds = [_alice, _alice, _bob] };
|
||||||
|
});
|
||||||
|
|
||||||
|
var loaded = _service.Get(created.Id);
|
||||||
|
|
||||||
|
Assert.NotNull(loaded);
|
||||||
|
Assert.Equal("Hello", loaded.Title);
|
||||||
|
Assert.Equal("Line one\nLine two", loaded.Body);
|
||||||
|
Assert.True(loaded.RequireAccept);
|
||||||
|
Assert.True(loaded.Enabled);
|
||||||
|
Assert.False(loaded.Target.AllUsers);
|
||||||
|
Assert.Equal([_alice, _bob], loaded.Target.UserIds);
|
||||||
|
Assert.Equal(1, loaded.Revision);
|
||||||
|
Assert.Equal(new DateTime(2026, 3, 10, 12, 0, 0, DateTimeKind.Utc), loaded.CreatedAt);
|
||||||
|
Assert.Equal(DateTimeKind.Utc, loaded.CreatedAt.Kind);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Pending_ShowsEachNoticeOnceOldestFirst()
|
||||||
|
{
|
||||||
|
var first = Create("First");
|
||||||
|
var second = Create("Second");
|
||||||
|
|
||||||
|
Assert.Equal([first.Id, second.Id], _service.GetPending(_alice).Select(n => n.Id));
|
||||||
|
|
||||||
|
Assert.Equal(AckResult.Ok, _service.Acknowledge(_alice, first.Id, 1, AckAction.Dismissed));
|
||||||
|
|
||||||
|
Assert.Equal([second.Id], _service.GetPending(_alice).Select(n => n.Id));
|
||||||
|
Assert.Equal(2, _service.GetPending(_bob).Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Reshow_BringsTheNoticeBackForEveryone()
|
||||||
|
{
|
||||||
|
var notice = Create("Rules");
|
||||||
|
_service.Acknowledge(_alice, notice.Id, 1, AckAction.Accepted);
|
||||||
|
Assert.Empty(_service.GetPending(_alice));
|
||||||
|
|
||||||
|
var bumped = _service.Reshow(notice.Id);
|
||||||
|
|
||||||
|
Assert.Equal(2, bumped!.Revision);
|
||||||
|
Assert.Equal(2, Assert.Single(_service.GetPending(_alice)).Revision);
|
||||||
|
|
||||||
|
// The old revision can no longer be answered.
|
||||||
|
Assert.Equal(AckResult.RevisionMismatch, _service.Acknowledge(_alice, notice.Id, 1, AckAction.Accepted));
|
||||||
|
Assert.Equal(AckResult.Ok, _service.Acknowledge(_alice, notice.Id, 2, AckAction.Accepted));
|
||||||
|
Assert.Empty(_service.GetPending(_alice));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Update_KeepsRevisionAndAcknowledgements()
|
||||||
|
{
|
||||||
|
var notice = Create("Typo");
|
||||||
|
_service.Acknowledge(_alice, notice.Id, 1, AckAction.Dismissed);
|
||||||
|
|
||||||
|
var updated = _service.Update(notice.Id, new NoticeDraft { Title = "Fixed", Body = "Body" });
|
||||||
|
|
||||||
|
Assert.Equal(1, updated!.Revision);
|
||||||
|
Assert.Equal(notice.CreatedAt, updated.CreatedAt);
|
||||||
|
Assert.True(updated.UpdatedAt > updated.CreatedAt);
|
||||||
|
Assert.Empty(_service.GetPending(_alice));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Disabled_NoticeIsNotPendingAndCannotBeAnswered()
|
||||||
|
{
|
||||||
|
var notice = Create("Off", d => d.Enabled = false);
|
||||||
|
|
||||||
|
Assert.Empty(_service.GetPending(_alice));
|
||||||
|
Assert.Equal(AckResult.NotFound, _service.Acknowledge(_alice, notice.Id, 1, AckAction.Accepted));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Targeted_NoticeIsOnlyPendingForItsUsers()
|
||||||
|
{
|
||||||
|
var notice = Create("Just Alice", d => d.Target = new NoticeTarget { AllUsers = false, UserIds = [_alice] });
|
||||||
|
|
||||||
|
Assert.Single(_service.GetPending(_alice));
|
||||||
|
Assert.Empty(_service.GetPending(_bob));
|
||||||
|
Assert.Equal(AckResult.NotFound, _service.Acknowledge(_bob, notice.Id, 1, AckAction.Dismissed));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void RequireAccept_DismissIsRejectedAndNothingIsStored()
|
||||||
|
{
|
||||||
|
var notice = Create("Terms", d => d.RequireAccept = true);
|
||||||
|
|
||||||
|
Assert.Equal(AckResult.AcceptRequired, _service.Acknowledge(_alice, notice.Id, 1, AckAction.Dismissed));
|
||||||
|
Assert.Single(_service.GetPending(_alice));
|
||||||
|
|
||||||
|
Assert.Equal(AckResult.Ok, _service.Acknowledge(_alice, notice.Id, 1, AckAction.Accepted));
|
||||||
|
Assert.Empty(_service.GetPending(_alice));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Acknowledge_TwiceKeepsTheFirstResponse()
|
||||||
|
{
|
||||||
|
var notice = Create("Once");
|
||||||
|
_service.Acknowledge(_alice, notice.Id, 1, AckAction.Dismissed);
|
||||||
|
_clock.Advance(TimeSpan.FromHours(1));
|
||||||
|
_service.Acknowledge(_alice, notice.Id, 1, AckAction.Accepted);
|
||||||
|
|
||||||
|
var response = Assert.Single(_service.GetAckReport(notice.Id, _userNames)!.Responses);
|
||||||
|
|
||||||
|
Assert.Equal(AckAction.Dismissed, response.Action);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void AckReport_ListsResponsesAndWhoIsStillPending()
|
||||||
|
{
|
||||||
|
var carol = Guid.NewGuid();
|
||||||
|
var notice = Create("Report", d => d.Target = new NoticeTarget { AllUsers = false, UserIds = [_alice, _bob, carol] });
|
||||||
|
var answeredAt = _clock.GetUtcNow().UtcDateTime;
|
||||||
|
_service.Acknowledge(_alice, notice.Id, 1, AckAction.Accepted);
|
||||||
|
|
||||||
|
// carol was deleted in the meantime and is not part of the user list.
|
||||||
|
var report = _service.GetAckReport(notice.Id, _userNames)!;
|
||||||
|
|
||||||
|
var response = Assert.Single(report.Responses);
|
||||||
|
Assert.Equal("alice", response.UserName);
|
||||||
|
Assert.Equal(AckAction.Accepted, response.Action);
|
||||||
|
Assert.Equal(answeredAt, response.Timestamp);
|
||||||
|
Assert.Equal("bob", Assert.Single(report.Pending).UserName);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void AckReport_OnlyCoversTheCurrentRevision()
|
||||||
|
{
|
||||||
|
var notice = Create("Again");
|
||||||
|
_service.Acknowledge(_alice, notice.Id, 1, AckAction.Dismissed);
|
||||||
|
_service.Reshow(notice.Id);
|
||||||
|
|
||||||
|
var report = _service.GetAckReport(notice.Id, _userNames)!;
|
||||||
|
|
||||||
|
Assert.Equal(2, report.Revision);
|
||||||
|
Assert.Empty(report.Responses);
|
||||||
|
Assert.Equal(["alice", "bob"], report.Pending.Select(p => p.UserName));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Delete_RemovesNoticeAndAcknowledgements()
|
||||||
|
{
|
||||||
|
var notice = Create("Gone");
|
||||||
|
_service.Acknowledge(_alice, notice.Id, 1, AckAction.Dismissed);
|
||||||
|
|
||||||
|
Assert.True(_service.Delete(notice.Id));
|
||||||
|
Assert.False(_service.Delete(notice.Id));
|
||||||
|
Assert.Null(_service.Get(notice.Id));
|
||||||
|
Assert.Null(_service.GetAckReport(notice.Id, _userNames));
|
||||||
|
Assert.Empty(new SqliteNoticeStore(_temp.Database).GetAcksByUser(_alice));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Missing_NoticeOperationsReturnNull()
|
||||||
|
{
|
||||||
|
var id = Guid.NewGuid();
|
||||||
|
|
||||||
|
Assert.Null(_service.Update(id, new NoticeDraft { Title = "x" }));
|
||||||
|
Assert.Null(_service.Reshow(id));
|
||||||
|
Assert.Equal(AckResult.NotFound, _service.Acknowledge(_alice, id, 1, AckAction.Accepted));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
using Jellyfin.Plugin.Herald.Stats;
|
||||||
|
using Jellyfin.Plugin.Herald.Storage;
|
||||||
|
|
||||||
|
namespace Jellyfin.Plugin.Herald.Tests;
|
||||||
|
|
||||||
|
public sealed class StatsStorageTests : IDisposable
|
||||||
|
{
|
||||||
|
private static readonly Guid _alice = Guid.NewGuid();
|
||||||
|
private static readonly Guid _bob = Guid.NewGuid();
|
||||||
|
private static readonly DateOnly _today = new(2026, 3, 10);
|
||||||
|
|
||||||
|
private readonly TempDatabase _temp = new();
|
||||||
|
private readonly ManualTimeProvider _clock = new(new DateTimeOffset(2026, 3, 10, 12, 0, 0, TimeSpan.Zero));
|
||||||
|
private readonly SqliteWatchStatsStore _store;
|
||||||
|
private readonly StatsService _service;
|
||||||
|
|
||||||
|
public StatsStorageTests()
|
||||||
|
{
|
||||||
|
_store = new SqliteWatchStatsStore(_temp.Database);
|
||||||
|
_service = new StatsService(_store, _clock);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose() => _temp.Dispose();
|
||||||
|
|
||||||
|
private static WatchIncrement Watched(Guid user, DateOnly date, double seconds, int plays = 0, int hour = 10)
|
||||||
|
{
|
||||||
|
return new WatchIncrement(user, date, seconds, plays, date.ToDateTime(new TimeOnly(hour, 0), DateTimeKind.Utc));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Add_AccumulatesIntoOneRowPerUserAndDay()
|
||||||
|
{
|
||||||
|
_store.Add([Watched(_alice, _today, 0, plays: 1, hour: 9)]);
|
||||||
|
_store.Add([Watched(_alice, _today, 10, hour: 11), Watched(_alice, _today, 15.5, hour: 10)]);
|
||||||
|
_store.Add([Watched(_bob, _today, 7, plays: 1)]);
|
||||||
|
|
||||||
|
var rows = _store.GetSince(_today);
|
||||||
|
|
||||||
|
Assert.Equal(2, rows.Count);
|
||||||
|
var alice = Assert.Single(rows, r => r.UserId == _alice);
|
||||||
|
Assert.Equal(25.5, alice.WatchedSeconds, 6);
|
||||||
|
Assert.Equal(1, alice.PlayCount);
|
||||||
|
Assert.Equal(new DateTime(2026, 3, 10, 11, 0, 0, DateTimeKind.Utc), alice.LastActivity);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Summary_CoversTheRequestedDaysIncludingToday()
|
||||||
|
{
|
||||||
|
_store.Add(
|
||||||
|
[
|
||||||
|
Watched(_alice, _today, 3600, plays: 1),
|
||||||
|
Watched(_alice, _today.AddDays(-6), 1800, plays: 2),
|
||||||
|
Watched(_alice, _today.AddDays(-7), 7200, plays: 4),
|
||||||
|
Watched(_alice, _today.AddDays(-29), 3600, plays: 1),
|
||||||
|
Watched(_alice, _today.AddDays(-30), 36000, plays: 9)
|
||||||
|
]);
|
||||||
|
var names = new Dictionary<Guid, string> { [_alice] = "alice", [_bob] = "bob" };
|
||||||
|
|
||||||
|
var week = _service.GetSummary(7, names);
|
||||||
|
var month = _service.GetSummary(30, names);
|
||||||
|
|
||||||
|
var aliceWeek = Assert.Single(week, s => s.UserName == "alice");
|
||||||
|
Assert.Equal(1.5, aliceWeek.WatchedHours);
|
||||||
|
Assert.Equal(5400, aliceWeek.WatchedSeconds);
|
||||||
|
Assert.Equal(3, aliceWeek.PlayCount);
|
||||||
|
|
||||||
|
var aliceMonth = Assert.Single(month, s => s.UserName == "alice");
|
||||||
|
Assert.Equal(4.5, aliceMonth.WatchedHours);
|
||||||
|
Assert.Equal(8, aliceMonth.PlayCount);
|
||||||
|
Assert.Equal(new DateTime(2026, 3, 10, 10, 0, 0, DateTimeKind.Utc), aliceMonth.LastActivity);
|
||||||
|
|
||||||
|
var bob = Assert.Single(month, s => s.UserName == "bob");
|
||||||
|
Assert.Equal(0, bob.WatchedHours);
|
||||||
|
Assert.Equal(0, bob.PlayCount);
|
||||||
|
Assert.Null(bob.LastActivity);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Summary_KeepsActivityOfDeletedUsersWithoutAName()
|
||||||
|
{
|
||||||
|
_store.Add([Watched(_alice, _today, 600, plays: 1)]);
|
||||||
|
|
||||||
|
var summary = _service.GetSummary(30, new Dictionary<Guid, string> { [_bob] = "bob" });
|
||||||
|
|
||||||
|
Assert.Equal(["bob", null], summary.Select(s => s.UserName));
|
||||||
|
Assert.Equal(_alice, summary[1].UserId);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Summary_UsesTheServerLocalDay()
|
||||||
|
{
|
||||||
|
// 23:30 UTC on the 10th is already the 11th at UTC+2.
|
||||||
|
var zone = TimeZoneInfo.CreateCustomTimeZone("test+2", TimeSpan.FromHours(2), "test+2", "test+2");
|
||||||
|
var service = new StatsService(_store, new ManualTimeProvider(new DateTimeOffset(2026, 3, 10, 23, 30, 0, TimeSpan.Zero), zone));
|
||||||
|
|
||||||
|
Assert.Equal(new DateOnly(2026, 3, 11), service.Today);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Cleanup_DeletesRowsOlderThanNinetyDays()
|
||||||
|
{
|
||||||
|
_store.Add(
|
||||||
|
[
|
||||||
|
Watched(_alice, _today, 10),
|
||||||
|
Watched(_alice, _today.AddDays(-90), 10),
|
||||||
|
Watched(_alice, _today.AddDays(-91), 10),
|
||||||
|
Watched(_bob, _today.AddDays(-200), 10)
|
||||||
|
]);
|
||||||
|
|
||||||
|
var deleted = _service.Cleanup();
|
||||||
|
|
||||||
|
Assert.Equal(2, deleted);
|
||||||
|
Assert.Equal([_today.AddDays(-90), _today], _store.GetSince(DateOnly.MinValue).Select(r => r.Date));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Database_IsCreatedOnFirstUseAndMigrationsRunOnce()
|
||||||
|
{
|
||||||
|
_store.Add([Watched(_alice, _today, 10)]);
|
||||||
|
Assert.True(File.Exists(_temp.FilePath));
|
||||||
|
|
||||||
|
// A second instance on the same file, as after a server restart.
|
||||||
|
var reopened = new SqliteWatchStatsStore(_temp.Open());
|
||||||
|
|
||||||
|
Assert.Single(reopened.GetSince(_today));
|
||||||
|
Assert.Equal(HeraldDatabase.SchemaVersion, _temp.Database.Read(connection =>
|
||||||
|
{
|
||||||
|
using var command = connection.CreateCommand();
|
||||||
|
command.CommandText = "PRAGMA user_version;";
|
||||||
|
return Convert.ToInt32(command.ExecuteScalar(), System.Globalization.CultureInfo.InvariantCulture);
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Add_FromManyThreadsLosesNothing()
|
||||||
|
{
|
||||||
|
var tasks = Enumerable.Range(0, 8).Select(_ => Task.Run(() =>
|
||||||
|
{
|
||||||
|
for (var i = 0; i < 50; i++)
|
||||||
|
{
|
||||||
|
_store.Add([Watched(_alice, _today, 1, plays: 1)]);
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
|
||||||
|
await Task.WhenAll(tasks);
|
||||||
|
|
||||||
|
var row = Assert.Single(_store.GetSince(_today));
|
||||||
|
Assert.Equal(400, row.WatchedSeconds, 6);
|
||||||
|
Assert.Equal(400, row.PlayCount);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
using Jellyfin.Plugin.Herald.Storage;
|
||||||
|
using Microsoft.Data.Sqlite;
|
||||||
|
using Microsoft.Extensions.Logging.Abstractions;
|
||||||
|
|
||||||
|
namespace Jellyfin.Plugin.Herald.Tests;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A database in a throwaway directory.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class TempDatabase : IDisposable
|
||||||
|
{
|
||||||
|
private readonly string _directory = Path.Combine(Path.GetTempPath(), "herald-tests-" + Guid.NewGuid().ToString("N"));
|
||||||
|
|
||||||
|
public TempDatabase()
|
||||||
|
{
|
||||||
|
Database = Open();
|
||||||
|
}
|
||||||
|
|
||||||
|
public HeraldDatabase Database { get; }
|
||||||
|
|
||||||
|
public string FilePath => Path.Combine(_directory, "nested", "herald.db");
|
||||||
|
|
||||||
|
public HeraldDatabase Open() => new(FilePath, NullLogger<HeraldDatabase>.Instance);
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
SqliteConnection.ClearAllPools();
|
||||||
|
if (Directory.Exists(_directory))
|
||||||
|
{
|
||||||
|
Directory.Delete(_directory, true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,224 @@
|
|||||||
|
using Jellyfin.Plugin.Herald.Stats;
|
||||||
|
|
||||||
|
namespace Jellyfin.Plugin.Herald.Tests;
|
||||||
|
|
||||||
|
public class WatchTimeTrackerTests
|
||||||
|
{
|
||||||
|
private const string Key = "session|item";
|
||||||
|
private static readonly Guid _alice = Guid.NewGuid();
|
||||||
|
private static readonly Guid _bob = Guid.NewGuid();
|
||||||
|
private static readonly Guid[] _users = [_alice];
|
||||||
|
private static readonly DateTimeOffset _noon = new(2026, 3, 10, 12, 0, 0, TimeSpan.Zero);
|
||||||
|
|
||||||
|
private readonly WatchTimeTracker _tracker = new(TimeZoneInfo.Utc);
|
||||||
|
|
||||||
|
private static double Seconds(IEnumerable<WatchIncrement> increments) => increments.Sum(i => i.Seconds);
|
||||||
|
|
||||||
|
private static DateTimeOffset At(double seconds) => _noon.AddSeconds(seconds);
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Start_CountsOnePlayPerUserAndNoTime()
|
||||||
|
{
|
||||||
|
var increments = _tracker.Start(Key, [_alice, _bob], _noon);
|
||||||
|
|
||||||
|
Assert.Equal(2, increments.Count);
|
||||||
|
Assert.All(increments, i =>
|
||||||
|
{
|
||||||
|
Assert.Equal(1, i.Plays);
|
||||||
|
Assert.Equal(0, i.Seconds);
|
||||||
|
Assert.Equal(new DateOnly(2026, 3, 10), i.Date);
|
||||||
|
Assert.Equal(_noon.UtcDateTime, i.Activity);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Progress_AddsTimeBetweenReports()
|
||||||
|
{
|
||||||
|
_tracker.Start(Key, _users, _noon);
|
||||||
|
|
||||||
|
var total = Seconds(_tracker.Progress(Key, _users, false, At(10)))
|
||||||
|
+ Seconds(_tracker.Progress(Key, _users, false, At(20)))
|
||||||
|
+ Seconds(_tracker.Stop(Key, _users, At(25)));
|
||||||
|
|
||||||
|
Assert.Equal(25, total);
|
||||||
|
Assert.Equal(0, _tracker.ActiveCount);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Progress_NeverAddsPlays()
|
||||||
|
{
|
||||||
|
_tracker.Start(Key, _users, _noon);
|
||||||
|
|
||||||
|
var increments = _tracker.Progress(Key, _users, false, At(10));
|
||||||
|
|
||||||
|
Assert.All(increments, i => Assert.Equal(0, i.Plays));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Pause_TimeWhilePausedIsNotCounted()
|
||||||
|
{
|
||||||
|
_tracker.Start(Key, _users, _noon);
|
||||||
|
|
||||||
|
// 10 s playing, then the client reports the pause.
|
||||||
|
var beforePause = Seconds(_tracker.Progress(Key, _users, true, At(10)));
|
||||||
|
// Paused clients keep reporting.
|
||||||
|
var paused = Seconds(_tracker.Progress(Key, _users, true, At(20)))
|
||||||
|
+ Seconds(_tracker.Progress(Key, _users, true, At(50)));
|
||||||
|
// Unpause report, then 10 s of playback.
|
||||||
|
var unpause = Seconds(_tracker.Progress(Key, _users, false, At(55)));
|
||||||
|
var afterPause = Seconds(_tracker.Progress(Key, _users, false, At(65)));
|
||||||
|
|
||||||
|
Assert.Equal(10, beforePause);
|
||||||
|
Assert.Equal(0, paused);
|
||||||
|
Assert.Equal(0, unpause);
|
||||||
|
Assert.Equal(10, afterPause);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Stop_WhilePausedAddsNothing()
|
||||||
|
{
|
||||||
|
_tracker.Start(Key, _users, _noon);
|
||||||
|
_tracker.Progress(Key, _users, true, At(10));
|
||||||
|
|
||||||
|
Assert.Empty(_tracker.Stop(Key, _users, At(40)));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Seek_ExtraReportsDoNotAddMoreThanElapsedTime()
|
||||||
|
{
|
||||||
|
_tracker.Start(Key, _users, _noon);
|
||||||
|
|
||||||
|
// Seeking an hour ahead makes clients send reports in quick succession.
|
||||||
|
// Only the clock matters, so the jump in position is worth nothing.
|
||||||
|
var total = Seconds(_tracker.Progress(Key, _users, false, At(10)))
|
||||||
|
+ Seconds(_tracker.Progress(Key, _users, false, At(10.2)))
|
||||||
|
+ Seconds(_tracker.Progress(Key, _users, false, At(10.4)))
|
||||||
|
+ Seconds(_tracker.Progress(Key, _users, false, At(20)));
|
||||||
|
|
||||||
|
Assert.Equal(20, total, 6);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Gap_IsCappedAtMaxDelta()
|
||||||
|
{
|
||||||
|
_tracker.Start(Key, _users, _noon);
|
||||||
|
|
||||||
|
var seconds = Seconds(_tracker.Progress(Key, _users, false, At(200)));
|
||||||
|
|
||||||
|
Assert.Equal(WatchTimeTracker.MaxDelta.TotalSeconds, seconds);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Gap_LongerThanStaleLimitAddsNothingAndResumes()
|
||||||
|
{
|
||||||
|
_tracker.Start(Key, _users, _noon);
|
||||||
|
|
||||||
|
var afterGap = Seconds(_tracker.Progress(Key, _users, false, At(301)));
|
||||||
|
var next = Seconds(_tracker.Progress(Key, _users, false, At(311)));
|
||||||
|
|
||||||
|
Assert.Equal(0, afterGap);
|
||||||
|
Assert.Equal(10, next);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ClockGoingBackwards_AddsNothing()
|
||||||
|
{
|
||||||
|
_tracker.Start(Key, _users, _noon);
|
||||||
|
|
||||||
|
Assert.Empty(_tracker.Progress(Key, _users, false, At(-30)));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void CloseStale_RemovesOnlySilentPlaybacks()
|
||||||
|
{
|
||||||
|
_tracker.Start("quiet", _users, _noon);
|
||||||
|
_tracker.Start("alive", _users, _noon);
|
||||||
|
_tracker.Progress("alive", _users, false, At(280));
|
||||||
|
|
||||||
|
var closed = _tracker.CloseStale(At(301));
|
||||||
|
|
||||||
|
Assert.Equal(1, closed);
|
||||||
|
Assert.Equal(1, _tracker.ActiveCount);
|
||||||
|
Assert.Equal(10, Seconds(_tracker.Progress("alive", _users, false, At(290))));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void StaleSession_StopAfterSweepAddsNothing()
|
||||||
|
{
|
||||||
|
_tracker.Start(Key, _users, _noon);
|
||||||
|
_tracker.CloseStale(At(400));
|
||||||
|
|
||||||
|
Assert.Empty(_tracker.Stop(Key, _users, At(410)));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Progress_ForUnknownPlaybackStartsTrackingWithoutTime()
|
||||||
|
{
|
||||||
|
var first = _tracker.Progress(Key, _users, false, _noon);
|
||||||
|
var second = Seconds(_tracker.Progress(Key, _users, false, At(10)));
|
||||||
|
|
||||||
|
Assert.Empty(first);
|
||||||
|
Assert.Equal(10, second);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Midnight_DeltaIsSplitBetweenBothDays()
|
||||||
|
{
|
||||||
|
var beforeMidnight = new DateTimeOffset(2026, 3, 10, 23, 59, 50, TimeSpan.Zero);
|
||||||
|
_tracker.Start(Key, _users, beforeMidnight);
|
||||||
|
|
||||||
|
var increments = _tracker.Progress(Key, _users, false, beforeMidnight.AddSeconds(30));
|
||||||
|
|
||||||
|
Assert.Equal(2, increments.Count);
|
||||||
|
var yesterday = Assert.Single(increments, i => i.Date == new DateOnly(2026, 3, 10));
|
||||||
|
var today = Assert.Single(increments, i => i.Date == new DateOnly(2026, 3, 11));
|
||||||
|
Assert.Equal(10, yesterday.Seconds, 6);
|
||||||
|
Assert.Equal(20, today.Seconds, 6);
|
||||||
|
Assert.Equal(new DateTime(2026, 3, 11, 0, 0, 0, DateTimeKind.Utc), yesterday.Activity);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Midnight_FollowsTheServerTimeZone()
|
||||||
|
{
|
||||||
|
var zone = TimeZoneInfo.CreateCustomTimeZone("test+2", TimeSpan.FromHours(2), "test+2", "test+2");
|
||||||
|
var tracker = new WatchTimeTracker(zone);
|
||||||
|
|
||||||
|
// 21:59:50 UTC is 23:59:50 local.
|
||||||
|
var start = new DateTimeOffset(2026, 3, 10, 21, 59, 50, TimeSpan.Zero);
|
||||||
|
var started = tracker.Start(Key, _users, start);
|
||||||
|
var increments = tracker.Progress(Key, _users, false, start.AddSeconds(30));
|
||||||
|
|
||||||
|
Assert.Equal(new DateOnly(2026, 3, 10), Assert.Single(started).Date);
|
||||||
|
Assert.Equal(10, Assert.Single(increments, i => i.Date == new DateOnly(2026, 3, 10)).Seconds, 6);
|
||||||
|
Assert.Equal(20, Assert.Single(increments, i => i.Date == new DateOnly(2026, 3, 11)).Seconds, 6);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Midnight_CappedGapOnlyCountsTheLastMinute()
|
||||||
|
{
|
||||||
|
var beforeMidnight = new DateTimeOffset(2026, 3, 10, 23, 57, 0, TimeSpan.Zero);
|
||||||
|
_tracker.Start(Key, _users, beforeMidnight);
|
||||||
|
|
||||||
|
// 4 minutes without a report, ending 60 s after midnight: all counted time is on the new day.
|
||||||
|
var increments = _tracker.Progress(Key, _users, false, beforeMidnight.AddMinutes(4));
|
||||||
|
|
||||||
|
var only = Assert.Single(increments);
|
||||||
|
Assert.Equal(new DateOnly(2026, 3, 11), only.Date);
|
||||||
|
Assert.Equal(60, only.Seconds, 6);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void SeparatePlaybacks_AreTrackedIndependently()
|
||||||
|
{
|
||||||
|
_tracker.Start("a", [_alice], _noon);
|
||||||
|
_tracker.Start("b", [_bob], At(5));
|
||||||
|
|
||||||
|
var a = _tracker.Progress("a", [_alice], false, At(10));
|
||||||
|
var b = _tracker.Progress("b", [_bob], false, At(10));
|
||||||
|
|
||||||
|
Assert.Equal(10, Assert.Single(a).Seconds);
|
||||||
|
Assert.Equal(_alice, a[0].UserId);
|
||||||
|
Assert.Equal(5, Assert.Single(b).Seconds);
|
||||||
|
Assert.Equal(_bob, b[0].UserId);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
<Solution>
|
<Solution>
|
||||||
<Project Path="Jellyfin.Plugin.Herald/Jellyfin.Plugin.Herald.csproj" />
|
<Project Path="Jellyfin.Plugin.Herald/Jellyfin.Plugin.Herald.csproj" />
|
||||||
|
<Project Path="Jellyfin.Plugin.Herald.Tests/Jellyfin.Plugin.Herald.Tests.csproj" />
|
||||||
</Solution>
|
</Solution>
|
||||||
|
|||||||
Reference in New Issue
Block a user