Merge remote-tracking branch 'origin/main' into j.lechner/openverse
# Conflicts: # src/Radiosender/Views/MainWindow.xaml
This commit is contained in:
commit
d3f9da32b8
14 files changed
+729
No files matched your search
@@ -0,0 +1,42 @@
|
|||||||
|
using Radiosender.Models;
|
||||||
|
using Radiosender.Services;
|
||||||
|
|
||||||
|
namespace Radiosender.Controllers;
|
||||||
|
|
||||||
|
public class LibraryController(SongRepository repository)
|
||||||
|
{
|
||||||
|
/// <summary>Returns all songs whose title or artist contains <paramref name="query"/> (case-insensitive).</summary>
|
||||||
|
public IReadOnlyList<Song> Search(string? query)
|
||||||
|
{
|
||||||
|
var songs = repository.GetAll();
|
||||||
|
if (string.IsNullOrWhiteSpace(query))
|
||||||
|
return songs;
|
||||||
|
|
||||||
|
query = query.Trim();
|
||||||
|
return songs
|
||||||
|
.Where(s => s.Title.Contains(query, StringComparison.OrdinalIgnoreCase)
|
||||||
|
|| s.Artist.Contains(query, StringComparison.OrdinalIgnoreCase))
|
||||||
|
.ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Writes the editable metadata; file path, duration and source keep their stored values.</summary>
|
||||||
|
/// <returns><c>false</c> if the song no longer exists.</returns>
|
||||||
|
public bool Update(long id, string title, string artist, string? license, string? attribution)
|
||||||
|
{
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(title);
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(artist);
|
||||||
|
|
||||||
|
var song = repository.GetById(id);
|
||||||
|
if (song is null)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
song.Title = title.Trim();
|
||||||
|
song.Artist = artist.Trim();
|
||||||
|
song.License = string.IsNullOrWhiteSpace(license) ? null : license.Trim();
|
||||||
|
song.Attribution = string.IsNullOrWhiteSpace(attribution) ? null : attribution.Trim();
|
||||||
|
return repository.Update(song);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <returns><c>false</c> if the song no longer exists.</returns>
|
||||||
|
public bool Delete(long id) => repository.Delete(id);
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace Radiosender.Models;
|
||||||
|
|
||||||
|
// Placeholder without audio: the schedule only needs a title and a length.
|
||||||
|
public record AdSpot(string Title, TimeSpan Duration);
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace Radiosender.Models;
|
||||||
|
|
||||||
|
// Placeholder without audio: the schedule only needs a title and a length.
|
||||||
|
public record ModeratorSegment(string Title, TimeSpan Duration);
|
||||||
@@ -10,6 +10,7 @@
|
|||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Microsoft.Data.Sqlite" Version="10.0.15" />
|
<PackageReference Include="Microsoft.Data.Sqlite" Version="10.0.15" />
|
||||||
|
<PackageReference Include="NAudio" Version="3.3.0" />
|
||||||
<PackageReference Include="WPF-UI" Version="4.3.0" />
|
<PackageReference Include="WPF-UI" Version="4.3.0" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,174 @@
|
|||||||
|
using System.IO;
|
||||||
|
using NAudio.Wave;
|
||||||
|
|
||||||
|
namespace Radiosender.Services;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Plays one audio file at a time through the default output device.
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// <see cref="TrackFinished"/> and <see cref="PositionChanged"/> are raised on a thread-pool thread,
|
||||||
|
/// never on the WPF UI thread. WPF callers must marshal with <c>Dispatcher.Invoke</c> or
|
||||||
|
/// <c>Dispatcher.BeginInvoke</c> before touching UI elements.
|
||||||
|
/// </remarks>
|
||||||
|
public sealed class MusicPlayer
|
||||||
|
{
|
||||||
|
private static readonly Lazy<MusicPlayer> LazyInstance = new(() => new MusicPlayer());
|
||||||
|
|
||||||
|
private static readonly TimeSpan PositionInterval = TimeSpan.FromMilliseconds(250);
|
||||||
|
|
||||||
|
private readonly Lock _lock = new();
|
||||||
|
private WaveOut? _output;
|
||||||
|
private AudioFileReader? _reader;
|
||||||
|
private Timer? _positionTimer;
|
||||||
|
private float _volume = 1f;
|
||||||
|
|
||||||
|
private MusicPlayer()
|
||||||
|
{
|
||||||
|
// Releases the audio device when the app exits.
|
||||||
|
AppDomain.CurrentDomain.ProcessExit += (_, _) => Stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static MusicPlayer Instance => LazyInstance.Value;
|
||||||
|
|
||||||
|
/// <summary>Raised when a track reaches its end. Not raised by <see cref="Stop"/> or by <see cref="Play"/> replacing a track.</summary>
|
||||||
|
public event EventHandler? TrackFinished;
|
||||||
|
|
||||||
|
/// <summary>Raised about every 250 ms while a track is playing, with the current position.</summary>
|
||||||
|
public event EventHandler<TimeSpan>? PositionChanged;
|
||||||
|
|
||||||
|
public bool IsPlaying
|
||||||
|
{
|
||||||
|
get { lock (_lock) return _output?.PlaybackState == PlaybackState.Playing; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public TimeSpan Position
|
||||||
|
{
|
||||||
|
get { lock (_lock) return _reader?.CurrentTime ?? TimeSpan.Zero; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public TimeSpan Duration
|
||||||
|
{
|
||||||
|
get { lock (_lock) return _reader?.TotalTime ?? TimeSpan.Zero; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Playback volume from 0 (silent) to 1 (full). Kept across tracks.</summary>
|
||||||
|
public float Volume
|
||||||
|
{
|
||||||
|
get { lock (_lock) return _volume; }
|
||||||
|
set
|
||||||
|
{
|
||||||
|
ArgumentOutOfRangeException.ThrowIfLessThan(value, 0f);
|
||||||
|
ArgumentOutOfRangeException.ThrowIfGreaterThan(value, 1f);
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
_volume = value;
|
||||||
|
if (_reader is not null) _reader.Volume = value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Stops the current track and starts playing <paramref name="filePath"/>.</summary>
|
||||||
|
/// <exception cref="FileNotFoundException">The file does not exist.</exception>
|
||||||
|
/// <exception cref="InvalidDataException">The file is not a readable audio file.</exception>
|
||||||
|
public void Play(string filePath)
|
||||||
|
{
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(filePath);
|
||||||
|
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
Release();
|
||||||
|
|
||||||
|
if (!File.Exists(filePath))
|
||||||
|
throw new FileNotFoundException($"Audio file not found: {filePath}", filePath);
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
_reader = new AudioFileReader(filePath) { Volume = _volume };
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||||
|
{
|
||||||
|
throw new InvalidDataException($"Cannot read audio file: {filePath}", ex);
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
_output = new WaveOut();
|
||||||
|
_output.PlaybackStopped += OnPlaybackStopped;
|
||||||
|
_output.Init(_reader);
|
||||||
|
_output.Play();
|
||||||
|
_positionTimer = new Timer(OnPositionTimer, null, PositionInterval, PositionInterval);
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
Release();
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Pause()
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
if (_output?.PlaybackState == PlaybackState.Playing) _output.Pause();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Resume()
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
if (_output?.PlaybackState == PlaybackState.Paused) _output.Play();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Stops playback and releases the file and audio device. Does not raise <see cref="TrackFinished"/>.</summary>
|
||||||
|
public void Stop()
|
||||||
|
{
|
||||||
|
lock (_lock) Release();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Caller holds _lock. Unsubscribing first keeps Stop and track replacement from raising TrackFinished.
|
||||||
|
private void Release()
|
||||||
|
{
|
||||||
|
_positionTimer?.Dispose();
|
||||||
|
_positionTimer = null;
|
||||||
|
|
||||||
|
if (_output is not null)
|
||||||
|
{
|
||||||
|
_output.PlaybackStopped -= OnPlaybackStopped;
|
||||||
|
_output.Dispose();
|
||||||
|
_output = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
_reader?.Dispose();
|
||||||
|
_reader = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnPlaybackStopped(object? sender, StoppedEventArgs e)
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
// A stale event from an output that Stop or Play already released.
|
||||||
|
if (!ReferenceEquals(sender, _output)) return;
|
||||||
|
Release();
|
||||||
|
}
|
||||||
|
|
||||||
|
// An exception means a device error, not a natural end of the track.
|
||||||
|
if (e.Exception is null)
|
||||||
|
ThreadPool.QueueUserWorkItem(_ => TrackFinished?.Invoke(this, EventArgs.Empty));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnPositionTimer(object? state)
|
||||||
|
{
|
||||||
|
TimeSpan position;
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
if (_output?.PlaybackState != PlaybackState.Playing || _reader is null) return;
|
||||||
|
position = _reader.CurrentTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
PositionChanged?.Invoke(this, position);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
using Radiosender.Models;
|
||||||
|
|
||||||
|
namespace Radiosender.Services;
|
||||||
|
|
||||||
|
// In-memory seed data; varied lengths let the schedule generator fill gaps before the news.
|
||||||
|
public static class PlaceholderContent
|
||||||
|
{
|
||||||
|
public static IReadOnlyList<AdSpot> AdSpots { get; } =
|
||||||
|
[
|
||||||
|
new("Bakery Sonnenschein", TimeSpan.FromSeconds(30)),
|
||||||
|
new("Autohaus Berger", TimeSpan.FromSeconds(45)),
|
||||||
|
new("Stadtwerke Energy Tips", TimeSpan.FromSeconds(60)),
|
||||||
|
new("Furniture Outlet Sale", TimeSpan.FromSeconds(75)),
|
||||||
|
new("Regional Bank Savings", TimeSpan.FromSeconds(90)),
|
||||||
|
new("Summer Festival Preview", TimeSpan.FromMinutes(2)),
|
||||||
|
];
|
||||||
|
|
||||||
|
public static IReadOnlyList<ModeratorSegment> ModeratorSegments { get; } =
|
||||||
|
[
|
||||||
|
new("Station ID", TimeSpan.FromSeconds(30)),
|
||||||
|
new("Weather Update", TimeSpan.FromSeconds(60)),
|
||||||
|
new("Traffic Report", TimeSpan.FromSeconds(90)),
|
||||||
|
new("Song Introduction", TimeSpan.FromMinutes(2)),
|
||||||
|
new("Local Events", TimeSpan.FromSeconds(150)),
|
||||||
|
new("Listener Greetings", TimeSpan.FromMinutes(3)),
|
||||||
|
];
|
||||||
|
}
|
||||||
@@ -22,6 +22,9 @@
|
|||||||
<ui:NavigationViewItem Content="Home"
|
<ui:NavigationViewItem Content="Home"
|
||||||
Icon="{ui:SymbolIcon Home24}"
|
Icon="{ui:SymbolIcon Home24}"
|
||||||
TargetPageType="{x:Type pages:HomePage}" />
|
TargetPageType="{x:Type pages:HomePage}" />
|
||||||
|
<ui:NavigationViewItem Content="Library"
|
||||||
|
Icon="{ui:SymbolIcon MusicNote224}"
|
||||||
|
TargetPageType="{x:Type pages:LibraryPage}" />
|
||||||
<ui:NavigationViewItem Content="Openverse"
|
<ui:NavigationViewItem Content="Openverse"
|
||||||
Icon="{ui:SymbolIcon Search24}"
|
Icon="{ui:SymbolIcon Search24}"
|
||||||
TargetPageType="{x:Type pages:OpenversePage}" />
|
TargetPageType="{x:Type pages:OpenversePage}" />
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
<Page x:Class="Radiosender.Views.Pages.LibraryPage"
|
||||||
|
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"
|
||||||
|
Loaded="OnLoaded">
|
||||||
|
<Grid Margin="24">
|
||||||
|
<Grid.RowDefinitions>
|
||||||
|
<RowDefinition Height="Auto" />
|
||||||
|
<RowDefinition Height="Auto" />
|
||||||
|
<RowDefinition Height="*" />
|
||||||
|
</Grid.RowDefinitions>
|
||||||
|
|
||||||
|
<ui:TextBlock Grid.Row="0" FontTypography="Title" Text="Library" />
|
||||||
|
|
||||||
|
<DockPanel Grid.Row="1" Margin="0,16,0,12" LastChildFill="True">
|
||||||
|
<ui:Button x:Name="DeleteButton"
|
||||||
|
DockPanel.Dock="Right"
|
||||||
|
Margin="8,0,0,0"
|
||||||
|
Content="Delete"
|
||||||
|
Icon="{ui:SymbolIcon Delete24}"
|
||||||
|
IsEnabled="False"
|
||||||
|
Click="OnDelete" />
|
||||||
|
<ui:Button x:Name="EditButton"
|
||||||
|
DockPanel.Dock="Right"
|
||||||
|
Margin="8,0,0,0"
|
||||||
|
Content="Edit"
|
||||||
|
Icon="{ui:SymbolIcon Edit24}"
|
||||||
|
IsEnabled="False"
|
||||||
|
Click="OnEdit" />
|
||||||
|
<ui:TextBox x:Name="SearchBox"
|
||||||
|
AutomationProperties.Name="Search songs"
|
||||||
|
PlaceholderText="Search title or artist"
|
||||||
|
Icon="{ui:SymbolIcon Search24}"
|
||||||
|
TextChanged="OnSearchChanged" />
|
||||||
|
</DockPanel>
|
||||||
|
|
||||||
|
<ui:ListView x:Name="SongList"
|
||||||
|
Grid.Row="2"
|
||||||
|
SelectionMode="Single"
|
||||||
|
AutomationProperties.Name="Songs"
|
||||||
|
SelectionChanged="OnSelectionChanged"
|
||||||
|
MouseDoubleClick="OnEdit">
|
||||||
|
<ui:ListView.View>
|
||||||
|
<ui:GridView>
|
||||||
|
<ui:GridViewColumn Width="260" Header="Title" DisplayMemberBinding="{Binding Title}" />
|
||||||
|
<ui:GridViewColumn Width="200" Header="Artist" DisplayMemberBinding="{Binding Artist}" />
|
||||||
|
<ui:GridViewColumn Width="80" Header="Duration">
|
||||||
|
<ui:GridViewColumn.DisplayMemberBinding>
|
||||||
|
<Binding Path="Duration" StringFormat="m\:ss" />
|
||||||
|
</ui:GridViewColumn.DisplayMemberBinding>
|
||||||
|
</ui:GridViewColumn>
|
||||||
|
<ui:GridViewColumn Width="140" Header="License" DisplayMemberBinding="{Binding License}" />
|
||||||
|
<ui:GridViewColumn Width="220" Header="Attribution" DisplayMemberBinding="{Binding Attribution}" />
|
||||||
|
</ui:GridView>
|
||||||
|
</ui:ListView.View>
|
||||||
|
</ui:ListView>
|
||||||
|
|
||||||
|
<ui:TextBlock x:Name="EmptyText"
|
||||||
|
Grid.Row="2"
|
||||||
|
Margin="0,48,0,0"
|
||||||
|
HorizontalAlignment="Center"
|
||||||
|
VerticalAlignment="Top"
|
||||||
|
Text="No songs found."
|
||||||
|
Visibility="Collapsed" />
|
||||||
|
</Grid>
|
||||||
|
</Page>
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
using System.Windows;
|
||||||
|
using System.Windows.Controls;
|
||||||
|
using Radiosender.Controllers;
|
||||||
|
using Radiosender.Models;
|
||||||
|
using Wpf.Ui.Controls;
|
||||||
|
using MessageBox = Wpf.Ui.Controls.MessageBox;
|
||||||
|
|
||||||
|
namespace Radiosender.Views.Pages;
|
||||||
|
|
||||||
|
public partial class LibraryPage : Page
|
||||||
|
{
|
||||||
|
private readonly LibraryController _controller = new(App.Songs);
|
||||||
|
|
||||||
|
public LibraryPage() => InitializeComponent();
|
||||||
|
|
||||||
|
private Song? Selected => SongList.SelectedItem as Song;
|
||||||
|
|
||||||
|
// Loaded fires on every navigation to the page, so the list is reloaded from the database each time.
|
||||||
|
private void OnLoaded(object sender, RoutedEventArgs e) => Refresh();
|
||||||
|
|
||||||
|
private void OnSearchChanged(object sender, TextChangedEventArgs e) => Refresh();
|
||||||
|
|
||||||
|
private void OnSelectionChanged(object sender, SelectionChangedEventArgs e) =>
|
||||||
|
EditButton.IsEnabled = DeleteButton.IsEnabled = Selected is not null;
|
||||||
|
|
||||||
|
private void Refresh()
|
||||||
|
{
|
||||||
|
var songs = _controller.Search(SearchBox.Text);
|
||||||
|
SongList.ItemsSource = songs;
|
||||||
|
EmptyText.Visibility = songs.Count == 0 ? Visibility.Visible : Visibility.Collapsed;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnEdit(object sender, RoutedEventArgs e)
|
||||||
|
{
|
||||||
|
if (Selected is not { } song)
|
||||||
|
return;
|
||||||
|
|
||||||
|
var dialog = new SongEditWindow(song) { Owner = Window.GetWindow(this) };
|
||||||
|
if (dialog.ShowDialog() == true)
|
||||||
|
_controller.Update(song.Id, dialog.SongTitle, dialog.Artist, dialog.License, dialog.Attribution);
|
||||||
|
Refresh();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async void OnDelete(object sender, RoutedEventArgs e)
|
||||||
|
{
|
||||||
|
if (Selected is not { } song)
|
||||||
|
return;
|
||||||
|
|
||||||
|
var result = await new MessageBox
|
||||||
|
{
|
||||||
|
Title = "Delete song",
|
||||||
|
Content = $"Delete \"{song.Title}\" by {song.Artist} from the library?",
|
||||||
|
PrimaryButtonText = "Delete",
|
||||||
|
CloseButtonText = "Cancel",
|
||||||
|
}.ShowDialogAsync();
|
||||||
|
|
||||||
|
if (result != Wpf.Ui.Controls.MessageBoxResult.Primary)
|
||||||
|
return;
|
||||||
|
|
||||||
|
_controller.Delete(song.Id);
|
||||||
|
Refresh();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
<ui:FluentWindow x:Class="Radiosender.Views.SongEditWindow"
|
||||||
|
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"
|
||||||
|
Width="460" SizeToContent="Height"
|
||||||
|
ResizeMode="NoResize"
|
||||||
|
ShowInTaskbar="False"
|
||||||
|
ExtendsContentIntoTitleBar="True"
|
||||||
|
WindowBackdropType="Mica"
|
||||||
|
WindowStartupLocation="CenterOwner"
|
||||||
|
FocusManager.FocusedElement="{Binding ElementName=TitleBox}">
|
||||||
|
<StackPanel>
|
||||||
|
<ui:TitleBar Title="Edit song" ShowMinimize="False" ShowMaximize="False" />
|
||||||
|
|
||||||
|
<StackPanel Margin="24,8,24,24">
|
||||||
|
<Label Content="_Title" Target="{Binding ElementName=TitleBox}" />
|
||||||
|
<ui:TextBox x:Name="TitleBox" Margin="0,0,0,12" />
|
||||||
|
|
||||||
|
<Label Content="_Artist" Target="{Binding ElementName=ArtistBox}" />
|
||||||
|
<ui:TextBox x:Name="ArtistBox" Margin="0,0,0,12" />
|
||||||
|
|
||||||
|
<Label Content="_License" Target="{Binding ElementName=LicenseBox}" />
|
||||||
|
<ui:TextBox x:Name="LicenseBox" Margin="0,0,0,12" PlaceholderText="Optional, e.g. CC BY 4.0" />
|
||||||
|
|
||||||
|
<Label Content="Attri_bution" Target="{Binding ElementName=AttributionBox}" />
|
||||||
|
<ui:TextBox x:Name="AttributionBox" PlaceholderText="Optional" />
|
||||||
|
|
||||||
|
<TextBlock x:Name="ErrorText"
|
||||||
|
Margin="0,12,0,0"
|
||||||
|
Foreground="{DynamicResource SystemFillColorCriticalBrush}"
|
||||||
|
Text="Title and artist are required."
|
||||||
|
Visibility="Collapsed" />
|
||||||
|
|
||||||
|
<StackPanel Margin="0,24,0,0" HorizontalAlignment="Right" Orientation="Horizontal">
|
||||||
|
<ui:Button Content="Save" Appearance="Primary" IsDefault="True" MinWidth="90" Click="OnSave" />
|
||||||
|
<ui:Button Margin="8,0,0,0" Content="Cancel" IsCancel="True" MinWidth="90" />
|
||||||
|
</StackPanel>
|
||||||
|
</StackPanel>
|
||||||
|
</StackPanel>
|
||||||
|
</ui:FluentWindow>
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
using System.Windows;
|
||||||
|
using Radiosender.Models;
|
||||||
|
using Wpf.Ui.Controls;
|
||||||
|
|
||||||
|
namespace Radiosender.Views;
|
||||||
|
|
||||||
|
/// <summary>Dialog for the editable song metadata. Only collects input; saving is done by the caller.</summary>
|
||||||
|
public partial class SongEditWindow : FluentWindow
|
||||||
|
{
|
||||||
|
public SongEditWindow(Song song)
|
||||||
|
{
|
||||||
|
InitializeComponent();
|
||||||
|
TitleBox.Text = song.Title;
|
||||||
|
ArtistBox.Text = song.Artist;
|
||||||
|
LicenseBox.Text = song.License;
|
||||||
|
AttributionBox.Text = song.Attribution;
|
||||||
|
}
|
||||||
|
|
||||||
|
public string SongTitle => TitleBox.Text;
|
||||||
|
public string Artist => ArtistBox.Text;
|
||||||
|
public string License => LicenseBox.Text;
|
||||||
|
public string Attribution => AttributionBox.Text;
|
||||||
|
|
||||||
|
private void OnSave(object sender, RoutedEventArgs e)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(SongTitle) || string.IsNullOrWhiteSpace(Artist))
|
||||||
|
{
|
||||||
|
ErrorText.Visibility = Visibility.Visible;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
DialogResult = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
using Microsoft.Data.Sqlite;
|
||||||
|
using Radiosender.Controllers;
|
||||||
|
using Radiosender.Models;
|
||||||
|
using Radiosender.Services;
|
||||||
|
|
||||||
|
namespace Radiosender.Tests;
|
||||||
|
|
||||||
|
public sealed class LibraryControllerTests : IDisposable
|
||||||
|
{
|
||||||
|
private readonly string _directory = Path.Combine(Path.GetTempPath(), "radiosender-tests", Guid.NewGuid().ToString("N"));
|
||||||
|
private readonly SongRepository _repository;
|
||||||
|
private readonly LibraryController _controller;
|
||||||
|
|
||||||
|
public LibraryControllerTests()
|
||||||
|
{
|
||||||
|
_repository = new SongRepository(Path.Combine(_directory, "test.db"));
|
||||||
|
_controller = new LibraryController(_repository);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
SqliteConnection.ClearAllPools(); // pooled connections keep the file locked
|
||||||
|
Directory.Delete(_directory, recursive: true);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Song AddSong(string title, string artist)
|
||||||
|
{
|
||||||
|
var song = new Song
|
||||||
|
{
|
||||||
|
Title = title,
|
||||||
|
Artist = artist,
|
||||||
|
Duration = TimeSpan.FromSeconds(200),
|
||||||
|
FilePath = @"C:\music\song.mp3",
|
||||||
|
Source = SongSource.Upload,
|
||||||
|
License = "CC BY 4.0",
|
||||||
|
};
|
||||||
|
_repository.Add(song);
|
||||||
|
return song;
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(null)]
|
||||||
|
[InlineData("")]
|
||||||
|
[InlineData(" ")]
|
||||||
|
public void Search_WithoutQuery_ReturnsAllSongs(string? query)
|
||||||
|
{
|
||||||
|
AddSong("Alpha", "Band");
|
||||||
|
AddSong("Beta", "Other");
|
||||||
|
|
||||||
|
Assert.Equal(2, _controller.Search(query).Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Search_MatchesTitleOrArtistCaseInsensitive()
|
||||||
|
{
|
||||||
|
AddSong("Morning Light", "Band");
|
||||||
|
AddSong("Evening", "The Lights");
|
||||||
|
AddSong("Unrelated", "Nobody");
|
||||||
|
|
||||||
|
var titles = _controller.Search(" LIGHT ").Select(s => s.Title).ToList();
|
||||||
|
|
||||||
|
Assert.Equal(["Evening", "Morning Light"], titles.Order());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Update_WritesEditableFieldsAndKeepsTheRest()
|
||||||
|
{
|
||||||
|
var song = AddSong("Old", "Old Artist");
|
||||||
|
|
||||||
|
Assert.True(_controller.Update(song.Id, " New ", "New Artist", " ", "by someone"));
|
||||||
|
|
||||||
|
var loaded = _repository.GetById(song.Id)!;
|
||||||
|
Assert.Equal("New", loaded.Title);
|
||||||
|
Assert.Equal("New Artist", loaded.Artist);
|
||||||
|
Assert.Null(loaded.License);
|
||||||
|
Assert.Equal("by someone", loaded.Attribution);
|
||||||
|
Assert.Equal(song.FilePath, loaded.FilePath);
|
||||||
|
Assert.Equal(song.Duration, loaded.Duration);
|
||||||
|
Assert.Equal(song.Source, loaded.Source);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Update_RejectsBlankTitleOrArtist()
|
||||||
|
{
|
||||||
|
var song = AddSong("Title", "Artist");
|
||||||
|
|
||||||
|
Assert.ThrowsAny<ArgumentException>(() => _controller.Update(song.Id, " ", "Artist", null, null));
|
||||||
|
Assert.ThrowsAny<ArgumentException>(() => _controller.Update(song.Id, "Title", "", null, null));
|
||||||
|
Assert.Equal("Title", _repository.GetById(song.Id)!.Title);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Update_ReturnsFalseForUnknownSong()
|
||||||
|
{
|
||||||
|
Assert.False(_controller.Update(42, "Title", "Artist", null, null));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Delete_RemovesSong()
|
||||||
|
{
|
||||||
|
var song = AddSong("Title", "Artist");
|
||||||
|
|
||||||
|
Assert.True(_controller.Delete(song.Id));
|
||||||
|
Assert.Empty(_controller.Search(null));
|
||||||
|
Assert.False(_controller.Delete(song.Id));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
using System.IO;
|
||||||
|
using NAudio.Wave;
|
||||||
|
using Radiosender.Services;
|
||||||
|
|
||||||
|
namespace Radiosender.Tests;
|
||||||
|
|
||||||
|
/// <summary>Skips the test on machines without an audio output device (for example CI agents).</summary>
|
||||||
|
public sealed class AudioDeviceFactAttribute : FactAttribute
|
||||||
|
{
|
||||||
|
public AudioDeviceFactAttribute()
|
||||||
|
{
|
||||||
|
if (WaveOut.DeviceCount == 0) Skip = "No audio output device available.";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class MusicPlayerTests : IDisposable
|
||||||
|
{
|
||||||
|
private readonly string _directory = Path.Combine(Path.GetTempPath(), "radiosender-tests", Guid.NewGuid().ToString("N"));
|
||||||
|
|
||||||
|
public MusicPlayerTests() => Directory.CreateDirectory(_directory);
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
MusicPlayer.Instance.Stop();
|
||||||
|
Directory.Delete(_directory, recursive: true);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Writes a short, quiet sine tone as 16-bit mono PCM.
|
||||||
|
private string CreateWav(TimeSpan length)
|
||||||
|
{
|
||||||
|
var path = Path.Combine(_directory, "tone.wav");
|
||||||
|
var format = new WaveFormat(44100, 16, 1);
|
||||||
|
using var writer = new WaveFileWriter(path, format);
|
||||||
|
var samples = (int)(format.SampleRate * length.TotalSeconds);
|
||||||
|
for (var i = 0; i < samples; i++)
|
||||||
|
writer.WriteSample(0.05f * MathF.Sin(2 * MathF.PI * 440 * i / format.SampleRate));
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Instance_ReturnsSameObjectOnRepeatedAccess()
|
||||||
|
{
|
||||||
|
Assert.Same(MusicPlayer.Instance, MusicPlayer.Instance);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Instance_ReturnsSameObjectAcrossThreads()
|
||||||
|
{
|
||||||
|
var instances = new MusicPlayer[16];
|
||||||
|
Parallel.For(0, instances.Length, i => instances[i] = MusicPlayer.Instance);
|
||||||
|
|
||||||
|
Assert.All(instances, instance => Assert.Same(MusicPlayer.Instance, instance));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Play_MissingFile_ThrowsAndStaysStopped()
|
||||||
|
{
|
||||||
|
var path = Path.Combine(_directory, "missing.mp3");
|
||||||
|
|
||||||
|
var exception = Assert.Throws<FileNotFoundException>(() => MusicPlayer.Instance.Play(path));
|
||||||
|
|
||||||
|
Assert.Equal(path, exception.FileName);
|
||||||
|
Assert.False(MusicPlayer.Instance.IsPlaying);
|
||||||
|
Assert.Equal(TimeSpan.Zero, MusicPlayer.Instance.Duration);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Play_UnreadableFile_ThrowsInvalidDataAndStaysStopped()
|
||||||
|
{
|
||||||
|
var path = Path.Combine(_directory, "broken.wav");
|
||||||
|
File.WriteAllText(path, "not audio");
|
||||||
|
|
||||||
|
Assert.Throws<InvalidDataException>(() => MusicPlayer.Instance.Play(path));
|
||||||
|
Assert.False(MusicPlayer.Instance.IsPlaying);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Volume_OutOfRange_Throws()
|
||||||
|
{
|
||||||
|
Assert.Throws<ArgumentOutOfRangeException>(() => MusicPlayer.Instance.Volume = 1.5f);
|
||||||
|
Assert.Throws<ArgumentOutOfRangeException>(() => MusicPlayer.Instance.Volume = -0.1f);
|
||||||
|
}
|
||||||
|
|
||||||
|
[AudioDeviceFact]
|
||||||
|
public void Stop_DoesNotRaiseTrackFinished()
|
||||||
|
{
|
||||||
|
var player = MusicPlayer.Instance;
|
||||||
|
var finished = 0;
|
||||||
|
EventHandler handler = (_, _) => Interlocked.Increment(ref finished);
|
||||||
|
player.TrackFinished += handler;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
player.Play(CreateWav(TimeSpan.FromSeconds(0.5)));
|
||||||
|
Assert.True(player.IsPlaying);
|
||||||
|
|
||||||
|
player.Stop();
|
||||||
|
Thread.Sleep(1000); // longer than the track, so a natural end would have fired by now
|
||||||
|
|
||||||
|
Assert.Equal(0, finished);
|
||||||
|
Assert.False(player.IsPlaying);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
player.TrackFinished -= handler;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[AudioDeviceFact]
|
||||||
|
public void Play_ShortWav_RaisesTrackFinishedAndPositionChanged()
|
||||||
|
{
|
||||||
|
var player = MusicPlayer.Instance;
|
||||||
|
using var finished = new ManualResetEventSlim();
|
||||||
|
var positionChanged = false;
|
||||||
|
EventHandler finishedHandler = (_, _) => finished.Set();
|
||||||
|
EventHandler<TimeSpan> positionHandler = (_, _) => positionChanged = true;
|
||||||
|
player.TrackFinished += finishedHandler;
|
||||||
|
player.PositionChanged += positionHandler;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
player.Play(CreateWav(TimeSpan.FromSeconds(0.6)));
|
||||||
|
Assert.InRange(player.Duration.TotalSeconds, 0.59, 0.61);
|
||||||
|
|
||||||
|
Assert.True(finished.Wait(TimeSpan.FromSeconds(5)), "TrackFinished was not raised.");
|
||||||
|
Assert.True(positionChanged);
|
||||||
|
Assert.False(player.IsPlaying);
|
||||||
|
Assert.Equal(TimeSpan.Zero, player.Duration);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
player.TrackFinished -= finishedHandler;
|
||||||
|
player.PositionChanged -= positionHandler;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
using Radiosender.Services;
|
||||||
|
|
||||||
|
namespace Radiosender.Tests;
|
||||||
|
|
||||||
|
public class PlaceholderContentTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public void AdSpots_AreNonEmptyWithTitlesAndPositiveDurations()
|
||||||
|
{
|
||||||
|
Assert.NotEmpty(PlaceholderContent.AdSpots);
|
||||||
|
Assert.All(PlaceholderContent.AdSpots, ad =>
|
||||||
|
{
|
||||||
|
Assert.False(string.IsNullOrWhiteSpace(ad.Title));
|
||||||
|
Assert.True(ad.Duration > TimeSpan.Zero);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ModeratorSegments_AreNonEmptyWithTitlesAndPositiveDurations()
|
||||||
|
{
|
||||||
|
Assert.NotEmpty(PlaceholderContent.ModeratorSegments);
|
||||||
|
Assert.All(PlaceholderContent.ModeratorSegments, segment =>
|
||||||
|
{
|
||||||
|
Assert.False(string.IsNullOrWhiteSpace(segment.Title));
|
||||||
|
Assert.True(segment.Duration > TimeSpan.Zero);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user