feat(import): add the Internet Archive as a music provider

Searches Creative Commons licensed MP3 audio. A search result there is an
item with several files, so the file list of each item is fetched too and
every MP3 becomes one result. Query operators are removed from the search
words, so they cannot change the license filter.

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:36 +01:00
1 parent a8ccb9b73d
commit d73b9b507f
4 files changed
+280

No files matched your search

@@ -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;
/// <summary>
/// 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.
/// </summary>
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<IReadOnlyList<MusicTrack>> 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<List<MusicTrack>> TracksOfAsync(JsonElement item, CancellationToken cancellationToken)
{
var tracks = new List<MusicTrack>();
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();
}
@@ -0,0 +1,87 @@
using System.Globalization;
using System.Net.Http;
using System.Text.Json;
using System.Text.RegularExpressions;
namespace Radiosender.Services;
/// <summary>Helpers for JSON-based music providers: fetching, and reading licenses and durations.</summary>
internal static partial class ProviderParsing
{
/// <summary>Fetches <paramref name="url"/> and parses it as JSON, whatever content type the server names.</summary>
/// <exception cref="MusicProviderException">The request failed or the answer is not JSON.</exception>
public static async Task<JsonDocument> 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),
};
}
}
/// <summary>
/// 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 <c>null</c>.
/// </summary>
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();
}
/// <summary>Readable name for a Creative Commons license URL, e.g. "CC BY-NC 3.0"; <c>null</c> for anything else.</summary>
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;
}
/// <summary>Reads "2:36", "05:32", "1:02:03" or seconds such as "3808.26"; <c>null</c> when it is none of them.</summary>
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();
}