refactor(import): put online sources behind IMusicProvider

A provider only has to search and return MusicTrack items. Downloading and
storing them is shared by all providers in TrackDownloader and
OnlineImportController. OpenverseProvider is the first implementation.
Song.OpenverseId becomes ExternalId and SongSource.Openverse becomes
Online; the database column and the stored values stay the same.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
fraujulianandClaude Fable 5.2 committed 2026-11-23 15:09:35 +01:00
1 parent c6e9bf4e82
commit a8ccb9b73d
14 files changed
+371 -260

No files matched your search

@@ -0,0 +1,48 @@
using System.IO;
using Radiosender.Models;
using Radiosender.Services;
namespace Radiosender.Controllers;
/// <summary>Searches the registered music providers and imports their results into the library.</summary>
public class OnlineImportController(IEnumerable<IMusicProvider> providers, TrackDownloader downloader, SongRepository songs)
{
/// <summary>Every provider registered in <c>App</c>, in registration order.</summary>
public IReadOnlyList<IMusicProvider> Providers { get; } = providers.ToList();
/// <summary>Ids of the provider results that are already in the library.</summary>
public IReadOnlySet<string> ImportedIds() => songs.GetExternalIds();
/// <summary>Downloads the track and stores it as a song with its license and attribution.</summary>
/// <exception cref="MusicProviderException">The track cannot be imported or the download failed.</exception>
public async Task<Song> ImportAsync(MusicTrack track, CancellationToken cancellationToken = default)
{
if (track.Duration is not { } duration)
throw new MusicProviderException("Dieses Ergebnis hat keine Dauer und kann nicht importiert werden.");
if (track.Id.Length > 0 && ImportedIds().Contains(track.Id))
throw new MusicProviderException($"\"{track.Title}\" ist bereits in der Bibliothek.");
var path = await downloader.DownloadAsync(track, cancellationToken);
var song = new Song
{
Title = track.Title,
Artist = string.IsNullOrWhiteSpace(track.Creator) ? "Unknown" : track.Creator,
Duration = duration,
FilePath = path,
Source = SongSource.Online,
License = track.License,
Attribution = track.Attribution,
ExternalId = track.Id.Length > 0 ? track.Id : null,
};
try
{
songs.Add(song);
}
catch
{
File.Delete(path); // no orphaned file without a database entry
throw;
}
return song;
}
}
@@ -1,46 +0,0 @@
using System.IO;
using Radiosender.Models;
using Radiosender.Services;
namespace Radiosender.Controllers;
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("Dieses Ergebnis hat keine Dauer und kann nicht importiert werden.");
if (track.Id.Length > 0 && ImportedIds().Contains(track.Id))
throw new OpenverseException($"\"{track.Title}\" ist bereits in der Bibliothek.");
var path = await client.DownloadAsync(track, cancellationToken);
var song = new Song
{
Title = track.Title,
Artist = string.IsNullOrWhiteSpace(track.Creator) ? "Unknown" : track.Creator,
Duration = duration,
FilePath = path,
Source = SongSource.Openverse,
License = track.LicenseName,
Attribution = track.Attribution,
OpenverseId = track.Id.Length > 0 ? track.Id : null,
};
try
{
songs.Add(song);
}
catch
{
File.Delete(path); // no orphaned file without a database entry
throw;
}
return song;
}
}
+34
View File
@@ -0,0 +1,34 @@
namespace Radiosender.Models;
/// <summary>One search result of a music provider, in the shape the import works with.</summary>
public record MusicTrack
{
/// <summary>
/// Identifies the track so it is not imported twice. Must be unique across all providers: a new provider
/// prefixes its ids with its own name. Empty when the provider has no id.
/// </summary>
public string Id { get; init; } = "";
public string Title { get; init; } = "";
public string? Creator { get; init; }
/// <summary>Direct https link to the audio file.</summary>
public string Url { get; init; } = "";
/// <summary>File extension without the dot, e.g. "mp3"; unknown ones are saved as mp3.</summary>
public string? FileType { get; init; }
/// <summary>Readable license name, for example "CC BY 4.0".</summary>
public string License { get; init; } = "";
public string? Attribution { get; init; }
/// <summary>Length of the track; <c>null</c> when the provider does not know it.</summary>
public TimeSpan? Duration { get; init; }
/// <summary>Songs need a duration for scheduling, so results without one cannot be imported.</summary>
public bool CanImport => Duration is not null;
public string DurationText => Duration?.ToString(@"m\:ss") ?? "unbekannt";
}
+14 -4
View File
@@ -23,10 +23,6 @@ public class OpenverseTrack
[JsonIgnore]
public TimeSpan? Duration => DurationMs > 0 ? TimeSpan.FromMilliseconds(DurationMs.Value) : null;
/// <summary>Songs need a duration for scheduling, so results without one cannot be imported.</summary>
public bool CanImport => Duration is not null;
public string DurationText => Duration?.ToString(@"m\:ss") ?? "unbekannt";
/// <summary>Readable license name, for example "CC BY 4.0", "CC0 1.0" or "Public Domain Mark 1.0".</summary>
public string LicenseName => License.ToLowerInvariant() switch
@@ -35,4 +31,18 @@ public class OpenverseTrack
"pdm" => $"Public Domain Mark {LicenseVersion}".Trim(),
_ => $"CC {License.ToUpperInvariant()} {LicenseVersion}".Trim(),
};
/// <summary>The result in the provider-neutral shape. Openverse ids are stored as they come.</summary>
public MusicTrack ToMusicTrack() => new()
{
Id = Id,
Title = Title,
Creator = Creator,
Url = Url,
// Openverse reports some MP3 files as "mp32".
FileType = FileType?.ToLowerInvariant() is "mp32" ? "mp3" : FileType,
License = LicenseName,
Attribution = Attribution,
Duration = Duration,
};
}
+5 -3
View File
@@ -3,7 +3,9 @@ namespace Radiosender.Models;
public enum SongSource
{
Upload,
Openverse,
/// <summary>Downloaded from a music provider such as Openverse.</summary>
Online,
}
public class Song
@@ -17,6 +19,6 @@ public class Song
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; }
/// <summary>Id of the provider result the song was imported from (<see cref="MusicTrack.Id"/>), so it is not imported twice.</summary>
public string? ExternalId { get; set; }
}
@@ -0,0 +1,20 @@
using Radiosender.Models;
namespace Radiosender.Services;
/// <summary>Error of a music provider or a download, with a message that can be shown to the user as is.</summary>
public class MusicProviderException(string message, Exception? inner = null) : Exception(message, inner);
/// <summary>
/// A catalog of music that can be searched online. To add one, implement this interface and register the
/// class in <c>App</c>; the import page lists every registered provider. Downloading and storing the
/// results is the same for all providers and not part of this interface.
/// </summary>
public interface IMusicProvider
{
/// <summary>Name shown to the user, for example "Openverse".</summary>
string Name { get; }
/// <exception cref="MusicProviderException">The search failed.</exception>
Task<IReadOnlyList<MusicTrack>> SearchAsync(string query, CancellationToken cancellationToken = default);
}
-136
View File
@@ -1,136 +0,0 @@
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using Radiosender.Models;
namespace Radiosender.Services;
/// <summary>Error with a message that can be shown to the user as is.</summary>
public class OpenverseException(string message, Exception? inner = null) : Exception(message, inner);
/// <summary>Anonymous client for the Openverse audio search API and for downloading results.</summary>
public class OpenverseClient(HttpClient http, string musicFolder)
{
public static string DefaultMusicFolder { get; } = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Radiosender", "Music");
public const long MaxDownloadBytes = 50 * 1024 * 1024;
private const string SearchUrl = "https://api.openverse.org/v1/audio/";
private const int PageSize = 20; // anonymous requests may ask for at most 20 results per page
private static readonly JsonSerializerOptions JsonOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower };
private static readonly HashSet<string> KnownExtensions = ["mp3", "ogg", "oga", "wav", "flac", "m4a", "aac", "opus"];
/// <summary>Limit for the whole download; <see cref="HttpClient.Timeout"/> only covers the response headers here.</summary>
public TimeSpan DownloadTimeout { get; init; } = TimeSpan.FromMinutes(3);
public static OpenverseClient CreateDefault()
{
var http = new HttpClient { Timeout = TimeSpan.FromSeconds(20) };
http.DefaultRequestHeaders.UserAgent.ParseAdd("Radiosender/1.0");
return new OpenverseClient(http, DefaultMusicFolder);
}
public async Task<IReadOnlyList<OpenverseTrack>> SearchAsync(string query, CancellationToken cancellationToken = default)
{
var url = $"{SearchUrl}?q={Uri.EscapeDataString(query)}&page_size={PageSize}";
try
{
using var response = await http.GetAsync(url, cancellationToken);
EnsureSuccess(response);
var page = await response.Content.ReadFromJsonAsync<SearchPage>(JsonOptions, cancellationToken);
return page?.Results ?? [];
}
catch (Exception e) when (e is not OpenverseException && !cancellationToken.IsCancellationRequested)
{
throw Wrap(e, "Openverse-Suche fehlgeschlagen");
}
}
/// <summary>
/// Downloads <see cref="OpenverseTrack.Url"/> into the music folder under a new, unique file name.
/// On any failure no file is left behind.
/// </summary>
/// <returns>Full path of the downloaded file.</returns>
public async Task<string> DownloadAsync(OpenverseTrack track, CancellationToken cancellationToken = default)
{
if (!Uri.TryCreate(track.Url, UriKind.Absolute, out var uri) || uri.Scheme != Uri.UriSchemeHttps)
throw new OpenverseException("Nur https-Downloads sind erlaubt.");
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeout.CancelAfter(DownloadTimeout);
string? path = null;
try
{
using var response = await http.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead, timeout.Token);
EnsureSuccess(response);
if (response.Content.Headers.ContentLength > MaxDownloadBytes)
throw new OpenverseException("Die Datei ist größer als 50 MB.");
Directory.CreateDirectory(musicFolder);
await using var file = CreateUniqueFile(track, out path);
await using var body = await response.Content.ReadAsStreamAsync(timeout.Token);
var buffer = new byte[81920];
long total = 0;
int read;
while ((read = await body.ReadAsync(buffer, timeout.Token)) > 0)
{
total += read;
if (total > MaxDownloadBytes)
throw new OpenverseException("Die Datei ist größer als 50 MB.");
await file.WriteAsync(buffer.AsMemory(0, read), timeout.Token);
}
if (total == 0)
throw new OpenverseException("Der Download war leer.");
return path;
}
catch (Exception e)
{
// "await using" in the try block has already closed the file here.
if (path is not null)
File.Delete(path);
if (e is OpenverseException || cancellationToken.IsCancellationRequested)
throw;
throw Wrap(e, "Download fehlgeschlagen");
}
}
private FileStream CreateUniqueFile(OpenverseTrack track, out string path)
{
var name = string.Join("_", $"{track.Creator} - {track.Title}".Split(Path.GetInvalidFileNameChars())).Trim(' ', '-', '.');
if (name.Length > 100) name = name[..100];
if (name.Length == 0) name = "openverse";
var type = track.FileType?.ToLowerInvariant();
var extension = type == "mp32" ? "mp3" : type is not null && KnownExtensions.Contains(type) ? type : "mp3";
for (var i = 1; ; i++)
{
var candidate = Path.Combine(musicFolder, i == 1 ? $"{name}.{extension}" : $"{name} ({i}).{extension}");
if (File.Exists(candidate)) continue;
// CreateNew never overwrites; path is only reported once this call owns the file.
var stream = new FileStream(candidate, FileMode.CreateNew, FileAccess.Write, FileShare.None, 81920, useAsync: true);
path = candidate;
return stream;
}
}
private static void EnsureSuccess(HttpResponseMessage response)
{
if (response.StatusCode == HttpStatusCode.TooManyRequests)
throw new OpenverseException("Openverse-Limit erreicht (anonym: 20 Anfragen pro Minute, 200 pro Tag). Bitte später erneut versuchen.");
if (!response.IsSuccessStatusCode)
throw new OpenverseException($"Openverse hat HTTP {(int)response.StatusCode} geliefert.");
}
private static OpenverseException Wrap(Exception e, string action) => e switch
{
OperationCanceledException => new OpenverseException($"{action}: ZeitĂĽberschreitung der Anfrage.", e),
JsonException => new OpenverseException($"{action}: unerwartete Antwort.", e),
_ => new OpenverseException($"{action}: {e.Message}", e),
};
private sealed record SearchPage(List<OpenverseTrack>? Results);
}
@@ -0,0 +1,44 @@
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using Radiosender.Models;
namespace Radiosender.Services;
/// <summary>Searches the Openverse audio catalog anonymously.</summary>
public class OpenverseProvider(HttpClient http) : IMusicProvider
{
private const string SearchUrl = "https://api.openverse.org/v1/audio/";
private const int PageSize = 20; // anonymous requests may ask for at most 20 results per page
private static readonly JsonSerializerOptions JsonOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower };
public string Name => "Openverse";
public async Task<IReadOnlyList<MusicTrack>> SearchAsync(string query, CancellationToken cancellationToken = default)
{
var url = $"{SearchUrl}?q={Uri.EscapeDataString(query)}&page_size={PageSize}";
try
{
using var response = await http.GetAsync(url, cancellationToken);
if (response.StatusCode == HttpStatusCode.TooManyRequests)
throw new MusicProviderException("Openverse-Limit erreicht (anonym: 20 Anfragen pro Minute, 200 pro Tag). Bitte später erneut versuchen.");
if (!response.IsSuccessStatusCode)
throw new MusicProviderException($"Openverse hat HTTP {(int)response.StatusCode} geliefert.");
var page = await response.Content.ReadFromJsonAsync<SearchPage>(JsonOptions, cancellationToken);
return page?.Results?.Select(result => result.ToMusicTrack()).ToList() ?? [];
}
catch (Exception e) when (e is not MusicProviderException && !cancellationToken.IsCancellationRequested)
{
throw e switch
{
OperationCanceledException => new MusicProviderException("Openverse-Suche fehlgeschlagen: ZeitĂĽberschreitung der Anfrage.", e),
JsonException => new MusicProviderException("Openverse-Suche fehlgeschlagen: unerwartete Antwort.", e),
_ => new MusicProviderException($"Openverse-Suche fehlgeschlagen: {e.Message}", e),
};
}
}
private sealed record SearchPage(List<OpenverseTrack>? Results);
}
+9 -7
View File
@@ -28,11 +28,11 @@ public class SongRepository
context.Database.EnsureCreated();
}
/// <summary>Ids of all Openverse results that are already in the library.</summary>
public IReadOnlySet<string> GetOpenverseIds()
/// <summary>Ids of all provider results that are already in the library.</summary>
public IReadOnlySet<string> GetExternalIds()
{
using var context = Open();
return context.Songs.Where(s => s.OpenverseId != null).Select(s => s.OpenverseId!).ToHashSet();
return context.Songs.Where(s => s.ExternalId != null).Select(s => s.ExternalId!).ToHashSet();
}
public IReadOnlyList<Song> GetAll()
@@ -49,7 +49,7 @@ public class SongRepository
/// <summary>Inserts the song and sets its <see cref="Song.Id"/>.</summary>
/// <exception cref="ArgumentException">The song has no duration.</exception>
/// <exception cref="DbUpdateException">The database rejected the song, e.g. a second song with the same Openverse id.</exception>
/// <exception cref="DbUpdateException">The database rejected the song, e.g. a second song with the same external id.</exception>
public void Add(Song song)
{
RequireDuration(song);
@@ -58,7 +58,7 @@ public class SongRepository
context.SaveChanges();
}
/// <summary>Stores everything except the Openverse id, which never changes after the import.</summary>
/// <summary>Stores everything except the external id, which never changes after the import.</summary>
/// <returns><c>false</c> if no song with this id exists.</returns>
/// <exception cref="ArgumentException">The song has no duration.</exception>
public bool Update(Song song)
@@ -104,9 +104,11 @@ public class SongRepository
song.Property(s => s.Duration)
.HasColumnName("DurationMs")
.HasConversion(duration => (long)duration.TotalMilliseconds, milliseconds => TimeSpan.FromMilliseconds(milliseconds));
// One song per Openverse result, also if two imports of the same track race.
// The column keeps the name it got when Openverse was the only provider.
song.Property(s => s.ExternalId).HasColumnName("OpenverseId");
// One song per provider result, also if two imports of the same track race.
// SQLite allows any number of rows without an id in a unique index.
song.HasIndex(s => s.OpenverseId).IsUnique();
song.HasIndex(s => s.ExternalId).IsUnique();
}
}
}
@@ -0,0 +1,90 @@
using System.IO;
using System.Net.Http;
using Radiosender.Models;
namespace Radiosender.Services;
/// <summary>Downloads the audio file of a <see cref="MusicTrack"/> into the music folder, for any provider.</summary>
public class TrackDownloader(HttpClient http, string musicFolder)
{
public static string DefaultMusicFolder { get; } = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Radiosender", "Music");
public const long MaxDownloadBytes = 50 * 1024 * 1024;
private static readonly HashSet<string> KnownExtensions = ["mp3", "ogg", "oga", "wav", "flac", "m4a", "aac", "opus"];
/// <summary>Limit for the whole download; <see cref="HttpClient.Timeout"/> only covers the response headers here.</summary>
public TimeSpan DownloadTimeout { get; init; } = TimeSpan.FromMinutes(3);
/// <summary>
/// Downloads <see cref="MusicTrack.Url"/> into the music folder under a new, unique file name.
/// On any failure no file is left behind.
/// </summary>
/// <returns>Full path of the downloaded file.</returns>
/// <exception cref="MusicProviderException">The download failed or the file is not acceptable.</exception>
public async Task<string> DownloadAsync(MusicTrack track, CancellationToken cancellationToken = default)
{
if (!Uri.TryCreate(track.Url, UriKind.Absolute, out var uri) || uri.Scheme != Uri.UriSchemeHttps)
throw new MusicProviderException("Nur https-Downloads sind erlaubt.");
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeout.CancelAfter(DownloadTimeout);
string? path = null;
try
{
using var response = await http.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead, timeout.Token);
if (!response.IsSuccessStatusCode)
throw new MusicProviderException($"Der Server hat HTTP {(int)response.StatusCode} geliefert.");
if (response.Content.Headers.ContentLength > MaxDownloadBytes)
throw new MusicProviderException("Die Datei ist größer als 50 MB.");
Directory.CreateDirectory(musicFolder);
await using var file = CreateUniqueFile(track, out path);
await using var body = await response.Content.ReadAsStreamAsync(timeout.Token);
var buffer = new byte[81920];
long total = 0;
int read;
while ((read = await body.ReadAsync(buffer, timeout.Token)) > 0)
{
total += read;
if (total > MaxDownloadBytes)
throw new MusicProviderException("Die Datei ist größer als 50 MB.");
await file.WriteAsync(buffer.AsMemory(0, read), timeout.Token);
}
if (total == 0)
throw new MusicProviderException("Der Download war leer.");
return path;
}
catch (Exception e)
{
// "await using" in the try block has already closed the file here.
if (path is not null)
File.Delete(path);
if (e is MusicProviderException || cancellationToken.IsCancellationRequested)
throw;
throw new MusicProviderException(e is OperationCanceledException
? "Download fehlgeschlagen: ZeitĂĽberschreitung der Anfrage."
: $"Download fehlgeschlagen: {e.Message}", e);
}
}
private FileStream CreateUniqueFile(MusicTrack track, out string path)
{
var name = string.Join("_", $"{track.Creator} - {track.Title}".Split(Path.GetInvalidFileNameChars())).Trim(' ', '-', '.');
if (name.Length > 100) name = name[..100];
if (name.Length == 0) name = "track";
var type = track.FileType?.ToLowerInvariant();
var extension = type is not null && KnownExtensions.Contains(type) ? type : "mp3";
for (var i = 1; ; i++)
{
var candidate = Path.Combine(musicFolder, i == 1 ? $"{name}.{extension}" : $"{name} ({i}).{extension}");
if (File.Exists(candidate)) continue;
// CreateNew never overwrites; path is only reported once this call owns the file.
var stream = new FileStream(candidate, FileMode.CreateNew, FileAccess.Write, FileShare.None, 81920, useAsync: true);
path = candidate;
return stream;
}
}
}
+13 -4
View File
@@ -60,8 +60,8 @@
</Grid>
</TabItem>
<!-- Openverse -->
<TabItem Header="Openverse">
<!-- Online providers; the header is the provider name when there is only one -->
<TabItem x:Name="OnlineTab" Header="Online">
<Grid Margin="0,12,0,0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
@@ -72,15 +72,24 @@
<Grid Grid.Row="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<!-- Only shown when more than one provider is registered -->
<ComboBox x:Name="ProviderBox"
MinWidth="140"
Margin="0,0,8,0"
AutomationProperties.Name="Musikquelle"
DisplayMemberPath="Name"
Visibility="Collapsed" />
<ui:TextBox x:Name="QueryBox"
Grid.Column="1"
PlaceholderText="Freie Musik suchen, zum Beispiel &quot;jazz piano&quot;"
AutomationProperties.Name="Suchbegriff"
KeyDown="OnQueryKeyDown" />
<ui:Button x:Name="SearchButton"
Grid.Column="1"
Grid.Column="2"
Margin="8,0,0,0"
Appearance="Primary"
Content="Suchen"
@@ -102,7 +111,7 @@
<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:GridViewColumn Width="130" Header="Lizenz" DisplayMemberBinding="{Binding Track.License}" />
</ui:GridView>
</ui:ListView.View>
</ui:ListView>
+27 -21
View File
@@ -12,15 +12,11 @@ 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>
/// <summary>Adds music to the library from local files or from an online provider; 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 OnlineImportController _online;
private readonly UploadController _upload;
private readonly ObservableCollection<SessionRow> _session = [];
// Preview has its own output, so it never interrupts a running broadcast.
@@ -31,9 +27,19 @@ public partial class ImportPage : Page
private bool _busy;
private bool _previewing;
public ImportPage()
public ImportPage(OnlineImportController online, UploadController upload)
{
_online = online;
_upload = upload;
InitializeComponent();
// One provider needs no choice: the tab carries its name. Several get a list next to the search box.
var providers = _online.Providers;
ProviderBox.ItemsSource = providers;
ProviderBox.SelectedIndex = providers.Count > 0 ? 0 : -1;
ProviderBox.Visibility = providers.Count > 1 ? Visibility.Visible : Visibility.Collapsed;
OnlineTab.Visibility = providers.Count > 0 ? Visibility.Visible : Visibility.Collapsed;
if (providers.Count == 1)
OnlineTab.Header = providers[0].Name;
Session.ItemsSource = _session;
_session.CollectionChanged += (_, _) =>
{
@@ -98,7 +104,7 @@ public partial class ImportPage : Page
}
}
// ---- Openverse ----
// ---- Online providers ----
private ResultRow? Selected => Results.SelectedItem as ResultRow;
@@ -111,21 +117,21 @@ public partial class ImportPage : Page
private async void OnSearch(object sender, RoutedEventArgs e)
{
var query = QueryBox.Text.Trim();
if (query.Length == 0 || _busy)
if (query.Length == 0 || _busy || ProviderBox.SelectedItem is not IMusicProvider provider)
return;
SetBusy($"Suche auf Openverse nach \"{query}\"...");
SetBusy($"Suche auf {provider.Name} nach \"{query}\"...");
Message.IsOpen = false;
try
{
var tracks = await Openverse.SearchAsync(query);
var imported = Openverse.ImportedIds();
var tracks = await provider.SearchAsync(query);
var imported = _online.ImportedIds();
Results.ItemsSource = tracks.Select(t => ResultRow.For(t, imported)).ToList();
GridColumns.Fit(Results);
if (tracks.Count == 0)
Show(InfoBarSeverity.Informational, "Keine Ergebnisse", $"Openverse hat nichts zu \"{query}\" gefunden.");
Show(InfoBarSeverity.Informational, "Keine Ergebnisse", $"{provider.Name} hat nichts zu \"{query}\" gefunden.");
}
catch (OpenverseException ex)
catch (MusicProviderException ex)
{
Show(InfoBarSeverity.Error, "Suche fehlgeschlagen", ex.Message);
}
@@ -208,7 +214,7 @@ public partial class ImportPage : Page
// 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.
// One after the other: providers limit anonymous requests, and each result shows up as soon as it is done.
private async void OnImport(object sender, RoutedEventArgs e)
{
var rows = Importable;
@@ -228,14 +234,14 @@ public partial class ImportPage : Page
: $"Lade {i + 1} von {rows.Count} herunter: \"{row.Track.Title}\"...");
try
{
var song = await Openverse.ImportAsync(row.Track);
var song = await _online.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.EntityFrameworkCore.DbUpdateException)
catch (Exception ex) when (ex is MusicProviderException or Microsoft.EntityFrameworkCore.DbUpdateException)
{
// The database error text is technical and English; the usual cause is a song that is already stored.
var reason = ex is OpenverseException ? ex.Message : "Der Song konnte nicht in der Bibliothek gespeichert werden.";
var reason = ex is MusicProviderException ? ex.Message : "Der Song konnte nicht in der Bibliothek gespeichert werden.";
_session.Insert(0, SessionRow.Failed(row.Track.Title, reason));
failed++;
lastError = reason;
@@ -296,9 +302,9 @@ public partial class ImportPage : Page
private void OnUnloaded(object sender, RoutedEventArgs e) => OnStop(sender, e);
private sealed record ResultRow(OpenverseTrack Track, string Status, bool CanImport)
private sealed record ResultRow(MusicTrack Track, string Status, bool CanImport)
{
public static ResultRow For(OpenverseTrack track, IReadOnlySet<string> imported) =>
public static ResultRow For(MusicTrack track, IReadOnlySet<string> imported) =>
imported.Contains(track.Id) ? new(track, "In Bibliothek", false)
: !track.CanImport ? new(track, "Keine Dauer", false)
: new(track, "", true);
+53 -25
View File
@@ -31,22 +31,30 @@ public sealed class OpenverseTests : IDisposable
Directory.Delete(_directory, recursive: true);
}
private OpenverseClient NewClient(Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> handle, TimeSpan? timeout = null) =>
new(new HttpClient(new FakeHandler(handle)) { Timeout = timeout ?? TimeSpan.FromSeconds(10) }, MusicFolder);
private static HttpClient Http(Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> handle, TimeSpan? timeout = null) =>
new(new FakeHandler(handle)) { Timeout = timeout ?? TimeSpan.FromSeconds(10) };
private static OpenverseProvider NewProvider(Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> handle, TimeSpan? timeout = null) =>
new(Http(handle, timeout));
private TrackDownloader NewClient(Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> handle) =>
new(Http(handle), MusicFolder);
private static OnlineImportController NewController(TrackDownloader downloader, SongRepository songs) =>
new([], downloader, songs);
private static Task<HttpResponseMessage> Respond(HttpStatusCode status, HttpContent? content = null) =>
Task.FromResult(new HttpResponseMessage(status) { Content = content ?? new ByteArrayContent([]) });
private static OpenverseTrack Track(string url = "https://cdn.example.org/a.mp3") => new()
private static MusicTrack Track(string url = "https://cdn.example.org/a.mp3") => new()
{
Id = "a",
Title = "Piano Melody",
Creator = "benpm",
Url = url,
FileType = "mp3",
License = "by",
LicenseVersion = "4.0",
DurationMs = 10193,
License = "CC BY 4.0",
Duration = TimeSpan.FromMilliseconds(10193),
Attribution = "\"Piano Melody\" by benpm is licensed under CC BY 4.0.",
};
@@ -62,11 +70,31 @@ public sealed class OpenverseTests : IDisposable
Assert.Equal("\"Rock\" by Angus", track.Attribution);
}
[Fact]
public void Track_MapsToTheNeutralShape()
{
var track = new OpenverseTrack { Id = "a", Title = "T", License = "by", LicenseVersion = "4.0", FileType = "MP32", DurationMs = 2000 }.ToMusicTrack();
Assert.Equal("a", track.Id);
Assert.Equal("CC BY 4.0", track.License);
Assert.Equal("mp3", track.FileType);
Assert.Equal(TimeSpan.FromSeconds(2), track.Duration);
}
[Fact]
public void Controller_ListsTheRegisteredProviders()
{
var provider = NewProvider((_, _) => Respond(HttpStatusCode.OK));
var controller = new OnlineImportController([provider], NewClient((_, _) => Respond(HttpStatusCode.OK)), new SongRepository(Path.Combine(_directory, "test.db")));
Assert.Equal("Openverse", Assert.Single(controller.Providers).Name);
}
[Fact]
public async Task Search_ParsesResults()
{
Uri? requested = null;
var client = NewClient((request, _) =>
var client = NewProvider((request, _) =>
{
requested = request.RequestUri;
return Respond(HttpStatusCode.OK, new StringContent(SearchJson, Encoding.UTF8, "application/json"));
@@ -83,19 +111,19 @@ public sealed class OpenverseTests : IDisposable
Assert.Equal("https://cdn.example.org/a.mp3", first.Url);
Assert.Equal("mp3", first.FileType);
Assert.Equal(TimeSpan.FromMilliseconds(10193), first.Duration);
Assert.Equal("CC BY 4.0", first.LicenseName);
Assert.Equal("CC BY 4.0", first.License);
Assert.StartsWith("\"Piano Melody\" by benpm", first.Attribution);
Assert.True(first.CanImport);
Assert.False(tracks[1].CanImport);
Assert.Equal("CC0 1.0", tracks[1].LicenseName);
Assert.Equal("CC0 1.0", tracks[1].License);
}
[Fact]
public async Task Search_RateLimited_ThrowsReadableError()
{
var client = NewClient((_, _) => Respond(HttpStatusCode.TooManyRequests));
var client = NewProvider((_, _) => Respond(HttpStatusCode.TooManyRequests));
var error = await Assert.ThrowsAsync<OpenverseException>(() => client.SearchAsync("x"));
var error = await Assert.ThrowsAsync<MusicProviderException>(() => client.SearchAsync("x"));
Assert.Contains("Limit erreicht", error.Message);
}
@@ -103,13 +131,13 @@ public sealed class OpenverseTests : IDisposable
[Fact]
public async Task Search_Timeout_ThrowsReadableError()
{
var client = NewClient(async (_, token) =>
var client = NewProvider(async (_, token) =>
{
await Task.Delay(Timeout.Infinite, token);
throw new InvalidOperationException("unreachable");
}, TimeSpan.FromMilliseconds(100));
var error = await Assert.ThrowsAsync<OpenverseException>(() => client.SearchAsync("x"));
var error = await Assert.ThrowsAsync<MusicProviderException>(() => client.SearchAsync("x"));
Assert.Contains("ZeitĂĽberschreitung", error.Message);
}
@@ -119,19 +147,19 @@ public sealed class OpenverseTests : IDisposable
{
var client = NewClient((_, _) => Respond(HttpStatusCode.OK, new ByteArrayContent(Audio)));
var songs = new SongRepository(Path.Combine(_directory, "test.db"));
var controller = new OpenverseController(client, songs);
var controller = NewController(client, songs);
var song = await controller.ImportAsync(Track());
var stored = songs.GetById(song.Id)!;
Assert.Equal(Path.Combine(MusicFolder, "benpm - Piano Melody.mp3"), stored.FilePath);
Assert.Equal(Audio, File.ReadAllBytes(stored.FilePath));
Assert.Equal(SongSource.Openverse, stored.Source);
Assert.Equal(SongSource.Online, stored.Source);
Assert.Equal("CC BY 4.0", stored.License);
Assert.Equal(Track().Attribution, stored.Attribution);
Assert.Equal(TimeSpan.FromMilliseconds(10193), stored.Duration);
Assert.Equal("benpm", stored.Artist);
Assert.Equal("a", stored.OpenverseId);
Assert.Equal("a", stored.ExternalId);
Assert.Contains("a", controller.ImportedIds());
}
@@ -154,7 +182,7 @@ public sealed class OpenverseTests : IDisposable
{
var client = NewClient((_, _) => Respond(HttpStatusCode.OK, new StreamContent(new FailingStream())));
await Assert.ThrowsAsync<OpenverseException>(() => client.DownloadAsync(Track()));
await Assert.ThrowsAsync<MusicProviderException>(() => client.DownloadAsync(Track()));
Assert.Empty(MusicFiles());
}
@@ -166,12 +194,12 @@ public sealed class OpenverseTests : IDisposable
var tooLarge = NewClient((_, _) =>
{
var content = new ByteArrayContent(Audio);
content.Headers.ContentLength = OpenverseClient.MaxDownloadBytes + 1;
content.Headers.ContentLength = TrackDownloader.MaxDownloadBytes + 1;
return Respond(HttpStatusCode.OK, content);
});
await Assert.ThrowsAsync<OpenverseException>(() => notFound.DownloadAsync(Track()));
await Assert.ThrowsAsync<OpenverseException>(() => tooLarge.DownloadAsync(Track()));
await Assert.ThrowsAsync<MusicProviderException>(() => notFound.DownloadAsync(Track()));
await Assert.ThrowsAsync<MusicProviderException>(() => tooLarge.DownloadAsync(Track()));
Assert.Empty(MusicFiles());
}
@@ -182,7 +210,7 @@ public sealed class OpenverseTests : IDisposable
var called = false;
var client = NewClient((_, _) => { called = true; return Respond(HttpStatusCode.OK); });
await Assert.ThrowsAsync<OpenverseException>(() => client.DownloadAsync(Track("http://cdn.example.org/a.mp3")));
await Assert.ThrowsAsync<MusicProviderException>(() => client.DownloadAsync(Track("http://cdn.example.org/a.mp3")));
Assert.False(called);
}
@@ -192,9 +220,9 @@ public sealed class OpenverseTests : IDisposable
{
var client = NewClient((_, _) => Respond(HttpStatusCode.OK, new ByteArrayContent(Audio)));
var songs = new SongRepository(Path.Combine(_directory, "test.db"));
var track = new OpenverseTrack { Title = "x", Url = "https://cdn.example.org/x.mp3", License = "by" };
var track = new MusicTrack { Title = "x", Url = "https://cdn.example.org/x.mp3", License = "CC BY 4.0" };
await Assert.ThrowsAsync<OpenverseException>(() => new OpenverseController(client, songs).ImportAsync(track));
await Assert.ThrowsAsync<MusicProviderException>(() => NewController(client, songs).ImportAsync(track));
Assert.Empty(MusicFiles());
Assert.Empty(songs.GetAll());
@@ -233,10 +261,10 @@ public sealed class OpenverseTests : IDisposable
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);
var controller = NewController(client, songs);
await controller.ImportAsync(Track());
var error = await Assert.ThrowsAsync<OpenverseException>(() => controller.ImportAsync(Track()));
var error = await Assert.ThrowsAsync<MusicProviderException>(() => controller.ImportAsync(Track()));
Assert.Contains("bereits in der Bibliothek", error.Message);
Assert.Equal(1, downloads);
+14 -14
View File
@@ -22,7 +22,7 @@ public sealed class SongRepositoryTests : IDisposable
Artist = "Artist",
Duration = TimeSpan.FromSeconds(185.5),
FilePath = @"C:\music\song.mp3",
Source = SongSource.Openverse,
Source = SongSource.Online,
License = "CC BY 4.0",
Attribution = null,
};
@@ -128,40 +128,40 @@ public sealed class SongRepositoryTests : IDisposable
}
[Fact]
public void OpenverseId_IsStoredAndListed()
public void ExternalId_IsStoredAndListed()
{
var repository = new SongRepository(DatabasePath);
var song = NewSong();
song.OpenverseId = "ov-1";
song.ExternalId = "ov-1";
repository.Add(song);
repository.Add(NewSong("Uploaded"));
Assert.Equal("ov-1", repository.GetById(song.Id)!.OpenverseId);
Assert.Equal(["ov-1"], repository.GetOpenverseIds());
Assert.Equal("ov-1", repository.GetById(song.Id)!.ExternalId);
Assert.Equal(["ov-1"], repository.GetExternalIds());
}
[Fact]
public void OpenverseId_CannotBeStoredTwice()
public void ExternalId_CannotBeStoredTwice()
{
var repository = new SongRepository(DatabasePath);
repository.Add(new Song { Title = "A", Artist = "", Duration = TimeSpan.FromSeconds(1), FilePath = "a", OpenverseId = "ov-1" });
repository.Add(new Song { Title = "A", Artist = "", Duration = TimeSpan.FromSeconds(1), FilePath = "a", ExternalId = "ov-1" });
Assert.Throws<DbUpdateException>(() =>
repository.Add(new Song { Title = "B", Artist = "", Duration = TimeSpan.FromSeconds(1), FilePath = "b", OpenverseId = "ov-1" }));
repository.Add(new Song { Title = "B", Artist = "", Duration = TimeSpan.FromSeconds(1), FilePath = "b", ExternalId = "ov-1" }));
}
[Fact]
public void Update_RejectsZeroDurationAndKeepsTheOpenverseId()
public void Update_RejectsZeroDurationAndKeepsTheExternalId()
{
var repository = new SongRepository(DatabasePath);
var song = NewSong();
song.OpenverseId = "ov-1";
song.ExternalId = "ov-1";
repository.Add(song);
song.Title = "Renamed";
song.OpenverseId = "changed";
song.ExternalId = "changed";
Assert.True(repository.Update(song));
Assert.Equal("ov-1", repository.GetById(song.Id)!.OpenverseId);
Assert.Equal("ov-1", repository.GetById(song.Id)!.ExternalId);
song.Duration = TimeSpan.Zero;
Assert.Throws<ArgumentException>(() => repository.Update(song));
@@ -192,8 +192,8 @@ public sealed class SongRepositoryTests : IDisposable
var old = Assert.Single(repository.GetAll());
Assert.Equal("Old", old.Title);
Assert.Equal(TimeSpan.FromSeconds(185.5), old.Duration);
Assert.Equal(SongSource.Openverse, old.Source);
Assert.Equal("ov-old", old.OpenverseId);
Assert.Equal(SongSource.Online, old.Source);
Assert.Equal("ov-old", old.ExternalId);
var added = NewSong("New");
repository.Add(added);