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:
1 parent
c6e9bf4e82
commit
a8ccb9b73d
14 files changed
+371
-260
No files matched your search
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user