Merge branch 'j.lechner/hot-swap' into 'main'
feat: add song requests with hot swap Closes #11 See merge request julian/blockwoche3.1-radiosender!11
This commit is contained in:
commit
ed289dd736
8 files changed
+386
-29
No files matched your search
@@ -81,4 +81,30 @@ public class ScheduleController
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void Stop() => _engine.Stop();
|
public void Stop() => _engine.Stop();
|
||||||
|
|
||||||
|
/// <summary>All songs in the library, for the song request picker.</summary>
|
||||||
|
public IReadOnlyList<Song> LibrarySongs() => _songs.GetAll();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Hot swap: plays the song <paramref name="songId"/> in place of the item at <paramref name="index"/>.
|
||||||
|
/// The rest of that half hour is rebuilt so the next news still starts on time; works while playing.
|
||||||
|
/// </summary>
|
||||||
|
/// <exception cref="ScheduleException">The item cannot be replaced or the song does not fit.</exception>
|
||||||
|
public IReadOnlyList<ScheduleItem> 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.");
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -61,6 +61,21 @@ public sealed class PlaybackEngine
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Hot swap: switches to <paramref name="items"/> while playing. Items before <paramref name="fromIndex"/>
|
||||||
|
/// must be unchanged. Returns <c>false</c> if the item at <paramref name="fromIndex"/> has already started.
|
||||||
|
/// </summary>
|
||||||
|
public bool ReplaceUpcoming(IReadOnlyList<ScheduleItem> items, int fromIndex)
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
if (IsRunning && CurrentIndex >= fromIndex)
|
||||||
|
return false;
|
||||||
|
Items = items;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>Stops playback. Waits until the running schedule has ended.</summary>
|
/// <summary>Stops playback. Waits until the running schedule has ended.</summary>
|
||||||
public void Stop()
|
public void Stop()
|
||||||
{
|
{
|
||||||
@@ -90,11 +105,17 @@ public sealed class PlaybackEngine
|
|||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
for (var i = 0; i < Items.Count; i++)
|
for (var i = 0; ; i++)
|
||||||
{
|
{
|
||||||
token.ThrowIfCancellationRequested();
|
token.ThrowIfCancellationRequested();
|
||||||
var item = Items[i];
|
ScheduleItem item;
|
||||||
|
// Under the lock so ReplaceUpcoming cannot swap the item that is about to start.
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
if (i >= Items.Count) break;
|
||||||
|
item = Items[i];
|
||||||
CurrentIndex = i;
|
CurrentIndex = i;
|
||||||
|
}
|
||||||
ItemStarted?.Invoke(this, (i, item));
|
ItemStarted?.Invoke(this, (i, item));
|
||||||
|
|
||||||
if (item.Kind == ScheduleItemKind.Song && item.Song is not null)
|
if (item.Kind == ScheduleItemKind.Song && item.Song is not null)
|
||||||
|
|||||||
@@ -73,13 +73,74 @@ public class ScheduleGenerator(ScheduleOptions options, Random random)
|
|||||||
$"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.");
|
$"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<Song> PickSongs(TimeSpan budget, List<Song> songs)
|
/// <summary>
|
||||||
|
/// Hot swap: puts <paramref name="requested"/> at <paramref name="index"/> in place of that item and
|
||||||
|
/// rebuilds the rest of its half-hour slot, so the last song still ends exactly when the next news starts.
|
||||||
|
/// Items before <paramref name="index"/> and all later slots stay as they are.
|
||||||
|
/// </summary>
|
||||||
|
/// <exception cref="ScheduleException">The song does not fit before the next news, or the rest cannot be filled.</exception>
|
||||||
|
public IReadOnlyList<ScheduleItem> Replace(IReadOnlyList<ScheduleItem> plan, int index, Song requested, IReadOnlyList<Song> songs)
|
||||||
|
{
|
||||||
|
ArgumentOutOfRangeException.ThrowIfNegative(index);
|
||||||
|
ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(index, plan.Count);
|
||||||
|
if (plan[index].Kind == ScheduleItemKind.News)
|
||||||
|
throw new ScheduleException("News cannot be replaced.");
|
||||||
|
if (requested.Duration <= TimeSpan.Zero)
|
||||||
|
throw new ScheduleException("The requested song has no duration.");
|
||||||
|
|
||||||
|
var slotStartIndex = LastIndexOf(plan, index, ScheduleItemKind.News); // -1 if the plan does not start with news
|
||||||
|
var nextNewsIndex = IndexOf(plan, index, ScheduleItemKind.News);
|
||||||
|
var slotEnd = nextNewsIndex < 0 ? plan[^1].End : plan[nextNewsIndex].Start;
|
||||||
|
var start = plan[index].Start;
|
||||||
|
var length = slotEnd - start;
|
||||||
|
|
||||||
|
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.");
|
||||||
|
|
||||||
|
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 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<Song> picked = [requested, .. PickSongs(length - requested.Duration, playable, requested)];
|
||||||
|
var gap = length - Sum(picked);
|
||||||
|
if (gap <= maxGap)
|
||||||
|
{
|
||||||
|
IEnumerable<ScheduleItem> 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.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int IndexOf(IReadOnlyList<ScheduleItem> plan, int from, ScheduleItemKind kind)
|
||||||
|
{
|
||||||
|
for (var i = from; i < plan.Count; i++)
|
||||||
|
if (plan[i].Kind == kind) return i;
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int LastIndexOf(IReadOnlyList<ScheduleItem> plan, int before, ScheduleItemKind kind)
|
||||||
|
{
|
||||||
|
for (var i = before - 1; i >= 0; i--)
|
||||||
|
if (plan[i].Kind == kind) return i;
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<Song> PickSongs(TimeSpan budget, List<Song> songs, Song? previous = null)
|
||||||
{
|
{
|
||||||
var picked = new List<Song>();
|
var picked = new List<Song>();
|
||||||
var left = budget;
|
var left = budget;
|
||||||
while (true)
|
while (true)
|
||||||
{
|
{
|
||||||
var fitting = songs.Where(s => s.Duration <= left && (picked.Count == 0 || s.Id != picked[^1].Id || songs.Count == 1)).ToList();
|
var last = picked.Count > 0 ? picked[^1] : previous;
|
||||||
|
var fitting = songs.Where(s => s.Duration <= left && (last is null || s.Id != last.Id || songs.Count == 1)).ToList();
|
||||||
if (fitting.Count == 0)
|
if (fitting.Count == 0)
|
||||||
return picked;
|
return picked;
|
||||||
var song = fitting[random.Next(fitting.Count)];
|
var song = fitting[random.Next(fitting.Count)];
|
||||||
@@ -89,10 +150,10 @@ public class ScheduleGenerator(ScheduleOptions options, Random random)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Alternates ad and moderator items, so ads never run back to back.
|
// Alternates ad and moderator items, so ads never run back to back.
|
||||||
private List<(ScheduleItemKind Kind, string Title, TimeSpan Duration)> BuildFiller(TimeSpan gap)
|
private List<(ScheduleItemKind Kind, string Title, TimeSpan Duration)> BuildFiller(TimeSpan gap, bool startWithAd = true)
|
||||||
{
|
{
|
||||||
var filler = new List<(ScheduleItemKind, string, TimeSpan)>();
|
var filler = new List<(ScheduleItemKind, string, TimeSpan)>();
|
||||||
var nextIsAd = true;
|
var nextIsAd = startWithAd;
|
||||||
while (gap > TimeSpan.Zero)
|
while (gap > TimeSpan.Zero)
|
||||||
{
|
{
|
||||||
(ScheduleItemKind kind, string title, TimeSpan duration) = nextIsAd
|
(ScheduleItemKind kind, string title, TimeSpan duration) = nextIsAd
|
||||||
@@ -133,5 +194,7 @@ public class ScheduleGenerator(ScheduleOptions options, Random random)
|
|||||||
|
|
||||||
private static TimeSpan Sum(IEnumerable<Song> songs) => songs.Aggregate(TimeSpan.Zero, (total, s) => total + s.Duration);
|
private static TimeSpan Sum(IEnumerable<Song> songs) => songs.Aggregate(TimeSpan.Zero, (total, s) => total + s.Duration);
|
||||||
|
|
||||||
|
private static TimeSpan Sum(IEnumerable<ScheduleItem> 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 Min(TimeSpan a, TimeSpan b) => a < b ? a : b;
|
||||||
}
|
}
|
||||||
@@ -37,6 +37,7 @@
|
|||||||
<RowDefinition Height="Auto" />
|
<RowDefinition Height="Auto" />
|
||||||
<RowDefinition Height="Auto" />
|
<RowDefinition Height="Auto" />
|
||||||
<RowDefinition Height="Auto" />
|
<RowDefinition Height="Auto" />
|
||||||
|
<RowDefinition Height="Auto" />
|
||||||
<RowDefinition Height="*" />
|
<RowDefinition Height="*" />
|
||||||
</Grid.RowDefinitions>
|
</Grid.RowDefinitions>
|
||||||
|
|
||||||
@@ -135,23 +136,81 @@
|
|||||||
</Grid>
|
</Grid>
|
||||||
</Border>
|
</Border>
|
||||||
|
|
||||||
|
<!-- Song request (hot swap) -->
|
||||||
|
<Grid Grid.Row="4" Margin="0,0,0,12">
|
||||||
|
<Grid.ColumnDefinitions>
|
||||||
|
<ColumnDefinition Width="Auto" />
|
||||||
|
<ColumnDefinition Width="*" MaxWidth="420" />
|
||||||
|
<ColumnDefinition Width="Auto" />
|
||||||
|
<ColumnDefinition Width="*" />
|
||||||
|
</Grid.ColumnDefinitions>
|
||||||
|
<ui:TextBlock Grid.Column="0" VerticalAlignment="Center" Text="Song request" />
|
||||||
|
<ComboBox x:Name="RequestSong"
|
||||||
|
Grid.Column="1"
|
||||||
|
Margin="12,0,0,0"
|
||||||
|
AutomationProperties.Name="Requested song"
|
||||||
|
DisplayMemberPath="Label"
|
||||||
|
IsEditable="True"
|
||||||
|
IsTextSearchEnabled="True"
|
||||||
|
TextSearch.TextPath="Label"
|
||||||
|
SelectionChanged="OnRequestChanged" />
|
||||||
|
<ui:Button x:Name="SwapButton"
|
||||||
|
Grid.Column="2"
|
||||||
|
Margin="12,0,0,0"
|
||||||
|
Content="Play instead of selected"
|
||||||
|
Icon="{ui:SymbolIcon ArrowSwap24}"
|
||||||
|
IsEnabled="False"
|
||||||
|
Click="OnSwap" />
|
||||||
|
<ui:TextBlock x:Name="SwapHint"
|
||||||
|
Grid.Column="3"
|
||||||
|
Margin="12,0,0,0"
|
||||||
|
VerticalAlignment="Center"
|
||||||
|
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
|
||||||
|
TextTrimming="CharacterEllipsis"
|
||||||
|
Text="Select an upcoming item in the schedule." />
|
||||||
|
</Grid>
|
||||||
|
|
||||||
<ui:ListView x:Name="Timeline"
|
<ui:ListView x:Name="Timeline"
|
||||||
Grid.Row="4"
|
Grid.Row="5"
|
||||||
SelectionMode="Single"
|
SelectionMode="Single"
|
||||||
IsHitTestVisible="True"
|
IsHitTestVisible="True"
|
||||||
AutomationProperties.Name="Schedule timeline">
|
AutomationProperties.Name="Schedule timeline"
|
||||||
|
SelectionChanged="OnTimelineSelectionChanged">
|
||||||
<ui:ListView.View>
|
<ui:ListView.View>
|
||||||
<ui:GridView>
|
<ui:GridView>
|
||||||
|
<ui:GridViewColumn Width="36">
|
||||||
|
<ui:GridViewColumn.CellTemplate>
|
||||||
|
<DataTemplate>
|
||||||
|
<ui:SymbolIcon x:Name="OnAir"
|
||||||
|
Symbol="Play24"
|
||||||
|
Filled="True"
|
||||||
|
Foreground="{DynamicResource AccentTextFillColorPrimaryBrush}"
|
||||||
|
AutomationProperties.Name="On air"
|
||||||
|
Visibility="Collapsed" />
|
||||||
|
<DataTemplate.Triggers>
|
||||||
|
<DataTrigger Binding="{Binding IsCurrent}" Value="True">
|
||||||
|
<Setter TargetName="OnAir" Property="Visibility" Value="Visible" />
|
||||||
|
</DataTrigger>
|
||||||
|
</DataTemplate.Triggers>
|
||||||
|
</DataTemplate>
|
||||||
|
</ui:GridViewColumn.CellTemplate>
|
||||||
|
</ui:GridViewColumn>
|
||||||
<ui:GridViewColumn Width="90" Header="Start">
|
<ui:GridViewColumn Width="90" Header="Start">
|
||||||
<ui:GridViewColumn.DisplayMemberBinding>
|
<ui:GridViewColumn.DisplayMemberBinding>
|
||||||
<Binding Path="Start" StringFormat="HH:mm:ss" />
|
<Binding Path="Item.Start" StringFormat="HH:mm:ss" />
|
||||||
</ui:GridViewColumn.DisplayMemberBinding>
|
</ui:GridViewColumn.DisplayMemberBinding>
|
||||||
</ui:GridViewColumn>
|
</ui:GridViewColumn>
|
||||||
<ui:GridViewColumn Width="120" Header="Type" CellTemplate="{StaticResource KindChip}" />
|
<ui:GridViewColumn Width="120" Header="Type">
|
||||||
<ui:GridViewColumn Width="420" Header="Title" DisplayMemberBinding="{Binding Title}" />
|
<ui:GridViewColumn.CellTemplate>
|
||||||
|
<DataTemplate>
|
||||||
|
<ContentPresenter Content="{Binding Item}" ContentTemplate="{StaticResource KindChip}" />
|
||||||
|
</DataTemplate>
|
||||||
|
</ui:GridViewColumn.CellTemplate>
|
||||||
|
</ui:GridViewColumn>
|
||||||
|
<ui:GridViewColumn Width="420" Header="Title" DisplayMemberBinding="{Binding Item.Title}" />
|
||||||
<ui:GridViewColumn Width="90" Header="Duration">
|
<ui:GridViewColumn Width="90" Header="Duration">
|
||||||
<ui:GridViewColumn.DisplayMemberBinding>
|
<ui:GridViewColumn.DisplayMemberBinding>
|
||||||
<Binding Path="Duration" StringFormat="m\:ss" />
|
<Binding Path="Item.Duration" StringFormat="m\:ss" />
|
||||||
</ui:GridViewColumn.DisplayMemberBinding>
|
</ui:GridViewColumn.DisplayMemberBinding>
|
||||||
</ui:GridViewColumn>
|
</ui:GridViewColumn>
|
||||||
</ui:GridView>
|
</ui:GridView>
|
||||||
@@ -159,7 +218,7 @@
|
|||||||
</ui:ListView>
|
</ui:ListView>
|
||||||
|
|
||||||
<ui:TextBlock x:Name="EmptyText"
|
<ui:TextBlock x:Name="EmptyText"
|
||||||
Grid.Row="4"
|
Grid.Row="5"
|
||||||
Margin="0,48,0,0"
|
Margin="0,48,0,0"
|
||||||
HorizontalAlignment="Center"
|
HorizontalAlignment="Center"
|
||||||
VerticalAlignment="Top"
|
VerticalAlignment="Top"
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ using System.Windows;
|
|||||||
using System.Windows.Controls;
|
using System.Windows.Controls;
|
||||||
using System.Windows.Threading;
|
using System.Windows.Threading;
|
||||||
using Radiosender.Controllers;
|
using Radiosender.Controllers;
|
||||||
|
using Radiosender.Models;
|
||||||
using Radiosender.Services;
|
using Radiosender.Services;
|
||||||
using Wpf.Ui.Controls;
|
using Wpf.Ui.Controls;
|
||||||
|
|
||||||
@@ -12,6 +13,7 @@ public partial class SchedulePage : Page
|
|||||||
private readonly ScheduleController _controller = App.Schedule;
|
private readonly ScheduleController _controller = App.Schedule;
|
||||||
private readonly DispatcherTimer _progressTimer = new() { Interval = TimeSpan.FromMilliseconds(250) };
|
private readonly DispatcherTimer _progressTimer = new() { Interval = TimeSpan.FromMilliseconds(250) };
|
||||||
private bool _loading;
|
private bool _loading;
|
||||||
|
private int _scrolledTo = -1;
|
||||||
|
|
||||||
public SchedulePage()
|
public SchedulePage()
|
||||||
{
|
{
|
||||||
@@ -35,7 +37,12 @@ public partial class SchedulePage : Page
|
|||||||
VolumeSlider.Value = _controller.Volume;
|
VolumeSlider.Value = _controller.Volume;
|
||||||
_loading = false;
|
_loading = false;
|
||||||
|
|
||||||
ShowPlan();
|
// The library can change on other pages.
|
||||||
|
RequestSong.ItemsSource = _controller.LibrarySongs()
|
||||||
|
.OrderBy(s => s.Artist).ThenBy(s => s.Title)
|
||||||
|
.Select(s => new SongOption(s.Id, $"{(string.IsNullOrWhiteSpace(s.Artist) ? s.Title : $"{s.Artist} - {s.Title}")} ({s.Duration:m\\:ss})"))
|
||||||
|
.ToList();
|
||||||
|
|
||||||
ShowCurrent();
|
ShowCurrent();
|
||||||
_progressTimer.Start();
|
_progressTimer.Start();
|
||||||
}
|
}
|
||||||
@@ -62,10 +69,31 @@ public partial class SchedulePage : Page
|
|||||||
{
|
{
|
||||||
ShowMessage(InfoBarSeverity.Error, "Could not create the schedule", ex.Message);
|
ShowMessage(InfoBarSeverity.Error, "Could not create the schedule", ex.Message);
|
||||||
}
|
}
|
||||||
ShowPlan();
|
|
||||||
ShowCurrent();
|
ShowCurrent();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private 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();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnRequestChanged(object sender, SelectionChangedEventArgs e) => UpdateButtons();
|
||||||
|
|
||||||
|
private void OnTimelineSelectionChanged(object sender, SelectionChangedEventArgs e) => UpdateButtons();
|
||||||
|
|
||||||
private void OnStart(object sender, RoutedEventArgs e)
|
private void OnStart(object sender, RoutedEventArgs e)
|
||||||
{
|
{
|
||||||
Message.IsOpen = false;
|
Message.IsOpen = false;
|
||||||
@@ -96,25 +124,30 @@ public partial class SchedulePage : Page
|
|||||||
ShowCurrent();
|
ShowCurrent();
|
||||||
});
|
});
|
||||||
|
|
||||||
private void ShowPlan()
|
// Rebuilds the rows from the controller; the selection is the user's swap target and is kept.
|
||||||
{
|
|
||||||
Timeline.ItemsSource = _controller.Plan;
|
|
||||||
EmptyText.Visibility = _controller.Plan.Count == 0 ? Visibility.Visible : Visibility.Collapsed;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void ShowCurrent()
|
private void ShowCurrent()
|
||||||
{
|
{
|
||||||
var item = _controller.CurrentItem;
|
var item = _controller.CurrentItem;
|
||||||
UpdateButtons();
|
var current = _controller.CurrentIndex;
|
||||||
|
var plan = _controller.Plan;
|
||||||
|
|
||||||
|
var selected = Timeline.SelectedIndex;
|
||||||
|
var rows = plan.Select((p, i) => new TimelineRow(i, p, i == current)).ToList();
|
||||||
|
Timeline.ItemsSource = rows;
|
||||||
|
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)
|
||||||
|
Timeline.ScrollIntoView(rows[current]);
|
||||||
|
else if (Timeline.SelectedItem is { } row)
|
||||||
|
Timeline.ScrollIntoView(row);
|
||||||
|
_scrolledTo = current;
|
||||||
|
EmptyText.Visibility = plan.Count == 0 ? Visibility.Visible : Visibility.Collapsed;
|
||||||
|
|
||||||
NowKind.Content = item;
|
NowKind.Content = item;
|
||||||
NowKind.Visibility = item is null ? Visibility.Collapsed : Visibility.Visible;
|
NowKind.Visibility = item is null ? Visibility.Collapsed : Visibility.Visible;
|
||||||
NowTitle.Text = item?.Title ?? "Nothing on air";
|
NowTitle.Text = item?.Title ?? "Nothing on air";
|
||||||
|
|
||||||
Timeline.SelectedIndex = _controller.CurrentIndex;
|
UpdateButtons();
|
||||||
if (Timeline.SelectedItem is { } selected)
|
|
||||||
Timeline.ScrollIntoView(selected);
|
|
||||||
|
|
||||||
UpdateProgress();
|
UpdateProgress();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -123,6 +156,18 @@ public partial class SchedulePage : Page
|
|||||||
var playing = _controller.IsPlaying;
|
var playing = _controller.IsPlaying;
|
||||||
StartButton.IsEnabled = !playing && _controller.Plan.Count > 0;
|
StartButton.IsEnabled = !playing && _controller.Plan.Count > 0;
|
||||||
StopButton.IsEnabled = playing;
|
StopButton.IsEnabled = playing;
|
||||||
|
|
||||||
|
var row = Timeline.SelectedItem as TimelineRow;
|
||||||
|
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,
|
||||||
|
};
|
||||||
|
SwapHint.Text = blocker ?? $"Replaces the item at {row!.Item.Start:HH:mm:ss}.";
|
||||||
|
SwapButton.IsEnabled = blocker is null;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void UpdateProgress()
|
private void UpdateProgress()
|
||||||
@@ -146,4 +191,8 @@ public partial class SchedulePage : Page
|
|||||||
Message.Message = text;
|
Message.Message = text;
|
||||||
Message.IsOpen = true;
|
Message.IsOpen = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private sealed record TimelineRow(int Index, ScheduleItem Item, bool IsCurrent);
|
||||||
|
|
||||||
|
private sealed record SongOption(long Id, string Label);
|
||||||
}
|
}
|
||||||
@@ -159,4 +159,33 @@ public class PlaybackEngineTests
|
|||||||
|
|
||||||
Assert.Equal(["c.mp3"], player.Played);
|
Assert.Equal(["c.mp3"], player.Played);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
[Fact]
|
||||||
|
public async Task ReplaceUpcoming_PlaysTheNewItemsButNotOverItemsAlreadyStarted()
|
||||||
|
{
|
||||||
|
var player = new FakePlayer();
|
||||||
|
var news = new TaskCompletionSource();
|
||||||
|
var first = true;
|
||||||
|
// The first delay is the news; it waits until released. Song timeouts never fire.
|
||||||
|
Task Delay(TimeSpan d, CancellationToken t)
|
||||||
|
{
|
||||||
|
if (first) { first = false; return news.Task.WaitAsync(t); }
|
||||||
|
return d > TimeSpan.FromSeconds(180) ? Task.Delay(Timeout.Infinite, t) : Task.CompletedTask;
|
||||||
|
}
|
||||||
|
var engine = new PlaybackEngine(player, Delay);
|
||||||
|
var started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||||
|
var finished = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||||
|
engine.ItemStarted += (_, _) => started.TrySetResult();
|
||||||
|
engine.Finished += (_, _) => finished.TrySetResult();
|
||||||
|
|
||||||
|
engine.Start(Plan);
|
||||||
|
await started.Task.WaitAsync(Wait);
|
||||||
|
IReadOnlyList<ScheduleItem> swapped = [Plan[0], SongItem("request.mp3", 200), .. Plan.Skip(2)];
|
||||||
|
|
||||||
|
Assert.False(engine.ReplaceUpcoming(swapped, 0));
|
||||||
|
Assert.True(engine.ReplaceUpcoming(swapped, 1));
|
||||||
|
news.SetResult();
|
||||||
|
await finished.Task.WaitAsync(Wait);
|
||||||
|
|
||||||
|
Assert.Equal(["request.mp3", "b.mp3"], player.Played);
|
||||||
|
}}
|
||||||
@@ -114,4 +114,49 @@ public sealed class ScheduleControllerTests : IDisposable
|
|||||||
Assert.False(controller.IsPlaying);
|
Assert.False(controller.IsPlaying);
|
||||||
Assert.Null(controller.CurrentItem);
|
Assert.Null(controller.CurrentItem);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
[Fact]
|
||||||
|
public void Swap_ReplacesAnItemBeforeStart()
|
||||||
|
{
|
||||||
|
AddSongs();
|
||||||
|
var controller = Create();
|
||||||
|
controller.CreatePlan(1);
|
||||||
|
var request = _songs.GetAll()[3];
|
||||||
|
|
||||||
|
var plan = controller.Swap(1, request.Id);
|
||||||
|
|
||||||
|
Assert.Equal(request.Id, plan[1].Song!.Id);
|
||||||
|
Assert.Same(plan, controller.Plan);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Swap_WhilePlayingRejectsTheItemOnAirAndAcceptsALaterOne()
|
||||||
|
{
|
||||||
|
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();
|
||||||
|
var request = _songs.GetAll()[3];
|
||||||
|
|
||||||
|
controller.Start();
|
||||||
|
await first.Task.WaitAsync(TimeSpan.FromSeconds(5));
|
||||||
|
|
||||||
|
var onAir = Assert.Throws<ScheduleException>(() => controller.Swap(0, request.Id));
|
||||||
|
Assert.Contains("already on air", onAir.Message);
|
||||||
|
controller.Swap(1, request.Id);
|
||||||
|
Assert.Equal(request.Id, controller.Plan[1].Song!.Id);
|
||||||
|
controller.Stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Swap_RejectsUnknownSongAndMissingPlan()
|
||||||
|
{
|
||||||
|
AddSongs();
|
||||||
|
var controller = Create();
|
||||||
|
Assert.Throws<ScheduleException>(() => controller.Swap(1, _songs.GetAll()[0].Id));
|
||||||
|
|
||||||
|
controller.CreatePlan(1);
|
||||||
|
Assert.Throws<ScheduleException>(() => controller.Swap(1, 12345));
|
||||||
|
}}
|
||||||
@@ -143,4 +143,69 @@ public class ScheduleGeneratorTests
|
|||||||
Assert.Throws<ArgumentException>(() =>
|
Assert.Throws<ArgumentException>(() =>
|
||||||
new ScheduleGenerator(new ScheduleOptions { MaxAdBlock = TimeSpan.FromMinutes(20) }, new Random(1)).Generate(Start, 1, Library));
|
new ScheduleGenerator(new ScheduleOptions { MaxAdBlock = TimeSpan.FromMinutes(20) }, new Random(1)).Generate(Start, 1, Library));
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
private static readonly Song Request = Song(99, 4 * 60 + 17);
|
||||||
|
|
||||||
|
private static ScheduleGenerator Generator(int seed) => new(new ScheduleOptions(), new Random(seed));
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(Seeds))]
|
||||||
|
public void Replace_PutsTheSongInPlaceAndKeepsEverythingElseOnTime(int seed)
|
||||||
|
{
|
||||||
|
var plan = Generate(seed, hours: 2);
|
||||||
|
var index = 1; // first item after the 14:00 news
|
||||||
|
var nextNews = plan.Select((p, i) => (p, i)).First(x => x.i > index && x.p.Kind == ScheduleItemKind.News).i;
|
||||||
|
|
||||||
|
var swapped = Generator(seed).Replace(plan, index, Request, Library);
|
||||||
|
|
||||||
|
Assert.Equal(plan.Take(index), swapped.Take(index));
|
||||||
|
Assert.Equal(Request, swapped[index].Song);
|
||||||
|
Assert.Equal(plan[index].Start, swapped[index].Start);
|
||||||
|
// Later slots are untouched, so the next news is still at 14:30.
|
||||||
|
var swappedNews = swapped.Select((p, i) => (p, i)).First(x => x.i > index && x.p.Kind == ScheduleItemKind.News).i;
|
||||||
|
Assert.Equal(plan.Skip(nextNews), swapped.Skip(swappedNews));
|
||||||
|
Assert.Equal(ScheduleItemKind.Song, swapped[swappedNews - 1].Kind);
|
||||||
|
for (var i = 1; i < swapped.Count; i++)
|
||||||
|
Assert.Equal(swapped[i - 1].End, swapped[i].Start);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(Seeds))]
|
||||||
|
public void Replace_KeepsFillerLimitsAndNoAdsBackToBack(int seed)
|
||||||
|
{
|
||||||
|
var plan = Generate(seed, hours: 1);
|
||||||
|
// Every non-news item in the first half hour, so prefixes with filler are covered too.
|
||||||
|
var last = plan.Select((p, i) => (p, i)).First(x => x.i > 0 && x.p.Kind == ScheduleItemKind.News).i;
|
||||||
|
for (var index = 1; index < last; index++)
|
||||||
|
{
|
||||||
|
IReadOnlyList<ScheduleItem> swapped;
|
||||||
|
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}");
|
||||||
|
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}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Replace_RejectsSongThatDoesNotFitBeforeTheNews()
|
||||||
|
{
|
||||||
|
var plan = Generate(1, hours: 1);
|
||||||
|
var beforeNews = plan.Select((p, i) => (p, i)).First(x => x.i > 0 && x.p.Kind == ScheduleItemKind.News).i - 1;
|
||||||
|
var tooLong = Song(98, 25 * 60);
|
||||||
|
|
||||||
|
var ex = Assert.Throws<ScheduleException>(() => Generator(1).Replace(plan, beforeNews, tooLong, Library));
|
||||||
|
Assert.Contains("does not fit", ex.Message);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Replace_RejectsNews()
|
||||||
|
{
|
||||||
|
var plan = Generate(1, hours: 1);
|
||||||
|
|
||||||
|
Assert.Throws<ScheduleException>(() => Generator(1).Replace(plan, 0, Request, Library));
|
||||||
|
}}
|
||||||
Reference in new issue
Block a user