From 0a0d8e1d4ce89bbc2dae02295fbda882529d1d8d Mon Sep 17 00:00:00 2001 From: Julian Lechner Date: Mon, 23 Nov 2026 11:34:35 +0100 Subject: [PATCH] feat: combine upload and Openverse into one import page Adding music took two navigation items that each did half the job. The new Import page has both sources as tabs and one shared list of what was added in this session, with the reason for every failure and a link to the library. From computer: drop several MP3 or WAV files or pick them with a multi-select dialog. Files are imported one by one on a background thread with a progress bar, and a failing file does not stop the rest. Openverse: search and download show a progress ring with a status text. Results that are already in the library or have no duration are marked in their row and cannot be imported; a double-click imports. To detect duplicates, songs now store the Openverse result id. The repository adds the column to existing databases and a unique index keeps one song per Openverse result. Refs #13 Co-Authored-By: Claude Opus 5.5 --- README.md | 13 +- .../Controllers/OpenverseController.cs | 6 + .../Controllers/UploadController.cs | 7 +- src/Radiosender/Models/OpenverseTrack.cs | 1 + src/Radiosender/Models/Song.cs | 3 + src/Radiosender/Services/SongRepository.cs | 36 ++- src/Radiosender/Views/MainWindow.xaml | 9 +- src/Radiosender/Views/Pages/HomePage.xaml | 2 +- src/Radiosender/Views/Pages/ImportPage.xaml | 198 +++++++++++++++ .../Views/Pages/ImportPage.xaml.cs | 233 ++++++++++++++++++ .../Views/Pages/OpenversePage.xaml | 62 ----- .../Views/Pages/OpenversePage.xaml.cs | 128 ---------- src/Radiosender/Views/Pages/UploadPage.xaml | 19 -- .../Views/Pages/UploadPage.xaml.cs | 35 --- tests/Radiosender.Tests/OpenverseTests.cs | 22 +- .../SongImportServiceTests.cs | 22 +- .../Radiosender.Tests/SongRepositoryTests.cs | 52 +++- 17 files changed, 582 insertions(+), 266 deletions(-) create mode 100644 src/Radiosender/Views/Pages/ImportPage.xaml create mode 100644 src/Radiosender/Views/Pages/ImportPage.xaml.cs delete mode 100644 src/Radiosender/Views/Pages/OpenversePage.xaml delete mode 100644 src/Radiosender/Views/Pages/OpenversePage.xaml.cs delete mode 100644 src/Radiosender/Views/Pages/UploadPage.xaml delete mode 100644 src/Radiosender/Views/Pages/UploadPage.xaml.cs diff --git a/README.md b/README.md index e814a08..ccc8ffb 100644 --- a/README.md +++ b/README.md @@ -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 | diff --git a/src/Radiosender/Controllers/OpenverseController.cs b/src/Radiosender/Controllers/OpenverseController.cs index 4d0386e..a2301b7 100644 --- a/src/Radiosender/Controllers/OpenverseController.cs +++ b/src/Radiosender/Controllers/OpenverseController.cs @@ -9,11 +9,16 @@ public class OpenverseController(OpenverseClient client, SongRepository songs) public Task> SearchAsync(string query, CancellationToken cancellationToken = default) => client.SearchAsync(query, cancellationToken); + /// Ids of the Openverse results that are already in the library. + public IReadOnlySet ImportedIds() => songs.GetOpenverseIds(); + /// Downloads the track and stores it as a song with its license and attribution. public async Task 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 { diff --git a/src/Radiosender/Controllers/UploadController.cs b/src/Radiosender/Controllers/UploadController.cs index b27f53d..0b3cc66 100644 --- a/src/Radiosender/Controllers/UploadController.cs +++ b/src/Radiosender/Controllers/UploadController.cs @@ -1,19 +1,22 @@ +using Radiosender.Models; using Radiosender.Services; namespace Radiosender.Controllers; -public record UploadResult(bool Success, string Message); +/// The saved song, or null when the upload failed. +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"; + /// Imports one file; failures come back as a result, so a batch can go on with the next file. 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) { diff --git a/src/Radiosender/Models/OpenverseTrack.cs b/src/Radiosender/Models/OpenverseTrack.cs index e3e2925..157ac31 100644 --- a/src/Radiosender/Models/OpenverseTrack.cs +++ b/src/Radiosender/Models/OpenverseTrack.cs @@ -5,6 +5,7 @@ namespace Radiosender.Models; /// One audio result of the Openverse search API (fields as documented at api.openverse.org/v1). public class OpenverseTrack { + public string Id { get; init; } = ""; public string Title { get; init; } = ""; public string? Creator { get; init; } public string Url { get; init; } = ""; diff --git a/src/Radiosender/Models/Song.cs b/src/Radiosender/Models/Song.cs index db91d7f..307d0d0 100644 --- a/src/Radiosender/Models/Song.cs +++ b/src/Radiosender/Models/Song.cs @@ -16,4 +16,7 @@ public class Song public SongSource Source { get; set; } public string? License { get; set; } public string? Attribution { get; set; } + + /// Id of the Openverse result the song was imported from, so it is not imported twice. + public string? OpenverseId { get; set; } } diff --git a/src/Radiosender/Services/SongRepository.cs b/src/Radiosender/Services/SongRepository.cs index dbb8bf1..58928e0 100644 --- a/src/Radiosender/Services/SongRepository.cs +++ b/src/Radiosender/Services/SongRepository.cs @@ -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(); + } + + /// Ids of all Openverse results that are already in the library. + public IReadOnlySet 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(); + while (reader.Read()) + ids.Add(reader.GetString(0)); + return ids; } public IReadOnlyList 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), }; } diff --git a/src/Radiosender/Views/MainWindow.xaml b/src/Radiosender/Views/MainWindow.xaml index 728ceff..22b586c 100644 --- a/src/Radiosender/Views/MainWindow.xaml +++ b/src/Radiosender/Views/MainWindow.xaml @@ -28,12 +28,9 @@ - - + diff --git a/src/Radiosender/Views/Pages/HomePage.xaml b/src/Radiosender/Views/Pages/HomePage.xaml index 1d69417..2170016 100644 --- a/src/Radiosender/Views/Pages/HomePage.xaml +++ b/src/Radiosender/Views/Pages/HomePage.xaml @@ -6,6 +6,6 @@ + Text="Add music on the Import page, then plan and start a broadcast on the Schedule page." /> diff --git a/src/Radiosender/Views/Pages/ImportPage.xaml b/src/Radiosender/Views/Pages/ImportPage.xaml new file mode 100644 index 0000000..ee0e6af --- /dev/null +++ b/src/Radiosender/Views/Pages/ImportPage.xaml @@ -0,0 +1,198 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Radiosender/Views/Pages/ImportPage.xaml.cs b/src/Radiosender/Views/Pages/ImportPage.xaml.cs new file mode 100644 index 0000000..1a593ef --- /dev/null +++ b/src/Radiosender/Views/Pages/ImportPage.xaml.cs @@ -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; + +/// Adds music to the library from local files or from Openverse; both list their results in one place. +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 _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 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 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 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); + } +} diff --git a/src/Radiosender/Views/Pages/OpenversePage.xaml b/src/Radiosender/Views/Pages/OpenversePage.xaml deleted file mode 100644 index c4a4830..0000000 --- a/src/Radiosender/Views/Pages/OpenversePage.xaml +++ /dev/null @@ -1,62 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Radiosender/Views/Pages/OpenversePage.xaml.cs b/src/Radiosender/Views/Pages/OpenversePage.xaml.cs deleted file mode 100644 index c6c6fb1..0000000 --- a/src/Radiosender/Views/Pages/OpenversePage.xaml.cs +++ /dev/null @@ -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; - } -} diff --git a/src/Radiosender/Views/Pages/UploadPage.xaml b/src/Radiosender/Views/Pages/UploadPage.xaml deleted file mode 100644 index 2fc416c..0000000 --- a/src/Radiosender/Views/Pages/UploadPage.xaml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - diff --git a/src/Radiosender/Views/Pages/UploadPage.xaml.cs b/src/Radiosender/Views/Pages/UploadPage.xaml.cs deleted file mode 100644 index 63519e7..0000000 --- a/src/Radiosender/Views/Pages/UploadPage.xaml.cs +++ /dev/null @@ -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(); - } -} diff --git a/tests/Radiosender.Tests/OpenverseTests.cs b/tests/Radiosender.Tests/OpenverseTests.cs index 5726073..6e9fed2 100644 --- a/tests/Radiosender.Tests/OpenverseTests.cs +++ b/tests/Radiosender.Tests/OpenverseTests.cs @@ -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(() => controller.ImportAsync(Track())); + + Assert.Contains("already in the library", error.Message); + Assert.Equal(1, downloads); + Assert.Single(songs.GetAll()); + Assert.Single(MusicFiles()); + }} diff --git a/tests/Radiosender.Tests/SongImportServiceTests.cs b/tests/Radiosender.Tests/SongImportServiceTests.cs index 8fc6a32..5628463 100644 --- a/tests/Radiosender.Tests/SongImportServiceTests.cs +++ b/tests/Radiosender.Tests/SongImportServiceTests.cs @@ -108,4 +108,24 @@ public sealed class SongImportServiceTests : IDisposable Assert.Throws(() => _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); + }} diff --git a/tests/Radiosender.Tests/SongRepositoryTests.cs b/tests/Radiosender.Tests/SongRepositoryTests.cs index a41967f..e7fd748 100644 --- a/tests/Radiosender.Tests/SongRepositoryTests.cs +++ b/tests/Radiosender.Tests/SongRepositoryTests.cs @@ -124,4 +124,54 @@ public sealed class SongRepositoryTests : IDisposable Assert.Throws(() => 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(() => + 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 + }}