diff --git a/src/Radiosender/App.xaml.cs b/src/Radiosender/App.xaml.cs index f0120d7..25865cf 100644 --- a/src/Radiosender/App.xaml.cs +++ b/src/Radiosender/App.xaml.cs @@ -36,6 +36,7 @@ public partial class App : Application }); // Music providers: add a line here for each new IMusicProvider; the import page lists them all. services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(provider => new TrackDownloader(provider.GetRequiredService(), TrackDownloader.DefaultMusicFolder)); services.AddSingleton(); services.AddSingleton(provider => new SongImportService(provider.GetRequiredService(), SongImportService.DefaultMusicDirectory)); diff --git a/src/Radiosender/Services/InternetArchiveProvider.cs b/src/Radiosender/Services/InternetArchiveProvider.cs new file mode 100644 index 0000000..cdbc954 --- /dev/null +++ b/src/Radiosender/Services/InternetArchiveProvider.cs @@ -0,0 +1,93 @@ +using System.IO; +using System.Net.Http; +using System.Text.Json; +using System.Text.RegularExpressions; +using Radiosender.Models; + +namespace Radiosender.Services; + +/// +/// Searches the Internet Archive for Creative Commons licensed MP3 audio. The search API returns items +/// (often whole albums), so each item's file list is fetched as well and every MP3 becomes one result. +/// +public partial class InternetArchiveProvider(HttpClient http) : IMusicProvider +{ + private const string SearchUrl = "https://archive.org/advancedsearch.php"; + private const string MetadataUrl = "https://archive.org/metadata/"; + + // One request per item follows the search, so the item count stays small. + private const int Items = 8; + private const int TracksPerItem = 5; + + public string Name => "Internet Archive"; + + public async Task> SearchAsync(string query, CancellationToken cancellationToken = default) + { + // The query language is Lucene; its operators are taken out of the user's words so they cannot change the filter. + var words = string.Join(' ', LuceneSyntax().Replace(query, " ").Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries)); + if (words.Length == 0) + return []; + var filter = $"({words}) AND mediatype:audio AND licenseurl:*creativecommons* AND format:(MP3)"; + var url = $"{SearchUrl}?q={Uri.EscapeDataString(filter)}&fl[]=identifier&fl[]=title&fl[]=creator&fl[]=licenseurl&rows={Items}&output=json"; + + using var json = await ProviderParsing.GetJsonAsync(http, url, Name, cancellationToken); + if (!json.RootElement.TryGetProperty("response", out var response) + || !response.TryGetProperty("docs", out var docs) || docs.ValueKind != JsonValueKind.Array) + throw new MusicProviderException($"{Name}-Suche fehlgeschlagen: unerwartete Antwort."); + + var perItem = await Task.WhenAll(docs.EnumerateArray().Select(doc => TracksOfAsync(doc, cancellationToken))); + return perItem.SelectMany(tracks => tracks).ToList(); + } + + private async Task> TracksOfAsync(JsonElement item, CancellationToken cancellationToken) + { + var tracks = new List(); + if (ProviderParsing.Text(item, "identifier") is not { } identifier) + return tracks; + + JsonDocument metadata; + try + { + metadata = await ProviderParsing.GetJsonAsync(http, MetadataUrl + Uri.EscapeDataString(identifier), Name, cancellationToken); + } + catch (MusicProviderException) + { + return tracks; // one unreachable item must not fail the whole search + } + + using (metadata) + { + if (!metadata.RootElement.TryGetProperty("files", out var files) || files.ValueKind != JsonValueKind.Array) + return tracks; + var license = ProviderParsing.License(ProviderParsing.Text(item, "licenseurl")) ?? ""; + foreach (var file in files.EnumerateArray()) + { + if (tracks.Count == TracksPerItem) + break; + if (ProviderParsing.Text(file, "name") is not { } name + || ProviderParsing.Text(file, "format")?.Contains("MP3", StringComparison.OrdinalIgnoreCase) != true) + continue; + var title = ProviderParsing.Text(file, "title") ?? Path.GetFileNameWithoutExtension(name); + var creator = ProviderParsing.Text(file, "creator") ?? ProviderParsing.Text(file, "artist") ?? ProviderParsing.Text(item, "creator"); + // A file name can contain folders; every part is escaped on its own. + var path = string.Join('/', name.Split('/').Select(Uri.EscapeDataString)); + tracks.Add(new MusicTrack + { + // Prefixed, so the id cannot collide with one from another provider. + Id = $"archive:{identifier}/{name}", + Title = title, + Creator = creator, + Url = $"https://archive.org/download/{Uri.EscapeDataString(identifier)}/{path}", + FileType = "mp3", + License = license, + Attribution = $"\"{title}\" by {creator ?? "Unknown"} (https://archive.org/details/{identifier}) is licensed under {license}.", + Duration = ProviderParsing.Duration(ProviderParsing.Text(file, "length")), + }); + } + } + return tracks; + } + + [GeneratedRegex("""[^\p{L}\p{N}\s]|\b(AND|OR|NOT|TO)\b""")] + private static partial Regex LuceneSyntax(); +} diff --git a/src/Radiosender/Services/ProviderParsing.cs b/src/Radiosender/Services/ProviderParsing.cs new file mode 100644 index 0000000..d77d058 --- /dev/null +++ b/src/Radiosender/Services/ProviderParsing.cs @@ -0,0 +1,87 @@ +using System.Globalization; +using System.Net.Http; +using System.Text.Json; +using System.Text.RegularExpressions; + +namespace Radiosender.Services; + +/// Helpers for JSON-based music providers: fetching, and reading licenses and durations. +internal static partial class ProviderParsing +{ + /// Fetches and parses it as JSON, whatever content type the server names. + /// The request failed or the answer is not JSON. + public static async Task GetJsonAsync(HttpClient http, string url, string provider, CancellationToken cancellationToken) + { + try + { + using var response = await http.GetAsync(url, cancellationToken); + if (!response.IsSuccessStatusCode) + throw new MusicProviderException($"{provider} hat HTTP {(int)response.StatusCode} geliefert."); + // Parsed without looking at the content type: not every API labels its JSON as such. + return JsonDocument.Parse(await response.Content.ReadAsStringAsync(cancellationToken)); + } + catch (Exception e) when (e is not MusicProviderException && !cancellationToken.IsCancellationRequested) + { + throw e switch + { + OperationCanceledException => new MusicProviderException($"{provider}-Suche fehlgeschlagen: Zeitüberschreitung der Anfrage.", e), + JsonException => new MusicProviderException($"{provider}-Suche fehlgeschlagen: unerwartete Antwort.", e), + _ => new MusicProviderException($"{provider}-Suche fehlgeschlagen: {e.Message}", e), + }; + } + } + + /// + /// The property as text: a string as it is, a number as its digits, and the first entry of a list + /// (the Internet Archive sends one creator as a string and several as a list). Otherwise null. + /// + public static string? Text(JsonElement element, string property) + { + if (element.ValueKind != JsonValueKind.Object || !element.TryGetProperty(property, out var value)) + return null; + if (value.ValueKind == JsonValueKind.Array) + value = value.EnumerateArray().FirstOrDefault(); + var text = value.ValueKind switch + { + JsonValueKind.String => System.Net.WebUtility.HtmlDecode(value.GetString()), + JsonValueKind.Number => value.GetRawText(), + _ => null, + }; + return string.IsNullOrWhiteSpace(text) ? null : text.Trim(); + } + + /// Readable name for a Creative Commons license URL, e.g. "CC BY-NC 3.0"; null for anything else. + public static string? License(string? url) + { + if (url is null) + return null; + if (LicensePattern().Match(url) is { Success: true } license) + return $"CC {license.Groups[1].Value.ToUpperInvariant()} {license.Groups[2].Value}"; + if (PublicDomainPattern().Match(url) is { Success: true } publicDomain) + return publicDomain.Groups[1].Value == "zero" ? $"CC0 {publicDomain.Groups[2].Value}" : $"Public Domain Mark {publicDomain.Groups[2].Value}"; + return null; + } + + /// Reads "2:36", "05:32", "1:02:03" or seconds such as "3808.26"; null when it is none of them. + public static TimeSpan? Duration(string? text) + { + if (string.IsNullOrWhiteSpace(text)) + return null; + var parts = text.Trim().Split(':'); + double seconds = 0; + foreach (var part in parts) + { + if (!double.TryParse(part, NumberStyles.Float, CultureInfo.InvariantCulture, out var value) || value < 0) + return null; + seconds = seconds * 60 + value; + } + // An upper bound keeps a nonsense value from overflowing TimeSpan. + return parts.Length <= 3 && seconds is > 0 and < 86400 ? TimeSpan.FromSeconds(seconds) : null; + } + + [GeneratedRegex(@"creativecommons\.org/licenses/([a-z-]+)/(\d+(?:\.\d+)*)", RegexOptions.IgnoreCase)] + private static partial Regex LicensePattern(); + + [GeneratedRegex(@"creativecommons\.org/publicdomain/(zero|mark)/(\d+(?:\.\d+)*)", RegexOptions.IgnoreCase)] + private static partial Regex PublicDomainPattern(); +} diff --git a/tests/Radiosender.Tests/MusicProviderTests.cs b/tests/Radiosender.Tests/MusicProviderTests.cs new file mode 100644 index 0000000..95f99db --- /dev/null +++ b/tests/Radiosender.Tests/MusicProviderTests.cs @@ -0,0 +1,99 @@ +using System.Net; +using System.Text; +using Radiosender.Services; + +namespace Radiosender.Tests; + +/// The Internet Archive provider against canned answers in the shape the real API sends. +public class MusicProviderTests +{ + private const string ArchiveSearchJson = """ + {"response":{"numFound":3,"docs":[ + {"identifier":"dancing-in-the-dark","title":"Dancing in the Dark","creator":["Bill Carrothers","José Encarnación"], + "licenseurl":"https://creativecommons.org/licenses/by-nc-nd/4.0/"}, + {"identifier":"broken-item","title":"Broken","licenseurl":"https://creativecommons.org/publicdomain/mark/1.0/"} + ]}} + """; + + private const string ArchiveMetadataJson = """ + {"metadata":{"identifier":"dancing-in-the-dark"},"files":[ + {"name":"cover.png","format":"PNG"}, + {"name":"01 just.mp3","format":"VBR MP3","length":"05:32","title":"Just in Time","creator":"Bill Carrothers"}, + {"name":"live/02 set.mp3","format":"VBR MP3","length":"3808.26"}, + {"name":"03 talk.mp3","format":"VBR MP3"}, + {"name":"01 just.flac","format":"24bit Flac","length":"05:32"} + ]} + """; + + private static HttpClient Http(Func respond) => new(new FakeHandler(respond)); + + private static HttpResponseMessage Json(string json, string contentType = "application/json") => + new(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, contentType) }; + + [Fact] + public async Task InternetArchive_TurnsTheMp3FilesOfEachItemIntoTracks() + { + var requests = new List(); + var provider = new InternetArchiveProvider(Http(uri => + { + lock (requests) requests.Add(uri); + if (uri.AbsolutePath == "/advancedsearch.php") return Json(ArchiveSearchJson); + return uri.AbsolutePath.EndsWith("/dancing-in-the-dark") ? Json(ArchiveMetadataJson) : new HttpResponseMessage(HttpStatusCode.InternalServerError); + })); + + var tracks = await provider.SearchAsync("jazz"); + + // The item whose file list failed is left out; the search still succeeds. + Assert.Equal(3, tracks.Count); + var first = tracks[0]; + Assert.Equal("archive:dancing-in-the-dark/01 just.mp3", first.Id); + Assert.Equal("Just in Time", first.Title); + Assert.Equal("Bill Carrothers", first.Creator); + Assert.Equal("https://archive.org/download/dancing-in-the-dark/01%20just.mp3", first.Url); + Assert.Equal("CC BY-NC-ND 4.0", first.License); + Assert.Equal(TimeSpan.FromSeconds(332), first.Duration); + Assert.Contains("https://archive.org/details/dancing-in-the-dark", first.Attribution); + // No title or creator on the file: file name and the item's first creator; seconds as length; folders kept in the link. + Assert.Equal("02 set", tracks[1].Title); + Assert.Equal("Bill Carrothers", tracks[1].Creator); + Assert.Equal("https://archive.org/download/dancing-in-the-dark/live/02%20set.mp3", tracks[1].Url); + Assert.Equal(TimeSpan.FromSeconds(3808.26), tracks[1].Duration); + Assert.False(tracks[2].CanImport); + } + + [Fact] + public async Task InternetArchive_ReportsHttpErrorsAndBrokenAnswers() + { + var failing = new InternetArchiveProvider(Http(_ => new HttpResponseMessage(HttpStatusCode.ServiceUnavailable))); + var broken = new InternetArchiveProvider(Http(_ => Json("maintenance", "text/html"))); + var wrongShape = new InternetArchiveProvider(Http(_ => Json("{}"))); + + Assert.Contains("503", (await Assert.ThrowsAsync(() => failing.SearchAsync("x"))).Message); + await Assert.ThrowsAsync(() => broken.SearchAsync("x")); + await Assert.ThrowsAsync(() => wrongShape.SearchAsync("x")); + } + + [Fact] + public async Task InternetArchive_KeepsQueryOperatorsOutOfTheFilter() + { + string? query = null; + var provider = new InternetArchiveProvider(Http(uri => + { + query = Uri.UnescapeDataString(uri.Query); + return Json("""{"response":{"docs":[]}}"""); + })); + + Assert.Empty(await provider.SearchAsync("jazz) OR mediatype:(movies")); + Assert.Contains("q=(jazz mediatype movies) AND mediatype:audio AND licenseurl:*creativecommons* AND format:(MP3)", query); + + query = null; + Assert.Empty(await provider.SearchAsync(" ()* ")); + Assert.Null(query); // nothing left to search for, so no request + } + + private sealed class FakeHandler(Func respond) : HttpMessageHandler + { + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => + Task.FromResult(respond(request.RequestUri!)); + } +}