From 5193427629334579a19e9f9fb2eb37b2d19cb902 Mon Sep 17 00:00:00 2001 From: Julian Lechner Date: Mon, 23 Nov 2026 14:22:46 +0100 Subject: [PATCH 01/11] feat(schedule): aim for target minutes and plan from any start time The generator takes targets for ads and moderator talk per hour. It tries several hundred random song picks per half hour, keeps the one that leaves closest to the target, and lets the second half hour make up for the first. A start between two news times gets a lead-in of music. News, ad and moderator items start without a title. Co-Authored-By: Claude Fable 5.2 --- src/Radiosender/Models/ScheduleItem.cs | 9 + src/Radiosender/Services/ScheduleGenerator.cs | 251 ++++++++++++------ .../ScheduleGeneratorTests.cs | 105 +++++++- 3 files changed, 278 insertions(+), 87 deletions(-) diff --git a/src/Radiosender/Models/ScheduleItem.cs b/src/Radiosender/Models/ScheduleItem.cs index acf506d..e8e2d5a 100644 --- a/src/Radiosender/Models/ScheduleItem.cs +++ b/src/Radiosender/Models/ScheduleItem.cs @@ -12,4 +12,13 @@ public enum ScheduleItemKind public record ScheduleItem(ScheduleItemKind Kind, string Title, DateTime Start, TimeSpan Duration, Song? Song = null) { public DateTime End => Start + Duration; + + /// The kind as the user reads it. + public string KindName => Kind switch + { + ScheduleItemKind.News => "Nachrichten", + ScheduleItemKind.Ad => "Werbung", + ScheduleItemKind.Moderator => "Moderation", + _ => "Song", + }; } diff --git a/src/Radiosender/Services/ScheduleGenerator.cs b/src/Radiosender/Services/ScheduleGenerator.cs index 358165a..596c179 100644 --- a/src/Radiosender/Services/ScheduleGenerator.cs +++ b/src/Radiosender/Services/ScheduleGenerator.cs @@ -6,71 +6,115 @@ public record ScheduleOptions { public TimeSpan NewsDuration { get; init; } = TimeSpan.FromMinutes(5); - /// Upper limit for ads and moderator talk together, per hour. - public TimeSpan MaxFillerPerHour { get; init; } = TimeSpan.FromMinutes(20); + /// Target for ads per hour. Met as closely as the song lengths allow. + public TimeSpan AdsPerHour { get; init; } = TimeSpan.FromMinutes(20); - /// Ads and moderator talk planned at least per half hour, so the music is broken up. - public TimeSpan MinFillerPerHalfHour { get; init; } = TimeSpan.FromMinutes(2); + /// Target for moderator talk per hour. Met as closely as the song lengths allow. + public TimeSpan ModeratorPerHour { get; init; } = TimeSpan.FromMinutes(10); - /// Longest run of consecutive ad items. Must be below 20 minutes. + /// Longest single ad item; longer ad time is split and separated by moderator talk or songs. public TimeSpan MaxAdBlock { get; init; } = TimeSpan.FromMinutes(5); - /// Random song picks tried per half hour before giving up. - public int Attempts { get; init; } = 1000; + /// Random song picks tried per half hour; the one closest to the targets wins. + public int Attempts { get; init; } = 400; } public class ScheduleException(string message) : Exception(message); /// -/// Builds the plan in half-hour slots: news at :00 and :30, then random songs, with ads and -/// moderator talk sized so that the last song of each slot ends exactly when the next news starts. +/// Builds the plan in half-hour slots: news at :00 and :30, then random songs with ads and moderator talk +/// in between. The last song of each slot ends exactly when the next news starts, so the ad and moderator +/// time is whatever the songs leave; the generator picks songs that leave as close to the targets as it can +/// and evens out the difference in the second half of the hour. +/// A start between two news times gets a lead-in without news up to the next :00 or :30. /// public class ScheduleGenerator(ScheduleOptions options, Random random) { + /// Can be replaced at any time, e.g. from the settings page; the next plan uses the new values. + public ScheduleOptions Options { get; set; } = options; + private static readonly TimeSpan HalfHour = TimeSpan.FromMinutes(30); + // A pick that misses the target by this little is taken at once. + private static readonly TimeSpan CloseEnough = TimeSpan.FromSeconds(1); + public ScheduleGenerator() : this(new ScheduleOptions(), Random.Shared) { } + /// + /// Plans full hours. They begin at if that is :00 or :30, + /// otherwise at the next :00 or :30 after a lead-in of music. + /// public IReadOnlyList Generate(DateTime start, int hours, IReadOnlyList songs) { + var options = Options; // one consistent set of values for the whole plan if (hours < 1) throw new ArgumentOutOfRangeException(nameof(hours), "At least one full hour is required."); - if (start.Minute != 0 || start.Second != 0 || start.Millisecond != 0 || start.Microsecond != 0) - throw new ArgumentException("The schedule must start at a full hour.", nameof(start)); if (options.MaxAdBlock <= TimeSpan.Zero || options.MaxAdBlock >= TimeSpan.FromMinutes(20)) throw new ArgumentException("MaxAdBlock must be between 0 and 20 minutes.", nameof(options)); var playable = songs.Where(s => s.Duration > TimeSpan.Zero).ToList(); if (playable.Count == 0) - throw new ScheduleException("The music library has no songs to plan with."); + throw new ScheduleException("Die Bibliothek enthält keine Songs zum Planen."); var items = new List(); - for (var slotStart = start; slotStart < start.AddHours(hours); slotStart += HalfHour) + var firstNews = new DateTime((start.Ticks + HalfHour.Ticks - 1) / HalfHour.Ticks * HalfHour.Ticks, start.Kind); + if (firstNews > start) + items.AddRange(BuildLeadIn(options, start, firstNews - start, playable)); + + var adHalf = options.AdsPerHour / 2; + var moderatorHalf = options.ModeratorPerHour / 2; + // How far the :00 slot ended up over (or under) its half of the hour; the :30 slot makes up for it. + var adOver = TimeSpan.Zero; + var moderatorOver = TimeSpan.Zero; + for (var slotStart = firstNews; slotStart < firstNews.AddHours(hours); slotStart += HalfHour) { - items.Add(new ScheduleItem(ScheduleItemKind.News, "News", slotStart, options.NewsDuration)); - items.AddRange(BuildSlot(slotStart + options.NewsDuration, HalfHour - options.NewsDuration, playable)); + if (slotStart.Minute == 0) + adOver = moderatorOver = TimeSpan.Zero; + + var news = Min(options.NewsDuration, HalfHour); + if (news > TimeSpan.Zero) + items.Add(new ScheduleItem(ScheduleItemKind.News, "", slotStart, news)); + var slot = BuildSlot(options, slotStart + news, HalfHour - news, + Max(adHalf - adOver, TimeSpan.Zero), Max(moderatorHalf - moderatorOver, TimeSpan.Zero), playable); + items.AddRange(slot); + + adOver = Sum(slot.Where(i => i.Kind == ScheduleItemKind.Ad)) - adHalf; + moderatorOver = Sum(slot.Where(i => i.Kind == ScheduleItemKind.Moderator)) - moderatorHalf; } return items; } - private List BuildSlot(DateTime slotStart, TimeSpan length, List songs) + private List BuildLeadIn(ScheduleOptions options, DateTime start, TimeSpan length, List songs) { - // Half of the hourly limit per slot keeps every hour within MaxFillerPerHour. - var maxFiller = options.MaxFillerPerHour / 2; - var minFiller = options.MinFillerPerHalfHour < maxFiller ? options.MinFillerPerHalfHour : maxFiller; - - for (var attempt = 0; attempt < options.Attempts; attempt++) + // The targets shrink with the lead-in: half of a half hour gets half of the ads. + var share = length / HalfHour; + try { - var picked = PickSongs(length - minFiller, songs); - var gap = length - Sum(picked); - if (picked.Count > 0 && gap <= maxFiller) - return Arrange(slotStart, picked, BuildFiller(gap)); + return BuildSlot(options, start, length, options.AdsPerHour / 2 * share, options.ModeratorPerHour / 2 * share, songs); } + catch (ScheduleException) when (length <= (options.AdsPerHour + options.ModeratorPerHour) / 2) + { + // Too short for any song: the moderator talks until the news. + return [new ScheduleItem(ScheduleItemKind.Moderator, "", start, length)]; + } + } - throw new ScheduleException( - $"No combination of songs fills the slot at {slotStart:HH:mm} so that the last song ends on time. Add more songs, especially shorter ones."); + private List BuildSlot( + ScheduleOptions options, DateTime slotStart, TimeSpan length, TimeSpan adTarget, TimeSpan moderatorTarget, List songs) + { + if (length <= TimeSpan.Zero) + return []; + var target = Min(adTarget + moderatorTarget, length); + var (picked, gap) = PickBest(options, length, target, songs); + // No song at all is only right when the targets leave no room for music. + if (picked.Count == 0 && target < length) + throw new ScheduleException( + $"Keine Song-Kombination füllt den Abschnitt ab {slotStart:HH:mm} so, dass der letzte Song pünktlich endet. Mehr Songs hinzufügen, vor allem kürzere."); + + var (ads, moderator) = Split(options, gap, adTarget, moderatorTarget); + return Arrange(options, slotStart, picked, ads, moderator, keepFirstSongFirst: false); } /// @@ -78,15 +122,15 @@ public class ScheduleGenerator(ScheduleOptions options, Random random) /// rebuilds the rest of its half-hour slot, so the last song still ends exactly when the next news starts. /// Items before and all later slots stay as they are. /// - /// The song does not fit before the next news, or the rest cannot be filled. + /// The song does not fit before the next news. public IReadOnlyList Replace(IReadOnlyList plan, int index, Song requested, IReadOnlyList songs) { ArgumentOutOfRangeException.ThrowIfNegative(index); ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(index, plan.Count); if (plan[index].Kind == ScheduleItemKind.News) - throw new ScheduleException("News cannot be replaced."); + throw new ScheduleException("Nachrichten können nicht ersetzt werden."); if (requested.Duration <= TimeSpan.Zero) - throw new ScheduleException("The requested song has no duration."); + throw new ScheduleException("Der gewünschte Song hat keine Dauer."); var slotStartIndex = LastIndexOf(plan, index, ScheduleItemKind.News); // -1 if the plan does not start with news var nextNewsIndex = IndexOf(plan, index, ScheduleItemKind.News); @@ -96,27 +140,20 @@ public class ScheduleGenerator(ScheduleOptions options, Random random) if (requested.Duration > length) throw new ScheduleException( - $"\"{requested.Title}\" ({requested.Duration:m\\:ss}) does not fit before the news at {slotEnd:HH:mm}; only {length:m\\:ss} are left. Choose an earlier item."); + $"\"{requested.Title}\" ({requested.Duration:m\\:ss}) passt nicht vor die Nachrichten um {slotEnd:HH:mm}; es sind nur noch {length:m\\:ss} übrig. Ein früheres Element wählen."); + // What the slot has already spent on ads and moderator talk before the request counts against its targets. + var options = Options; var prefix = plan.Take(index).ToList(); - var prefixFiller = Sum(prefix.Skip(slotStartIndex + 1).Where(i => i.Kind is ScheduleItemKind.Ad or ScheduleItemKind.Moderator)); - var maxGap = options.MaxFillerPerHour / 2 - prefixFiller; + var slotPrefix = prefix.Skip(slotStartIndex + 1).ToList(); + var adTarget = Max(options.AdsPerHour / 2 - Sum(slotPrefix.Where(i => i.Kind == ScheduleItemKind.Ad)), TimeSpan.Zero); + var moderatorTarget = Max(options.ModeratorPerHour / 2 - Sum(slotPrefix.Where(i => i.Kind == ScheduleItemKind.Moderator)), TimeSpan.Zero); var playable = songs.Where(s => s.Duration > TimeSpan.Zero).ToList(); - var startWithAd = prefix.Count == 0 || prefix[^1].Kind != ScheduleItemKind.Ad; - for (var attempt = 0; attempt < options.Attempts; attempt++) - { - List picked = [requested, .. PickSongs(length - requested.Duration, playable, requested)]; - var gap = length - Sum(picked); - if (gap <= maxGap) - { - IEnumerable rest = nextNewsIndex < 0 ? [] : plan.Skip(nextNewsIndex); - return [.. prefix, .. Arrange(start, picked, BuildFiller(gap, startWithAd)), .. rest]; - } - } - - throw new ScheduleException( - $"After \"{requested.Title}\" the slot up to {slotEnd:HH:mm} cannot be filled without exceeding the ad limit. Choose another item or song."); + var (picked, gap) = PickBest(options, length, Min(adTarget + moderatorTarget, length), playable, requested); + var (ads, moderator) = Split(options, gap, adTarget, moderatorTarget); + IEnumerable rest = nextNewsIndex < 0 ? [] : plan.Skip(nextNewsIndex); + return [.. prefix, .. Arrange(options, start, picked, ads, moderator, keepFirstSongFirst: true), .. rest]; } private static int IndexOf(IReadOnlyList plan, int from, ScheduleItemKind kind) @@ -133,6 +170,27 @@ public class ScheduleGenerator(ScheduleOptions options, Random random) return -1; } + // Tries random song picks and keeps the one whose leftover time is closest to the target for ads and + // moderator talk. Picks never go over the music time, so the leftover is the target or more. + private (List Songs, TimeSpan Gap) PickBest( + ScheduleOptions options, TimeSpan length, TimeSpan target, List songs, Song? first = null) + { + var fixedTime = first?.Duration ?? TimeSpan.Zero; + var budget = Max(length - fixedTime - target, TimeSpan.Zero); + (List Songs, TimeSpan Gap)? best = null; + for (var attempt = 0; attempt < options.Attempts; attempt++) + { + var more = PickSongs(budget, songs, first); + List picked = first is null ? more : [first, .. more]; + var gap = length - Sum(picked); + if (best is null || gap < best.Value.Gap) + best = (picked, gap); + if (gap - target <= CloseEnough || budget == TimeSpan.Zero) + break; + } + return best ?? ([], length); + } + private List PickSongs(TimeSpan budget, List songs, Song? previous = null) { var picked = new List(); @@ -149,52 +207,95 @@ public class ScheduleGenerator(ScheduleOptions options, Random random) } } - // Alternates ad and moderator items, so ads never run back to back. - private List<(ScheduleItemKind Kind, string Title, TimeSpan Duration)> BuildFiller(TimeSpan gap, bool startWithAd = true) + // Shares the leftover time between ads and moderator talk in the ratio of their targets. + private static (TimeSpan Ads, TimeSpan Moderator) Split(ScheduleOptions options, TimeSpan gap, TimeSpan adTarget, TimeSpan moderatorTarget) { - var filler = new List<(ScheduleItemKind, string, TimeSpan)>(); - var nextIsAd = startWithAd; - while (gap > TimeSpan.Zero) + if (adTarget + moderatorTarget <= TimeSpan.Zero) { - (ScheduleItemKind kind, string title, TimeSpan duration) = nextIsAd - ? Pick(PlaceholderContent.AdSpots, a => (ScheduleItemKind.Ad, a.Title, Min(a.Duration, options.MaxAdBlock))) - : Pick(PlaceholderContent.ModeratorSegments, m => (ScheduleItemKind.Moderator, m.Title, m.Duration)); - duration = Min(duration, gap); // shortcut: the last placeholder is cut to fit; fine while they have no audio - filler.Add((kind, title, duration)); - gap -= duration; - nextIsAd = !nextIsAd; + // This slot has nothing left to aim for; fall back to the hourly ratio, or to talk alone. + adTarget = options.AdsPerHour; + moderatorTarget = options.ModeratorPerHour; + if (adTarget + moderatorTarget <= TimeSpan.Zero) + return (TimeSpan.Zero, gap); } - return filler; + var ads = TimeSpan.FromSeconds(Math.Round(gap.TotalSeconds * (adTarget / (adTarget + moderatorTarget)))); + ads = Min(ads, gap); + return (ads, gap - ads); } - // Spreads the filler between songs; the slot always ends with a song. - private static List Arrange(DateTime start, List songs, List<(ScheduleItemKind Kind, string Title, TimeSpan Duration)> filler) + // Lays out the slot: songs with breaks in between, each break "moderator, ad, moderator, ad ...". + // Ads are cut into pieces of at most MaxAdBlock and never follow each other directly as long as there + // is moderator talk or a song to put between them. The slot always ends with a song. + private static List Arrange( + ScheduleOptions options, DateTime start, List songs, TimeSpan ads, TimeSpan moderator, bool keepFirstSongFirst) { + var adPieces = Pieces(ads, (int)Math.Ceiling(ads / options.MaxAdBlock)); + // One moderator piece in front of every ad piece; without ads, one piece per five minutes of talk. + var moderatorPieces = Pieces(moderator, adPieces.Count > 0 ? adPieces.Count : (int)Math.Ceiling(moderator / TimeSpan.FromMinutes(5))); + var pairs = Math.Max(adPieces.Count, moderatorPieces.Count); + + // A hot swap keeps the requested song at its position, so breaks start after it when another song follows. + var firstBreakSong = keepFirstSongFirst && songs.Count > 1 ? 1 : 0; + var breakSlots = Math.Max(songs.Count - firstBreakSong, 1); + var breaks = Math.Min(pairs, breakSlots); + var items = new List(); var time = start; - var fillerIndex = 0; + void Add(ScheduleItemKind kind, TimeSpan duration, Song? song = null) + { + if (duration <= TimeSpan.Zero) + return; + // News, ads and moderator items start without a title; the user can name them in the timeline. + var title = song is null ? "" : string.IsNullOrWhiteSpace(song.Artist) ? song.Title : $"{song.Artist} - {song.Title}"; + items.Add(new ScheduleItem(kind, title, time, duration, song)); + time += duration; + } + + var pair = 0; + void AddBreak(int number) + { + // Pairs are dealt out evenly; the last break takes what is left. + var until = number == breaks - 1 ? pairs : pairs * (number + 1) / breaks; + for (; pair < until; pair++) + { + if (pair < moderatorPieces.Count) Add(ScheduleItemKind.Moderator, moderatorPieces[pair]); + if (pair < adPieces.Count) Add(ScheduleItemKind.Ad, adPieces[pair]); + } + } + + var nextBreak = 0; for (var i = 0; i < songs.Count; i++) { - // Filler goes before song i; the share grows with i so it ends up spread over the slot. - var until = filler.Count * (i + 1) / songs.Count; - for (; fillerIndex < until; fillerIndex++) - { - var f = filler[fillerIndex]; - items.Add(new ScheduleItem(f.Kind, f.Title, time, f.Duration)); - time += f.Duration; - } - var title = string.IsNullOrWhiteSpace(songs[i].Artist) ? songs[i].Title : $"{songs[i].Artist} - {songs[i].Title}"; - items.Add(new ScheduleItem(ScheduleItemKind.Song, title, time, songs[i].Duration, songs[i])); - time += songs[i].Duration; + // Break n sits before the song at its share of the way through the slot. + while (nextBreak < breaks && i == firstBreakSong + nextBreak * breakSlots / breaks) + AddBreak(nextBreak++); + Add(ScheduleItemKind.Song, songs[i].Duration, songs[i]); } + // No songs at all: the slot is ads and talk only. + while (nextBreak < breaks) + AddBreak(nextBreak++); return items; } - private T Pick(IReadOnlyList source, Func map) => map(source[random.Next(source.Count)]); + // Cuts a time into pieces of whole seconds that differ by at most one second, so no piece grows past + // the limit the count was chosen for. A fraction of a second goes to the last piece. + private static List Pieces(TimeSpan total, int count) + { + var pieces = new List(); + if (total <= TimeSpan.Zero || count < 1) + return pieces; + var seconds = (long)Math.Floor(total.TotalSeconds); + for (var i = 0; i < count; i++) + pieces.Add(TimeSpan.FromSeconds(seconds / count + (i < seconds % count ? 1 : 0))); + pieces[^1] += total - TimeSpan.FromSeconds(seconds); + return pieces; + } private static TimeSpan Sum(IEnumerable songs) => songs.Aggregate(TimeSpan.Zero, (total, s) => total + s.Duration); private static TimeSpan Sum(IEnumerable items) => items.Aggregate(TimeSpan.Zero, (total, i) => total + i.Duration); private static TimeSpan Min(TimeSpan a, TimeSpan b) => a < b ? a : b; + + private static TimeSpan Max(TimeSpan a, TimeSpan b) => a > b ? a : b; } diff --git a/tests/Radiosender.Tests/ScheduleGeneratorTests.cs b/tests/Radiosender.Tests/ScheduleGeneratorTests.cs index d96323d..550146a 100644 --- a/tests/Radiosender.Tests/ScheduleGeneratorTests.cs +++ b/tests/Radiosender.Tests/ScheduleGeneratorTests.cs @@ -75,21 +75,29 @@ public class ScheduleGeneratorTests } } + private static TimeSpan Total(IEnumerable items, ScheduleItemKind kind) => + TimeSpan.FromTicks(items.Where(i => i.Kind == kind).Sum(i => i.Duration.Ticks)); + + // The targets are met as closely as the songs allow; with this library that is within a few seconds per hour. + private static readonly TimeSpan TargetTolerance = TimeSpan.FromSeconds(15); + + private static void AssertNear(TimeSpan expected, TimeSpan actual, string what) => + Assert.True((actual - expected).Duration() <= TargetTolerance, $"{what}: {actual}, target {expected}"); + [Theory] [MemberData(nameof(Seeds))] - public void AdsAndModeratorStayWithinTwentyMinutesPerHour(int seed) + public void AdsAndModeratorMeetTheirTargetsPerHour(int seed) { + var options = new ScheduleOptions(); var items = Generate(seed); for (var hour = 0; hour < 3; hour++) { var from = Start.AddHours(hour); - var filler = items - .Where(i => i.Start >= from && i.Start < from.AddHours(1)) - .Where(i => i.Kind is ScheduleItemKind.Ad or ScheduleItemKind.Moderator) - .Aggregate(TimeSpan.Zero, (sum, i) => sum + i.Duration); + var inHour = items.Where(i => i.Start >= from && i.Start < from.AddHours(1)).ToList(); - Assert.InRange(filler, TimeSpan.FromMinutes(2), TimeSpan.FromMinutes(20)); + AssertNear(options.AdsPerHour, Total(inHour, ScheduleItemKind.Ad), $"ads in hour {hour}"); + AssertNear(options.ModeratorPerHour, Total(inHour, ScheduleItemKind.Moderator), $"moderator in hour {hour}"); } } @@ -97,6 +105,7 @@ public class ScheduleGeneratorTests [MemberData(nameof(Seeds))] public void NoAdBlockIsLongerThanTheConfiguredMaximum(int seed) { + // Moderator talk separates the ad pieces, so ten one-minute ads per half hour never run together. var options = new ScheduleOptions { MaxAdBlock = TimeSpan.FromMinutes(1) }; var block = TimeSpan.Zero; @@ -133,13 +142,87 @@ public class ScheduleGeneratorTests Assert.Throws(() => generator.Generate(Start, 1, [])); } + [Theory] + [MemberData(nameof(Seeds))] + public void Generate_FromAnOddTimeLeadsInWithMusicUpToTheFirstNews(int seed) + { + var start = Start.AddMinutes(37).AddSeconds(12); + var items = new ScheduleGenerator(new ScheduleOptions(), new Random(seed)).Generate(start, 1, Library); + + Assert.Equal(start, items[0].Start); + for (var i = 1; i < items.Count; i++) + Assert.Equal(items[i - 1].End, items[i].Start); + var firstNews = items.ToList().FindIndex(i => i.Kind == ScheduleItemKind.News); + Assert.Equal(Start.AddHours(1), items[firstNews].Start); + Assert.Equal(ScheduleItemKind.Song, items[firstNews - 1].Kind); + Assert.Equal(Start.AddHours(2), items[^1].End); + } + + [Fact] + public void Generate_FillsALeadInTooShortForASongWithModeratorTalk() + { + var start = Start.AddMinutes(28); + var items = new ScheduleGenerator(new ScheduleOptions(), new Random(1)).Generate(start, 1, Library); + + Assert.Equal(ScheduleItemKind.Moderator, items[0].Kind); + Assert.Equal(TimeSpan.FromMinutes(2), items[0].Duration); + Assert.Equal(ScheduleItemKind.News, items[1].Kind); + Assert.Equal(Start.AddMinutes(90), items[^1].End); + } + + [Fact] + public void Generate_LeavesNewsAdAndModeratorTitlesEmpty() + { + var items = Generate(1); + + Assert.All(items, i => Assert.Equal(i.Kind != ScheduleItemKind.Song, i.Title.Length == 0)); + } + + [Theory] + [MemberData(nameof(Seeds))] + public void Generate_FollowsChangedTargets(int seed) + { + var options = new ScheduleOptions + { + NewsDuration = TimeSpan.FromMinutes(3), + AdsPerHour = TimeSpan.FromMinutes(4), + ModeratorPerHour = TimeSpan.FromMinutes(12), + }; + var items = Generate(seed, hours: 2, options); + + Assert.All(items.Where(i => i.Kind == ScheduleItemKind.News), n => Assert.Equal(TimeSpan.FromMinutes(3), n.Duration)); + for (var hour = 0; hour < 2; hour++) + { + var inHour = items.Where(i => i.Start >= Start.AddHours(hour) && i.Start < Start.AddHours(hour + 1)).ToList(); + AssertNear(options.AdsPerHour, Total(inHour, ScheduleItemKind.Ad), $"ads in hour {hour}"); + AssertNear(options.ModeratorPerHour, Total(inHour, ScheduleItemKind.Moderator), $"moderator in hour {hour}"); + } + Assert.Equal(Start.AddHours(2), items[^1].End); + } + + [Fact] + public void Generate_FillsAnHourWithoutMusicWhenTheTargetsTakeAllOfIt() + { + var options = new ScheduleOptions + { + NewsDuration = TimeSpan.FromMinutes(5), + AdsPerHour = TimeSpan.FromMinutes(20), + ModeratorPerHour = TimeSpan.FromMinutes(30), + }; + var items = Generate(1, hours: 1, options); + + Assert.DoesNotContain(items, i => i.Kind == ScheduleItemKind.Song); + Assert.Equal(TimeSpan.FromMinutes(20), Total(items, ScheduleItemKind.Ad)); + Assert.Equal(TimeSpan.FromMinutes(30), Total(items, ScheduleItemKind.Moderator)); + Assert.Equal(Start.AddHours(1), items[^1].End); + } + [Fact] public void Generate_RejectsInvalidInput() { var generator = new ScheduleGenerator(new ScheduleOptions(), new Random(1)); Assert.Throws(() => generator.Generate(Start, 0, Library)); - Assert.Throws(() => generator.Generate(Start.AddMinutes(15), 1, Library)); Assert.Throws(() => new ScheduleGenerator(new ScheduleOptions { MaxAdBlock = TimeSpan.FromMinutes(20) }, new Random(1)).Generate(Start, 1, Library)); } @@ -171,7 +254,7 @@ public class ScheduleGeneratorTests [Theory] [MemberData(nameof(Seeds))] - public void Replace_KeepsFillerLimitsAndNoAdsBackToBack(int seed) + public void Replace_KeepsTheSlotOnTimeAndNoAdsBackToBack(int seed) { var plan = Generate(seed, hours: 1); // Every non-news item in the first half hour, so prefixes with filler are covered too. @@ -182,9 +265,7 @@ public class ScheduleGeneratorTests try { swapped = Generator(seed).Replace(plan, index, Request, Library); } catch (ScheduleException) { continue; } // too little time left before the news - var filler = swapped.Where(i => i.Kind is ScheduleItemKind.Ad or ScheduleItemKind.Moderator) - .Aggregate(TimeSpan.Zero, (sum, i) => sum + i.Duration); - Assert.True(filler <= TimeSpan.FromMinutes(20), $"{filler} filler after swap at {index}"); + Assert.Equal(plan[^1].End, swapped[^1].End); for (var i = 1; i < swapped.Count; i++) Assert.False(swapped[i - 1].Kind == ScheduleItemKind.Ad && swapped[i].Kind == ScheduleItemKind.Ad, $"Ads back to back at {swapped[i].Start:HH:mm:ss}"); @@ -199,7 +280,7 @@ public class ScheduleGeneratorTests var tooLong = Song(98, 25 * 60); var ex = Assert.Throws(() => Generator(1).Replace(plan, beforeNews, tooLong, Library)); - Assert.Contains("does not fit", ex.Message); + Assert.Contains("passt nicht", ex.Message); } [Fact] From 1482402852a8d3194d4f184f86383f4a8c232c43 Mon Sep 17 00:00:00 2001 From: Julian Lechner Date: Mon, 23 Nov 2026 14:22:47 +0100 Subject: [PATCH 02/11] feat(playback): re-time or end the item on air ReplaceCurrent hands the engine a plan in which the running item changed. A news, ad or moderator item then runs for its new length, counted from its start, and a song ends at once. Co-Authored-By: Claude Fable 5.2 --- src/Radiosender/Services/PlaybackEngine.cs | 58 ++++++++++++++++++++-- 1 file changed, 55 insertions(+), 3 deletions(-) diff --git a/src/Radiosender/Services/PlaybackEngine.cs b/src/Radiosender/Services/PlaybackEngine.cs index 250123a..4ef1e5a 100644 --- a/src/Radiosender/Services/PlaybackEngine.cs +++ b/src/Radiosender/Services/PlaybackEngine.cs @@ -27,6 +27,9 @@ public sealed class PlaybackEngine private CancellationTokenSource? _cts; private Task _run = Task.CompletedTask; + // Completed by ReplaceCurrent to wake the wait of the item on air; a new one per wait. + private TaskCompletionSource? _currentChanged; + public PlaybackEngine() : this(MusicPlayer.Instance, Task.Delay, () => DateTime.Now) { } @@ -88,6 +91,24 @@ public sealed class PlaybackEngine } } + /// + /// Switches to while the item at is on air and that item + /// itself changed: a news, ad or moderator item then runs for its new length, counted from when it started, + /// and a song ends at once. Items before must be unchanged. Returns false + /// if that item is not the one on air. + /// + public bool ReplaceCurrent(IReadOnlyList items, int index) + { + lock (_lock) + { + if (!IsRunning || CurrentIndex != index || index >= items.Count) + return false; + Items = items; + _currentChanged?.TrySetResult(); + return true; + } + } + /// Stops playback. Waits until the running schedule has ended. public void Stop() { @@ -151,7 +172,7 @@ public sealed class PlaybackEngine if (item.Kind == ScheduleItemKind.Song && item.Song is not null) await PlaySongAsync(item, token); else - await _delay(item.Duration, token); + await HoldAsync(i, token); } CurrentIndex = -1; @@ -163,6 +184,33 @@ public sealed class PlaybackEngine } } + // Keeps a news, ad or moderator item on air for its length. ReplaceCurrent can change that length + // meanwhile; the wait then starts over with what is left. + private async Task HoldAsync(int index, CancellationToken token) + { + var startedAt = _now(); + while (true) + { + TaskCompletionSource changed; + TimeSpan remaining; + lock (_lock) + { + changed = _currentChanged = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + remaining = Items[index].Duration - (_now() - startedAt); + } + if (remaining <= TimeSpan.Zero) + return; + + using var wait = CancellationTokenSource.CreateLinkedTokenSource(token); + var delay = _delay(remaining, wait.Token); + var done = await Task.WhenAny(delay, changed.Task); + wait.Cancel(); + token.ThrowIfCancellationRequested(); + if (done == delay) + return; + } + } + private async Task PlaySongAsync(ScheduleItem item, CancellationToken token) { var finished = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); @@ -181,13 +229,17 @@ public sealed class PlaybackEngine return; } + TaskCompletionSource changed; + lock (_lock) + changed = _currentChanged = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token); var stuck = _delay(item.Duration + SongGrace, timeout.Token); - var done = await Task.WhenAny(finished.Task, stuck); + // changed: the user ended the song early; the finally block stops the player. + var done = await Task.WhenAny(finished.Task, stuck, changed.Task); timeout.Cancel(); token.ThrowIfCancellationRequested(); if (done == stuck) - ItemFailed?.Invoke(this, (item, new TimeoutException($"Song did not finish in time: {item.Title}"))); + ItemFailed?.Invoke(this, (item, new TimeoutException($"Der Song wurde nicht rechtzeitig fertig: {item.Title}"))); } finally { From 65c0e39e473b11591cadefc2051b177a909d0ac8 Mon Sep 17 00:00:00 2001 From: Julian Lechner Date: Mon, 23 Nov 2026 14:22:47 +0100 Subject: [PATCH 03/11] feat(schedule): add unlimited plans, start from now and timeline edits The controller can plan from a chosen hour or from this moment, keep an unlimited plan five hours ahead, move, remove and edit items, end the item on air, and report the next news or moderator item that is due for a reminder. Co-Authored-By: Claude Fable 5.2 --- .../Controllers/ScheduleController.cs | 218 +++++++++++++-- .../ScheduleControllerTests.cs | 250 +++++++++++++++++- 2 files changed, 445 insertions(+), 23 deletions(-) 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(); From f0726bc9fa028b54c81e68d435fb6b86fedae68c Mon Sep 17 00:00:00 2001 From: Julian Lechner Date: Mon, 23 Nov 2026 14:22:48 +0100 Subject: [PATCH 04/11] feat(settings): store alert and minutes-per-hour settings Settings live in settings.json next to the database. News, moderator talk and ads together can take at most 60 minutes per hour. The app also follows the Windows light, dark or high-contrast theme at startup. Co-Authored-By: Claude Fable 5.2 --- src/Radiosender/App.xaml.cs | 20 ++++- src/Radiosender/Services/AppSettings.cs | 80 ++++++++++++++++++++ tests/Radiosender.Tests/AppSettingsTests.cs | 81 +++++++++++++++++++++ 3 files changed, 180 insertions(+), 1 deletion(-) create mode 100644 src/Radiosender/Services/AppSettings.cs create mode 100644 tests/Radiosender.Tests/AppSettingsTests.cs diff --git a/src/Radiosender/App.xaml.cs b/src/Radiosender/App.xaml.cs index d33ba2d..212796f 100644 --- a/src/Radiosender/App.xaml.cs +++ b/src/Radiosender/App.xaml.cs @@ -11,11 +11,29 @@ public partial class App : Application /// App-wide, so a running broadcast keeps going while the user switches pages. public static ScheduleController Schedule { get; private set; } = null!; + public static AppSettings Settings { get; private set; } = new(); + + private static readonly ScheduleGenerator Generator = new(); + + /// Stores the settings and applies them: alerts at once, minutes per hour from the next plan on. + /// The settings file cannot be written. + /// The settings file cannot be written. + public static void SaveSettings(AppSettings settings) + { + settings.Save(AppSettings.DefaultPath); + Settings = settings; + Generator.Options = settings.ToScheduleOptions(); + } + protected override void OnStartup(StartupEventArgs e) { + Settings = AppSettings.Load(AppSettings.DefaultPath); + Generator.Options = Settings.ToScheduleOptions(); // Creates the database file and table on first start. Songs = new SongRepository(SongRepository.DefaultDatabasePath); - Schedule = new ScheduleController(Songs, new ScheduleGenerator(), new PlaybackEngine(), () => DateTime.Now); + Schedule = new ScheduleController(Songs, Generator, new PlaybackEngine(), () => DateTime.Now); + // Follow the Windows setting: light, dark or a high-contrast theme. + Wpf.Ui.Appearance.ApplicationThemeManager.ApplySystemTheme(); base.OnStartup(e); } diff --git a/src/Radiosender/Services/AppSettings.cs b/src/Radiosender/Services/AppSettings.cs new file mode 100644 index 0000000..c309ecc --- /dev/null +++ b/src/Radiosender/Services/AppSettings.cs @@ -0,0 +1,80 @@ +using System.IO; +using System.Text.Json; + +namespace Radiosender.Services; + +/// What the user can change on the Settings page. The defaults are the values the app shipped with. +public record AppSettings +{ + public const int MinAlertSeconds = 5; + public const int MaxAlertSeconds = 300; + + public bool NewsAlert { get; init; } = true; + + /// How long before a news item the reminder appears. + public int NewsAlertSeconds { get; init; } = 30; + + public bool NewsAlertSound { get; init; } = true; + + public bool ModeratorAlert { get; init; } = true; + + /// How long before a moderator item the reminder appears. + public int ModeratorAlertSeconds { get; init; } = 30; + + public bool ModeratorAlertSound { get; init; } = true; + + /// News time per hour, split over the two news at :00 and :30. + public int NewsMinutesPerHour { get; init; } = 10; + + /// Target; the plan gets as close as the song lengths allow. + public int ModeratorMinutesPerHour { get; init; } = 10; + + /// Target; the plan gets as close as the song lengths allow. + public int AdMinutesPerHour { get; init; } = 20; + + public static string DefaultPath { get; } = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Radiosender", "settings.json"); + + /// The first problem with these values as a message for the user, or null when they are fine. + public string? Validate() + { + if (NewsAlertSeconds is < MinAlertSeconds or > MaxAlertSeconds || ModeratorAlertSeconds is < MinAlertSeconds or > MaxAlertSeconds) + return $"Die Hinweiszeit muss zwischen {MinAlertSeconds} und {MaxAlertSeconds} Sekunden liegen."; + if (NewsMinutesPerHour < 2) + return "Nachrichten brauchen mindestens 2 Minuten pro Stunde."; + if (ModeratorMinutesPerHour < 0 || AdMinutesPerHour < 0) + return "Minuten pro Stunde dürfen nicht negativ sein."; + if (NewsMinutesPerHour + ModeratorMinutesPerHour + AdMinutesPerHour > 60) + return "Nachrichten, Moderation und Werbung dürfen zusammen höchstens 60 Minuten pro Stunde dauern."; + return null; + } + + public ScheduleOptions ToScheduleOptions() => new() + { + NewsDuration = TimeSpan.FromMinutes(NewsMinutesPerHour / 2.0), + AdsPerHour = TimeSpan.FromMinutes(AdMinutesPerHour), + ModeratorPerHour = TimeSpan.FromMinutes(ModeratorMinutesPerHour), + }; + + /// Reads the settings; a missing, unreadable or invalid file gives the defaults. + public static AppSettings Load(string path) + { + try + { + var settings = JsonSerializer.Deserialize(File.ReadAllText(path)); + return settings is not null && settings.Validate() is null ? settings : new AppSettings(); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException) + { + return new AppSettings(); + } + } + + /// The file cannot be written. + /// The file cannot be written. + public void Save(string path) + { + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllText(path, JsonSerializer.Serialize(this, new JsonSerializerOptions { WriteIndented = true })); + } +} diff --git a/tests/Radiosender.Tests/AppSettingsTests.cs b/tests/Radiosender.Tests/AppSettingsTests.cs new file mode 100644 index 0000000..b393ae9 --- /dev/null +++ b/tests/Radiosender.Tests/AppSettingsTests.cs @@ -0,0 +1,81 @@ +using Radiosender.Services; + +namespace Radiosender.Tests; + +public sealed class AppSettingsTests : IDisposable +{ + private readonly string _directory = Path.Combine(Path.GetTempPath(), "radiosender-tests", Guid.NewGuid().ToString("N")); + + private string File => Path.Combine(_directory, "settings.json"); + + public void Dispose() + { + if (Directory.Exists(_directory)) + Directory.Delete(_directory, recursive: true); + } + + [Fact] + public void Defaults_AreValidAndMatchTheOriginalSchedule() + { + var defaults = new AppSettings(); + + Assert.Null(defaults.Validate()); + Assert.Equal(TimeSpan.FromMinutes(5), defaults.ToScheduleOptions().NewsDuration); + Assert.Equal(TimeSpan.FromMinutes(20), defaults.ToScheduleOptions().AdsPerHour); + Assert.Equal(TimeSpan.FromMinutes(10), defaults.ToScheduleOptions().ModeratorPerHour); + Assert.True(defaults.NewsAlert && defaults.ModeratorAlert); + Assert.True(defaults.NewsAlertSound && defaults.ModeratorAlertSound); + Assert.Equal(30, defaults.NewsAlertSeconds); + } + + [Fact] + public void SaveAndLoad_RoundTrip() + { + var settings = new AppSettings { NewsAlert = false, ModeratorAlertSeconds = 45, ModeratorAlertSound = true, AdMinutesPerHour = 6 }; + + settings.Save(File); + + Assert.Equal(settings, AppSettings.Load(File)); + } + + [Fact] + public void Load_FallsBackToDefaultsForMissingBrokenOrInvalidFiles() + { + Assert.Equal(new AppSettings(), AppSettings.Load(File)); + + Directory.CreateDirectory(_directory); + System.IO.File.WriteAllText(File, "{ not json"); + Assert.Equal(new AppSettings(), AppSettings.Load(File)); + + System.IO.File.WriteAllText(File, """{"AdMinutesPerHour":500}"""); + Assert.Equal(new AppSettings(), AppSettings.Load(File)); + } + + [Theory] + [InlineData(10, 30, 20)] // exactly one hour + [InlineData(2, 0, 0)] + public void Validate_AcceptsUpToSixtyMinutesTogether(int news, int moderator, int ads) + { + Assert.Null(new AppSettings { NewsMinutesPerHour = news, ModeratorMinutesPerHour = moderator, AdMinutesPerHour = ads }.Validate()); + } + + [Theory] + [InlineData(4, 30, 10, 10, 10)] // alert too early + [InlineData(30, 301, 10, 10, 10)] // alert too late + [InlineData(30, 30, 1, 10, 10)] // too little news + [InlineData(30, 30, 10, 25, 26)] // more than 60 minutes together + [InlineData(30, 30, 10, -1, 5)] // negative + public void Validate_ReportsValuesOutOfRange(int newsSeconds, int moderatorSeconds, int news, int moderator, int ads) + { + var settings = new AppSettings + { + NewsAlertSeconds = newsSeconds, + ModeratorAlertSeconds = moderatorSeconds, + NewsMinutesPerHour = news, + ModeratorMinutesPerHour = moderator, + AdMinutesPerHour = ads, + }; + + Assert.NotNull(settings.Validate()); + } +} From 44d07a10df9bf4e3aef9b880b6bf3703795fb8cd Mon Sep 17 00:00:00 2001 From: Julian Lechner Date: Mon, 23 Nov 2026 14:22:49 +0100 Subject: [PATCH 05/11] fix(openverse): decode HTML entities in titles and creators Openverse sends some texts HTML-encoded, so "Angus & Friends" showed up as it came. Error messages are in German like the rest of the interface. Co-Authored-By: Claude Fable 5.2 --- .../Controllers/OpenverseController.cs | 4 ++-- src/Radiosender/Models/OpenverseTrack.cs | 9 +++++---- src/Radiosender/Services/OpenverseClient.cs | 20 +++++++++---------- tests/Radiosender.Tests/OpenverseTests.cs | 16 ++++++++++++--- 4 files changed, 30 insertions(+), 19 deletions(-) diff --git a/src/Radiosender/Controllers/OpenverseController.cs b/src/Radiosender/Controllers/OpenverseController.cs index a2301b7..4336684 100644 --- a/src/Radiosender/Controllers/OpenverseController.cs +++ b/src/Radiosender/Controllers/OpenverseController.cs @@ -16,9 +16,9 @@ public class OpenverseController(OpenverseClient client, SongRepository songs) public async Task ImportAsync(OpenverseTrack track, CancellationToken cancellationToken = default) { if (track.Duration is not { } duration) - throw new OpenverseException("This result has no duration and cannot be imported."); + throw new OpenverseException("Dieses Ergebnis hat keine Dauer und kann nicht importiert werden."); if (track.Id.Length > 0 && ImportedIds().Contains(track.Id)) - throw new OpenverseException($"\"{track.Title}\" is already in the library."); + throw new OpenverseException($"\"{track.Title}\" ist bereits in der Bibliothek."); var path = await client.DownloadAsync(track, cancellationToken); var song = new Song diff --git a/src/Radiosender/Models/OpenverseTrack.cs b/src/Radiosender/Models/OpenverseTrack.cs index 157ac31..a234030 100644 --- a/src/Radiosender/Models/OpenverseTrack.cs +++ b/src/Radiosender/Models/OpenverseTrack.cs @@ -3,17 +3,18 @@ using System.Text.Json.Serialization; namespace Radiosender.Models; /// One audio result of the Openverse search API (fields as documented at api.openverse.org/v1). +/// Openverse sends some texts HTML-encoded (&amp;), so the text fields decode on assignment. public class OpenverseTrack { public string Id { get; init; } = ""; - public string Title { get; init; } = ""; - public string? Creator { get; init; } + public string Title { get; init => field = System.Net.WebUtility.HtmlDecode(value); } = ""; + public string? Creator { get; init => field = System.Net.WebUtility.HtmlDecode(value); } public string Url { get; init; } = ""; [JsonPropertyName("filetype")] public string? FileType { get; init; } public string License { get; init; } = ""; public string? LicenseVersion { get; init; } - public string? Attribution { get; init; } + public string? Attribution { get; init => field = System.Net.WebUtility.HtmlDecode(value); } /// Length in milliseconds; Openverse leaves it empty for some results. [JsonPropertyName("duration")] @@ -25,7 +26,7 @@ public class OpenverseTrack /// Songs need a duration for scheduling, so results without one cannot be imported. public bool CanImport => Duration is not null; - public string DurationText => Duration?.ToString(@"m\:ss") ?? "unknown"; + public string DurationText => Duration?.ToString(@"m\:ss") ?? "unbekannt"; /// Readable license name, for example "CC BY 4.0", "CC0 1.0" or "Public Domain Mark 1.0". public string LicenseName => License.ToLowerInvariant() switch diff --git a/src/Radiosender/Services/OpenverseClient.cs b/src/Radiosender/Services/OpenverseClient.cs index 7d491f7..c93ef54 100644 --- a/src/Radiosender/Services/OpenverseClient.cs +++ b/src/Radiosender/Services/OpenverseClient.cs @@ -46,7 +46,7 @@ public class OpenverseClient(HttpClient http, string musicFolder) } catch (Exception e) when (e is not OpenverseException && !cancellationToken.IsCancellationRequested) { - throw Wrap(e, "Openverse search failed"); + throw Wrap(e, "Openverse-Suche fehlgeschlagen"); } } @@ -58,7 +58,7 @@ public class OpenverseClient(HttpClient http, string musicFolder) public async Task DownloadAsync(OpenverseTrack track, CancellationToken cancellationToken = default) { if (!Uri.TryCreate(track.Url, UriKind.Absolute, out var uri) || uri.Scheme != Uri.UriSchemeHttps) - throw new OpenverseException("Only https downloads are allowed."); + throw new OpenverseException("Nur https-Downloads sind erlaubt."); using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); timeout.CancelAfter(DownloadTimeout); @@ -68,7 +68,7 @@ public class OpenverseClient(HttpClient http, string musicFolder) using var response = await http.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead, timeout.Token); EnsureSuccess(response); if (response.Content.Headers.ContentLength > MaxDownloadBytes) - throw new OpenverseException("The file is larger than 50 MB."); + throw new OpenverseException("Die Datei ist größer als 50 MB."); Directory.CreateDirectory(musicFolder); await using var file = CreateUniqueFile(track, out path); @@ -80,11 +80,11 @@ public class OpenverseClient(HttpClient http, string musicFolder) { total += read; if (total > MaxDownloadBytes) - throw new OpenverseException("The file is larger than 50 MB."); + throw new OpenverseException("Die Datei ist größer als 50 MB."); await file.WriteAsync(buffer.AsMemory(0, read), timeout.Token); } if (total == 0) - throw new OpenverseException("The download was empty."); + throw new OpenverseException("Der Download war leer."); return path; } catch (Exception e) @@ -94,7 +94,7 @@ public class OpenverseClient(HttpClient http, string musicFolder) File.Delete(path); if (e is OpenverseException || cancellationToken.IsCancellationRequested) throw; - throw Wrap(e, "Download failed"); + throw Wrap(e, "Download fehlgeschlagen"); } } @@ -120,15 +120,15 @@ public class OpenverseClient(HttpClient http, string musicFolder) private static void EnsureSuccess(HttpResponseMessage response) { if (response.StatusCode == HttpStatusCode.TooManyRequests) - throw new OpenverseException("Openverse rate limit reached (anonymous: 20 requests per minute, 200 per day). Please try again later."); + throw new OpenverseException("Openverse-Limit erreicht (anonym: 20 Anfragen pro Minute, 200 pro Tag). Bitte später erneut versuchen."); if (!response.IsSuccessStatusCode) - throw new OpenverseException($"Openverse returned HTTP {(int)response.StatusCode}."); + throw new OpenverseException($"Openverse hat HTTP {(int)response.StatusCode} geliefert."); } private static OpenverseException Wrap(Exception e, string action) => e switch { - OperationCanceledException => new OpenverseException($"{action}: the request timed out.", e), - JsonException => new OpenverseException($"{action}: unexpected response.", e), + OperationCanceledException => new OpenverseException($"{action}: Zeitüberschreitung der Anfrage.", e), + JsonException => new OpenverseException($"{action}: unerwartete Antwort.", e), _ => new OpenverseException($"{action}: {e.Message}", e), }; diff --git a/tests/Radiosender.Tests/OpenverseTests.cs b/tests/Radiosender.Tests/OpenverseTests.cs index 6e9fed2..4ae80a7 100644 --- a/tests/Radiosender.Tests/OpenverseTests.cs +++ b/tests/Radiosender.Tests/OpenverseTests.cs @@ -52,6 +52,16 @@ public sealed class OpenverseTests : IDisposable private string[] MusicFiles() => Directory.Exists(MusicFolder) ? Directory.GetFiles(MusicFolder) : []; + [Fact] + public void Track_DecodesHtmlEntitiesInTexts() + { + var track = new OpenverseTrack { Title = "Rock & Roll", Creator = "Angus & Friends", Attribution = ""Rock" by Angus" }; + + Assert.Equal("Rock & Roll", track.Title); + Assert.Equal("Angus & Friends", track.Creator); + Assert.Equal("\"Rock\" by Angus", track.Attribution); + } + [Fact] public async Task Search_ParsesResults() { @@ -87,7 +97,7 @@ public sealed class OpenverseTests : IDisposable var error = await Assert.ThrowsAsync(() => client.SearchAsync("x")); - Assert.Contains("rate limit", error.Message); + Assert.Contains("Limit erreicht", error.Message); } [Fact] @@ -101,7 +111,7 @@ public sealed class OpenverseTests : IDisposable var error = await Assert.ThrowsAsync(() => client.SearchAsync("x")); - Assert.Contains("timed out", error.Message); + Assert.Contains("Zeitüberschreitung", error.Message); } [Fact] @@ -228,7 +238,7 @@ public sealed class OpenverseTests : IDisposable var error = await Assert.ThrowsAsync(() => controller.ImportAsync(Track())); - Assert.Contains("already in the library", error.Message); + Assert.Contains("bereits in der Bibliothek", error.Message); Assert.Equal(1, downloads); Assert.Single(songs.GetAll()); Assert.Single(MusicFiles()); From b8f5a3e46904c638e13080e034f9a167178156aa Mon Sep 17 00:00:00 2001 From: Julian Lechner Date: Mon, 23 Nov 2026 14:22:49 +0100 Subject: [PATCH 06/11] feat(i18n): translate import and player messages to German Co-Authored-By: Claude Fable 5.2 --- src/Radiosender/Controllers/UploadController.cs | 6 +++--- src/Radiosender/Services/MusicPlayer.cs | 4 ++-- src/Radiosender/Services/SongImportService.cs | 8 ++++---- tests/Radiosender.Tests/SongImportServiceTests.cs | 2 +- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/Radiosender/Controllers/UploadController.cs b/src/Radiosender/Controllers/UploadController.cs index 0b3cc66..15c71ca 100644 --- a/src/Radiosender/Controllers/UploadController.cs +++ b/src/Radiosender/Controllers/UploadController.cs @@ -8,7 +8,7 @@ public record UploadResult(bool Success, string Message, Song? Song = null); public class UploadController(SongImportService importService) { - public static string FileDialogFilter { get; } = "Audio files (*.mp3;*.wav)|*.mp3;*.wav"; + public static string FileDialogFilter { get; } = "Audiodateien (*.mp3;*.wav)|*.mp3;*.wav"; /// Imports one file; failures come back as a result, so a batch can go on with the next file. public UploadResult Upload(string filePath) @@ -16,7 +16,7 @@ public class UploadController(SongImportService importService) try { var song = importService.Import(filePath); - return new UploadResult(true, $"\"{song.Title}\" ({(int)song.Duration.TotalMinutes}:{song.Duration.Seconds:00}) was added to the library.", song); + return new UploadResult(true, $"\"{song.Title}\" ({(int)song.Duration.TotalMinutes}:{song.Duration.Seconds:00}) wurde zur Bibliothek hinzugefügt.", song); } catch (SongImportException e) { @@ -24,7 +24,7 @@ public class UploadController(SongImportService importService) } catch (Exception e) { - return new UploadResult(false, $"The song could not be saved: {e.Message}"); + return new UploadResult(false, $"Der Song konnte nicht gespeichert werden: {e.Message}"); } } } diff --git a/src/Radiosender/Services/MusicPlayer.cs b/src/Radiosender/Services/MusicPlayer.cs index eb51a31..f4d5b09 100644 --- a/src/Radiosender/Services/MusicPlayer.cs +++ b/src/Radiosender/Services/MusicPlayer.cs @@ -80,7 +80,7 @@ public sealed class MusicPlayer : IAudioPlayer Release(); if (!File.Exists(filePath)) - throw new FileNotFoundException($"Audio file not found: {filePath}", filePath); + throw new FileNotFoundException($"Audiodatei nicht gefunden: {filePath}", filePath); try { @@ -88,7 +88,7 @@ public sealed class MusicPlayer : IAudioPlayer } catch (Exception ex) when (ex is not OutOfMemoryException) { - throw new InvalidDataException($"Cannot read audio file: {filePath}", ex); + throw new InvalidDataException($"Audiodatei kann nicht gelesen werden: {filePath}", ex); } try diff --git a/src/Radiosender/Services/SongImportService.cs b/src/Radiosender/Services/SongImportService.cs index 00caad6..4787c32 100644 --- a/src/Radiosender/Services/SongImportService.cs +++ b/src/Radiosender/Services/SongImportService.cs @@ -19,7 +19,7 @@ public class SongImportService(SongRepository songs, string musicDirectory) public Song Import(string sourcePath) { if (!SupportedExtensions.Contains(Path.GetExtension(sourcePath).ToLowerInvariant())) - throw new SongImportException("Only MP3 and WAV files are supported."); + throw new SongImportException("Nur MP3- und WAV-Dateien werden unterstützt."); Directory.CreateDirectory(musicDirectory); var targetPath = GetUniqueTargetPath(Path.GetFileName(sourcePath)); @@ -29,7 +29,7 @@ public class SongImportService(SongRepository songs, string musicDirectory) } catch (Exception e) when (e is IOException or UnauthorizedAccessException) { - throw new SongImportException($"The file could not be read: {e.Message}", e); + throw new SongImportException($"Die Datei konnte nicht gelesen werden: {e.Message}", e); } try @@ -75,11 +75,11 @@ public class SongImportService(SongRepository songs, string musicDirectory) catch (Exception e) { // NAudio and Media Foundation throw many unrelated exception types for corrupt files. - throw new SongImportException("The file is not a readable MP3 or WAV file.", e); + throw new SongImportException("Die Datei ist keine lesbare MP3- oder WAV-Datei.", e); } if (duration <= TimeSpan.Zero) - throw new SongImportException("The file contains no audio."); + throw new SongImportException("Die Datei enthält kein Audio."); return duration; } diff --git a/tests/Radiosender.Tests/SongImportServiceTests.cs b/tests/Radiosender.Tests/SongImportServiceTests.cs index 5628463..2c1c240 100644 --- a/tests/Radiosender.Tests/SongImportServiceTests.cs +++ b/tests/Radiosender.Tests/SongImportServiceTests.cs @@ -126,6 +126,6 @@ public sealed class SongImportServiceTests : IDisposable Assert.Equal([true, false, true], results.Select(r => r.Success)); Assert.Equal("first", results[0].Song!.Title); Assert.Null(results[1].Song); - Assert.Contains("MP3 and WAV", results[1].Message); + Assert.Contains("MP3- und WAV", results[1].Message); Assert.Equal(2, _repository.GetAll().Count); }} From d7388fbfc3b3f4053d014313242c1f57e8baa400 Mon Sep 17 00:00:00 2001 From: Julian Lechner Date: Mon, 23 Nov 2026 14:22:50 +0100 Subject: [PATCH 07/11] feat(library): simplify the library page and fit columns to their text GridColumns widens text columns to the longest entry over all rows, since the lists are virtualized and the built-in auto width only sees visible rows. The page loses its license and attribution columns, gets Enter and Delete on the list, and is in German. Co-Authored-By: Claude Fable 5.2 --- src/Radiosender/Views/GridColumns.cs | 83 +++++++++++++++++++ src/Radiosender/Views/Pages/LibraryPage.xaml | 29 ++++--- .../Views/Pages/LibraryPage.xaml.cs | 18 +++- src/Radiosender/Views/SongEditWindow.xaml | 20 ++--- 4 files changed, 121 insertions(+), 29 deletions(-) create mode 100644 src/Radiosender/Views/GridColumns.cs diff --git a/src/Radiosender/Views/GridColumns.cs b/src/Radiosender/Views/GridColumns.cs new file mode 100644 index 0000000..095ffec --- /dev/null +++ b/src/Radiosender/Views/GridColumns.cs @@ -0,0 +1,83 @@ +using System.Globalization; +using System.Runtime.CompilerServices; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Media; + +namespace Radiosender.Views; + +/// Sizes the text columns of a list so that every row can be read in full. +public static class GridColumns +{ + // Cell padding on both sides plus a little air, so the text never touches the next column. + private const double Slack = 28; + + // Rows use this size when no row exists yet to ask. + private const double DefaultFontSize = 14; + + // The width from the XAML stays the minimum, so an empty or short list keeps its designed look. + private static readonly ConditionalWeakTable MinWidths = []; + + // Laying out text is the slow part and the same titles come up on every refresh, so widths are remembered. + // All lists share one font. shortcut: never trimmed; clear it if libraries reach hundreds of thousands of songs. + private static readonly Dictionary TextWidths = []; + + /// + /// Widens each column with a to its longest text over + /// all rows, not only the visible ones: the lists are virtualized, so the built-in auto width would miss + /// rows that are scrolled out of view. Columns with a cell template keep their width, and so do columns + /// with a string format: those show times, which always have the same length. + /// + public static void Fit(ListView list) + { + if (list.View is not GridView view) + return; + + // The rows have their own font size, so a realized row is asked rather than the list. + var row = list.ItemContainerGenerator.ContainerFromIndex(0) as Control; + var typeface = new Typeface(row?.FontFamily ?? list.FontFamily, FontStyles.Normal, FontWeights.Normal, FontStretches.Normal); + var fontSize = row?.FontSize ?? DefaultFontSize; + var pixelsPerDip = VisualTreeHelper.GetDpi(list).PixelsPerDip; + + foreach (var column in view.Columns) + { + if (column.DisplayMemberBinding is not Binding { StringFormat: null, Path.Path: { } path }) + continue; + var min = (double)MinWidths.GetValue(column, c => double.IsNaN(c.Width) ? 0d : c.Width); + var properties = path.Split('.'); + + var widest = 0d; + foreach (var item in list.Items) + { + var text = Text(item, properties); + if (text.Length == 0) + continue; + if (!TextWidths.TryGetValue(text, out var width)) + { + width = new FormattedText(text, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, + typeface, fontSize, Brushes.Black, pixelsPerDip).WidthIncludingTrailingWhitespace; + TextWidths[text] = width; + } + widest = Math.Max(widest, width); + } + + var fitted = Math.Max(min, Math.Ceiling(widest + Slack)); + if (column.Width != fitted) // setting it triggers a layout pass + column.Width = fitted; + } + } + + // Follows a simple property path such as "Item.Title". A binding on a probe element would not do: + // it only resolves once the element is part of the window. + private static string Text(object? value, string[] properties) + { + foreach (var property in properties) + { + value = value?.GetType().GetProperty(property)?.GetValue(value); + if (value is null) + return ""; + } + return value?.ToString() ?? ""; + } +} diff --git a/src/Radiosender/Views/Pages/LibraryPage.xaml b/src/Radiosender/Views/Pages/LibraryPage.xaml index dcf4e56..8b38fa6 100644 --- a/src/Radiosender/Views/Pages/LibraryPage.xaml +++ b/src/Radiosender/Views/Pages/LibraryPage.xaml @@ -2,7 +2,9 @@ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml" - Title="Library" + Title="Bibliothek" + Foreground="{DynamicResource TextFillColorPrimaryBrush}" + ScrollViewer.CanContentScroll="False" Loaded="OnLoaded"> @@ -11,26 +13,24 @@ - - - + @@ -40,18 +40,17 @@ SelectionMode="Single" AutomationProperties.Name="Songs" SelectionChanged="OnSelectionChanged" - MouseDoubleClick="OnEdit"> + MouseDoubleClick="OnEdit" + KeyDown="OnListKeyDown"> - - - + + + - - @@ -61,7 +60,7 @@ Margin="0,48,0,0" HorizontalAlignment="Center" VerticalAlignment="Top" - Text="No songs found." + Foreground="{DynamicResource TextFillColorSecondaryBrush}" Visibility="Collapsed" /> diff --git a/src/Radiosender/Views/Pages/LibraryPage.xaml.cs b/src/Radiosender/Views/Pages/LibraryPage.xaml.cs index 43a7857..ff45ae7 100644 --- a/src/Radiosender/Views/Pages/LibraryPage.xaml.cs +++ b/src/Radiosender/Views/Pages/LibraryPage.xaml.cs @@ -27,9 +27,19 @@ public partial class LibraryPage : Page { var songs = _controller.Search(SearchBox.Text); SongList.ItemsSource = songs; + GridColumns.Fit(SongList); + EmptyText.Text = string.IsNullOrWhiteSpace(SearchBox.Text) + ? "Noch keine Songs. Musik auf der Seite Import hinzufügen." + : "Kein Song passt zur Suche."; EmptyText.Visibility = songs.Count == 0 ? Visibility.Visible : Visibility.Collapsed; } + private void OnListKeyDown(object sender, System.Windows.Input.KeyEventArgs e) + { + if (e.Key == System.Windows.Input.Key.Enter) OnEdit(sender, e); + else if (e.Key == System.Windows.Input.Key.Delete) OnDelete(sender, e); + } + private void OnEdit(object sender, RoutedEventArgs e) { if (Selected is not { } song) @@ -48,10 +58,10 @@ public partial class LibraryPage : Page var result = await new MessageBox { - Title = "Delete song", - Content = $"Delete \"{song.Title}\" by {song.Artist} from the library?", - PrimaryButtonText = "Delete", - CloseButtonText = "Cancel", + Title = "Song löschen", + Content = $"\"{song.Title}\" von {song.Artist} aus der Bibliothek löschen?", + PrimaryButtonText = "Löschen", + CloseButtonText = "Abbrechen", }.ShowDialogAsync(); if (result != Wpf.Ui.Controls.MessageBoxResult.Primary) diff --git a/src/Radiosender/Views/SongEditWindow.xaml b/src/Radiosender/Views/SongEditWindow.xaml index f0537ea..c842a6a 100644 --- a/src/Radiosender/Views/SongEditWindow.xaml +++ b/src/Radiosender/Views/SongEditWindow.xaml @@ -2,7 +2,7 @@ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml" - Title="Edit song" + Title="Song bearbeiten" Width="460" SizeToContent="Height" ResizeMode="NoResize" ShowInTaskbar="False" @@ -11,30 +11,30 @@ WindowStartupLocation="CenterOwner" FocusManager.FocusedElement="{Binding ElementName=TitleBox}"> - + - From d6a45cafa6a14230cd2f456d083a659d1beb878f Mon Sep 17 00:00:00 2001 From: Julian Lechner Date: Mon, 23 Nov 2026 14:22:51 +0100 Subject: [PATCH 08/11] feat(import): batch import, working preview and a leaner page Several Openverse results can be selected and imported in one go. The preview streams through NAudio, because the WPF MediaPlayer cannot open https URLs. The list of imported songs appears only once there is one. Co-Authored-By: Claude Fable 5.2 --- src/Radiosender/Views/Pages/ImportPage.xaml | 148 +++++++--------- .../Views/Pages/ImportPage.xaml.cs | 160 +++++++++++++----- 2 files changed, 183 insertions(+), 125 deletions(-) diff --git a/src/Radiosender/Views/Pages/ImportPage.xaml b/src/Radiosender/Views/Pages/ImportPage.xaml index ee0e6af..84eceeb 100644 --- a/src/Radiosender/Views/Pages/ImportPage.xaml +++ b/src/Radiosender/Views/Pages/ImportPage.xaml @@ -3,20 +3,19 @@ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml" Title="Import" + Foreground="{DynamicResource TextFillColorPrimaryBrush}" + ScrollViewer.CanContentScroll="False" Unloaded="OnUnloaded"> - + - - - - + - + @@ -26,7 +25,7 @@ + Stroke="{DynamicResource ControlStrongStrokeColorDefaultBrush}" /> - - + Text="MP3- oder WAV-Dateien hier ablegen" /> @@ -60,7 +55,7 @@ + AutomationProperties.Name="Import-Fortschritt" /> @@ -81,14 +76,14 @@ @@ -98,34 +93,25 @@ - - - - - - - - - - - + + + + - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Radiosender/Views/Pages/ImportPage.xaml.cs b/src/Radiosender/Views/Pages/ImportPage.xaml.cs index 1a593ef..a58aba0 100644 --- a/src/Radiosender/Views/Pages/ImportPage.xaml.cs +++ b/src/Radiosender/Views/Pages/ImportPage.xaml.cs @@ -3,8 +3,8 @@ using System.IO; using System.Windows; using System.Windows.Controls; using System.Windows.Input; -using System.Windows.Media; using Microsoft.Win32; +using NAudio.Wave; using Radiosender.Controllers; using Radiosender.Models; using Radiosender.Services; @@ -23,21 +23,22 @@ public partial class ImportPage : Page new(new SongImportService(App.Songs, SongImportService.DefaultMusicDirectory)); private readonly ObservableCollection _session = []; - private readonly MediaPlayer _preview = new(); + // Preview has its own output, so it never interrupts a running broadcast. + private WaveOut? _previewOutput; + private MediaFoundationReader? _previewReader; + private int _previewId; // changes on every start and stop; a late callback with an old id is ignored private bool _uploading; private bool _busy; + private bool _previewing; public ImportPage() { InitializeComponent(); Session.ItemsSource = _session; _session.CollectionChanged += (_, _) => - SessionEmpty.Visibility = _session.Count == 0 ? Visibility.Visible : Visibility.Collapsed; - _preview.MediaEnded += (_, _) => OnStop(this, new RoutedEventArgs()); - _preview.MediaFailed += (_, e) => { - OnStop(this, new RoutedEventArgs()); - Show(InfoBarSeverity.Error, "Preview failed", e.ErrorException.Message); + SessionPanel.Visibility = _session.Count == 0 ? Visibility.Collapsed : Visibility.Visible; + GridColumns.Fit(Session); }; } @@ -54,12 +55,12 @@ public partial class ImportPage : Page { var ok = !_uploading && e.Data.GetDataPresent(DataFormats.FileDrop); e.Effects = ok ? DragDropEffects.Copy : DragDropEffects.None; - DropBorder.SetResourceReference(System.Windows.Shapes.Shape.StrokeProperty, ok ? "AccentTextFillColorPrimaryBrush" : "TextFillColorTertiaryBrush"); + DropBorder.SetResourceReference(System.Windows.Shapes.Shape.StrokeProperty, ok ? "AccentTextFillColorPrimaryBrush" : "ControlStrongStrokeColorDefaultBrush"); e.Handled = true; } private void OnDragLeave(object sender, DragEventArgs e) => - DropBorder.SetResourceReference(System.Windows.Shapes.Shape.StrokeProperty, "TextFillColorTertiaryBrush"); + DropBorder.SetResourceReference(System.Windows.Shapes.Shape.StrokeProperty, "ControlStrongStrokeColorDefaultBrush"); private async void OnDrop(object sender, DragEventArgs e) { @@ -82,11 +83,11 @@ public partial class ImportPage : Page { var path = paths[i]; UploadProgress.Value = i; - UploadProgressText.Text = $"Importing {i + 1} of {paths.Count}: {Path.GetFileName(path)}"; + UploadProgressText.Text = $"Importiere {i + 1} von {paths.Count}: {Path.GetFileName(path)}"; var result = await Task.Run(() => _upload.Upload(path)); _session.Insert(0, result.Song is { } song - ? SessionRow.Added(song, "Upload", Path.GetFileName(path)) - : SessionRow.Failed(Path.GetFileName(path), "Upload", result.Message)); + ? SessionRow.Added(song, Path.GetFileName(path)) + : SessionRow.Failed(Path.GetFileName(path), result.Message)); } } finally @@ -113,19 +114,20 @@ public partial class ImportPage : Page if (query.Length == 0 || _busy) return; - SetBusy($"Searching Openverse for \"{query}\"..."); + SetBusy($"Suche auf Openverse nach \"{query}\"..."); Message.IsOpen = false; try { var tracks = await Openverse.SearchAsync(query); var imported = Openverse.ImportedIds(); Results.ItemsSource = tracks.Select(t => ResultRow.For(t, imported)).ToList(); + GridColumns.Fit(Results); if (tracks.Count == 0) - Show(InfoBarSeverity.Informational, "No results", $"Openverse found no audio for \"{query}\"."); + Show(InfoBarSeverity.Informational, "Keine Ergebnisse", $"Openverse hat nichts zu \"{query}\" gefunden."); } catch (OpenverseException ex) { - Show(InfoBarSeverity.Error, "Search failed", ex.Message); + Show(InfoBarSeverity.Error, "Suche fehlgeschlagen", ex.Message); } finally { @@ -133,46 +135,120 @@ public partial class ImportPage : Page } } - private void OnPreview(object sender, RoutedEventArgs e) + // One button: starts the preview, or stops the running one. + // NAudio, not WPF's MediaPlayer: that one cannot open https URLs. + private async void OnPreview(object sender, RoutedEventArgs e) { + if (_previewing) + { + OnStop(sender, e); + return; + } if (Selected is not { } row || !Uri.TryCreate(row.Track.Url, UriKind.Absolute, out var uri) || uri.Scheme != Uri.UriSchemeHttps) return; - _preview.Open(uri); // streams the file, nothing is saved - _preview.Play(); - StopButton.IsEnabled = true; + SetPreviewing(true); + Message.IsOpen = false; + var id = ++_previewId; + try + { + // Connects to the server, so it runs off the UI thread. The file is streamed, nothing is saved. + var reader = await Task.Run(() => new MediaFoundationReader(uri.AbsoluteUri)); + if (id != _previewId) // stopped or page left in the meantime + { + reader.Dispose(); + return; + } + _previewReader = reader; + _previewOutput = new WaveOut(); + _previewOutput.PlaybackStopped += (_, stopped) => Dispatcher.BeginInvoke(() => + { + if (id != _previewId) return; + OnStop(this, new RoutedEventArgs()); + if (stopped.Exception is { } error) + Show(InfoBarSeverity.Error, "Vorhören fehlgeschlagen", error.Message); + }); + _previewOutput.Init(reader); + _previewOutput.Play(); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + if (id != _previewId) return; + OnStop(this, new RoutedEventArgs()); + Show(InfoBarSeverity.Error, "Vorhören fehlgeschlagen", ex.Message); + } + } + + private void SetPreviewing(bool on) + { + _previewing = on; + PreviewButton.Content = on ? "Stopp" : "Vorhören"; + PreviewButton.Icon = new SymbolIcon(on ? SymbolRegular.Stop24 : SymbolRegular.Play24); + UpdateButtons(); } private void OnStop(object sender, RoutedEventArgs e) { - _preview.Stop(); - _preview.Close(); - StopButton.IsEnabled = false; + _previewId++; + var output = _previewOutput; + var reader = _previewReader; + _previewOutput = null; + _previewReader = null; + SetPreviewing(false); + // Disposing waits for the audio thread, which can sit in a network read; not on the UI thread. + if (output is not null || reader is not null) + Task.Run(() => + { + output?.Dispose(); + reader?.Dispose(); + }); } private void OnResultDoubleClick(object sender, MouseButtonEventArgs e) => OnImport(sender, e); + // Everything selected that can still be imported. + private List Importable => Results.SelectedItems.OfType().Where(r => r.CanImport).ToList(); + + // One after the other: Openverse limits anonymous requests, and each result shows up as soon as it is done. private async void OnImport(object sender, RoutedEventArgs e) { - if (Selected is not { CanImport: true } row || _busy) + var rows = Importable; + if (rows.Count == 0 || _busy) return; - SetBusy($"Downloading \"{row.Track.Title}\"..."); Message.IsOpen = false; + var failed = 0; + var lastError = ""; try { - var song = await Openverse.ImportAsync(row.Track); - _session.Insert(0, SessionRow.Added(song, "Openverse", song.License ?? "")); - ReplaceRow(row, row with { Status = "In library", CanImport = false }); - } - catch (Exception ex) when (ex is OpenverseException or Microsoft.Data.Sqlite.SqliteException) - { - _session.Insert(0, SessionRow.Failed(row.Track.Title, "Openverse", ex.Message)); - Show(InfoBarSeverity.Error, "Import failed", ex.Message); + for (var i = 0; i < rows.Count; i++) + { + var row = rows[i]; + SetBusy(rows.Count == 1 + ? $"Lade \"{row.Track.Title}\" herunter..." + : $"Lade {i + 1} von {rows.Count} herunter: \"{row.Track.Title}\"..."); + try + { + var song = await Openverse.ImportAsync(row.Track); + _session.Insert(0, SessionRow.Added(song, song.License ?? "")); + ReplaceRow(row, row with { Status = "In Bibliothek", CanImport = false }); + } + catch (Exception ex) when (ex is OpenverseException or Microsoft.Data.Sqlite.SqliteException) + { + _session.Insert(0, SessionRow.Failed(row.Track.Title, ex.Message)); + failed++; + lastError = ex.Message; + } + } } finally { SetBusy(null); } + + if (failed > 0) + Show(InfoBarSeverity.Error, "Import fehlgeschlagen", rows.Count == 1 + ? lastError + : $"{failed} von {rows.Count} Songs konnten nicht importiert werden. Die Gründe stehen in der Liste \"Importiert\"."); } private void ReplaceRow(ResultRow old, ResultRow updated) @@ -180,7 +256,6 @@ public partial class ImportPage : Page if (Results.ItemsSource is not List rows || rows.IndexOf(old) is var i && i < 0) return; rows[i] = updated; Results.Items.Refresh(); - Results.SelectedIndex = i; } private void OnSelectionChanged(object sender, SelectionChangedEventArgs e) => UpdateButtons(); @@ -196,8 +271,12 @@ public partial class ImportPage : Page private void UpdateButtons() { - PreviewButton.IsEnabled = Selected is not null; - ImportButton.IsEnabled = !_busy && Selected is { CanImport: true }; + PreviewButton.IsEnabled = _previewing || Selected is not null; + var importable = Importable.Count; + ImportButton.IsEnabled = !_busy && importable > 0; + ImportButton.Content = importable > 1 ? $"{importable} in Bibliothek importieren" : "In Bibliothek importieren"; + // Why the selection cannot be imported ("In Bibliothek", "Keine Dauer"); shown on the disabled button. + ImportButton.ToolTip = importable == 0 && Selected is { } blocked ? blocked.Status : null; } private void Show(InfoBarSeverity severity, string title, string message) @@ -218,16 +297,15 @@ public partial class ImportPage : Page private sealed record ResultRow(OpenverseTrack Track, string Status, bool CanImport) { public static ResultRow For(OpenverseTrack track, IReadOnlySet imported) => - imported.Contains(track.Id) ? new(track, "In library", false) - : !track.CanImport ? new(track, "No duration", false) + imported.Contains(track.Id) ? new(track, "In Bibliothek", false) + : !track.CanImport ? new(track, "Keine Dauer", false) : new(track, "", true); } - private sealed record SessionRow(bool Success, string Title, string Artist, string Duration, string Source, string Details) + private sealed record SessionRow(bool Success, string Title, string Artist, string Details) { - public static SessionRow Added(Song song, string source, string details) => - new(true, song.Title, song.Artist, $"{(int)song.Duration.TotalMinutes}:{song.Duration.Seconds:00}", source, details); + public static SessionRow Added(Song song, string details) => new(true, song.Title, song.Artist, details); - public static SessionRow Failed(string name, string source, string error) => new(false, name, "", "", source, error); + public static SessionRow Failed(string name, string error) => new(false, name, "", error); } } From 80292ac90b5ed21dc34d4ecec6a022da3b9dc269 Mon Sep 17 00:00:00 2001 From: Julian Lechner Date: Mon, 23 Nov 2026 14:22:52 +0100 Subject: [PATCH 09/11] feat(schedule): rework the schedule page Adds the start time, unlimited mode, start from now, end now and the buttons to move, edit and remove timeline items. Rows update in place and slow controller calls run off the UI thread, with the buttons switching at once. Co-Authored-By: Claude Fable 5.2 --- src/Radiosender/Views/Pages/SchedulePage.xaml | 193 +++++++++----- .../Views/Pages/SchedulePage.xaml.cs | 246 ++++++++++++++---- .../Views/ScheduleItemEditWindow.xaml | 36 +++ .../Views/ScheduleItemEditWindow.xaml.cs | 46 ++++ 4 files changed, 401 insertions(+), 120 deletions(-) create mode 100644 src/Radiosender/Views/ScheduleItemEditWindow.xaml create mode 100644 src/Radiosender/Views/ScheduleItemEditWindow.xaml.cs diff --git a/src/Radiosender/Views/Pages/SchedulePage.xaml b/src/Radiosender/Views/Pages/SchedulePage.xaml index 0b90f55..a846fe2 100644 --- a/src/Radiosender/Views/Pages/SchedulePage.xaml +++ b/src/Radiosender/Views/Pages/SchedulePage.xaml @@ -2,7 +2,9 @@ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml" - Title="Schedule" + Title="Sendeplan" + Foreground="{DynamicResource TextFillColorPrimaryBrush}" + ScrollViewer.CanContentScroll="False" Loaded="OnLoaded" Unloaded="OnUnloaded"> @@ -14,8 +16,8 @@ HorizontalAlignment="Left" BorderThickness="1" CornerRadius="4" - BorderBrush="{DynamicResource TextFillColorTertiaryBrush}"> - + BorderBrush="{DynamicResource ControlStrongStrokeColorDefaultBrush}"> + @@ -41,26 +43,50 @@ - - - - + + + + + - + - + + @@ -83,7 +111,7 @@ + Text="Läuft gerade" /> + Text="Nichts auf Sendung" /> - - + + + - + Click="OnPlayToggle" /> @@ -125,7 +156,7 @@ Width="140" Margin="8,0,0,0" VerticalAlignment="Center" - AutomationProperties.Name="Volume" + AutomationProperties.Name="Lautstärke" Minimum="0" Maximum="1" SmallChange="0.05" @@ -136,46 +167,77 @@ - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + - + TextWrapping="Wrap" + Visibility="Collapsed" /> + + AutomationProperties.Name="Sendeplan" + SelectionChanged="OnTimelineSelectionChanged" + MouseDoubleClick="OnEditItem"> @@ -185,7 +247,7 @@ Symbol="Play24" Filled="True" Foreground="{DynamicResource AccentTextFillColorPrimaryBrush}" - AutomationProperties.Name="On air" + AutomationProperties.Name="Auf Sendung" Visibility="Collapsed" /> @@ -200,15 +262,15 @@ - + - - + + @@ -222,7 +284,8 @@ Margin="0,48,0,0" HorizontalAlignment="Center" VerticalAlignment="Top" - Text="No schedule yet. Choose the hours and create one." + Foreground="{DynamicResource TextFillColorSecondaryBrush}" + Text="Noch kein Plan. Stunden wählen und Plan erstellen." Visibility="Visible" /> diff --git a/src/Radiosender/Views/Pages/SchedulePage.xaml.cs b/src/Radiosender/Views/Pages/SchedulePage.xaml.cs index 5480b1e..a0cd37a 100644 --- a/src/Radiosender/Views/Pages/SchedulePage.xaml.cs +++ b/src/Radiosender/Views/Pages/SchedulePage.xaml.cs @@ -1,3 +1,4 @@ +using System.Collections.ObjectModel; using System.Windows; using System.Windows.Controls; using System.Windows.Threading; @@ -14,10 +15,24 @@ public partial class SchedulePage : Page private readonly DispatcherTimer _progressTimer = new() { Interval = TimeSpan.FromMilliseconds(250) }; private bool _loading; private int _scrolledTo = -1; + private bool _shownPlaying; + + // Weekday names in the start list follow the interface language, not the Windows setting. + private static readonly System.Globalization.CultureInfo German = new("de-DE"); + + // Bound once and updated row by row, so a click never rebuilds the whole list. + private readonly ObservableCollection _rows = []; + + // A controller call is running on a pool thread; the buttons that would collide with it are off. + private bool _working; + + // Optimistic state: what the user just asked for, shown before the engine has caught up. + private bool? _expectPlaying; public SchedulePage() { InitializeComponent(); + Timeline.ItemsSource = _rows; // Also refreshes the buttons: Finished can arrive just before the engine reports it stopped. _progressTimer.Tick += (_, _) => { @@ -36,6 +51,9 @@ public partial class SchedulePage : Page _loading = true; VolumeSlider.Value = _controller.Volume; _loading = false; + FillStartTimes(); + if (_controller.Plan.Count > 0) + UnlimitedBox.IsChecked = _controller.IsUnlimited; // The library can change on other pages. RequestSong.ItemsSource = _controller.LibrarySongs() @@ -55,65 +73,148 @@ public partial class SchedulePage : Page _progressTimer.Stop(); } - private void OnCreate(object sender, RoutedEventArgs e) + // The next 12 full hours; rebuilt when the list opens, so it never offers a past hour. + private void FillStartTimes() { - var hours = (int)(HoursBox.Value ?? 1); - try - { - _controller.CreatePlan(hours); - var plan = _controller.Plan; - ShowMessage(InfoBarSeverity.Success, "Schedule created", - $"{hours} h from {plan[0].Start:HH:mm} to {plan[^1].End:HH:mm}, {plan.Count} items."); - } - catch (Exception ex) when (ex is ScheduleException or ArgumentOutOfRangeException) - { - ShowMessage(InfoBarSeverity.Error, "Could not create the schedule", ex.Message); - } - ShowCurrent(); + var selected = (StartBox.SelectedItem as StartOption)?.Time; + var now = DateTime.Now; + var next = now.Date.AddHours(now.Hour + 1); + var options = Enumerable.Range(0, 12) + .Select(i => next.AddHours(i)) + .Select(t => new StartOption(t, t.Date == now.Date ? $"{t:HH:mm}" : t.ToString("ddd HH:mm", German))) + .ToList(); + StartBox.ItemsSource = options; + StartBox.SelectedItem = options.FirstOrDefault(o => o.Time == selected) ?? options[0]; } - private void OnSwap(object sender, RoutedEventArgs e) + private void OnStartDropDownOpened(object? sender, EventArgs e) => FillStartTimes(); + + private void OnUnlimitedChanged(object sender, RoutedEventArgs e) => + HoursBox.IsEnabled = UnlimitedBox.IsChecked != true; + + private void OnCreate(object sender, RoutedEventArgs e) => CreatePlan(startNow: false); + + private void OnStartNow(object sender, RoutedEventArgs e) => CreatePlan(startNow: true); + + private async void CreatePlan(bool startNow) + { + int? hours = UnlimitedBox.IsChecked == true ? null : (int)(HoursBox.Value ?? 1); + var start = (StartBox.SelectedItem as StartOption)?.Time; + if (startNow) + _expectPlaying = true; + await RunAsync("Der Plan konnte nicht erstellt werden", () => + { + if (startNow) + _controller.StartNow(hours); + else + _controller.CreatePlan(hours, start); + }); + } + + /// + /// Runs a controller call that can take a moment (planning, waiting for the audio thread to stop) + /// off the UI thread, so the window stays responsive. Returns false after showing the error. + /// + private async Task RunAsync(string errorTitle, Action work) + { + _working = true; + UpdateButtons(); + try + { + await Task.Run(work); + Message.IsOpen = false; + return true; + } + catch (Exception ex) when (ex is ScheduleException or ArgumentOutOfRangeException or InvalidOperationException) + { + ShowMessage(InfoBarSeverity.Error, errorTitle, ex.Message); + return false; + } + finally + { + _working = false; + _expectPlaying = null; + ShowCurrent(); + } + } + + private async void OnSwap(object sender, RoutedEventArgs e) { if (Timeline.SelectedItem is not TimelineRow row || RequestSong.SelectedItem is not SongOption song) return; - try - { - var plan = _controller.Swap(row.Index, song.Id); - var placed = plan[row.Index]; - ShowMessage(InfoBarSeverity.Success, "Song request planned", - $"\"{placed.Title}\" plays at {placed.Start:HH:mm:ss} instead of \"{row.Item.Title}\". The rest of that half hour was replanned, the news stays on time."); - } - catch (ScheduleException ex) - { - ShowMessage(InfoBarSeverity.Error, "Could not play the request", ex.Message); - } - ShowCurrent(); + ScheduleItem? placed = null; + if (await RunAsync("Der Songwunsch konnte nicht eingeplant werden", () => placed = _controller.Swap(row.Index, song.Id)[row.Index])) + ShowMessage(InfoBarSeverity.Success, "Songwunsch eingeplant", + $"\"{placed!.Title}\" läuft um {placed.Start:HH:mm:ss}."); } private void OnRequestChanged(object sender, SelectionChangedEventArgs e) => UpdateButtons(); - private void OnTimelineSelectionChanged(object sender, SelectionChangedEventArgs e) => UpdateButtons(); + private void OnMoveUp(object sender, RoutedEventArgs e) => MoveSelected(-1); - private void OnStart(object sender, RoutedEventArgs e) + private void OnMoveDown(object sender, RoutedEventArgs e) => MoveSelected(1); + + // The selection follows the item, so it can be moved several steps in a row. + private void MoveSelected(int offset) => ChangeSelected(row => + { + _controller.Move(row.Index, offset); + Timeline.SelectedIndex = row.Index + offset; + }); + + private void OnEndNow(object sender, RoutedEventArgs e) { - Message.IsOpen = false; try { - _controller.Start(); + _controller.EndCurrentNow(); + Message.IsOpen = false; } - catch (InvalidOperationException ex) + catch (ScheduleException ex) { - ShowMessage(InfoBarSeverity.Warning, "Could not start", ex.Message); + ShowMessage(InfoBarSeverity.Error, "Das Element konnte nicht beendet werden", ex.Message); } ShowCurrent(); } - private void OnStop(object sender, RoutedEventArgs e) + private void OnRemove(object sender, RoutedEventArgs e) => ChangeSelected(row => _controller.Remove(row.Index)); + + private void OnEditItem(object sender, RoutedEventArgs e) { - _controller.Stop(); + if (!EditItemButton.IsEnabled || Timeline.SelectedItem is not TimelineRow row) + return; + var dialog = new ScheduleItemEditWindow(row.Item) { Owner = Window.GetWindow(this) }; + if (dialog.ShowDialog() == true) + ChangeSelected(r => _controller.EditItem(r.Index, dialog.ItemTitle, dialog.Duration)); + } + + private void ChangeSelected(Action change) + { + if (Timeline.SelectedItem is not TimelineRow row) + return; + try + { + change(row); + Message.IsOpen = false; + } + catch (ScheduleException ex) + { + ShowMessage(InfoBarSeverity.Error, "Der Plan konnte nicht geändert werden", ex.Message); + } ShowCurrent(); } + private void OnTimelineSelectionChanged(object sender, SelectionChangedEventArgs e) => UpdateButtons(); + + private async void OnPlayToggle(object sender, RoutedEventArgs e) + { + var stop = _controller.IsPlaying; + // The button and the card switch at once; stopping waits for the audio thread in the background. + _expectPlaying = !stop; + if (stop) + NowKind.Visibility = Visibility.Collapsed; + UpdateProgress(); + await RunAsync("Start nicht möglich", stop ? _controller.Stop : _controller.Start); + } + private void OnVolumeChanged(object sender, RoutedPropertyChangedEventArgs e) { if (!_loading) _controller.Volume = (float)e.NewValue; @@ -123,15 +224,15 @@ public partial class SchedulePage : Page private void OnItemStarted(object? sender, int index) => Dispatcher.BeginInvoke(ShowCurrent); private void OnItemFailed(object? sender, string message) => - Dispatcher.BeginInvoke(() => ShowMessage(InfoBarSeverity.Warning, "Item skipped", message)); + Dispatcher.BeginInvoke(() => ShowMessage(InfoBarSeverity.Warning, "Element übersprungen", message)); private void OnFinished(object? sender, EventArgs e) => Dispatcher.BeginInvoke(() => { - ShowMessage(InfoBarSeverity.Informational, "Broadcast finished", "The whole schedule has been played."); + ShowMessage(InfoBarSeverity.Informational, "Sendung beendet", "Der ganze Plan wurde gespielt."); ShowCurrent(); }); - // Rebuilds the rows from the controller; the selection is the user's swap target and is kept. + // Syncs the rows with the controller; the selection is the user's swap target and is kept. private void ShowCurrent() { var item = _controller.CurrentItem; @@ -139,8 +240,19 @@ public partial class SchedulePage : Page var plan = _controller.Plan; var selected = Timeline.SelectedIndex; - var rows = plan.Select((p, i) => new TimelineRow(i, p, i == current)).ToList(); - Timeline.ItemsSource = rows; + // Rows are records: only the ones whose content changed are replaced. + for (var i = 0; i < plan.Count; i++) + { + var updated = new TimelineRow(i, plan[i], i == current); + if (i == _rows.Count) + _rows.Add(updated); + else if (_rows[i] != updated) + _rows[i] = updated; + } + while (_rows.Count > plan.Count) + _rows.RemoveAt(_rows.Count - 1); + var rows = _rows; + GridColumns.Fit(Timeline); Timeline.SelectedIndex = selected < rows.Count ? selected : -1; // Follow the broadcast when it moves on; otherwise keep the user's row in view. if (current != _scrolledTo && current >= 0 && current < rows.Count) @@ -152,7 +264,7 @@ public partial class SchedulePage : Page NowKind.Content = item; NowKind.Visibility = item is null ? Visibility.Collapsed : Visibility.Visible; - if (item is not null) NowTitle.Text = item.Title; + if (item is not null) NowTitle.Text = item.Title.Length > 0 ? item.Title : item.KindName; UpdateButtons(); UpdateProgress(); @@ -160,38 +272,60 @@ public partial class SchedulePage : Page private void UpdateButtons() { - var playing = _controller.IsPlaying; - StartButton.IsEnabled = !playing && _controller.Plan.Count > 0; - StopButton.IsEnabled = playing; + var playing = _expectPlaying ?? _controller.IsPlaying; + PlayButton.IsEnabled = !_working && (playing || _controller.Plan.Count > 0); + CreateButton.IsEnabled = StartNowButton.IsEnabled = !_working; + // Called every timer tick, so the label and icon change only with the state. + if (playing != _shownPlaying) + { + _shownPlaying = playing; + PlayButton.Content = playing ? "Stopp" : "Start"; + PlayButton.Icon = new SymbolIcon(playing ? SymbolRegular.Stop24 : SymbolRegular.Play24); + } var row = Timeline.SelectedItem as TimelineRow; + + // Only items that are not on air or over can be moved or removed; the one on air can still be edited. + var count = _controller.Plan.Count; + var current = _controller.CurrentIndex; + bool Editable(int i) => !_working && i >= 0 && i < count && (!playing || i > current); + var index = row?.Index ?? -1; + MoveUpButton.IsEnabled = Editable(index) && Editable(index - 1); + MoveDownButton.IsEnabled = Editable(index) && Editable(index + 1); + RemoveButton.IsEnabled = Editable(index); + var onAir = !_working && playing && index >= 0 && index == current; + EditItemButton.IsEnabled = (Editable(index) || onAir) && row!.Item.Kind != ScheduleItemKind.Song; + EndNowButton.IsEnabled = !_working && _expectPlaying != false && _controller.CurrentItem is not null; + var blocker = row switch { - null => "Select an upcoming item in the schedule.", - { Item.Kind: ScheduleItemKind.News } => "News cannot be replaced.", - _ when playing && row.Index <= _controller.CurrentIndex => "This item is already on air or over.", - _ when RequestSong.SelectedItem is null => "Choose a song from the library.", + null => "Ein kommendes Element im Plan auswählen.", + { Item.Kind: ScheduleItemKind.News } => "Nachrichten können nicht ersetzt werden.", + _ when playing && row.Index <= _controller.CurrentIndex => "Dieses Element ist bereits auf Sendung oder vorbei.", _ => null, }; - SwapHint.Text = blocker ?? $"Replaces the item at {row!.Item.Start:HH:mm:ss}."; - SwapButton.IsEnabled = blocker is null; + SwapHint.Text = blocker ?? $"Ersetzt das Element um {row!.Item.Start:HH:mm:ss}."; + // The hint only matters once a song is chosen. + var requested = RequestSong.SelectedItem is not null; + SwapHint.Visibility = requested ? Visibility.Visible : Visibility.Collapsed; + SwapButton.IsEnabled = !_working && requested && blocker is null; } private void UpdateProgress() { - if (_controller.CurrentItem is not { } item) + if (_expectPlaying == false || _controller.CurrentItem is not { } item) { NowProgress.Value = 0; // Checked here, not in ShowCurrent: the engine starts waiting a moment after Start. - var waiting = _controller.WaitingUntil; - NowTitle.Text = waiting is { } at ? $"On air at {at:HH:mm:ss}" : "Nothing on air"; - NowTime.Text = waiting is null ? " " : "Waiting for the planned start, so the news comes at :00 and :30."; + var waiting = _expectPlaying == false ? null : _controller.WaitingUntil; + NowTitle.Text = waiting is { } at ? $"Auf Sendung um {at:HH:mm:ss}" : "Nichts auf Sendung"; + NowTime.Text = " "; return; } var elapsed = _controller.CurrentElapsed; NowProgress.Value = item.Duration.Ticks == 0 ? 0 : (double)elapsed.Ticks / item.Duration.Ticks; - NowTime.Text = $"{elapsed:m\\:ss} / {item.Duration:m\\:ss} · planned {item.Start:HH:mm:ss}"; + NowTime.Text = $"{elapsed:m\\:ss} / {item.Duration:m\\:ss}"; } private void ShowMessage(InfoBarSeverity severity, string title, string text) @@ -205,4 +339,6 @@ public partial class SchedulePage : Page private sealed record TimelineRow(int Index, ScheduleItem Item, bool IsCurrent); private sealed record SongOption(long Id, string Label); + + private sealed record StartOption(DateTime Time, string Label); } diff --git a/src/Radiosender/Views/ScheduleItemEditWindow.xaml b/src/Radiosender/Views/ScheduleItemEditWindow.xaml new file mode 100644 index 0000000..eeb4627 --- /dev/null +++ b/src/Radiosender/Views/ScheduleItemEditWindow.xaml @@ -0,0 +1,36 @@ + + + + + + + + diff --git a/src/Radiosender/Views/ScheduleItemEditWindow.xaml.cs b/src/Radiosender/Views/ScheduleItemEditWindow.xaml.cs new file mode 100644 index 0000000..69100f5 --- /dev/null +++ b/src/Radiosender/Views/ScheduleItemEditWindow.xaml.cs @@ -0,0 +1,46 @@ +using System.Globalization; +using System.Windows; +using Radiosender.Models; +using Wpf.Ui.Controls; + +namespace Radiosender.Views; + +/// +/// Dialog for the title of a news, ad or moderator item and, for news and moderator items, its length. +/// Only collects input; the caller changes the schedule. +/// +public partial class ScheduleItemEditWindow : FluentWindow +{ + private static readonly string[] DurationFormats = [@"m\:ss", @"mm\:ss"]; + + public ScheduleItemEditWindow(ScheduleItem item) + { + InitializeComponent(); + Title = Bar.Title = $"{item.KindName} bearbeiten"; + TitleBox.Text = item.Title; + DurationBox.Text = item.Duration.ToString(@"m\:ss"); + Duration = item.Duration; + // Ads keep their length. + DurationLabel.IsEnabled = DurationBox.IsEnabled = item.Kind is ScheduleItemKind.News or ScheduleItemKind.Moderator; + } + + public string ItemTitle => TitleBox.Text; + + public TimeSpan Duration { get; private set; } + + private void OnSave(object sender, RoutedEventArgs e) + { + if (DurationBox.IsEnabled) + { + if (!TimeSpan.TryParseExact(DurationBox.Text.Trim(), DurationFormats, CultureInfo.InvariantCulture, out var duration) + || duration <= TimeSpan.Zero) + { + ErrorText.Visibility = Visibility.Visible; + return; + } + Duration = duration; + } + + DialogResult = true; + } +} From 54b02c3fd62b4b122e65a4e923fe3ed8f6ea33fe Mon Sep 17 00:00:00 2001 From: Julian Lechner Date: Mon, 23 Nov 2026 14:22:52 +0100 Subject: [PATCH 10/11] feat(settings): add the settings page and speaking reminders The main window shows a dialog, optionally with a bing sound, shortly before a news or moderator item goes on air. The settings page sits in the footer of the navigation; the empty home page is gone and the app starts on the schedule. Pages switch off the navigation view's outer scrolling so their lists stay virtualized. Co-Authored-By: Claude Fable 5.2 --- src/Radiosender/Views/MainWindow.xaml | 15 +- src/Radiosender/Views/MainWindow.xaml.cs | 55 ++++++- src/Radiosender/Views/Pages/HomePage.xaml | 11 -- src/Radiosender/Views/Pages/HomePage.xaml.cs | 11 -- src/Radiosender/Views/Pages/SettingsPage.xaml | 136 ++++++++++++++++++ .../Views/Pages/SettingsPage.xaml.cs | 79 ++++++++++ 6 files changed, 279 insertions(+), 28 deletions(-) delete mode 100644 src/Radiosender/Views/Pages/HomePage.xaml delete mode 100644 src/Radiosender/Views/Pages/HomePage.xaml.cs create mode 100644 src/Radiosender/Views/Pages/SettingsPage.xaml create mode 100644 src/Radiosender/Views/Pages/SettingsPage.xaml.cs diff --git a/src/Radiosender/Views/MainWindow.xaml b/src/Radiosender/Views/MainWindow.xaml index 22b586c..321b7dd 100644 --- a/src/Radiosender/Views/MainWindow.xaml +++ b/src/Radiosender/Views/MainWindow.xaml @@ -17,21 +17,26 @@ + - - - + + + diff --git a/src/Radiosender/Views/MainWindow.xaml.cs b/src/Radiosender/Views/MainWindow.xaml.cs index 164aa58..1792a4e 100644 --- a/src/Radiosender/Views/MainWindow.xaml.cs +++ b/src/Radiosender/Views/MainWindow.xaml.cs @@ -1,3 +1,7 @@ +using System.Windows.Threading; +using NAudio.Wave; +using NAudio.Wave.SampleProviders; +using Radiosender.Models; using Radiosender.Views.Pages; using Wpf.Ui.Controls; @@ -5,9 +9,58 @@ namespace Radiosender.Views; public partial class MainWindow : FluentWindow { + private readonly DispatcherTimer _reminderTimer = new() { Interval = TimeSpan.FromSeconds(1) }; + private DateTime _remindedFor; + public MainWindow() { InitializeComponent(); - Loaded += (_, _) => RootNavigation.Navigate(typeof(HomePage)); + // Re-themes the app when the user switches the Windows theme while it runs. + Wpf.Ui.Appearance.SystemThemeWatcher.Watch(this); + Loaded += (_, _) => RootNavigation.Navigate(typeof(SchedulePage)); + _reminderTimer.Tick += (_, _) => RemindSpeaker(); + _reminderTimer.Start(); + } + + // Shortly before news or moderator talk goes on air, the person at the microphone gets a heads-up. + private void RemindSpeaker() + { + var settings = App.Settings; + TimeSpan? newsLead = settings.NewsAlert ? TimeSpan.FromSeconds(settings.NewsAlertSeconds) : null; + TimeSpan? moderatorLead = settings.ModeratorAlert ? TimeSpan.FromSeconds(settings.ModeratorAlertSeconds) : null; + if (App.Schedule.UpcomingSpeech(newsLead, moderatorLead) is not { } item || item.Start == _remindedFor) + return; + _remindedFor = item.Start; // once per item + var isNews = item.Kind == ScheduleItemKind.News; + var what = item.KindName; + if (isNews ? settings.NewsAlertSound : settings.ModeratorAlertSound) + PlayBing(); + // A dialog in the middle of the screen that stays until OK is clicked; the broadcast keeps running behind it. + _ = new Wpf.Ui.Controls.MessageBox + { + Title = "Gleich bist du dran.", + Content = item.Title.Length > 0 ? $"{what} um {item.Start:HH:mm:ss}: {item.Title}" : $"{what} um {item.Start:HH:mm:ss}", + CloseButtonText = "OK", + WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen, + Topmost = true, + }.ShowDialogAsync(); + } + + // A short generated tone on its own output, so it sounds over the running broadcast. + private static void PlayBing() + { + try + { + var tone = new SignalGenerator(44100, 1) { Type = SignalGeneratorType.Sin, Frequency = 880, Gain = 0.25 } + .Take(TimeSpan.FromMilliseconds(350)); + var output = new WaveOut(); + output.PlaybackStopped += (_, _) => output.Dispose(); + output.Init(tone); + output.Play(); + } + catch (Exception ex) when (ex is NAudio.MmException or InvalidOperationException) + { + // No audio device: the dialog still reminds the speaker. + } } } diff --git a/src/Radiosender/Views/Pages/HomePage.xaml b/src/Radiosender/Views/Pages/HomePage.xaml deleted file mode 100644 index 2170016..0000000 --- a/src/Radiosender/Views/Pages/HomePage.xaml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - diff --git a/src/Radiosender/Views/Pages/HomePage.xaml.cs b/src/Radiosender/Views/Pages/HomePage.xaml.cs deleted file mode 100644 index f90b2ea..0000000 --- a/src/Radiosender/Views/Pages/HomePage.xaml.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System.Windows.Controls; - -namespace Radiosender.Views.Pages; - -public partial class HomePage : Page -{ - public HomePage() - { - InitializeComponent(); - } -} diff --git a/src/Radiosender/Views/Pages/SettingsPage.xaml b/src/Radiosender/Views/Pages/SettingsPage.xaml new file mode 100644 index 0000000..1e33094 --- /dev/null +++ b/src/Radiosender/Views/Pages/SettingsPage.xaml @@ -0,0 +1,136 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Radiosender/Views/Pages/SettingsPage.xaml.cs b/src/Radiosender/Views/Pages/SettingsPage.xaml.cs new file mode 100644 index 0000000..a3cb375 --- /dev/null +++ b/src/Radiosender/Views/Pages/SettingsPage.xaml.cs @@ -0,0 +1,79 @@ +using System.IO; +using System.Windows; +using System.Windows.Controls; +using Radiosender.Services; +using Wpf.Ui.Controls; + +namespace Radiosender.Views.Pages; + +/// Edits . Nothing changes until Save. +public partial class SettingsPage : Page +{ + public SettingsPage() => InitializeComponent(); + + // Loaded fires on every navigation to the page, so unsaved edits from an earlier visit are dropped. + private void OnLoaded(object sender, RoutedEventArgs e) => Show(App.Settings); + + private void Show(AppSettings settings) + { + NewsAlertSwitch.IsChecked = settings.NewsAlert; + NewsSecondsBox.Value = settings.NewsAlertSeconds; + NewsSoundBox.IsChecked = settings.NewsAlertSound; + ModeratorAlertSwitch.IsChecked = settings.ModeratorAlert; + ModeratorSecondsBox.Value = settings.ModeratorAlertSeconds; + ModeratorSoundBox.IsChecked = settings.ModeratorAlertSound; + NewsMinutesBox.Value = settings.NewsMinutesPerHour; + ModeratorMinutesBox.Value = settings.ModeratorMinutesPerHour; + AdMinutesBox.Value = settings.AdMinutesPerHour; + } + + // An emptied number box counts as its default. + private static AppSettings Defaults { get; } = new(); + + private AppSettings Read() => new() + { + NewsAlert = NewsAlertSwitch.IsChecked == true, + NewsAlertSeconds = (int)(NewsSecondsBox.Value ?? Defaults.NewsAlertSeconds), + NewsAlertSound = NewsSoundBox.IsChecked == true, + ModeratorAlert = ModeratorAlertSwitch.IsChecked == true, + ModeratorAlertSeconds = (int)(ModeratorSecondsBox.Value ?? Defaults.ModeratorAlertSeconds), + ModeratorAlertSound = ModeratorSoundBox.IsChecked == true, + NewsMinutesPerHour = (int)(NewsMinutesBox.Value ?? Defaults.NewsMinutesPerHour), + ModeratorMinutesPerHour = (int)(ModeratorMinutesBox.Value ?? Defaults.ModeratorMinutesPerHour), + AdMinutesPerHour = (int)(AdMinutesBox.Value ?? Defaults.AdMinutesPerHour), + }; + + private void OnSave(object sender, RoutedEventArgs e) + { + var settings = Read(); + if (settings.Validate() is { } problem) + { + ShowMessage(InfoBarSeverity.Error, "Nicht gespeichert", problem); + return; + } + + try + { + App.SaveSettings(settings); + ShowMessage(InfoBarSeverity.Success, "Gespeichert", "Minuten pro Stunde gelten für den nächsten Plan."); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + ShowMessage(InfoBarSeverity.Error, "Nicht gespeichert", ex.Message); + } + } + + private void OnReset(object sender, RoutedEventArgs e) + { + Show(Defaults); + ShowMessage(InfoBarSeverity.Informational, "Standardwerte eingesetzt", "Mit Speichern übernehmen."); + } + + private void ShowMessage(InfoBarSeverity severity, string title, string text) + { + Message.Severity = severity; + Message.Title = title; + Message.Message = text; + Message.IsOpen = true; + } +} From ac9170249bcb3c94baf3259cf9d0fdfc96800fbd Mon Sep 17 00:00:00 2001 From: Julian Lechner Date: Mon, 23 Nov 2026 14:22:53 +0100 Subject: [PATCH 11/11] docs: describe the new schedule options, settings and German labels Co-Authored-By: Claude Fable 5.2 --- README.md | 54 +++++++++++++++++++++++++++++++++--------------------- 1 file changed, 33 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index ccc8ffb..d386684 100644 --- a/README.md +++ b/README.md @@ -19,30 +19,39 @@ dotnet test Radiosender.slnx On first start the app creates its data under `%LOCALAPPDATA%\Radiosender`: - `radiosender.db`: the SQLite music library +- `settings.json`: the values from the Settings page - `Music\`: copies of uploaded files and downloaded Openverse tracks ## Usage -1. **Import**: one page for both ways of adding music. Every result, added or failed, is listed under "Added in this session", with a link to the Library. - - **From computer**: drop MP3 or WAV files on the page or click **Choose files...**; several files at once are fine. The app copies each file into the music folder, reads title and artist from the file tags and measures the duration. A file that fails is reported and the others still get imported. - - **Openverse**: search the [Openverse](https://openverse.org) audio catalog, preview a result and import it with **Import to library** or a double-click. The app downloads the file and stores its license and attribution with the song. Results that are already in the library or have no duration are marked and cannot be imported. -2. **Library**: lists and searches all songs. Edit title, artist, license and attribution, or delete a song. -3. **Schedule**: - 1. Enter the number of hours (1 to 24) and click **Create schedule**. The plan starts at the next full hour. - 2. The timeline shows every item with start time, type (song, news, ad, moderator), title and duration. - 3. **Start** puts the plan on air on the real clock. Before the planned start the now-playing card shows when the broadcast begins; if the plan has already begun, playback joins at the next item. **Stop** ends it. The now-playing card shows the current item, its progress and the volume. - 4. **Song request**: choose a song, select an upcoming row in the timeline and click **Play instead of selected**. This also works while the broadcast is running. +The interface is in German. This section names the controls as they appear on screen. -News, ads and moderator talk are placeholders: the app shows them in the timeline and keeps silent for their duration. +1. **Import**: one page for both ways of adding music. Every result, added or failed, is listed under "Importiert" as soon as there is one, with a link to the library. + - **Vom Computer**: drop MP3 or WAV files on the page or click **Dateien auswählen...**; several files at once are fine. The app copies each file into the music folder, reads title and artist from the file tags and measures the duration. A file that fails is reported and the others still get imported. + - **Openverse**: search the [Openverse](https://openverse.org) audio catalog, preview a result and import it with **In Bibliothek importieren** or a double-click. Select several results with Ctrl or Shift to import them in one go; they are downloaded one after the other. The app downloads the file and stores its license and attribution with the song. Results that are already in the library or have no duration cannot be imported; the tooltip of the disabled button says why. +2. **Bibliothek**: lists and searches all songs. Edit title, artist, license and attribution, or delete a song. +3. **Sendeplan** (the start page): + 1. Choose the start (one of the next 12 full hours) and the number of hours (1 to 24), then click **Plan erstellen**. + - **Unbegrenzt** plans without an end: the timeline shows the next 5 hours, and while the broadcast runs one more hour is added whenever less than 5 hours are left. + - **Jetzt starten** ignores the start time, plans from this moment and goes on air at once. Music leads up to the first news at the next :00 or :30; the chosen hours count from there. + 2. The timeline shows every item with start time, type (song, news, ad, moderator), title and duration. + 3. **Start** puts the plan on air on the real clock. Before the planned start the now-playing card shows when the broadcast begins; if the plan has already begun, playback joins at the next item. The same button then reads **Stopp** and ends it. The now-playing card shows the current item, its progress and the volume. + 4. **Edit the timeline**: select an upcoming row and use the buttons above the list to move it up or down, edit it, or remove it (trash icon). News, ad and moderator items have no title until you give them one; news and moderator items can also change their length. A double-click opens the editor too. Every item after a change follows on without a gap. The item on air can be edited too, but not moved or removed; **Jetzt beenden** in the now-playing card ends it at once and starts the next item. + 5. **Speaking reminder**: 30 seconds before a news or moderator item goes on air, a dialog in the middle of the screen reminds you on any page and stays until you click **OK**. + 6. **Songwunsch**: choose a song, select an upcoming row in the timeline and click **Auswahl ersetzen**. This also works while the broadcast is running. + +4. **Einstellungen** (bottom left): switch the speaking alert on or off for news and for moderator talk, set how many seconds before the start it appears and whether it plays a bing sound. Set the minutes per hour for news, moderator talk and ads (defaults 10, 10 and 20); together they can take at most 60 minutes. **Zurücksetzen** puts the default values into the form, **Speichern** stores them in `settings.json` next to the database. Alerts change at once; minutes per hour apply to the next schedule. + +News, ads and moderator talk are placeholders: the app shows them in the timeline and keeps silent for their duration, so the speaker can talk live. ## How the schedule is built `ScheduleGenerator` plans in half-hour slots: -- Each slot starts with 5 minutes of news at :00 or :30. -- The rest of the slot is random songs plus 2 to 10 minutes of ads and moderator talk. Ten minutes per half hour keeps every hour at 20 minutes or less. -- Ads and moderator items alternate, and one ad item lasts at most 5 minutes, so there is never a long block of ads. -- The filler sits between the songs and the slot always ends with a song, so that song ends exactly when the next news starts. Songs are never cut. When the filler does not add up, the last placeholder is shortened. +- Each slot starts with news at :00 or :30; the news minutes per hour are split over the two. +- The rest of the slot is random songs plus ads and moderator talk. The minutes per hour from the settings are targets: the last song has to end exactly when the next news starts and songs are never cut, so the ad and moderator time is what the songs leave. The generator tries several hundred random song picks per slot and keeps the one that leaves closest to the target. What the :00 slot misses, the :30 slot makes up for, so the hour comes out within a few seconds of the targets with a normal library. +- Ads are cut into items of at most 5 minutes. Each ad item follows a moderator item, and the breaks sit between the songs, so ads never run back to back as long as there is moderator time or a song to put between them. +- The slot always ends with a song. If the targets take the whole hour, the slot has no songs. During playback `PlaybackEngine` starts every item at its planned time. If the previous item ended early, it waits; if it ran late, the next item starts right after it and is never cut. The news therefore comes at the real :00 and :30. @@ -76,21 +85,21 @@ Tests are in `tests/Radiosender.Tests` (xUnit). They cover the repository, impor Music search uses the [Openverse API](https://api.openverse.org/v1/) without an API key. Openverse lists openly licensed works (Creative Commons and public domain) from many sources. The rights stay with the creators. -For each downloaded track the app stores the license (for example `CC BY 4.0`) and the attribution text from Openverse. The Library page shows both. Anyone who plays or shares these tracks must keep this attribution, as the licenses require. +For each downloaded track the app stores the license (for example `CC BY 4.0`) and the attribution text from Openverse. Both are shown in the edit dialog of a song (**Bearbeiten** on the library page). Anyone who plays or shares these tracks must keep this attribution, as the licenses require. ## Assignment checklist | Requirement | Where | Status | | --- | --- | --- | -| Plays random music for X hours; only full hours, entered by the user | Schedule page, hours 1 to 24; `ScheduleGenerator.PickSongs` | Done | +| Plays random music for X hours; only full hours, entered by the user | Schedule page, hours 1 to 24 or unlimited; `ScheduleGenerator.PickSongs` | Done | | 2 × 5 minutes of news per hour, at :00 and :30 | `ScheduleGenerator.Generate`; `PlaybackEngine` waits for each planned start | Done | | News comes after a song, no song is cut | Slot ends with a song that ends at the news start; tests in `ScheduleGeneratorTests` | Done | -| Up to 20 minutes of ads and moderator talk per hour | At most 10 minutes per half hour | Done | -| Ads never 20 minutes in a row | Ads alternate with moderator items, one ad item lasts at most 5 minutes | Done | +| Up to 20 minutes of ads and moderator talk per hour | Targets in the settings. The defaults are 20 minutes of ads plus 10 of moderator talk, which is 30; set them to 20 together to meet this rule | Configurable | +| Ads never 20 minutes in a row | One ad item lasts at most 5 minutes and follows a moderator item | Done | | Remaining time filled with music | Songs fill each slot | Done | | Music comes from a SQLite database | `SongRepository`, `radiosender.db` | Done | | Library can be extended at any time: add, edit, delete | Library page and `SongEditWindow` | Done | -| Add by simple upload | Import page, "From computer" (MP3, WAV, several files, drag and drop) | Done | +| Add by simple upload | Import page, "Vom Computer" (MP3, WAV, several files, drag and drop) | Done | | Add through the Openverse API | Import page, "Openverse" | Done | | Music player is a singleton class | `MusicPlayer.Instance` | Done | | Hot swap: a requested song replaces an item during the planned run, everything after adapts | Song request on the Schedule page; `ScheduleGenerator.Replace`, `PlaybackEngine.ReplaceUpcoming` | Done | @@ -100,8 +109,11 @@ For each downloaded track the app stores the license (for example `CC BY 4.0`) a ## Known limitations -- **Waiting for the start**: a new plan starts at the next full hour, so after **Start** the app can stay silent for up to an hour. +- **Waiting for the start**: a plan made with **Plan erstellen** starts at a full hour, so after **Start** the app stays silent until then. **Jetzt starten** avoids the wait. +- **Unlimited plans** keep every played item in the timeline, so the list grows by about 20 rows per hour. +- **Manual edits** shift every later item, so after moving, removing or resizing an item the news can leave :00 and :30 and the plan can end earlier or later. - **Late items**: if a song plays longer than its stored duration, the following items start late by the same amount. Nothing is cut to catch up; the delay only disappears when a later item ends early. - **Skipped songs**: a song that cannot be played (missing file, unsupported format) is skipped with a warning, and the station stays silent until the next planned item. - **Deleting a song** removes it from the library but keeps its file in the `Music` folder. -- **Placeholders** have no audio. The last filler of a half hour can be very short (for example 2 seconds) because it is cut to fit. +- **Placeholders** have no audio. +- **Targets** for ads and moderator talk are missed by the time the songs cannot fill, usually a few seconds per hour; a small library or only long songs make that more.