Merge remote-tracking branch 'origin/main' into j.lechner/song-upload
# Conflicts: # src/Radiosender/Radiosender.csproj # src/Radiosender/Views/MainWindow.xaml
This commit is contained in:
commit
360077ff64
13 files changed
+728
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);
|
||||
@@ -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"
|
||||
Icon="{ui:SymbolIcon Home24}"
|
||||
TargetPageType="{x:Type pages:HomePage}" />
|
||||
<ui:NavigationViewItem Content="Library"
|
||||
Icon="{ui:SymbolIcon MusicNote224}"
|
||||
TargetPageType="{x:Type pages:LibraryPage}" />
|
||||
<ui:NavigationViewItem Content="Upload"
|
||||
Icon="{ui:SymbolIcon ArrowUpload24}"
|
||||
TargetPageType="{x:Type pages:UploadPage}" />
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user