feat(import): batch import, working preview and a leaner page

Several Openverse results can be selected and imported in one go. The
preview streams through NAudio, because the WPF MediaPlayer cannot open
https URLs. The list of imported songs appears only once there is one.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
fraujulianandClaude Fable 5.2 committed 2026-11-23 14:22:51 +01:00
1 parent d7388fbfc3
commit d6a45cafa6
2 files changed
+155 -97

No files matched your search

+40 -60
View File
@@ -3,20 +3,19 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
Title="Import"
Foreground="{DynamicResource TextFillColorPrimaryBrush}"
ScrollViewer.CanContentScroll="False"
Unloaded="OnUnloaded">
<Grid Margin="24">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="3*" MinHeight="260" />
<RowDefinition Height="*" 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">
<TabControl x:Name="Sources" Grid.Row="1">
<!-- From computer -->
<TabItem Header="From computer">
<TabItem Header="Vom Computer">
<Grid Margin="0,12,0,0">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
@@ -26,7 +25,7 @@
<Grid x:Name="DropZone"
Background="Transparent"
AllowDrop="True"
AutomationProperties.Name="Drop zone for MP3 and WAV files"
AutomationProperties.Name="Ablagebereich für MP3- und WAV-Dateien"
DragEnter="OnDragOver"
DragOver="OnDragOver"
DragLeave="OnDragLeave"
@@ -36,21 +35,17 @@
RadiusY="8"
StrokeThickness="2"
StrokeDashArray="4 3"
Stroke="{DynamicResource TextFillColorTertiaryBrush}" />
Stroke="{DynamicResource ControlStrongStrokeColorDefaultBrush}" />
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
<ui:SymbolIcon HorizontalAlignment="Center" FontSize="40" Symbol="ArrowUpload24" />
<ui:TextBlock Margin="0,8,0,0"
<ui:TextBlock Margin="0,8,0,12"
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." />
Text="MP3- oder WAV-Dateien hier ablegen" />
<ui:Button x:Name="ChooseFilesButton"
HorizontalAlignment="Center"
Appearance="Primary"
Content="Choose files..."
Content="Dateien auswählen..."
Icon="{ui:SymbolIcon FolderOpen24}"
Click="OnChooseFiles" />
</StackPanel>
@@ -60,7 +55,7 @@
<ui:TextBlock x:Name="UploadProgressText" />
<ProgressBar x:Name="UploadProgress"
Margin="0,6,0,0"
AutomationProperties.Name="Upload progress" />
AutomationProperties.Name="Import-Fortschritt" />
</StackPanel>
</Grid>
</TabItem>
@@ -81,14 +76,14 @@
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ui:TextBox x:Name="QueryBox"
PlaceholderText="Search free audio, for example &quot;jazz piano&quot;"
AutomationProperties.Name="Search term"
PlaceholderText="Freie Musik suchen, zum Beispiel &quot;jazz piano&quot;"
AutomationProperties.Name="Suchbegriff"
KeyDown="OnQueryKeyDown" />
<ui:Button x:Name="SearchButton"
Grid.Column="1"
Margin="8,0,0,0"
Appearance="Primary"
Content="Search"
Content="Suchen"
Icon="{ui:SymbolIcon Search24}"
Click="OnSearch" />
</Grid>
@@ -98,34 +93,25 @@
<ui:ListView x:Name="Results"
Grid.Row="2"
Margin="0,12,0,0"
SelectionMode="Single"
AutomationProperties.Name="Search results"
SelectionMode="Extended"
AutomationProperties.Name="Suchergebnisse"
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:GridViewColumn Width="300" Header="Titel" DisplayMemberBinding="{Binding Track.Title}" />
<ui:GridViewColumn Width="180" Header="Urheber" DisplayMemberBinding="{Binding Track.Creator}" />
<ui:GridViewColumn Width="80" Header="Dauer" DisplayMemberBinding="{Binding Track.DurationText}" />
<ui:GridViewColumn Width="130" Header="Lizenz" DisplayMemberBinding="{Binding Track.LicenseName}" />
</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}"
<ui:Button x:Name="PreviewButton" MinWidth="110" Content="Vorhören" 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}"
<ui:Button x:Name="ImportButton" ToolTipService.ShowOnDisabled="True" Margin="8,0,0,0" Appearance="Primary"
Content="In Bibliothek importieren" Icon="{ui:SymbolIcon ArrowDownload24}"
IsEnabled="False" Click="OnImport" />
<ui:ProgressRing x:Name="Busy"
Width="20"
@@ -142,23 +128,26 @@
</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" />
<!-- Results of this session from both sources; hidden until something was imported. -->
<Grid x:Name="SessionPanel" Grid.Row="2" Margin="0,16,0,0" Visibility="Collapsed">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<ui:TextBlock VerticalAlignment="Center" FontTypography="BodyStrong" Text="Importiert" />
<ui:Button HorizontalAlignment="Right"
Appearance="Transparent"
Content="Open library"
Content="Bibliothek öffnen"
Icon="{ui:SymbolIcon MusicNote224}"
Click="OnOpenLibrary" />
</Grid>
<ui:ListView x:Name="Session"
Grid.Row="3"
Grid.Row="1"
MaxHeight="200"
Margin="0,8,0,0"
AutomationProperties.Name="Songs added in this session">
AutomationProperties.Name="In dieser Sitzung importierte Songs">
<ui:ListView.View>
<ui:GridView>
<ui:GridViewColumn Width="110" Header="Status">
<ui:GridViewColumn Width="160" Header="Status">
<ui:GridViewColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
@@ -166,33 +155,24 @@
Symbol="CheckmarkCircle24"
Filled="True"
Foreground="{DynamicResource SystemFillColorSuccessBrush}" />
<ui:TextBlock x:Name="Label" Margin="6,0,0,0" Text="Added" />
<ui:TextBlock x:Name="Label" Margin="6,0,0,0" Text="Hinzugefügt" />
</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" />
<Setter TargetName="Label" Property="Text" Value="Fehlgeschlagen" />
</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="240" Header="Titel" DisplayMemberBinding="{Binding Title}" />
<ui:GridViewColumn Width="160" Header="Interpret" DisplayMemberBinding="{Binding Artist}" />
<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>
</Grid>
</Page>
+115 -37
View File
@@ -3,8 +3,8 @@ using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using Microsoft.Win32;
using NAudio.Wave;
using Radiosender.Controllers;
using Radiosender.Models;
using Radiosender.Services;
@@ -23,21 +23,22 @@ public partial class ImportPage : Page
new(new SongImportService(App.Songs, SongImportService.DefaultMusicDirectory));
private readonly ObservableCollection<SessionRow> _session = [];
private readonly MediaPlayer _preview = new();
// Preview has its own output, so it never interrupts a running broadcast.
private WaveOut? _previewOutput;
private MediaFoundationReader? _previewReader;
private int _previewId; // changes on every start and stop; a late callback with an old id is ignored
private bool _uploading;
private bool _busy;
private bool _previewing;
public ImportPage()
{
InitializeComponent();
Session.ItemsSource = _session;
_session.CollectionChanged += (_, _) =>
SessionEmpty.Visibility = _session.Count == 0 ? Visibility.Visible : Visibility.Collapsed;
_preview.MediaEnded += (_, _) => OnStop(this, new RoutedEventArgs());
_preview.MediaFailed += (_, e) =>
{
OnStop(this, new RoutedEventArgs());
Show(InfoBarSeverity.Error, "Preview failed", e.ErrorException.Message);
SessionPanel.Visibility = _session.Count == 0 ? Visibility.Collapsed : Visibility.Visible;
GridColumns.Fit(Session);
};
}
@@ -54,12 +55,12 @@ public partial class ImportPage : Page
{
var ok = !_uploading && e.Data.GetDataPresent(DataFormats.FileDrop);
e.Effects = ok ? DragDropEffects.Copy : DragDropEffects.None;
DropBorder.SetResourceReference(System.Windows.Shapes.Shape.StrokeProperty, ok ? "AccentTextFillColorPrimaryBrush" : "TextFillColorTertiaryBrush");
DropBorder.SetResourceReference(System.Windows.Shapes.Shape.StrokeProperty, ok ? "AccentTextFillColorPrimaryBrush" : "ControlStrongStrokeColorDefaultBrush");
e.Handled = true;
}
private void OnDragLeave(object sender, DragEventArgs e) =>
DropBorder.SetResourceReference(System.Windows.Shapes.Shape.StrokeProperty, "TextFillColorTertiaryBrush");
DropBorder.SetResourceReference(System.Windows.Shapes.Shape.StrokeProperty, "ControlStrongStrokeColorDefaultBrush");
private async void OnDrop(object sender, DragEventArgs e)
{
@@ -82,11 +83,11 @@ public partial class ImportPage : Page
{
var path = paths[i];
UploadProgress.Value = i;
UploadProgressText.Text = $"Importing {i + 1} of {paths.Count}: {Path.GetFileName(path)}";
UploadProgressText.Text = $"Importiere {i + 1} von {paths.Count}: {Path.GetFileName(path)}";
var result = await Task.Run(() => _upload.Upload(path));
_session.Insert(0, result.Song is { } song
? SessionRow.Added(song, "Upload", Path.GetFileName(path))
: SessionRow.Failed(Path.GetFileName(path), "Upload", result.Message));
? SessionRow.Added(song, Path.GetFileName(path))
: SessionRow.Failed(Path.GetFileName(path), result.Message));
}
}
finally
@@ -113,19 +114,20 @@ public partial class ImportPage : Page
if (query.Length == 0 || _busy)
return;
SetBusy($"Searching Openverse for \"{query}\"...");
SetBusy($"Suche auf Openverse nach \"{query}\"...");
Message.IsOpen = false;
try
{
var tracks = await Openverse.SearchAsync(query);
var imported = Openverse.ImportedIds();
Results.ItemsSource = tracks.Select(t => ResultRow.For(t, imported)).ToList();
GridColumns.Fit(Results);
if (tracks.Count == 0)
Show(InfoBarSeverity.Informational, "No results", $"Openverse found no audio for \"{query}\".");
Show(InfoBarSeverity.Informational, "Keine Ergebnisse", $"Openverse hat nichts zu \"{query}\" gefunden.");
}
catch (OpenverseException ex)
{
Show(InfoBarSeverity.Error, "Search failed", ex.Message);
Show(InfoBarSeverity.Error, "Suche fehlgeschlagen", ex.Message);
}
finally
{
@@ -133,46 +135,120 @@ public partial class ImportPage : Page
}
}
private void OnPreview(object sender, RoutedEventArgs e)
// One button: starts the preview, or stops the running one.
// NAudio, not WPF's MediaPlayer: that one cannot open https URLs.
private async void OnPreview(object sender, RoutedEventArgs e)
{
if (_previewing)
{
OnStop(sender, e);
return;
}
if (Selected is not { } row || !Uri.TryCreate(row.Track.Url, UriKind.Absolute, out var uri) || uri.Scheme != Uri.UriSchemeHttps)
return;
_preview.Open(uri); // streams the file, nothing is saved
_preview.Play();
StopButton.IsEnabled = true;
SetPreviewing(true);
Message.IsOpen = false;
var id = ++_previewId;
try
{
// Connects to the server, so it runs off the UI thread. The file is streamed, nothing is saved.
var reader = await Task.Run(() => new MediaFoundationReader(uri.AbsoluteUri));
if (id != _previewId) // stopped or page left in the meantime
{
reader.Dispose();
return;
}
_previewReader = reader;
_previewOutput = new WaveOut();
_previewOutput.PlaybackStopped += (_, stopped) => Dispatcher.BeginInvoke(() =>
{
if (id != _previewId) return;
OnStop(this, new RoutedEventArgs());
if (stopped.Exception is { } error)
Show(InfoBarSeverity.Error, "Vorhören fehlgeschlagen", error.Message);
});
_previewOutput.Init(reader);
_previewOutput.Play();
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
if (id != _previewId) return;
OnStop(this, new RoutedEventArgs());
Show(InfoBarSeverity.Error, "Vorhören fehlgeschlagen", ex.Message);
}
}
private void SetPreviewing(bool on)
{
_previewing = on;
PreviewButton.Content = on ? "Stopp" : "Vorhören";
PreviewButton.Icon = new SymbolIcon(on ? SymbolRegular.Stop24 : SymbolRegular.Play24);
UpdateButtons();
}
private void OnStop(object sender, RoutedEventArgs e)
{
_preview.Stop();
_preview.Close();
StopButton.IsEnabled = false;
_previewId++;
var output = _previewOutput;
var reader = _previewReader;
_previewOutput = null;
_previewReader = null;
SetPreviewing(false);
// Disposing waits for the audio thread, which can sit in a network read; not on the UI thread.
if (output is not null || reader is not null)
Task.Run(() =>
{
output?.Dispose();
reader?.Dispose();
});
}
private void OnResultDoubleClick(object sender, MouseButtonEventArgs e) => OnImport(sender, e);
// Everything selected that can still be imported.
private List<ResultRow> Importable => Results.SelectedItems.OfType<ResultRow>().Where(r => r.CanImport).ToList();
// One after the other: Openverse limits anonymous requests, and each result shows up as soon as it is done.
private async void OnImport(object sender, RoutedEventArgs e)
{
if (Selected is not { CanImport: true } row || _busy)
var rows = Importable;
if (rows.Count == 0 || _busy)
return;
SetBusy($"Downloading \"{row.Track.Title}\"...");
Message.IsOpen = false;
var failed = 0;
var lastError = "";
try
{
for (var i = 0; i < rows.Count; i++)
{
var row = rows[i];
SetBusy(rows.Count == 1
? $"Lade \"{row.Track.Title}\" herunter..."
: $"Lade {i + 1} von {rows.Count} herunter: \"{row.Track.Title}\"...");
try
{
var song = await Openverse.ImportAsync(row.Track);
_session.Insert(0, SessionRow.Added(song, "Openverse", song.License ?? ""));
ReplaceRow(row, row with { Status = "In library", CanImport = false });
_session.Insert(0, SessionRow.Added(song, song.License ?? ""));
ReplaceRow(row, row with { Status = "In Bibliothek", CanImport = false });
}
catch (Exception ex) when (ex is OpenverseException or Microsoft.Data.Sqlite.SqliteException)
{
_session.Insert(0, SessionRow.Failed(row.Track.Title, "Openverse", ex.Message));
Show(InfoBarSeverity.Error, "Import failed", ex.Message);
_session.Insert(0, SessionRow.Failed(row.Track.Title, ex.Message));
failed++;
lastError = ex.Message;
}
}
}
finally
{
SetBusy(null);
}
if (failed > 0)
Show(InfoBarSeverity.Error, "Import fehlgeschlagen", rows.Count == 1
? lastError
: $"{failed} von {rows.Count} Songs konnten nicht importiert werden. Die Gründe stehen in der Liste \"Importiert\".");
}
private void ReplaceRow(ResultRow old, ResultRow updated)
@@ -180,7 +256,6 @@ public partial class ImportPage : Page
if (Results.ItemsSource is not List<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();
@@ -196,8 +271,12 @@ public partial class ImportPage : Page
private void UpdateButtons()
{
PreviewButton.IsEnabled = Selected is not null;
ImportButton.IsEnabled = !_busy && Selected is { CanImport: true };
PreviewButton.IsEnabled = _previewing || Selected is not null;
var importable = Importable.Count;
ImportButton.IsEnabled = !_busy && importable > 0;
ImportButton.Content = importable > 1 ? $"{importable} in Bibliothek importieren" : "In Bibliothek importieren";
// Why the selection cannot be imported ("In Bibliothek", "Keine Dauer"); shown on the disabled button.
ImportButton.ToolTip = importable == 0 && Selected is { } blocked ? blocked.Status : null;
}
private void Show(InfoBarSeverity severity, string title, string message)
@@ -218,16 +297,15 @@ public partial class ImportPage : Page
private sealed record ResultRow(OpenverseTrack Track, string Status, bool CanImport)
{
public static ResultRow For(OpenverseTrack track, IReadOnlySet<string> imported) =>
imported.Contains(track.Id) ? new(track, "In library", false)
: !track.CanImport ? new(track, "No duration", false)
imported.Contains(track.Id) ? new(track, "In Bibliothek", false)
: !track.CanImport ? new(track, "Keine Dauer", false)
: new(track, "", true);
}
private sealed record SessionRow(bool Success, string Title, string Artist, string Duration, string Source, string Details)
private sealed record SessionRow(bool Success, string Title, string Artist, string Details)
{
public static SessionRow Added(Song song, string source, string details) =>
new(true, song.Title, song.Artist, $"{(int)song.Duration.TotalMinutes}:{song.Duration.Seconds:00}", source, details);
public static SessionRow Added(Song song, string details) => new(true, song.Title, song.Artist, details);
public static SessionRow Failed(string name, string source, string error) => new(false, name, "", "", source, error);
public static SessionRow Failed(string name, string error) => new(false, name, "", error);
}
}