From d6a45cafa6a14230cd2f456d083a659d1beb878f Mon Sep 17 00:00:00 2001 From: Julian Lechner Date: Mon, 23 Nov 2026 14:22:51 +0100 Subject: [PATCH] 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 --- src/Radiosender/Views/Pages/ImportPage.xaml | 148 +++++++--------- .../Views/Pages/ImportPage.xaml.cs | 160 +++++++++++++----- 2 files changed, 183 insertions(+), 125 deletions(-) diff --git a/src/Radiosender/Views/Pages/ImportPage.xaml b/src/Radiosender/Views/Pages/ImportPage.xaml index ee0e6af..84eceeb 100644 --- a/src/Radiosender/Views/Pages/ImportPage.xaml +++ b/src/Radiosender/Views/Pages/ImportPage.xaml @@ -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"> - + - - - - + - + @@ -26,7 +25,7 @@ + Stroke="{DynamicResource ControlStrongStrokeColorDefaultBrush}" /> - - + Text="MP3- oder WAV-Dateien hier ablegen" /> @@ -60,7 +55,7 @@ + AutomationProperties.Name="Import-Fortschritt" /> @@ -81,14 +76,14 @@ @@ -98,34 +93,25 @@ - - - - - - - - - - - + + + + - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Radiosender/Views/Pages/ImportPage.xaml.cs b/src/Radiosender/Views/Pages/ImportPage.xaml.cs index 1a593ef..a58aba0 100644 --- a/src/Radiosender/Views/Pages/ImportPage.xaml.cs +++ b/src/Radiosender/Views/Pages/ImportPage.xaml.cs @@ -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 _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 Importable => Results.SelectedItems.OfType().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 { - 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); + 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, 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, 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 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 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); } }