diff --git a/src/Radiosender/Controllers/ScheduleController.cs b/src/Radiosender/Controllers/ScheduleController.cs
index f88bb1f..ed5a1b8 100644
--- a/src/Radiosender/Controllers/ScheduleController.cs
+++ b/src/Radiosender/Controllers/ScheduleController.cs
@@ -12,10 +12,15 @@ public class ScheduleController
{
public const int MaxHours = 24;
+ /// How far ahead an unlimited plan always reaches.
+ public const int UnlimitedLookaheadHours = 5;
+
private readonly SongRepository _songs;
private readonly ScheduleGenerator _generator;
private readonly PlaybackEngine _engine;
private readonly Func _now;
+ // Guards Plan against a song request (UI thread) racing the hourly extension (engine thread).
+ private readonly Lock _planLock = new();
private DateTime _itemStartedAt;
public ScheduleController(SongRepository songs, ScheduleGenerator generator, PlaybackEngine engine, Func now)
@@ -27,9 +32,10 @@ public class ScheduleController
_engine.ItemStarted += (_, e) =>
{
_itemStartedAt = _now();
+ ExtendIfUnlimited();
ItemStarted?.Invoke(this, e.Index);
};
- _engine.ItemFailed += (_, e) => ItemFailed?.Invoke(this, $"Skipped \"{e.Item.Title}\": {e.Error.Message}");
+ _engine.ItemFailed += (_, e) => ItemFailed?.Invoke(this, $"\"{e.Item.Title}\" übersprungen: {e.Error.Message}");
_engine.Finished += (_, _) => Finished?.Invoke(this, EventArgs.Empty);
}
@@ -39,6 +45,10 @@ public class ScheduleController
public IReadOnlyList Plan { get; private set; } = [];
+ /// true for a plan without an end: it grows by an hour whenever less than
+ /// hours are left.
+ public bool IsUnlimited { get; private set; }
+
public bool IsPlaying => _engine.IsRunning;
public int CurrentIndex => _engine.CurrentIndex;
@@ -58,18 +68,66 @@ public class ScheduleController
set => MusicPlayer.Instance.Volume = value;
}
- /// Plans full hours from the next full hour with the songs in the library.
+ ///
+ /// Plans full hours with the songs in the library; null plans without an end.
+ /// The plan begins at , or at the next full hour when that is null.
+ ///
/// The library cannot fill the plan.
- public IReadOnlyList CreatePlan(int hours)
+ public IReadOnlyList CreatePlan(int? hours, DateTime? start = null)
{
- ArgumentOutOfRangeException.ThrowIfLessThan(hours, 1);
- ArgumentOutOfRangeException.ThrowIfGreaterThan(hours, MaxHours);
+ if (hours is { } h)
+ {
+ ArgumentOutOfRangeException.ThrowIfLessThan(h, 1, nameof(hours));
+ ArgumentOutOfRangeException.ThrowIfGreaterThan(h, MaxHours, nameof(hours));
+ }
var now = _now();
var nextHour = new DateTime(now.Year, now.Month, now.Day, now.Hour, 0, 0, now.Kind).AddHours(1);
+ // Whole seconds, so the timeline and the item ends stay on the second.
+ var from = start is { } s ? new DateTime(s.Ticks - s.Ticks % TimeSpan.TicksPerSecond, s.Kind) : nextHour;
Stop();
- Plan = _generator.Generate(nextHour, hours, _songs.GetAll());
- return Plan;
+ var plan = _generator.Generate(from, hours ?? UnlimitedLookaheadHours, _songs.GetAll());
+ lock (_planLock)
+ {
+ Plan = plan;
+ IsUnlimited = hours is null;
+ }
+ return plan;
+ }
+
+ /// Plans from this moment and goes on air at once; music leads up to the first news at :00 or :30.
+ /// The library cannot fill the plan.
+ public void StartNow(int? hours)
+ {
+ CreatePlan(hours, _now());
+ _engine.Start(Plan);
+ }
+
+ // Runs on the engine thread whenever an item starts.
+ // shortcut: played items stay in the plan (about 20 per hour); trim them if broadcasts run for weeks.
+ private void ExtendIfUnlimited()
+ {
+ if (!IsUnlimited)
+ return;
+ try
+ {
+ lock (_planLock)
+ {
+ var plan = Plan;
+ if (plan.Count == 0) // the user removed every item
+ return;
+ var until = _now().AddHours(UnlimitedLookaheadHours);
+ while (plan[^1].End < until)
+ plan = [.. plan, .. _generator.Generate(plan[^1].End, 1, _songs.GetAll())];
+ // Only appends, so the engine keeps everything up to the old end.
+ if (!ReferenceEquals(plan, Plan) && _engine.ReplaceUpcoming(plan, Plan.Count))
+ Plan = plan;
+ }
+ }
+ catch (ScheduleException ex)
+ {
+ ItemFailed?.Invoke(this, $"Der Plan konnte nicht verlängert werden: {ex.Message}");
+ }
}
/// Planned start of the next item while the broadcast waits for it, otherwise null.
@@ -82,14 +140,127 @@ public class ScheduleController
public void Start()
{
if (Plan.Count == 0)
- throw new InvalidOperationException("Create a schedule first.");
+ throw new InvalidOperationException("Zuerst einen Plan erstellen.");
if (Plan[^1].Start <= _now())
- throw new InvalidOperationException("This schedule is already over. Create a new one.");
+ throw new InvalidOperationException("Dieser Plan ist bereits vorbei. Einen neuen erstellen.");
_engine.Start(Plan);
}
public void Stop() => _engine.Stop();
+ ///
+ /// The next news or moderator item that is due for a reminder while the broadcast runs: it starts within
+ /// the lead time of its kind. null as lead time switches that kind off. Returns null when
+ /// nothing is due.
+ ///
+ public ScheduleItem? UpcomingSpeech(TimeSpan? newsLead, TimeSpan? moderatorLead)
+ {
+ if (!IsPlaying)
+ return null;
+ var now = _now();
+ var plan = Plan;
+ var longest = TimeSpan.FromTicks(Math.Max((newsLead ?? TimeSpan.Zero).Ticks, (moderatorLead ?? TimeSpan.Zero).Ticks));
+ for (var i = Math.Max(CurrentIndex + 1, 0); i < plan.Count; i++)
+ {
+ var wait = plan[i].Start - now;
+ if (wait > longest)
+ return null;
+ var lead = plan[i].Kind switch
+ {
+ ScheduleItemKind.News => newsLead,
+ ScheduleItemKind.Moderator => moderatorLead,
+ _ => null,
+ };
+ if (wait > TimeSpan.Zero && wait <= lead)
+ return plan[i];
+ }
+ return null;
+ }
+
+ /// Moves the item at by positions; later items shift in time.
+ /// An affected item is already on air or over, or the target is outside the plan.
+ public IReadOnlyList Move(int index, int offset)
+ {
+ var target = index + offset;
+ if (target < 0 || target >= Plan.Count)
+ throw new ScheduleException("Das Element ist bereits am Rand des Plans.");
+ return Change(Math.Min(index, target), change: items =>
+ {
+ var item = items[index];
+ items.RemoveAt(index);
+ items.Insert(target, item);
+ });
+ }
+
+ /// Removes the item at ; later items move up in time.
+ /// The item is already on air or over.
+ public IReadOnlyList Remove(int index) => Change(index, change: items => items.RemoveAt(index));
+
+ /// Ends the item on air now: its length becomes the time it has run, and the next item starts.
+ /// Nothing is on air.
+ public IReadOnlyList EndCurrentNow()
+ {
+ var index = CurrentIndex;
+ if (CurrentItem is null)
+ throw new ScheduleException("Es ist nichts auf Sendung.");
+ var now = _now();
+ // Whole seconds, like every other time in the plan; the next start is then not in the future.
+ var end = new DateTime(now.Ticks - now.Ticks % TimeSpan.TicksPerSecond, now.Kind);
+ return Change(index, currentAllowed: true, change: items =>
+ {
+ var item = items[index];
+ items[index] = item with { Duration = end > item.Start ? end - item.Start : TimeSpan.Zero };
+ });
+ }
+
+ ///
+ /// Sets the title of a news, ad or moderator item, and the length of a news or moderator item;
+ /// later items shift in time. Also works for the item on air: its new length counts from its start.
+ ///
+ /// The item cannot be edited that way, or is already over.
+ public IReadOnlyList EditItem(int index, string title, TimeSpan duration) => Change(index, currentAllowed: true, change: items =>
+ {
+ var item = items[index];
+ if (item.Kind == ScheduleItemKind.Song)
+ throw new ScheduleException("Songs werden in der Bibliothek bearbeitet.");
+ if (duration != item.Duration && item.Kind == ScheduleItemKind.Ad)
+ throw new ScheduleException("Nur Nachrichten und Moderation können ihre Länge ändern.");
+ if (duration <= TimeSpan.Zero)
+ throw new ScheduleException("Die Länge muss größer als null sein.");
+ items[index] = item with { Title = title.Trim(), Duration = duration };
+ });
+
+ // Manual edits ripple: from the first changed position on, every item starts when the one before ends.
+ // News can therefore leave :00 and :30; that is the user's call.
+ // currentAllowed: the item on air may change too; the engine is then told to re-time it.
+ private IReadOnlyList Change(int firstChanged, Action> change, bool currentAllowed = false)
+ {
+ lock (_planLock)
+ {
+ if (firstChanged < 0 || firstChanged >= Plan.Count)
+ throw new ScheduleException("Ein Element im Plan auswählen.");
+ var onAir = IsPlaying && firstChanged == CurrentIndex;
+ if (IsPlaying && (firstChanged < CurrentIndex || (onAir && !currentAllowed)))
+ throw new ScheduleException(onAir
+ ? "Dieses Element ist auf Sendung. Es kann bearbeitet oder beendet, aber nicht verschoben oder entfernt werden."
+ : "Dieses Element ist bereits vorbei. Ein späteres wählen.");
+
+ var items = Plan.ToList();
+ var start = items[firstChanged].Start;
+ change(items);
+ for (var i = firstChanged; i < items.Count; i++)
+ {
+ items[i] = items[i] with { Start = start };
+ start = items[i].End;
+ }
+
+ if (IsPlaying && !(onAir ? _engine.ReplaceCurrent(items, firstChanged) : _engine.ReplaceUpcoming(items, firstChanged)))
+ throw new ScheduleException("Die Sendung ist inzwischen weitergelaufen. Erneut versuchen.");
+ Plan = items;
+ return items;
+ }
+ }
+
/// All songs in the library, for the song request picker.
public IReadOnlyList LibrarySongs() => _songs.GetAll();
@@ -100,19 +271,22 @@ public class ScheduleController
/// The item cannot be replaced or the song does not fit.
public IReadOnlyList Swap(int index, long songId)
{
- if (Plan.Count == 0)
- throw new ScheduleException("Create a schedule first.");
- if (index < 0 || index >= Plan.Count)
- throw new ScheduleException("Select an item in the schedule.");
- if (IsPlaying && index <= CurrentIndex)
- throw new ScheduleException("This item is already on air or over. Choose a later item.");
- var song = _songs.GetById(songId) ?? throw new ScheduleException("The song is no longer in the library.");
+ lock (_planLock)
+ {
+ if (Plan.Count == 0)
+ throw new ScheduleException("Zuerst einen Plan erstellen.");
+ if (index < 0 || index >= Plan.Count)
+ throw new ScheduleException("Ein Element im Plan auswählen.");
+ if (IsPlaying && index <= CurrentIndex)
+ throw new ScheduleException("Dieses Element ist bereits auf Sendung oder vorbei. Ein späteres wählen.");
+ var song = _songs.GetById(songId) ?? throw new ScheduleException("Der Song ist nicht mehr in der Bibliothek.");
- var plan = _generator.Replace(Plan, index, song, _songs.GetAll());
- // The engine may have moved on while the plan was rebuilt.
- if (IsPlaying && !_engine.ReplaceUpcoming(plan, index))
- throw new ScheduleException("This item went on air in the meantime. Choose a later item.");
- Plan = plan;
- return plan;
+ var plan = _generator.Replace(Plan, index, song, _songs.GetAll());
+ // The engine may have moved on while the plan was rebuilt.
+ if (IsPlaying && !_engine.ReplaceUpcoming(plan, index))
+ throw new ScheduleException("Dieses Element ist inzwischen auf Sendung gegangen. Ein späteres wählen.");
+ Plan = plan;
+ return plan;
+ }
}
}
diff --git a/tests/Radiosender.Tests/ScheduleControllerTests.cs b/tests/Radiosender.Tests/ScheduleControllerTests.cs
index 6f4d33e..8359bc3 100644
--- a/tests/Radiosender.Tests/ScheduleControllerTests.cs
+++ b/tests/Radiosender.Tests/ScheduleControllerTests.cs
@@ -52,6 +52,254 @@ public sealed class ScheduleControllerTests : IDisposable
Assert.Same(plan, controller.Plan);
}
+ [Fact]
+ public void CreatePlan_StartsAtTheGivenHour()
+ {
+ AddSongs();
+
+ var plan = Create().CreatePlan(1, new DateTime(2026, 11, 23, 18, 0, 0));
+
+ Assert.Equal(new DateTime(2026, 11, 23, 18, 0, 0), plan[0].Start);
+ Assert.Equal(new DateTime(2026, 11, 23, 19, 0, 0), plan[^1].End);
+ }
+
+ [Fact]
+ public void CreatePlan_UnlimitedPlansTheLookahead()
+ {
+ AddSongs();
+ var controller = Create();
+
+ var plan = controller.CreatePlan(null);
+
+ Assert.True(controller.IsUnlimited);
+ Assert.Equal(new DateTime(2026, 11, 23, 20, 0, 0), plan[^1].End);
+ }
+
+ [Fact]
+ public async Task Unlimited_AppendsHoursWhilePlaying()
+ {
+ AddSongs();
+ var hold = new TaskCompletionSource();
+ var controller = Create((_, token) => hold.Task.WaitAsync(token));
+ controller.CreatePlan(null); // 15:00 to 20:00
+ var first = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ controller.ItemStarted += (_, _) => first.TrySetResult();
+
+ _now = new DateTime(2026, 11, 23, 16, 30, 0); // the news at 16:30 goes on air
+ controller.Start();
+ await first.Task.WaitAsync(TimeSpan.FromSeconds(5));
+
+ var plan = controller.Plan;
+ Assert.Equal(new DateTime(2026, 11, 23, 22, 0, 0), plan[^1].End); // 5 h ahead of 16:30, in full hours
+ for (var i = 1; i < plan.Count; i++)
+ Assert.Equal(plan[i - 1].End, plan[i].Start);
+ Assert.Equal(ScheduleItemKind.News, controller.CurrentItem!.Kind);
+ controller.Stop();
+ }
+
+ [Fact]
+ public void StartNow_PlansFromThisMomentAndGoesOnAir()
+ {
+ AddSongs();
+ var hold = new TaskCompletionSource();
+ var controller = Create((_, token) => hold.Task.WaitAsync(token));
+
+ controller.StartNow(1);
+
+ Assert.True(controller.IsPlaying);
+ Assert.Equal(_now, controller.Plan[0].Start);
+ Assert.NotEqual(ScheduleItemKind.News, controller.Plan[0].Kind);
+ Assert.Equal(new DateTime(2026, 11, 23, 16, 0, 0), controller.Plan[^1].End);
+ controller.Stop();
+ }
+
+ private static void AssertContiguousFrom(IReadOnlyList plan, DateTime start)
+ {
+ Assert.Equal(start, plan[0].Start);
+ for (var i = 1; i < plan.Count; i++)
+ Assert.Equal(plan[i - 1].End, plan[i].Start);
+ }
+
+ [Fact]
+ public void Move_SwapsItemsAndShiftsTheTimes()
+ {
+ AddSongs();
+ var controller = Create();
+ var before = controller.CreatePlan(1);
+
+ var plan = controller.Move(2, -2);
+
+ Assert.Equal(before[2].Song?.Id, plan[0].Song?.Id);
+ Assert.Equal(before[2].Kind, plan[0].Kind);
+ Assert.Equal(ScheduleItemKind.News, plan[1].Kind);
+ Assert.Equal(before.Count, plan.Count);
+ AssertContiguousFrom(plan, before[0].Start);
+ Assert.Equal(before[^1].End, plan[^1].End);
+ Assert.Same(plan, controller.Plan);
+ }
+
+ [Fact]
+ public void Move_PastTheEdgeThrows()
+ {
+ AddSongs();
+ var controller = Create();
+ controller.CreatePlan(1);
+
+ Assert.Throws(() => controller.Move(0, -1));
+ }
+
+ [Fact]
+ public void Remove_ClosesTheGap()
+ {
+ AddSongs();
+ var controller = Create();
+ var before = controller.CreatePlan(1);
+
+ var plan = controller.Remove(1);
+
+ Assert.Equal(before.Count - 1, plan.Count);
+ AssertContiguousFrom(plan, before[0].Start);
+ Assert.Equal(before[^1].End - before[1].Duration, plan[^1].End);
+ }
+
+ [Fact]
+ public void EditItem_SetsTitleAndLengthOfNews()
+ {
+ AddSongs();
+ var controller = Create();
+ var before = controller.CreatePlan(1);
+
+ var plan = controller.EditItem(0, " Evening news ", TimeSpan.FromMinutes(3));
+
+ Assert.Equal("Evening news", plan[0].Title);
+ Assert.Equal(TimeSpan.FromMinutes(3), plan[0].Duration);
+ AssertContiguousFrom(plan, before[0].Start);
+ Assert.Equal(before[^1].End - TimeSpan.FromMinutes(2), plan[^1].End);
+ }
+
+ [Fact]
+ public void EditItem_RejectsSongsAndAdLengths()
+ {
+ AddSongs();
+ var controller = Create();
+ var plan = controller.CreatePlan(1);
+ var song = plan.ToList().FindIndex(i => i.Kind == ScheduleItemKind.Song);
+ var ad = plan.ToList().FindIndex(i => i.Kind == ScheduleItemKind.Ad);
+
+ Assert.Throws(() => controller.EditItem(song, "x", plan[song].Duration));
+ Assert.Throws(() => controller.EditItem(ad, "x", plan[ad].Duration + TimeSpan.FromSeconds(1)));
+ Assert.Equal("Spot", controller.EditItem(ad, "Spot", plan[ad].Duration)[ad].Title);
+ }
+
+ [Fact]
+ public async Task Edits_WhilePlayingRejectTheItemOnAir()
+ {
+ AddSongs();
+ var hold = new TaskCompletionSource();
+ var controller = Create((_, token) => hold.Task.WaitAsync(token));
+ controller.CreatePlan(1);
+ var first = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ controller.ItemStarted += (_, _) => first.TrySetResult();
+ _now = controller.Plan[0].Start;
+ controller.Start();
+ await first.Task.WaitAsync(TimeSpan.FromSeconds(5));
+
+ Assert.Throws(() => controller.Remove(0));
+ Assert.Throws(() => controller.Move(1, -1));
+ var count = controller.Plan.Count;
+ Assert.Equal(count - 1, controller.Remove(1).Count);
+ controller.Stop();
+ }
+
+ private async Task<(ScheduleController Controller, SemaphoreSlim Started)> OnAirWithTheFirstNewsAsync()
+ {
+ AddSongs();
+ var hold = new TaskCompletionSource();
+ var controller = Create((_, token) => hold.Task.WaitAsync(token));
+ controller.CreatePlan(1);
+ var started = new SemaphoreSlim(0);
+ controller.ItemStarted += (_, _) => started.Release();
+ _now = controller.Plan[0].Start;
+ controller.Start();
+ Assert.True(await started.WaitAsync(TimeSpan.FromSeconds(5)));
+ return (controller, started);
+ }
+
+ [Fact]
+ public async Task EndCurrentNow_EndsTheItemOnAirAndStartsTheNext()
+ {
+ var (controller, started) = await OnAirWithTheFirstNewsAsync();
+ _now = _now.AddMinutes(2);
+
+ var plan = controller.EndCurrentNow();
+
+ Assert.Equal(TimeSpan.FromMinutes(2), plan[0].Duration);
+ AssertContiguousFrom(plan, plan[0].Start);
+ Assert.Equal(_now, plan[1].Start);
+ Assert.True(await started.WaitAsync(TimeSpan.FromSeconds(5)));
+ Assert.Equal(1, controller.CurrentIndex);
+ controller.Stop();
+ }
+
+ [Fact]
+ public void EndCurrentNow_WithNothingOnAirThrows()
+ {
+ AddSongs();
+ var controller = Create();
+ controller.CreatePlan(1);
+
+ Assert.Throws(() => controller.EndCurrentNow());
+ }
+
+ [Fact]
+ public async Task EditItem_ChangesTheItemOnAirButItCannotBeRemoved()
+ {
+ var (controller, _) = await OnAirWithTheFirstNewsAsync();
+ var start = controller.Plan[0].Start;
+
+ var plan = controller.EditItem(0, "Late news", TimeSpan.FromMinutes(7));
+
+ Assert.Equal("Late news", plan[0].Title);
+ Assert.Equal(start.AddMinutes(7), plan[1].Start);
+ Assert.Equal(0, controller.CurrentIndex);
+ Assert.Equal("Late news", controller.CurrentItem!.Title);
+ Assert.Throws(() => controller.Remove(0));
+ controller.Stop();
+ }
+
+ [Fact]
+ public async Task EditItem_ShorteningTheItemOnAirBelowItsRunTimeEndsIt()
+ {
+ var (controller, started) = await OnAirWithTheFirstNewsAsync();
+ _now = _now.AddMinutes(3);
+
+ controller.EditItem(0, "", TimeSpan.FromMinutes(1));
+
+ Assert.True(await started.WaitAsync(TimeSpan.FromSeconds(5)));
+ Assert.Equal(1, controller.CurrentIndex);
+ controller.Stop();
+ }
+
+ [Fact]
+ public void UpcomingSpeech_ReturnsNewsWithinTheLeadTimeWhileOnAir()
+ {
+ AddSongs();
+ var hold = new TaskCompletionSource();
+ var controller = Create((_, token) => hold.Task.WaitAsync(token));
+ controller.CreatePlan(1); // news at 15:00
+ var lead = TimeSpan.FromSeconds(30);
+
+ _now = new DateTime(2026, 11, 23, 14, 59, 40);
+ Assert.Null(controller.UpcomingSpeech(lead, lead)); // not on air
+ controller.Start();
+ Assert.Equal(ScheduleItemKind.News, controller.UpcomingSpeech(lead, lead)!.Kind);
+ Assert.Null(controller.UpcomingSpeech(null, lead)); // news alert switched off
+ _now = new DateTime(2026, 11, 23, 14, 59, 0);
+ Assert.Null(controller.UpcomingSpeech(lead, lead));
+ Assert.NotNull(controller.UpcomingSpeech(TimeSpan.FromSeconds(60), null)); // longer lead time
+ controller.Stop();
+ }
+
[Fact]
public void CreatePlan_ThrowsScheduleExceptionForEmptyLibrary()
{
@@ -146,7 +394,7 @@ public sealed class ScheduleControllerTests : IDisposable
await first.Task.WaitAsync(TimeSpan.FromSeconds(5));
var onAir = Assert.Throws(() => controller.Swap(0, request.Id));
- Assert.Contains("already on air", onAir.Message);
+ Assert.Contains("bereits auf Sendung", onAir.Message);
controller.Swap(1, request.Id);
Assert.Equal(request.Id, controller.Plan[1].Song!.Id);
controller.Stop();