feat(api): schedule item duration estimates (#111) #118

Merged
timothy merged 3 commits from feat/111-schedule-durations into main 2026-07-04 00:00:33 +02:00
9 changed files with 489 additions and 18 deletions
@@ -44,6 +44,33 @@ public abstract record ProgramScheduleItemViewModel(
string PreferredSubtitleLanguageCode,
ChannelSubtitleMode? SubtitleMode)
{
/// <summary>
/// A rough estimate, in wall-clock time, of how long a single pass of this schedule item will play,
/// derived from the aggregated playout runtimes of the referenced content.
/// <para>
/// Semantics by <see cref="PlayoutMode" />:
/// <list type="bullet">
/// <item><b>One</b> — the average runtime of one item in the referenced collection.</item>
/// <item>
/// <b>Multiple</b> — the average item runtime multiplied by the configured count
/// (<see cref="MultipleMode.Count" />), or the whole collection runtime for
/// <see cref="MultipleMode.CollectionSize" />. An expression-based (non-integer)
/// count cannot be evaluated here and yields <c>null</c>.
/// </item>
/// <item><b>Flood</b> — always <c>null</c>: a flood item fills the remaining time and is unbounded.</item>
/// <item><b>Duration</b> — the explicit <c>playoutDuration</c> setting on the item.</item>
/// </list>
/// </para>
/// <para>
/// <c>null</c> whenever a bounded estimate cannot be produced — an unbounded mode (Flood),
/// a referenced collection with no items that have a known positive duration, a Multiple mode other
/// than Count/CollectionSize, or a collection type other than <see cref="CollectionType.Collection" />
/// (smart/multi/playlist/search/rerun/show/season/artist references are not aggregated in this pass).
/// Callers should treat a <c>null</c> as "unknown", never as zero.
/// </para>
/// </summary>
public TimeSpan? DurationEstimate { get; init; }
public string Name => CollectionType switch
{
CollectionType.Collection => Collection?.Name,
@@ -0,0 +1,18 @@
namespace ErsatzTV.Application.ProgramSchedules;
/// <summary>
/// The items of a schedule together with computed runtime estimates. Each item carries its own
/// <see cref="ProgramScheduleItemViewModel.DurationEstimate" /> (nullable — see that property for
/// the per-mode semantics), and <see cref="TotalDurationEstimate" /> is the sum of the items that
/// could be estimated.
/// </summary>
/// <param name="Items">The schedule items, each with a nullable <c>DurationEstimate</c>.</param>
/// <param name="TotalDurationEstimate">
/// The sum of every non-null per-item estimate, i.e. a rough runtime for a single pass through the
/// estimable items. <c>null</c> when no item in the schedule could be estimated (for example a
/// schedule made up entirely of Flood items, or of collection types that are not aggregated).
/// Because unbounded items contribute nothing, this is a lower bound, never an exact schedule length.
/// </param>
public record ProgramScheduleItemsWithDurationViewModel(
List<ProgramScheduleItemViewModel> Items,
TimeSpan? TotalDurationEstimate);
@@ -0,0 +1,4 @@
namespace ErsatzTV.Application.ProgramSchedules;
public record GetProgramScheduleItemsWithDurations(int Id)
: IRequest<ProgramScheduleItemsWithDurationViewModel>;
@@ -0,0 +1,70 @@
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Extensions;
using ErsatzTV.Core.Interfaces.Repositories;
using static ErsatzTV.Application.ProgramSchedules.ScheduleItemDurationEstimator;
namespace ErsatzTV.Application.ProgramSchedules;
public class GetProgramScheduleItemsWithDurationsHandler(
IMediator mediator,
IMediaCollectionRepository mediaCollectionRepository)
: IRequestHandler<GetProgramScheduleItemsWithDurations, ProgramScheduleItemsWithDurationViewModel>
{
public async Task<ProgramScheduleItemsWithDurationViewModel> Handle(
GetProgramScheduleItemsWithDurations request,
CancellationToken cancellationToken)
{
List<ProgramScheduleItemViewModel> items =
await mediator.Send(new GetProgramScheduleItems(request.Id), cancellationToken);
Dictionary<int, CollectionDuration> durationsByCollectionId =
await AggregateReferencedCollections(items);
var itemsWithEstimates = items
.Map(item => item with { DurationEstimate = Estimate(item, durationsByCollectionId) })
.ToList();
List<TimeSpan> estimates = itemsWithEstimates
.Map(item => Optional(item.DurationEstimate))
.Somes()
.ToList();
TimeSpan? total = estimates.Count > 0
? TimeSpan.FromTicks(estimates.Sum(estimate => estimate.Ticks))
: null;
return new ProgramScheduleItemsWithDurationViewModel(itemsWithEstimates, total);
}
// Aggregate MediaVersion.Duration once per distinct referenced collection (not per item). Only plain
// collections are resolved here; other reference types are estimated as null (see DurationEstimate docs).
private async Task<Dictionary<int, CollectionDuration>> AggregateReferencedCollections(
IReadOnlyList<ProgramScheduleItemViewModel> items)
{
List<int> collectionIds = items
.Filter(item => item.CollectionType is CollectionType.Collection && item.Collection is not null)
.Filter(item => item.PlayoutMode is PlayoutMode.One or PlayoutMode.Multiple)
.Map(item => item.Collection.Id)
.Distinct()
.ToList();
var result = new Dictionary<int, CollectionDuration>();
foreach (int collectionId in collectionIds)
{
List<MediaItem> mediaItems = await mediaCollectionRepository.GetItems(collectionId);
List<TimeSpan> durations = mediaItems
.Map(mediaItem => mediaItem.GetDurationForPlayout())
.Filter(duration => duration > TimeSpan.Zero)
.ToList();
if (durations.Count > 0)
{
var total = TimeSpan.FromTicks(durations.Sum(duration => duration.Ticks));
result[collectionId] = new CollectionDuration(total, durations.Count);
}
}
return result;
}
}
@@ -0,0 +1,73 @@
using System.Globalization;
using ErsatzTV.Core.Domain;
namespace ErsatzTV.Application.ProgramSchedules;
/// <summary>
/// Pure computation of per-item runtime estimates from pre-aggregated collection durations.
/// Kept separate from the query handler so the (non-trivial) per-mode math can be unit-tested
/// without a database. See <see cref="ProgramScheduleItemViewModel.DurationEstimate" /> for the
/// documented semantics this implements.
/// </summary>
internal static class ScheduleItemDurationEstimator
{
/// <summary>
/// Aggregate runtime of a single referenced collection: the total runtime of every item with a
/// known non-zero duration, and how many such items there are.
/// </summary>
public sealed record CollectionDuration(TimeSpan Total, int ItemCount)
{
public TimeSpan? Average => ItemCount > 0 ? Total / ItemCount : null;
}
/// <summary>
/// Estimate the runtime of one pass of <paramref name="item" />, or <c>null</c> when no bounded
/// estimate is possible. <paramref name="durationsByCollectionId" /> holds aggregates only for the
/// plain collections that were resolved; a missing entry yields <c>null</c>.
/// </summary>
public static TimeSpan? Estimate(
ProgramScheduleItemViewModel item,
IReadOnlyDictionary<int, CollectionDuration> durationsByCollectionId)
{
if (item is ProgramScheduleItemDurationViewModel durationItem)
{
return durationItem.PlayoutDuration;
}
// only plain collections are aggregated in this pass
if (item.CollectionType is not CollectionType.Collection || item.Collection is null)
{
return null;
}
if (!durationsByCollectionId.TryGetValue(item.Collection.Id, out CollectionDuration duration))
{
return null;
}
return item switch
{
// one item per pass -> the average item runtime
ProgramScheduleItemOneViewModel => duration.Average,
// a fixed count of items, or the whole collection once
ProgramScheduleItemMultipleViewModel multiple => EstimateMultiple(multiple, duration),
// Flood is an unbounded fill; Duration is handled above from its explicit playoutDuration.
_ => null
};
}
private static TimeSpan? EstimateMultiple(
ProgramScheduleItemMultipleViewModel multiple,
CollectionDuration duration) =>
multiple.MultipleMode switch
{
MultipleMode.Count when
int.TryParse(multiple.Count, NumberStyles.Integer, CultureInfo.InvariantCulture, out int count)
&& count > 0
&& duration.Average is { } average => average * count,
MultipleMode.CollectionSize => duration.Total,
_ => null
};
}
@@ -0,0 +1,247 @@
using ErsatzTV.Application.MediaCollections;
using ErsatzTV.Application.ProgramSchedules;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Interfaces.Repositories;
using ErsatzTV.Core.Scheduling;
using MediatR;
using NSubstitute;
using NUnit.Framework;
using Shouldly;
namespace ErsatzTV.Tests.Application.ProgramSchedules;
[TestFixture]
public class GetProgramScheduleItemsWithDurationsHandlerTests
{
private IMediaCollectionRepository _mediaCollectionRepository = null!;
private IMediator _mediator = null!;
[SetUp]
public void SetUp()
{
_mediator = Substitute.For<IMediator>();
_mediaCollectionRepository = Substitute.For<IMediaCollectionRepository>();
}
[Test]
public async Task Handle_Should_Estimate_Items_And_Total_From_Collection_Durations()
{
ProgramScheduleItemViewModel one = MakeOneItem(1, 10);
ProgramScheduleItemViewModel multipleCount = MakeMultipleItem(2, 10, MultipleMode.Count, "3");
ProgramScheduleItemViewModel multipleCollectionSize = MakeMultipleItem(3, 20, MultipleMode.CollectionSize, "0");
ProgramScheduleItemViewModel duration = MakeDurationItem(4, TimeSpan.FromMinutes(45));
ProgramScheduleItemViewModel flood = MakeFloodItem(5, 10);
ProgramScheduleItemViewModel remote = MakeOneItem(6, 30);
_mediator.Send(Arg.Is<GetProgramScheduleItems>(q => q.Id == 99), Arg.Any<CancellationToken>())
.Returns([one, multipleCount, multipleCollectionSize, duration, flood, remote]);
_mediaCollectionRepository.GetItems(10)
.Returns([MakeMovie(30), MakeMovie(60), MakeMovie(0)]);
_mediaCollectionRepository.GetItems(20)
.Returns([MakeMovie(10), MakeMovie(20)]);
_mediaCollectionRepository.GetItems(30)
.Returns([MakeRemoteStreamWithFallbackDuration(20)]);
var handler = new GetProgramScheduleItemsWithDurationsHandler(_mediator, _mediaCollectionRepository);
ProgramScheduleItemsWithDurationViewModel result =
await handler.Handle(new GetProgramScheduleItemsWithDurations(99), CancellationToken.None);
result.Items[0].DurationEstimate.ShouldBe(TimeSpan.FromMinutes(45));
result.Items[1].DurationEstimate.ShouldBe(TimeSpan.FromMinutes(135));
result.Items[2].DurationEstimate.ShouldBe(TimeSpan.FromMinutes(30));
result.Items[3].DurationEstimate.ShouldBe(TimeSpan.FromMinutes(45));
result.Items[4].DurationEstimate.ShouldBeNull();
result.Items[5].DurationEstimate.ShouldBe(TimeSpan.FromMinutes(20));
result.TotalDurationEstimate.ShouldBe(TimeSpan.FromMinutes(275));
}
[Test]
public async Task Handle_Should_Return_Null_Total_When_No_Items_Can_Be_Estimated()
{
ProgramScheduleItemViewModel one = MakeOneItem(1, 10);
ProgramScheduleItemViewModel flood = MakeFloodItem(2, 10);
_mediator.Send(Arg.Is<GetProgramScheduleItems>(q => q.Id == 99), Arg.Any<CancellationToken>())
.Returns([one, flood]);
_mediaCollectionRepository.GetItems(10)
.Returns([MakeMovie(0)]);
var handler = new GetProgramScheduleItemsWithDurationsHandler(_mediator, _mediaCollectionRepository);
ProgramScheduleItemsWithDurationViewModel result =
await handler.Handle(new GetProgramScheduleItemsWithDurations(99), CancellationToken.None);
result.Items.ShouldAllBe(item => item.DurationEstimate == null);
result.TotalDurationEstimate.ShouldBeNull();
}
private static ProgramScheduleItemOneViewModel MakeOneItem(int id, int collectionId) =>
new(
id,
id,
StartType.Dynamic,
null,
null,
CollectionType.Collection,
MakeCollection(collectionId),
null,
null,
null,
null,
null,
null,
null,
PlaybackOrder.Shuffle,
MarathonGroupBy.None,
false,
false,
null,
FillWithGroupMode.None,
null,
GuideMode.Normal,
null,
null,
null,
null,
null,
[],
[],
null,
null,
null,
null);
private static ProgramScheduleItemMultipleViewModel MakeMultipleItem(
int id,
int collectionId,
MultipleMode multipleMode,
string count) =>
new(
id,
id,
StartType.Dynamic,
null,
null,
CollectionType.Collection,
MakeCollection(collectionId),
null,
null,
null,
null,
null,
null,
null,
PlaybackOrder.Shuffle,
MarathonGroupBy.None,
false,
false,
null,
FillWithGroupMode.None,
multipleMode,
count,
null,
GuideMode.Normal,
null,
null,
null,
null,
null,
[],
[],
null,
null,
null,
null);
private static ProgramScheduleItemDurationViewModel MakeDurationItem(int id, TimeSpan playoutDuration) =>
new(
id,
id,
StartType.Dynamic,
null,
null,
CollectionType.Collection,
MakeCollection(10),
null,
null,
null,
null,
null,
null,
null,
PlaybackOrder.Shuffle,
MarathonGroupBy.None,
false,
false,
null,
FillWithGroupMode.None,
playoutDuration,
TailMode.None,
0,
null,
GuideMode.Normal,
null,
null,
null,
null,
null,
[],
[],
null,
null,
null,
null);
private static ProgramScheduleItemFloodViewModel MakeFloodItem(int id, int collectionId) =>
new(
id,
id,
StartType.Dynamic,
null,
null,
CollectionType.Collection,
MakeCollection(collectionId),
null,
null,
null,
null,
null,
null,
null,
PlaybackOrder.Shuffle,
MarathonGroupBy.None,
false,
false,
null,
FillWithGroupMode.None,
null,
GuideMode.Normal,
null,
null,
null,
null,
null,
[],
[],
null,
null,
null,
null);
private static MediaCollectionViewModel MakeCollection(int id) =>
new(CollectionType.Collection, id, $"Collection {id}", false, MediaItemState.Normal);
private static Movie MakeMovie(int minutes) =>
new()
{
MediaVersions = [new MediaVersion { Duration = TimeSpan.FromMinutes(minutes) }]
};
private static RemoteStream MakeRemoteStreamWithFallbackDuration(int minutes) =>
new()
{
Duration = TimeSpan.FromMinutes(minutes),
MediaVersions = [new MediaVersion { Duration = TimeSpan.Zero }]
};
}
@@ -189,14 +189,18 @@ public class ScheduleControllerTests
public async Task GetItems_Should_Return_200_With_Items()
{
List<ProgramScheduleItemViewModel> items = [MakeOneItem(11)];
var response = new ProgramScheduleItemsWithDurationViewModel(items, TimeSpan.FromMinutes(25));
_mediator.Send(Arg.Any<GetProgramScheduleById>(), Arg.Any<CancellationToken>())
.Returns(Option<ProgramScheduleViewModel>.Some(MakeSchedule(4, "Daily")));
_mediator.Send(Arg.Any<GetProgramScheduleItems>(), Arg.Any<CancellationToken>())
.Returns(items);
_mediator.Send(Arg.Any<GetProgramScheduleItemsWithDurations>(), Arg.Any<CancellationToken>())
.Returns(response);
IActionResult result = await _controller.GetItems(4, CancellationToken.None);
result.ShouldBeOfType<OkObjectResult>().Value.ShouldBe(items);
result.ShouldBeOfType<OkObjectResult>().Value.ShouldBe(response);
await _mediator.Received(1).Send(
Arg.Is<GetProgramScheduleItemsWithDurations>(q => q.Id == 4),
Arg.Any<CancellationToken>());
}
[Test]
@@ -99,8 +99,12 @@ public class ScheduleController(IMediator mediator) : ControllerBase
[HttpGet("/api/schedules/{id:int}/items")]
[Tags("Schedules")]
[EndpointSummary("Get schedule items")]
[EndpointDescription(
"Returns the schedule's items plus a computed, best-effort runtime estimate: each item carries a " +
"nullable durationEstimate and the envelope carries a nullable totalDurationEstimate. Estimates are " +
"derived from referenced collection/media runtimes and are null when unbounded or unknown.")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(List<ProgramScheduleItemViewModel>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProgramScheduleItemsWithDurationViewModel), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetItems(int id, CancellationToken cancellationToken)
{
@@ -110,8 +114,8 @@ public class ScheduleController(IMediator mediator) : ControllerBase
return ApiResults.NotFoundProblem();
}
List<ProgramScheduleItemViewModel> items =
await mediator.Send(new GetProgramScheduleItems(id), cancellationToken);
ProgramScheduleItemsWithDurationViewModel items =
await mediator.Send(new GetProgramScheduleItemsWithDurations(id), cancellationToken);
return new OkObjectResult(items);
}
+36 -12
View File
@@ -2580,6 +2580,7 @@
"Schedules"
],
"summary": "Get schedule items",
"description": "Returns the schedule's items plus a computed, best-effort runtime estimate: each item carries a nullable durationEstimate and the envelope carries a nullable totalDurationEstimate. Estimates are derived from referenced collection/media runtimes and are null when unbounded or unknown.",
"parameters": [
{
"name": "id",
@@ -2597,26 +2598,17 @@
"content": {
"text/plain": {
"schema": {
"type": "array",
"items": {
"$ref": "#/components/schemas/ProgramScheduleItemViewModel"
}
"$ref": "#/components/schemas/ProgramScheduleItemsWithDurationViewModel"
}
},
"application/json": {
"schema": {
"type": "array",
"items": {
"$ref": "#/components/schemas/ProgramScheduleItemViewModel"
}
"$ref": "#/components/schemas/ProgramScheduleItemsWithDurationViewModel"
}
},
"text/json": {
"schema": {
"type": "array",
"items": {
"$ref": "#/components/schemas/ProgramScheduleItemViewModel"
}
"$ref": "#/components/schemas/ProgramScheduleItemsWithDurationViewModel"
}
}
}
@@ -5445,6 +5437,31 @@
}
}
},
"ProgramScheduleItemsWithDurationViewModel": {
"required": [
"items",
"totalDurationEstimate"
],
"type": "object",
"properties": {
"items": {
"type": [
"null",
"array"
],
"items": {
"$ref": "#/components/schemas/ProgramScheduleItemViewModel"
}
},
"totalDurationEstimate": {
"pattern": "^-?(\\d+\\.)?\\d{2}:\\d{2}:\\d{2}(\\.\\d{1,7})?$",
"type": [
"null",
"string"
]
}
}
},
"ProgramScheduleItemViewModel": {
"type": "object",
"properties": {
@@ -5604,6 +5621,13 @@
}
]
},
"durationEstimate": {
"pattern": "^-?(\\d+\\.)?\\d{2}:\\d{2}:\\d{2}(\\.\\d{1,7})?$",
"type": [
"null",
"string"
]
},
"name": {
"type": [
"null",