Merge branch 'j.lechner/openverse' into 'main'

feat: add Openverse audio search and import

Closes #5

See merge request julian/blockwoche3.1-radiosender!7
This commit is contained in:
Julian Lechner committed 2026-11-23 09:43:49 +00:00
commit e7a18f9a8f
7 files changed
+620

No files matched your search

@@ -0,0 +1,40 @@
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>Downloads the track and stores it as a song with its license and attribution.</summary>
public async Task<Song> ImportAsync(OpenverseTrack track, CancellationToken cancellationToken = default)
{
if (track.Duration is not { } duration)
throw new OpenverseException("This result has no duration and cannot be imported.");
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,
};
try
{
songs.Add(song);
}
catch
{
File.Delete(path); // no orphaned file without a database entry
throw;
}
return song;
}
}
+36
View File
@@ -0,0 +1,36 @@
using System.Text.Json.Serialization;
namespace Radiosender.Models;
/// <summary>One audio result of the Openverse search API (fields as documented at api.openverse.org/v1).</summary>
public class OpenverseTrack
{
public string Title { get; init; } = "";
public string? Creator { get; init; }
public string Url { get; init; } = "";
[JsonPropertyName("filetype")]
public string? FileType { get; init; }
public string License { get; init; } = "";
public string? LicenseVersion { get; init; }
public string? Attribution { get; init; }
/// <summary>Length in milliseconds; Openverse leaves it empty for some results.</summary>
[JsonPropertyName("duration")]
public int? DurationMs { get; init; }
[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") ?? "unknown";
/// <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
{
"cc0" => $"CC0 {LicenseVersion}".Trim(),
"pdm" => $"Public Domain Mark {LicenseVersion}".Trim(),
_ => $"CC {License.ToUpperInvariant()} {LicenseVersion}".Trim(),
};
}
+136
View File
@@ -0,0 +1,136 @@
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 search failed");
}
}
/// <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("Only https downloads are allowed.");
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("The file is larger than 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("The file is larger than 50 MB.");
await file.WriteAsync(buffer.AsMemory(0, read), timeout.Token);
}
if (total == 0)
throw new OpenverseException("The download was empty.");
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 failed");
}
}
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 rate limit reached (anonymous: 20 requests per minute, 200 per day). Please try again later.");
if (!response.IsSuccessStatusCode)
throw new OpenverseException($"Openverse returned HTTP {(int)response.StatusCode}.");
}
private static OpenverseException Wrap(Exception e, string action) => e switch
{
OperationCanceledException => new OpenverseException($"{action}: the request timed out.", e),
JsonException => new OpenverseException($"{action}: unexpected response.", e),
_ => new OpenverseException($"{action}: {e.Message}", e),
};
private sealed record SearchPage(List<OpenverseTrack>? Results);
}
+3
View File
@@ -28,6 +28,9 @@
<ui:NavigationViewItem Content="Upload" <ui:NavigationViewItem Content="Upload"
Icon="{ui:SymbolIcon ArrowUpload24}" Icon="{ui:SymbolIcon ArrowUpload24}"
TargetPageType="{x:Type pages:UploadPage}" /> TargetPageType="{x:Type pages:UploadPage}" />
<ui:NavigationViewItem Content="Openverse"
Icon="{ui:SymbolIcon Search24}"
TargetPageType="{x:Type pages:OpenversePage}" />
</ui:NavigationView.MenuItems> </ui:NavigationView.MenuItems>
</ui:NavigationView> </ui:NavigationView>
</Grid> </Grid>
@@ -0,0 +1,62 @@
<Page x:Class="Radiosender.Views.Pages.OpenversePage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
Title="Openverse"
Unloaded="OnUnloaded">
<Grid Margin="24">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<ui:TextBlock Grid.Row="0" FontTypography="Title" Text="Openverse" />
<Grid Grid.Row="1" Margin="0,12,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ui:TextBox x:Name="QueryBox"
PlaceholderText="Search free audio, for example &quot;jazz piano&quot;"
AutomationProperties.Name="Search term"
KeyDown="OnQueryKeyDown" />
<ui:Button x:Name="SearchButton" Grid.Column="1" Margin="8,0,0,0"
Appearance="Primary" Content="Search"
Icon="{ui:SymbolIcon Search24}"
Click="OnSearch" />
</Grid>
<ui:InfoBar x:Name="Message" Grid.Row="2" Margin="0,12,0,0" IsClosable="True" />
<ui:ListView x:Name="Results" Grid.Row="3" Margin="0,12,0,0"
SelectionMode="Single"
AutomationProperties.Name="Search results"
SelectionChanged="OnSelectionChanged">
<ui:ListView.View>
<ui:GridView>
<GridViewColumn Header="Title" Width="320" DisplayMemberBinding="{Binding Title}" />
<GridViewColumn Header="Creator" Width="200" DisplayMemberBinding="{Binding Creator}" />
<GridViewColumn Header="Duration" Width="90" DisplayMemberBinding="{Binding DurationText}" />
<GridViewColumn Header="License" Width="150" DisplayMemberBinding="{Binding LicenseName}" />
</ui:GridView>
</ui:ListView.View>
</ui:ListView>
<StackPanel Grid.Row="4" Margin="0,12,0,0" Orientation="Horizontal">
<ui:Button x:Name="PreviewButton" Content="Preview" Icon="{ui:SymbolIcon Play24}"
IsEnabled="False" Click="OnPreview" />
<ui:Button x:Name="StopButton" Margin="8,0,0,0" Content="Stop" Icon="{ui:SymbolIcon Stop24}"
IsEnabled="False" Click="OnStop" />
<ui:Button x:Name="ImportButton" Margin="8,0,0,0" Appearance="Primary"
Content="Import to library" Icon="{ui:SymbolIcon ArrowDownload24}"
IsEnabled="False" Click="OnImport" />
<ui:TextBlock x:Name="ImportHint" Margin="12,0,0,0" VerticalAlignment="Center"
Visibility="Collapsed"
Text="This result has no duration and cannot be imported." />
</StackPanel>
</Grid>
</Page>
@@ -0,0 +1,128 @@
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;
}
}
+215
View File
@@ -0,0 +1,215 @@
using System.Net;
using System.Text;
using Microsoft.Data.Sqlite;
using Radiosender.Controllers;
using Radiosender.Models;
using Radiosender.Services;
namespace Radiosender.Tests;
public sealed class OpenverseTests : IDisposable
{
private const string SearchJson = """
{"result_count":2,"page_count":1,"page_size":20,"page":1,"results":[
{"id":"a","title":"Piano Melody","url":"https://cdn.example.org/a.mp3","creator":"benpm",
"license":"by","license_version":"4.0","filetype":"mp3","duration":10193,
"attribution":"\"Piano Melody\" by benpm is licensed under CC BY 4.0."},
{"id":"b","title":"No Length","url":"https://cdn.example.org/b","creator":null,
"license":"cc0","license_version":"1.0","filetype":null,"duration":null,"attribution":null}
]}
""";
private static readonly byte[] Audio = [0x49, 0x44, 0x33, 1, 2, 3, 4, 5];
private readonly string _directory = Path.Combine(Path.GetTempPath(), "radiosender-tests", Guid.NewGuid().ToString("N"));
private string MusicFolder => Path.Combine(_directory, "Music");
public void Dispose()
{
SqliteConnection.ClearAllPools();
if (Directory.Exists(_directory))
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 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()
{
Title = "Piano Melody",
Creator = "benpm",
Url = url,
FileType = "mp3",
License = "by",
LicenseVersion = "4.0",
DurationMs = 10193,
Attribution = "\"Piano Melody\" by benpm is licensed under CC BY 4.0.",
};
private string[] MusicFiles() => Directory.Exists(MusicFolder) ? Directory.GetFiles(MusicFolder) : [];
[Fact]
public async Task Search_ParsesResults()
{
Uri? requested = null;
var client = NewClient((request, _) =>
{
requested = request.RequestUri;
return Respond(HttpStatusCode.OK, new StringContent(SearchJson, Encoding.UTF8, "application/json"));
});
var tracks = await client.SearchAsync("jazz piano");
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("Piano Melody", first.Title);
Assert.Equal("benpm", first.Creator);
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.StartsWith("\"Piano Melody\" by benpm", first.Attribution);
Assert.True(first.CanImport);
Assert.False(tracks[1].CanImport);
Assert.Equal("CC0 1.0", tracks[1].LicenseName);
}
[Fact]
public async Task Search_RateLimited_ThrowsReadableError()
{
var client = NewClient((_, _) => Respond(HttpStatusCode.TooManyRequests));
var error = await Assert.ThrowsAsync<OpenverseException>(() => client.SearchAsync("x"));
Assert.Contains("rate limit", error.Message);
}
[Fact]
public async Task Search_Timeout_ThrowsReadableError()
{
var client = NewClient(async (_, token) =>
{
await Task.Delay(Timeout.Infinite, token);
throw new InvalidOperationException("unreachable");
}, TimeSpan.FromMilliseconds(100));
var error = await Assert.ThrowsAsync<OpenverseException>(() => client.SearchAsync("x"));
Assert.Contains("timed out", error.Message);
}
[Fact]
public async Task Import_WritesFileAndDatabaseEntryWithLicense()
{
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 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("CC BY 4.0", stored.License);
Assert.Equal(Track().Attribution, stored.Attribution);
Assert.Equal(TimeSpan.FromMilliseconds(10193), stored.Duration);
Assert.Equal("benpm", stored.Artist);
}
[Fact]
public async Task Download_NeverOverwritesExistingFile()
{
Directory.CreateDirectory(MusicFolder);
var existing = Path.Combine(MusicFolder, "benpm - Piano Melody.mp3");
File.WriteAllText(existing, "keep");
var client = NewClient((_, _) => Respond(HttpStatusCode.OK, new ByteArrayContent(Audio)));
var path = await client.DownloadAsync(Track());
Assert.Equal(Path.Combine(MusicFolder, "benpm - Piano Melody (2).mp3"), path);
Assert.Equal("keep", File.ReadAllText(existing));
}
[Fact]
public async Task Download_FailingMidStream_LeavesNoFile()
{
var client = NewClient((_, _) => Respond(HttpStatusCode.OK, new StreamContent(new FailingStream())));
await Assert.ThrowsAsync<OpenverseException>(() => client.DownloadAsync(Track()));
Assert.Empty(MusicFiles());
}
[Fact]
public async Task Download_HttpErrorOrTooLarge_LeavesNoFile()
{
var notFound = NewClient((_, _) => Respond(HttpStatusCode.NotFound));
var tooLarge = NewClient((_, _) =>
{
var content = new ByteArrayContent(Audio);
content.Headers.ContentLength = OpenverseClient.MaxDownloadBytes + 1;
return Respond(HttpStatusCode.OK, content);
});
await Assert.ThrowsAsync<OpenverseException>(() => notFound.DownloadAsync(Track()));
await Assert.ThrowsAsync<OpenverseException>(() => tooLarge.DownloadAsync(Track()));
Assert.Empty(MusicFiles());
}
[Fact]
public async Task Download_RejectsNonHttpsUrl()
{
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")));
Assert.False(called);
}
[Fact]
public async Task Import_WithoutDuration_IsRejected()
{
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" };
await Assert.ThrowsAsync<OpenverseException>(() => new OpenverseController(client, songs).ImportAsync(track));
Assert.Empty(MusicFiles());
Assert.Empty(songs.GetAll());
}
private sealed class FakeHandler(Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> handle) : HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) =>
handle(request, cancellationToken);
}
/// <summary>Returns some bytes, then fails like a dropped connection.</summary>
private sealed class FailingStream : MemoryStream
{
private bool _sent;
public FailingStream() : base(Audio) { }
public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
{
if (_sent)
throw new IOException("connection reset");
_sent = true;
return base.ReadAsync(buffer, cancellationToken);
}
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask();
public override int Read(byte[] buffer, int offset, int count) => throw new IOException("connection reset");
}
}