Merge branch 'j.lechner/import-page' into 'main'

feat: combine upload and Openverse into one import page

Closes #13

See merge request julian/blockwoche3.1-radiosender!13
This commit is contained in:
Julian Lechner committed 2026-11-23 10:35:13 +00:00
commit e5c4d0e720
17 files changed
+581 -265

No files matched your search

+7 -6
View File
@@ -23,10 +23,11 @@ On first start the app creates its data under `%LOCALAPPDATA%\Radiosender`:
## Usage
1. **Upload**: pick MP3 or WAV files. The app copies them into the music folder, reads title and artist from the file tags and measures the duration.
2. **Openverse**: search the [Openverse](https://openverse.org) audio catalog and add a result. The app downloads the file and stores its license and attribution with the song.
3. **Library**: lists and searches all songs. Edit title, artist, license and attribution, or delete a song.
4. **Schedule**:
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.
@@ -89,8 +90,8 @@ For each downloaded track the app stores the license (for example `CC BY 4.0`) a
| 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 | Upload page (MP3, WAV) | Done |
| Add through the Openverse API | Openverse page | Done |
| Add by simple upload | Import page, "From 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 |
| News and ad blocks are shown | Timeline with type labels, now-playing card | Done |
@@ -9,11 +9,16 @@ public class OpenverseController(OpenverseClient client, SongRepository songs)
public Task<IReadOnlyList<OpenverseTrack>> SearchAsync(string query, CancellationToken cancellationToken = default) =>
client.SearchAsync(query, cancellationToken);
/// <summary>Ids of the Openverse results that are already in the library.</summary>
public IReadOnlySet<string> ImportedIds() => songs.GetOpenverseIds();
/// <summary>Downloads the track and stores it as a song with its license and attribution.</summary>
public async Task<Song> ImportAsync(OpenverseTrack track, CancellationToken cancellationToken = default)
{
if (track.Duration is not { } duration)
throw new OpenverseException("This result has no duration and cannot be imported.");
if (track.Id.Length > 0 && ImportedIds().Contains(track.Id))
throw new OpenverseException($"\"{track.Title}\" is already in the library.");
var path = await client.DownloadAsync(track, cancellationToken);
var song = new Song
@@ -25,6 +30,7 @@ public class OpenverseController(OpenverseClient client, SongRepository songs)
Source = SongSource.Openverse,
License = track.LicenseName,
Attribution = track.Attribution,
OpenverseId = track.Id.Length > 0 ? track.Id : null,
};
try
{
@@ -1,19 +1,22 @@
using Radiosender.Models;
using Radiosender.Services;
namespace Radiosender.Controllers;
public record UploadResult(bool Success, string Message);
/// <param name="Song">The saved song, or <c>null</c> when the upload failed.</param>
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";
/// <summary>Imports one file; failures come back as a result, so a batch can go on with the next file.</summary>
public UploadResult Upload(string filePath)
{
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.");
return new UploadResult(true, $"\"{song.Title}\" ({(int)song.Duration.TotalMinutes}:{song.Duration.Seconds:00}) was added to the library.", song);
}
catch (SongImportException e)
{
+1
View File
@@ -5,6 +5,7 @@ namespace Radiosender.Models;
/// <summary>One audio result of the Openverse search API (fields as documented at api.openverse.org/v1).</summary>
public class OpenverseTrack
{
public string Id { get; init; } = "";
public string Title { get; init; } = "";
public string? Creator { get; init; }
public string Url { get; init; } = "";
+3
View File
@@ -16,4 +16,7 @@ public class Song
public SongSource Source { get; set; }
public string? License { get; set; }
public string? Attribution { get; set; }
/// <summary>Id of the Openverse result the song was imported from, so it is not imported twice.</summary>
public string? OpenverseId { get; set; }
}
+32 -4
View File
@@ -9,7 +9,7 @@ public class SongRepository
public static string DefaultDatabasePath { get; } = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Radiosender", "radiosender.db");
private const string Columns = "Id, Title, Artist, DurationMs, FilePath, Source, License, Attribution";
private const string Columns = "Id, Title, Artist, DurationMs, FilePath, Source, License, Attribution, OpenverseId";
private readonly string _connectionString;
@@ -29,10 +29,36 @@ public class SongRepository
FilePath TEXT NOT NULL,
Source INTEGER NOT NULL,
License TEXT,
Attribution TEXT
Attribution TEXT,
OpenverseId TEXT
)
""";
command.ExecuteNonQuery();
// Databases from before the Openverse id get the column added.
command.CommandText = "SELECT COUNT(*) FROM pragma_table_info('Songs') WHERE name = 'OpenverseId'";
if ((long)command.ExecuteScalar()! == 0)
{
command.CommandText = "ALTER TABLE Songs ADD COLUMN OpenverseId TEXT";
command.ExecuteNonQuery();
}
// One song per Openverse result, also if two imports of the same track race.
command.CommandText = "CREATE UNIQUE INDEX IF NOT EXISTS IX_Songs_OpenverseId ON Songs (OpenverseId) WHERE OpenverseId IS NOT NULL";
command.ExecuteNonQuery();
}
/// <summary>Ids of all Openverse results that are already in the library.</summary>
public IReadOnlySet<string> GetOpenverseIds()
{
using var connection = Open();
using var command = connection.CreateCommand();
command.CommandText = "SELECT OpenverseId FROM Songs WHERE OpenverseId IS NOT NULL";
using var reader = command.ExecuteReader();
var ids = new HashSet<string>();
while (reader.Read())
ids.Add(reader.GetString(0));
return ids;
}
public IReadOnlyList<Song> GetAll()
@@ -63,8 +89,8 @@ public class SongRepository
using var connection = Open();
using var command = connection.CreateCommand();
command.CommandText = """
INSERT INTO Songs (Title, Artist, DurationMs, FilePath, Source, License, Attribution)
VALUES ($title, $artist, $durationMs, $filePath, $source, $license, $attribution);
INSERT INTO Songs (Title, Artist, DurationMs, FilePath, Source, License, Attribution, OpenverseId)
VALUES ($title, $artist, $durationMs, $filePath, $source, $license, $attribution, $openverseId);
SELECT last_insert_rowid();
""";
AddParameters(command, song);
@@ -112,6 +138,7 @@ public class SongRepository
command.Parameters.AddWithValue("$source", (int)song.Source);
command.Parameters.AddWithValue("$license", (object?)song.License ?? DBNull.Value);
command.Parameters.AddWithValue("$attribution", (object?)song.Attribution ?? DBNull.Value);
command.Parameters.AddWithValue("$openverseId", (object?)song.OpenverseId ?? DBNull.Value);
}
private static Song Read(SqliteDataReader reader) => new()
@@ -124,5 +151,6 @@ public class SongRepository
Source = (SongSource)reader.GetInt32(5),
License = reader.IsDBNull(6) ? null : reader.GetString(6),
Attribution = reader.IsDBNull(7) ? null : reader.GetString(7),
OpenverseId = reader.IsDBNull(8) ? null : reader.GetString(8),
};
}
+3 -6
View File
@@ -28,12 +28,9 @@
<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}" />
<ui:NavigationViewItem Content="Openverse"
Icon="{ui:SymbolIcon Search24}"
TargetPageType="{x:Type pages:OpenversePage}" />
<ui:NavigationViewItem Content="Import"
Icon="{ui:SymbolIcon ArrowDownload24}"
TargetPageType="{x:Type pages:ImportPage}" />
</ui:NavigationView.MenuItems>
</ui:NavigationView>
</Grid>
+1 -1
View File
@@ -6,6 +6,6 @@
<StackPanel Margin="24">
<ui:TextBlock FontTypography="Title" Text="Radiosender" />
<ui:TextBlock Margin="0,8,0,0" TextWrapping="Wrap"
Text="Add music under Library, Upload or Openverse, then plan and start a broadcast on the Schedule page." />
Text="Add music on the Import page, then plan and start a broadcast on the Schedule page." />
</StackPanel>
</Page>
+198
View File
@@ -0,0 +1,198 @@
<Page x:Class="Radiosender.Views.Pages.ImportPage"
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="Import"
Unloaded="OnUnloaded">
<Grid Margin="24">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="3*" MinHeight="260" />
<RowDefinition Height="Auto" />
<RowDefinition Height="2*" MinHeight="120" />
</Grid.RowDefinitions>
<ui:TextBlock Grid.Row="0" FontTypography="Title" Text="Import" />
<TabControl x:Name="Sources" Grid.Row="1" Margin="0,12,0,0">
<!-- From computer -->
<TabItem Header="From computer">
<Grid Margin="0,12,0,0">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid x:Name="DropZone"
Background="Transparent"
AllowDrop="True"
AutomationProperties.Name="Drop zone for MP3 and WAV files"
DragEnter="OnDragOver"
DragOver="OnDragOver"
DragLeave="OnDragLeave"
Drop="OnDrop">
<Rectangle x:Name="DropBorder"
RadiusX="8"
RadiusY="8"
StrokeThickness="2"
StrokeDashArray="4 3"
Stroke="{DynamicResource TextFillColorTertiaryBrush}" />
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
<ui:SymbolIcon HorizontalAlignment="Center" FontSize="40" Symbol="ArrowUpload24" />
<ui:TextBlock Margin="0,8,0,0"
HorizontalAlignment="Center"
FontTypography="BodyStrong"
Text="Drop MP3 or WAV files here" />
<ui:TextBlock Margin="0,4,0,12"
HorizontalAlignment="Center"
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
Text="You can add several files at once." />
<ui:Button x:Name="ChooseFilesButton"
HorizontalAlignment="Center"
Appearance="Primary"
Content="Choose files..."
Icon="{ui:SymbolIcon FolderOpen24}"
Click="OnChooseFiles" />
</StackPanel>
</Grid>
<StackPanel x:Name="UploadProgressPanel" Grid.Row="1" Margin="0,12,0,0" Visibility="Collapsed">
<ui:TextBlock x:Name="UploadProgressText" />
<ProgressBar x:Name="UploadProgress"
Margin="0,6,0,0"
AutomationProperties.Name="Upload progress" />
</StackPanel>
</Grid>
</TabItem>
<!-- Openverse -->
<TabItem Header="Openverse">
<Grid Margin="0,12,0,0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid Grid.Row="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ui:TextBox x:Name="QueryBox"
PlaceholderText="Search free audio, for example &quot;jazz piano&quot;"
AutomationProperties.Name="Search term"
KeyDown="OnQueryKeyDown" />
<ui:Button x:Name="SearchButton"
Grid.Column="1"
Margin="8,0,0,0"
Appearance="Primary"
Content="Search"
Icon="{ui:SymbolIcon Search24}"
Click="OnSearch" />
</Grid>
<ui:InfoBar x:Name="Message" Grid.Row="1" Margin="0,12,0,0" IsClosable="True" />
<ui:ListView x:Name="Results"
Grid.Row="2"
Margin="0,12,0,0"
SelectionMode="Single"
AutomationProperties.Name="Search results"
SelectionChanged="OnSelectionChanged"
MouseDoubleClick="OnResultDoubleClick">
<ui:ListView.View>
<ui:GridView>
<ui:GridViewColumn Width="300" Header="Title" DisplayMemberBinding="{Binding Track.Title}" />
<ui:GridViewColumn Width="180" Header="Creator" DisplayMemberBinding="{Binding Track.Creator}" />
<ui:GridViewColumn Width="80" Header="Duration" DisplayMemberBinding="{Binding Track.DurationText}" />
<ui:GridViewColumn Width="130" Header="License" DisplayMemberBinding="{Binding Track.LicenseName}" />
<ui:GridViewColumn Width="150" Header="Status">
<ui:GridViewColumn.CellTemplate>
<DataTemplate>
<ui:TextBlock Text="{Binding Status}" Foreground="{DynamicResource TextFillColorSecondaryBrush}" />
</DataTemplate>
</ui:GridViewColumn.CellTemplate>
</ui:GridViewColumn>
</ui:GridView>
</ui:ListView.View>
</ui:ListView>
<StackPanel Grid.Row="3" Margin="0,12,0,0" Orientation="Horizontal">
<ui:Button x:Name="PreviewButton" Content="Preview" Icon="{ui:SymbolIcon Play24}"
IsEnabled="False" Click="OnPreview" />
<ui:Button x:Name="StopButton" Margin="8,0,0,0" Content="Stop" Icon="{ui:SymbolIcon Stop24}"
IsEnabled="False" Click="OnStop" />
<ui:Button x:Name="ImportButton" Margin="8,0,0,0" Appearance="Primary"
Content="Import to library" Icon="{ui:SymbolIcon ArrowDownload24}"
IsEnabled="False" Click="OnImport" />
<ui:ProgressRing x:Name="Busy"
Width="20"
Height="20"
Margin="12,0,0,0"
IsIndeterminate="True"
Visibility="Collapsed" />
<ui:TextBlock x:Name="BusyText"
Margin="8,0,0,0"
VerticalAlignment="Center"
Foreground="{DynamicResource TextFillColorSecondaryBrush}" />
</StackPanel>
</Grid>
</TabItem>
</TabControl>
<!-- Added in this session, from both sources -->
<Grid Grid.Row="2" Margin="0,16,0,0">
<ui:TextBlock VerticalAlignment="Center" FontTypography="Subtitle" Text="Added in this session" />
<ui:Button HorizontalAlignment="Right"
Appearance="Transparent"
Content="Open library"
Icon="{ui:SymbolIcon MusicNote224}"
Click="OnOpenLibrary" />
</Grid>
<ui:ListView x:Name="Session"
Grid.Row="3"
Margin="0,8,0,0"
AutomationProperties.Name="Songs added in this session">
<ui:ListView.View>
<ui:GridView>
<ui:GridViewColumn Width="110" Header="Status">
<ui:GridViewColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<ui:SymbolIcon x:Name="Icon"
Symbol="CheckmarkCircle24"
Filled="True"
Foreground="{DynamicResource SystemFillColorSuccessBrush}" />
<ui:TextBlock x:Name="Label" Margin="6,0,0,0" Text="Added" />
</StackPanel>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Success}" Value="False">
<Setter TargetName="Icon" Property="Symbol" Value="ErrorCircle24" />
<Setter TargetName="Icon" Property="Foreground" Value="{DynamicResource SystemFillColorCriticalBrush}" />
<Setter TargetName="Label" Property="Text" Value="Failed" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ui:GridViewColumn.CellTemplate>
</ui:GridViewColumn>
<ui:GridViewColumn Width="240" Header="Title" DisplayMemberBinding="{Binding Title}" />
<ui:GridViewColumn Width="160" Header="Artist" DisplayMemberBinding="{Binding Artist}" />
<ui:GridViewColumn Width="80" Header="Duration" DisplayMemberBinding="{Binding Duration}" />
<ui:GridViewColumn Width="100" Header="Source" DisplayMemberBinding="{Binding Source}" />
<ui:GridViewColumn Width="320" Header="Details" DisplayMemberBinding="{Binding Details}" />
</ui:GridView>
</ui:ListView.View>
</ui:ListView>
<ui:TextBlock x:Name="SessionEmpty"
Grid.Row="3"
Margin="0,32,0,0"
HorizontalAlignment="Center"
VerticalAlignment="Top"
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
Text="Songs you import appear here." />
</Grid>
</Page>
@@ -0,0 +1,233 @@
using System.Collections.ObjectModel;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using Microsoft.Win32;
using Radiosender.Controllers;
using Radiosender.Models;
using Radiosender.Services;
using Wpf.Ui.Controls;
namespace Radiosender.Views.Pages;
/// <summary>Adds music to the library from local files or from Openverse; both list their results in one place.</summary>
public partial class ImportPage : Page
{
// One Openverse controller (and HttpClient) for the app lifetime; created on first use, after App.Songs exists.
private static OpenverseController? _openverse;
private static OpenverseController Openverse => _openverse ??= new(OpenverseClient.CreateDefault(), App.Songs);
private readonly UploadController _upload =
new(new SongImportService(App.Songs, SongImportService.DefaultMusicDirectory));
private readonly ObservableCollection<SessionRow> _session = [];
private readonly MediaPlayer _preview = new();
private bool _uploading;
private bool _busy;
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);
};
}
// ---- From computer ----
private async void OnChooseFiles(object sender, RoutedEventArgs e)
{
var dialog = new OpenFileDialog { Filter = UploadController.FileDialogFilter, Multiselect = true };
if (dialog.ShowDialog() == true)
await UploadAsync(dialog.FileNames);
}
private void OnDragOver(object sender, DragEventArgs e)
{
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");
e.Handled = true;
}
private void OnDragLeave(object sender, DragEventArgs e) =>
DropBorder.SetResourceReference(System.Windows.Shapes.Shape.StrokeProperty, "TextFillColorTertiaryBrush");
private async void OnDrop(object sender, DragEventArgs e)
{
OnDragLeave(sender, e);
if (!_uploading && e.Data.GetData(DataFormats.FileDrop) is string[] paths)
await UploadAsync(paths);
}
// Files are imported one by one on a pool thread; each result shows up as soon as it is known.
private async Task UploadAsync(IReadOnlyList<string> paths)
{
if (paths.Count == 0) return;
_uploading = true;
ChooseFilesButton.IsEnabled = false;
UploadProgressPanel.Visibility = Visibility.Visible;
UploadProgress.Maximum = paths.Count;
try
{
for (var i = 0; i < paths.Count; i++)
{
var path = paths[i];
UploadProgress.Value = i;
UploadProgressText.Text = $"Importing {i + 1} of {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));
}
}
finally
{
_uploading = false;
ChooseFilesButton.IsEnabled = true;
UploadProgressPanel.Visibility = Visibility.Collapsed;
}
}
// ---- Openverse ----
private ResultRow? Selected => Results.SelectedItem as ResultRow;
private void OnQueryKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
OnSearch(sender, e);
}
private async void OnSearch(object sender, RoutedEventArgs e)
{
var query = QueryBox.Text.Trim();
if (query.Length == 0 || _busy)
return;
SetBusy($"Searching Openverse for \"{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();
if (tracks.Count == 0)
Show(InfoBarSeverity.Informational, "No results", $"Openverse found no audio for \"{query}\".");
}
catch (OpenverseException ex)
{
Show(InfoBarSeverity.Error, "Search failed", ex.Message);
}
finally
{
SetBusy(null);
}
}
private void OnPreview(object sender, RoutedEventArgs e)
{
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;
}
private void OnStop(object sender, RoutedEventArgs e)
{
_preview.Stop();
_preview.Close();
StopButton.IsEnabled = false;
}
private void OnResultDoubleClick(object sender, MouseButtonEventArgs e) => OnImport(sender, e);
private async void OnImport(object sender, RoutedEventArgs e)
{
if (Selected is not { CanImport: true } row || _busy)
return;
SetBusy($"Downloading \"{row.Track.Title}\"...");
Message.IsOpen = false;
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);
}
finally
{
SetBusy(null);
}
}
private void ReplaceRow(ResultRow old, ResultRow updated)
{
if (Results.ItemsSource is not List<ResultRow> 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();
private void SetBusy(string? text)
{
_busy = text is not null;
Busy.Visibility = _busy ? Visibility.Visible : Visibility.Collapsed;
BusyText.Text = text ?? "";
SearchButton.IsEnabled = !_busy;
UpdateButtons();
}
private void UpdateButtons()
{
PreviewButton.IsEnabled = Selected is not null;
ImportButton.IsEnabled = !_busy && Selected is { CanImport: true };
}
private void Show(InfoBarSeverity severity, string title, string message)
{
Message.Severity = severity;
Message.Title = title;
Message.Message = message;
Message.IsOpen = true;
}
// ---- Shared ----
private void OnOpenLibrary(object sender, RoutedEventArgs e) =>
(Window.GetWindow(this) as MainWindow)?.RootNavigation.Navigate(typeof(LibraryPage));
private void OnUnloaded(object sender, RoutedEventArgs e) => OnStop(sender, e);
private sealed record ResultRow(OpenverseTrack Track, string Status, bool CanImport)
{
public static ResultRow For(OpenverseTrack track, IReadOnlySet<string> imported) =>
imported.Contains(track.Id) ? new(track, "In library", false)
: !track.CanImport ? new(track, "No duration", false)
: new(track, "", true);
}
private sealed record SessionRow(bool Success, string Title, string Artist, string Duration, string Source, 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 Failed(string name, string source, string error) => new(false, name, "", "", source, error);
}
}
@@ -1,62 +0,0 @@
<Page x:Class="Radiosender.Views.Pages.OpenversePage"
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="Openverse"
Unloaded="OnUnloaded">
<Grid Margin="24">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<ui:TextBlock Grid.Row="0" FontTypography="Title" Text="Openverse" />
<Grid Grid.Row="1" Margin="0,12,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ui:TextBox x:Name="QueryBox"
PlaceholderText="Search free audio, for example &quot;jazz piano&quot;"
AutomationProperties.Name="Search term"
KeyDown="OnQueryKeyDown" />
<ui:Button x:Name="SearchButton" Grid.Column="1" Margin="8,0,0,0"
Appearance="Primary" Content="Search"
Icon="{ui:SymbolIcon Search24}"
Click="OnSearch" />
</Grid>
<ui:InfoBar x:Name="Message" Grid.Row="2" Margin="0,12,0,0" IsClosable="True" />
<ui:ListView x:Name="Results" Grid.Row="3" Margin="0,12,0,0"
SelectionMode="Single"
AutomationProperties.Name="Search results"
SelectionChanged="OnSelectionChanged">
<ui:ListView.View>
<ui:GridView>
<GridViewColumn Header="Title" Width="320" DisplayMemberBinding="{Binding Title}" />
<GridViewColumn Header="Creator" Width="200" DisplayMemberBinding="{Binding Creator}" />
<GridViewColumn Header="Duration" Width="90" DisplayMemberBinding="{Binding DurationText}" />
<GridViewColumn Header="License" Width="150" DisplayMemberBinding="{Binding LicenseName}" />
</ui:GridView>
</ui:ListView.View>
</ui:ListView>
<StackPanel Grid.Row="4" Margin="0,12,0,0" Orientation="Horizontal">
<ui:Button x:Name="PreviewButton" Content="Preview" Icon="{ui:SymbolIcon Play24}"
IsEnabled="False" Click="OnPreview" />
<ui:Button x:Name="StopButton" Margin="8,0,0,0" Content="Stop" Icon="{ui:SymbolIcon Stop24}"
IsEnabled="False" Click="OnStop" />
<ui:Button x:Name="ImportButton" Margin="8,0,0,0" Appearance="Primary"
Content="Import to library" Icon="{ui:SymbolIcon ArrowDownload24}"
IsEnabled="False" Click="OnImport" />
<ui:TextBlock x:Name="ImportHint" Margin="12,0,0,0" VerticalAlignment="Center"
Visibility="Collapsed"
Text="This result has no duration and cannot be imported." />
</StackPanel>
</Grid>
</Page>
@@ -1,128 +0,0 @@
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using Radiosender.Controllers;
using Radiosender.Models;
using Radiosender.Services;
using Wpf.Ui.Controls;
namespace Radiosender.Views.Pages;
public partial class OpenversePage : Page
{
// One controller (and HttpClient) for the app lifetime; created on first use, after App.Songs exists.
private static OpenverseController? _controller;
private static OpenverseController Controller => _controller ??= new(OpenverseClient.CreateDefault(), App.Songs);
private readonly MediaPlayer _preview = new();
private bool _busy;
public OpenversePage()
{
InitializeComponent();
_preview.MediaEnded += (_, _) => OnStop(this, new RoutedEventArgs());
_preview.MediaFailed += (_, e) =>
{
OnStop(this, new RoutedEventArgs());
Show(InfoBarSeverity.Error, "Preview failed", e.ErrorException.Message);
};
}
private OpenverseTrack? Selected => Results.SelectedItem as OpenverseTrack;
private void OnQueryKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
OnSearch(sender, e);
}
private async void OnSearch(object sender, RoutedEventArgs e)
{
var query = QueryBox.Text.Trim();
if (query.Length == 0 || _busy)
return;
SetBusy(true);
Message.IsOpen = false;
try
{
var tracks = await Controller.SearchAsync(query);
Results.ItemsSource = tracks;
if (tracks.Count == 0)
Show(InfoBarSeverity.Informational, "No results", $"Openverse found no audio for \"{query}\".");
}
catch (OpenverseException ex)
{
Show(InfoBarSeverity.Error, "Search failed", ex.Message);
}
finally
{
SetBusy(false);
}
}
private void OnPreview(object sender, RoutedEventArgs e)
{
if (Selected is not { } track || !Uri.TryCreate(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;
}
private void OnStop(object sender, RoutedEventArgs e)
{
_preview.Stop();
_preview.Close();
StopButton.IsEnabled = false;
}
private async void OnImport(object sender, RoutedEventArgs e)
{
if (Selected is not { CanImport: true } track || _busy)
return;
SetBusy(true);
Message.IsOpen = false;
try
{
var song = await Controller.ImportAsync(track);
Show(InfoBarSeverity.Success, "Imported", $"\"{song.Title}\" was added to the library.");
}
catch (Exception ex) when (ex is OpenverseException or Microsoft.Data.Sqlite.SqliteException)
{
Show(InfoBarSeverity.Error, "Import failed", ex.Message);
}
finally
{
SetBusy(false);
}
}
private void OnSelectionChanged(object sender, SelectionChangedEventArgs e) => UpdateButtons();
private void OnUnloaded(object sender, RoutedEventArgs e) => OnStop(sender, e);
private void SetBusy(bool busy)
{
_busy = busy;
SearchButton.IsEnabled = !busy;
UpdateButtons();
}
private void UpdateButtons()
{
PreviewButton.IsEnabled = Selected is not null;
ImportButton.IsEnabled = !_busy && Selected is { CanImport: true };
ImportHint.Visibility = Selected is { CanImport: false } ? Visibility.Visible : Visibility.Collapsed;
}
private void Show(InfoBarSeverity severity, string title, string message)
{
Message.Severity = severity;
Message.Title = title;
Message.Message = message;
Message.IsOpen = true;
}
}
@@ -1,19 +0,0 @@
<Page x:Class="Radiosender.Views.Pages.UploadPage"
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="Upload">
<Grid>
<StackPanel Margin="24">
<ui:TextBlock FontTypography="Title" Text="Upload" />
<ui:TextBlock Margin="0,8,0,0" Text="Add an MP3 or WAV file from your computer to the library." />
<ui:Button x:Name="ChooseFileButton"
Margin="0,16,0,0"
Appearance="Primary"
Content="Choose file..."
Icon="{ui:SymbolIcon ArrowUpload24}"
Click="ChooseFileButton_Click" />
</StackPanel>
<ui:SnackbarPresenter x:Name="SnackbarPresenter" VerticalAlignment="Bottom" />
</Grid>
</Page>
@@ -1,35 +0,0 @@
using System.Windows;
using Microsoft.Win32;
using Radiosender.Controllers;
using Radiosender.Services;
using Wpf.Ui.Controls;
namespace Radiosender.Views.Pages;
public partial class UploadPage
{
private readonly UploadController _controller =
new(new SongImportService(App.Songs, SongImportService.DefaultMusicDirectory));
public UploadPage()
{
InitializeComponent();
}
private void ChooseFileButton_Click(object sender, RoutedEventArgs e)
{
var dialog = new OpenFileDialog { Filter = UploadController.FileDialogFilter };
if (dialog.ShowDialog() != true)
return;
var result = _controller.Upload(dialog.FileName);
new Snackbar(SnackbarPresenter)
{
Title = result.Success ? "Song uploaded" : "Upload failed",
Content = result.Message,
Appearance = result.Success ? ControlAppearance.Success : ControlAppearance.Danger,
Icon = new SymbolIcon(result.Success ? SymbolRegular.CheckmarkCircle24 : SymbolRegular.ErrorCircle24),
Timeout = TimeSpan.FromSeconds(5),
}.Show();
}
}
+21 -1
View File
@@ -39,6 +39,7 @@ public sealed class OpenverseTests : IDisposable
private static OpenverseTrack Track(string url = "https://cdn.example.org/a.mp3") => new()
{
Id = "a",
Title = "Piano Melody",
Creator = "benpm",
Url = url,
@@ -66,6 +67,7 @@ public sealed class OpenverseTests : IDisposable
Assert.Equal("https://api.openverse.org/v1/audio/?q=jazz%20piano&page_size=20", requested!.AbsoluteUri);
Assert.Equal(2, tracks.Count);
var first = tracks[0];
Assert.Equal("a", first.Id);
Assert.Equal("Piano Melody", first.Title);
Assert.Equal("benpm", first.Creator);
Assert.Equal("https://cdn.example.org/a.mp3", first.Url);
@@ -119,6 +121,8 @@ public sealed class OpenverseTests : IDisposable
Assert.Equal(Track().Attribution, stored.Attribution);
Assert.Equal(TimeSpan.FromMilliseconds(10193), stored.Duration);
Assert.Equal("benpm", stored.Artist);
Assert.Equal("a", stored.OpenverseId);
Assert.Contains("a", controller.ImportedIds());
}
[Fact]
@@ -212,4 +216,20 @@ public sealed class OpenverseTests : IDisposable
public override int Read(byte[] buffer, int offset, int count) => throw new IOException("connection reset");
}
}
[Fact]
public async Task Import_TrackAlreadyInLibrary_IsRejectedWithoutDownload()
{
var downloads = 0;
var client = NewClient((_, _) => { downloads++; return Respond(HttpStatusCode.OK, new ByteArrayContent(Audio)); });
var songs = new SongRepository(Path.Combine(_directory, "test.db"));
var controller = new OpenverseController(client, songs);
await controller.ImportAsync(Track());
var error = await Assert.ThrowsAsync<OpenverseException>(() => controller.ImportAsync(Track()));
Assert.Contains("already in the library", error.Message);
Assert.Equal(1, downloads);
Assert.Single(songs.GetAll());
Assert.Single(MusicFiles());
}}
@@ -108,4 +108,24 @@ public sealed class SongImportServiceTests : IDisposable
Assert.Throws<SongImportException>(() => _service.Import(Path.Combine(SourceDirectory, "missing.mp3")));
Assert.Empty(MusicFiles());
}
}
[Fact]
public void UploadController_ImportsEachFileAndReportsFailuresPerFile()
{
var controller = new Radiosender.Controllers.UploadController(_service);
string[] files =
[
CreateWav("first.wav", TimeSpan.FromSeconds(2)),
Path.Combine(SourceDirectory, "notes.txt"),
CreateWav("second.wav", TimeSpan.FromSeconds(3)),
];
File.WriteAllText(files[1], "not audio");
var results = files.Select(controller.Upload).ToList();
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.Equal(2, _repository.GetAll().Count);
}}
@@ -124,4 +124,54 @@ public sealed class SongRepositoryTests : IDisposable
Assert.Throws<SqliteException>(() => repository.Add(song));
}
[Fact]
public void OpenverseId_IsStoredAndListed()
{
var repository = new SongRepository(DatabasePath);
var song = NewSong();
song.OpenverseId = "ov-1";
repository.Add(song);
repository.Add(NewSong("Uploaded"));
Assert.Equal("ov-1", repository.GetById(song.Id)!.OpenverseId);
Assert.Equal(["ov-1"], repository.GetOpenverseIds());
}
[Fact]
public void OpenverseId_CannotBeStoredTwice()
{
var repository = new SongRepository(DatabasePath);
repository.Add(new Song { Title = "A", Artist = "", Duration = TimeSpan.FromSeconds(1), FilePath = "a", OpenverseId = "ov-1" });
Assert.Throws<SqliteException>(() =>
repository.Add(new Song { Title = "B", Artist = "", Duration = TimeSpan.FromSeconds(1), FilePath = "b", OpenverseId = "ov-1" }));
}
[Fact]
public void Constructor_AddsOpenverseIdColumnToOlderDatabase()
{
Directory.CreateDirectory(_directory);
using (var connection = new SqliteConnection($"Data Source={DatabasePath}"))
{
connection.Open();
using var command = connection.CreateCommand();
command.CommandText = """
CREATE TABLE Songs (
Id INTEGER PRIMARY KEY AUTOINCREMENT, Title TEXT NOT NULL, Artist TEXT NOT NULL,
DurationMs INTEGER NOT NULL CHECK (DurationMs > 0), FilePath TEXT NOT NULL,
Source INTEGER NOT NULL, License TEXT, Attribution TEXT);
INSERT INTO Songs (Title, Artist, DurationMs, FilePath, Source) VALUES ('Old', 'Artist', 1000, 'old.mp3', 0);
""";
command.ExecuteNonQuery();
}
var repository = new SongRepository(DatabasePath);
var song = NewSong();
song.OpenverseId = "ov-1";
repository.Add(song);
Assert.Null(Assert.Single(repository.GetAll(), s => s.Title == "Old").OpenverseId);
Assert.Equal("ov-1", repository.GetById(song.Id)!.OpenverseId);
_ = new SongRepository(DatabasePath); // second start must not try to add the column again
}}