feat(import): search all providers in parallel with a license filter
The import page searches Openverse and the Internet Archive at the same time and lists each source's results as they arrive, with a Quelle column. A multiselect dropdown picks the licenses: Openverse filters on its server, the Internet Archive after the search. Provider texts are translated, and the unused bearer token support is gone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
c3c698aa93
commit
8d1790d164
9 files changed
+268
-101
No files matched your search
@@ -1,25 +1,45 @@
|
|||||||
using System.IO;
|
using System.IO;
|
||||||
|
using System.Runtime.CompilerServices;
|
||||||
using Radiosender.Models;
|
using Radiosender.Models;
|
||||||
using Radiosender.Services.Library;
|
using Radiosender.Services.Library;
|
||||||
|
using Radiosender.Services.Localization;
|
||||||
using Radiosender.Services.Providers;
|
using Radiosender.Services.Providers;
|
||||||
|
|
||||||
namespace Radiosender.Controllers;
|
namespace Radiosender.Controllers;
|
||||||
|
|
||||||
public class OnlineImportController(IEnumerable<IMusicProvider> providers, TrackDownloader downloader, SongRepository songs)
|
public class OnlineImportController(IEnumerable<IMusicProvider> providers, TrackDownloader downloader, SongRepository songs)
|
||||||
{
|
{
|
||||||
private readonly IReadOnlyList<IMusicProvider> _providers = [.. providers];
|
public IReadOnlyList<IMusicProvider> Providers { get; } = [.. providers];
|
||||||
|
|
||||||
public IReadOnlyList<IMusicProvider> Providers => [.. _providers.Where(provider => provider.IsAvailable)];
|
|
||||||
|
|
||||||
public IReadOnlySet<string> ImportedIds() => songs.GetExternalIds();
|
public IReadOnlySet<string> ImportedIds() => songs.GetExternalIds();
|
||||||
|
|
||||||
|
// All providers at once; each result as soon as its provider is done. One failure never stops the others.
|
||||||
|
public async IAsyncEnumerable<ProviderResult> SearchAllAsync(string query, IReadOnlySet<string>? licenses,
|
||||||
|
[EnumeratorCancellation] CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
await foreach (var search in Task.WhenEach(Providers.Select(provider => SearchOneAsync(provider, query, licenses, cancellationToken))))
|
||||||
|
yield return await search;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task<ProviderResult> SearchOneAsync(IMusicProvider provider, string query, IReadOnlySet<string>? licenses, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return new(provider, await provider.SearchAsync(query, licenses, cancellationToken));
|
||||||
|
}
|
||||||
|
catch (MusicProviderException ex)
|
||||||
|
{
|
||||||
|
return new(provider, [], ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <exception cref="MusicProviderException">Track not importable or download failed.</exception>
|
/// <exception cref="MusicProviderException">Track not importable or download failed.</exception>
|
||||||
public async Task<Song> ImportAsync(MusicTrack track, CancellationToken cancellationToken = default)
|
public async Task<Song> ImportAsync(MusicTrack track, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
if (track.Duration is not { } duration)
|
if (track.Duration is not { } duration)
|
||||||
throw new MusicProviderException("Dieses Ergebnis hat keine Dauer und kann nicht importiert werden.");
|
throw new MusicProviderException(Loc.T("Provider_NoDuration"));
|
||||||
if (track.Id.Length > 0 && ImportedIds().Contains(track.Id))
|
if (track.Id.Length > 0 && ImportedIds().Contains(track.Id))
|
||||||
throw new MusicProviderException($"\"{track.Title}\" ist bereits in der Bibliothek.");
|
throw new MusicProviderException(Loc.F("Provider_AlreadyInLibrary", track.Title));
|
||||||
|
|
||||||
var path = await downloader.DownloadAsync(track, cancellationToken);
|
var path = await downloader.DownloadAsync(track, cancellationToken);
|
||||||
var song = new Song
|
var song = new Song
|
||||||
|
|||||||
@@ -7,8 +7,7 @@ public interface IMusicProvider
|
|||||||
{
|
{
|
||||||
string Name { get; }
|
string Name { get; }
|
||||||
|
|
||||||
bool IsAvailable => true;
|
// licenses: LicenseType codes to keep; null = all.
|
||||||
|
|
||||||
/// <exception cref="MusicProviderException">Search failed.</exception>
|
/// <exception cref="MusicProviderException">Search failed.</exception>
|
||||||
Task<IReadOnlyList<MusicTrack>> SearchAsync(string query, CancellationToken cancellationToken = default);
|
Task<IReadOnlyList<MusicTrack>> SearchAsync(string query, IReadOnlySet<string>? licenses = null, CancellationToken cancellationToken = default);
|
||||||
}
|
}
|
||||||
@@ -3,6 +3,7 @@ using System.Net.Http;
|
|||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using System.Text.RegularExpressions;
|
using System.Text.RegularExpressions;
|
||||||
using Radiosender.Models;
|
using Radiosender.Models;
|
||||||
|
using Radiosender.Services.Localization;
|
||||||
|
|
||||||
namespace Radiosender.Services.Providers;
|
namespace Radiosender.Services.Providers;
|
||||||
|
|
||||||
@@ -18,8 +19,10 @@ public partial class InternetArchiveProvider(HttpClient http) : IMusicProvider
|
|||||||
|
|
||||||
public string Name => "Internet Archive";
|
public string Name => "Internet Archive";
|
||||||
|
|
||||||
public async Task<IReadOnlyList<MusicTrack>> SearchAsync(string query, CancellationToken cancellationToken = default)
|
public async Task<IReadOnlyList<MusicTrack>> SearchAsync(string query, IReadOnlySet<string>? licenses = null, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
|
if (licenses is { Count: 0 })
|
||||||
|
return [];
|
||||||
// Strip Lucene operators: user input must not change the filter.
|
// Strip Lucene operators: user input must not change the filter.
|
||||||
var words = string.Join(' ', LuceneSyntax().Replace(query, " ").Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries));
|
var words = string.Join(' ', LuceneSyntax().Replace(query, " ").Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries));
|
||||||
if (words.Length == 0)
|
if (words.Length == 0)
|
||||||
@@ -30,10 +33,12 @@ public partial class InternetArchiveProvider(HttpClient http) : IMusicProvider
|
|||||||
using var json = await ProviderParsing.GetJsonAsync(http, url, Name, cancellationToken);
|
using var json = await ProviderParsing.GetJsonAsync(http, url, Name, cancellationToken);
|
||||||
if (!json.RootElement.TryGetProperty("response", out var response)
|
if (!json.RootElement.TryGetProperty("response", out var response)
|
||||||
|| !response.TryGetProperty("docs", out var docs) || docs.ValueKind != JsonValueKind.Array)
|
|| !response.TryGetProperty("docs", out var docs) || docs.ValueKind != JsonValueKind.Array)
|
||||||
throw new MusicProviderException($"{Name}-Suche fehlgeschlagen: unerwartete Antwort.");
|
throw new MusicProviderException(Loc.F("Provider_SearchUnexpected", Name));
|
||||||
|
|
||||||
var perItem = await Task.WhenAll(docs.EnumerateArray().Select(doc => TracksOfAsync(doc, cancellationToken)));
|
var perItem = await Task.WhenAll(docs.EnumerateArray().Select(doc => TracksOfAsync(doc, cancellationToken)));
|
||||||
return [.. perItem.SelectMany(tracks => tracks)];
|
// shortcut: filtered after the search, so fewer than Items results; move into the Lucene query if too few.
|
||||||
|
return [.. perItem.SelectMany(tracks => tracks)
|
||||||
|
.Where(track => licenses is null || LicenseType.CodeOf(track.License) is { } code && licenses.Contains(code))];
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task<List<MusicTrack>> TracksOfAsync(JsonElement item, CancellationToken cancellationToken)
|
private async Task<List<MusicTrack>> TracksOfAsync(JsonElement item, CancellationToken cancellationToken)
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ using System.Net.Http;
|
|||||||
using System.Net.Http.Json;
|
using System.Net.Http.Json;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using Radiosender.Models;
|
using Radiosender.Models;
|
||||||
|
using Radiosender.Services.Localization;
|
||||||
|
|
||||||
namespace Radiosender.Services.Providers;
|
namespace Radiosender.Services.Providers;
|
||||||
|
|
||||||
@@ -15,16 +16,21 @@ public class OpenverseProvider(HttpClient http) : IMusicProvider
|
|||||||
|
|
||||||
public string Name => "Openverse";
|
public string Name => "Openverse";
|
||||||
|
|
||||||
public async Task<IReadOnlyList<MusicTrack>> SearchAsync(string query, CancellationToken cancellationToken = default)
|
public async Task<IReadOnlyList<MusicTrack>> SearchAsync(string query, IReadOnlySet<string>? licenses = null, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
|
if (licenses is { Count: 0 })
|
||||||
|
return [];
|
||||||
var url = $"{SearchUrl}?q={Uri.EscapeDataString(query)}&page_size={PageSize}";
|
var url = $"{SearchUrl}?q={Uri.EscapeDataString(query)}&page_size={PageSize}";
|
||||||
|
// Server filters: full page of matches instead of a thinned-out one.
|
||||||
|
if (licenses is not null)
|
||||||
|
url += "&license=" + Uri.EscapeDataString(string.Join(',', licenses.Order()));
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
using var response = await http.GetAsync(url, cancellationToken);
|
using var response = await http.GetAsync(url, cancellationToken);
|
||||||
if (response.StatusCode == HttpStatusCode.TooManyRequests)
|
if (response.StatusCode == HttpStatusCode.TooManyRequests)
|
||||||
throw new MusicProviderException("Openverse-Limit erreicht (anonym: 20 Anfragen pro Minute, 200 pro Tag). Bitte später erneut versuchen.");
|
throw new MusicProviderException(Loc.F("Provider_RateLimit", Name));
|
||||||
if (!response.IsSuccessStatusCode)
|
if (!response.IsSuccessStatusCode)
|
||||||
throw new MusicProviderException($"Openverse hat HTTP {(int)response.StatusCode} geliefert.");
|
throw new MusicProviderException(Loc.F("Provider_HttpStatus", Name, (int)response.StatusCode));
|
||||||
var page = await response.Content.ReadFromJsonAsync<SearchPage>(JsonOptions, cancellationToken);
|
var page = await response.Content.ReadFromJsonAsync<SearchPage>(JsonOptions, cancellationToken);
|
||||||
return page?.Results?.Select(result => result.ToMusicTrack()).ToList() ?? [];
|
return page?.Results?.Select(result => result.ToMusicTrack()).ToList() ?? [];
|
||||||
}
|
}
|
||||||
@@ -32,9 +38,9 @@ public class OpenverseProvider(HttpClient http) : IMusicProvider
|
|||||||
{
|
{
|
||||||
throw e switch
|
throw e switch
|
||||||
{
|
{
|
||||||
OperationCanceledException => new MusicProviderException("Openverse-Suche fehlgeschlagen: ZeitĂĽberschreitung der Anfrage.", e),
|
OperationCanceledException => new MusicProviderException(Loc.F("Provider_SearchTimeout", Name), e),
|
||||||
JsonException => new MusicProviderException("Openverse-Suche fehlgeschlagen: unerwartete Antwort.", e),
|
JsonException => new MusicProviderException(Loc.F("Provider_SearchUnexpected", Name), e),
|
||||||
_ => new MusicProviderException($"Openverse-Suche fehlgeschlagen: {e.Message}", e),
|
_ => new MusicProviderException(Loc.F("Provider_SearchError", Name, e.Message), e),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,24 +3,20 @@ using System.Net;
|
|||||||
using System.Net.Http;
|
using System.Net.Http;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using System.Text.RegularExpressions;
|
using System.Text.RegularExpressions;
|
||||||
|
using Radiosender.Services.Localization;
|
||||||
|
|
||||||
namespace Radiosender.Services.Providers;
|
namespace Radiosender.Services.Providers;
|
||||||
|
|
||||||
internal static partial class ProviderParsing
|
internal static partial class ProviderParsing
|
||||||
{
|
{
|
||||||
/// <exception cref="MusicProviderException">Request failed or answer is not JSON.</exception>
|
/// <exception cref="MusicProviderException">Request failed or answer is not JSON.</exception>
|
||||||
public static async Task<JsonDocument> GetJsonAsync(HttpClient http, string url, string provider, CancellationToken cancellationToken, string? bearerToken = null)
|
public static async Task<JsonDocument> GetJsonAsync(HttpClient http, string url, string provider, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
using var request = new HttpRequestMessage(HttpMethod.Get, url);
|
using var response = await http.GetAsync(url, cancellationToken);
|
||||||
if (bearerToken is not null)
|
|
||||||
request.Headers.Authorization = new("Bearer", bearerToken);
|
|
||||||
using var response = await http.SendAsync(request, cancellationToken);
|
|
||||||
if (response.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden && bearerToken is not null)
|
|
||||||
throw new MusicProviderException($"{provider} hat die Anmeldung abgelehnt. Den Token in den Einstellungen prĂĽfen.");
|
|
||||||
if (!response.IsSuccessStatusCode)
|
if (!response.IsSuccessStatusCode)
|
||||||
throw new MusicProviderException($"{provider} hat HTTP {(int)response.StatusCode} geliefert.");
|
throw new MusicProviderException(Loc.F("Provider_HttpStatus", provider, (int)response.StatusCode));
|
||||||
// Content type ignored: not every API labels JSON.
|
// Content type ignored: not every API labels JSON.
|
||||||
return JsonDocument.Parse(await response.Content.ReadAsStringAsync(cancellationToken));
|
return JsonDocument.Parse(await response.Content.ReadAsStringAsync(cancellationToken));
|
||||||
}
|
}
|
||||||
@@ -28,9 +24,9 @@ internal static partial class ProviderParsing
|
|||||||
{
|
{
|
||||||
throw e switch
|
throw e switch
|
||||||
{
|
{
|
||||||
OperationCanceledException => new MusicProviderException($"{provider}-Suche fehlgeschlagen: ZeitĂĽberschreitung der Anfrage.", e),
|
OperationCanceledException => new MusicProviderException(Loc.F("Provider_SearchTimeout", provider), e),
|
||||||
JsonException => new MusicProviderException($"{provider}-Suche fehlgeschlagen: unerwartete Antwort.", e),
|
JsonException => new MusicProviderException(Loc.F("Provider_SearchUnexpected", provider), e),
|
||||||
_ => new MusicProviderException($"{provider}-Suche fehlgeschlagen: {e.Message}", e),
|
_ => new MusicProviderException(Loc.F("Provider_SearchError", provider, e.Message), e),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,9 +2,11 @@
|
|||||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||||
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
|
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
|
||||||
Title="Import"
|
xmlns:l="clr-namespace:Radiosender.Views"
|
||||||
|
Title="{l:Tr Import_Title}"
|
||||||
Foreground="{DynamicResource TextFillColorPrimaryBrush}"
|
Foreground="{DynamicResource TextFillColorPrimaryBrush}"
|
||||||
ScrollViewer.CanContentScroll="False"
|
ScrollViewer.CanContentScroll="False"
|
||||||
|
Loaded="OnLoaded"
|
||||||
Unloaded="OnUnloaded">
|
Unloaded="OnUnloaded">
|
||||||
<Grid Margin="24">
|
<Grid Margin="24">
|
||||||
<Grid.RowDefinitions>
|
<Grid.RowDefinitions>
|
||||||
@@ -39,7 +41,7 @@
|
|||||||
</Style>
|
</Style>
|
||||||
</TabControl.Resources>
|
</TabControl.Resources>
|
||||||
<!-- From computer -->
|
<!-- From computer -->
|
||||||
<TabItem Header="Vom Computer">
|
<TabItem Header="{l:Tr Import_TabComputer}">
|
||||||
<Grid Margin="0,12,0,0">
|
<Grid Margin="0,12,0,0">
|
||||||
<Grid.RowDefinitions>
|
<Grid.RowDefinitions>
|
||||||
<RowDefinition Height="*" />
|
<RowDefinition Height="*" />
|
||||||
@@ -49,7 +51,7 @@
|
|||||||
<Grid x:Name="DropZone"
|
<Grid x:Name="DropZone"
|
||||||
Background="Transparent"
|
Background="Transparent"
|
||||||
AllowDrop="True"
|
AllowDrop="True"
|
||||||
AutomationProperties.Name="Ablagebereich fĂĽr MP3- und WAV-Dateien"
|
AutomationProperties.Name="{l:Tr Import_DropZoneName}"
|
||||||
DragEnter="OnDragOver"
|
DragEnter="OnDragOver"
|
||||||
DragOver="OnDragOver"
|
DragOver="OnDragOver"
|
||||||
DragLeave="OnDragLeave"
|
DragLeave="OnDragLeave"
|
||||||
@@ -65,11 +67,11 @@
|
|||||||
<ui:TextBlock Margin="0,8,0,12"
|
<ui:TextBlock Margin="0,8,0,12"
|
||||||
HorizontalAlignment="Center"
|
HorizontalAlignment="Center"
|
||||||
FontTypography="BodyStrong"
|
FontTypography="BodyStrong"
|
||||||
Text="MP3- oder WAV-Dateien hier ablegen" />
|
Text="{l:Tr Import_DropHint}" />
|
||||||
<ui:Button x:Name="ChooseFilesButton"
|
<ui:Button x:Name="ChooseFilesButton"
|
||||||
HorizontalAlignment="Center"
|
HorizontalAlignment="Center"
|
||||||
Appearance="Primary"
|
Appearance="Primary"
|
||||||
Content="Dateien auswählen..."
|
Content="{l:Tr Import_ChooseFiles}"
|
||||||
Icon="{ui:SymbolIcon FolderOpen24}"
|
Icon="{ui:SymbolIcon FolderOpen24}"
|
||||||
Click="OnChooseFiles" />
|
Click="OnChooseFiles" />
|
||||||
</StackPanel>
|
</StackPanel>
|
||||||
@@ -79,13 +81,13 @@
|
|||||||
<ui:TextBlock x:Name="UploadProgressText" />
|
<ui:TextBlock x:Name="UploadProgressText" />
|
||||||
<ProgressBar x:Name="UploadProgress"
|
<ProgressBar x:Name="UploadProgress"
|
||||||
Margin="0,6,0,0"
|
Margin="0,6,0,0"
|
||||||
AutomationProperties.Name="Import-Fortschritt" />
|
AutomationProperties.Name="{l:Tr Import_ProgressName}" />
|
||||||
</StackPanel>
|
</StackPanel>
|
||||||
</Grid>
|
</Grid>
|
||||||
</TabItem>
|
</TabItem>
|
||||||
|
|
||||||
<!-- Online providers; the header is the provider name when there is only one -->
|
<!-- Searches all providers in parallel -->
|
||||||
<TabItem x:Name="OnlineTab" Header="Online">
|
<TabItem x:Name="OnlineTab" Header="{l:Tr Import_TabOnline}">
|
||||||
<Grid Margin="0,12,0,0">
|
<Grid Margin="0,12,0,0">
|
||||||
<Grid.RowDefinitions>
|
<Grid.RowDefinitions>
|
||||||
<RowDefinition Height="Auto" />
|
<RowDefinition Height="Auto" />
|
||||||
@@ -100,23 +102,25 @@
|
|||||||
<ColumnDefinition Width="*" />
|
<ColumnDefinition Width="*" />
|
||||||
<ColumnDefinition Width="Auto" />
|
<ColumnDefinition Width="Auto" />
|
||||||
</Grid.ColumnDefinitions>
|
</Grid.ColumnDefinitions>
|
||||||
<!-- Only shown when more than one provider is registered -->
|
<!-- Multiselect: checkable items filled from LicenseType.All in code -->
|
||||||
<ComboBox x:Name="ProviderBox"
|
<ui:DropDownButton x:Name="LicenseButton"
|
||||||
MinWidth="140"
|
MinWidth="150"
|
||||||
Margin="0,0,8,0"
|
Margin="0,0,8,0"
|
||||||
AutomationProperties.Name="Musikquelle"
|
AutomationProperties.Name="{l:Tr Import_LicensesName}">
|
||||||
DisplayMemberPath="Name"
|
<ui:DropDownButton.Flyout>
|
||||||
Visibility="Collapsed" />
|
<ContextMenu x:Name="LicenseMenu" />
|
||||||
|
</ui:DropDownButton.Flyout>
|
||||||
|
</ui:DropDownButton>
|
||||||
<ui:TextBox x:Name="QueryBox"
|
<ui:TextBox x:Name="QueryBox"
|
||||||
Grid.Column="1"
|
Grid.Column="1"
|
||||||
PlaceholderText="Freie Musik suchen, zum Beispiel "jazz piano""
|
PlaceholderText="{l:Tr Import_SearchPlaceholder}"
|
||||||
AutomationProperties.Name="Suchbegriff"
|
AutomationProperties.Name="{l:Tr Import_QueryName}"
|
||||||
KeyDown="OnQueryKeyDown" />
|
KeyDown="OnQueryKeyDown" />
|
||||||
<ui:Button x:Name="SearchButton"
|
<ui:Button x:Name="SearchButton"
|
||||||
Grid.Column="2"
|
Grid.Column="2"
|
||||||
Margin="8,0,0,0"
|
Margin="8,0,0,0"
|
||||||
Appearance="Primary"
|
Appearance="Primary"
|
||||||
Content="Suchen"
|
Content="{l:Tr Import_Search}"
|
||||||
Icon="{ui:SymbolIcon Search24}"
|
Icon="{ui:SymbolIcon Search24}"
|
||||||
Click="OnSearch" />
|
Click="OnSearch" />
|
||||||
</Grid>
|
</Grid>
|
||||||
@@ -127,24 +131,25 @@
|
|||||||
Grid.Row="2"
|
Grid.Row="2"
|
||||||
Margin="0,12,0,0"
|
Margin="0,12,0,0"
|
||||||
SelectionMode="Extended"
|
SelectionMode="Extended"
|
||||||
AutomationProperties.Name="Suchergebnisse"
|
AutomationProperties.Name="{l:Tr Import_ResultsName}"
|
||||||
SelectionChanged="OnSelectionChanged"
|
SelectionChanged="OnSelectionChanged"
|
||||||
MouseDoubleClick="OnResultDoubleClick">
|
MouseDoubleClick="OnResultDoubleClick">
|
||||||
<ui:ListView.View>
|
<ui:ListView.View>
|
||||||
<ui:GridView>
|
<ui:GridView>
|
||||||
<ui:GridViewColumn Width="300" Header="Titel" DisplayMemberBinding="{Binding Track.Title}" />
|
<ui:GridViewColumn Width="300" Header="{l:Tr Song_Title}" DisplayMemberBinding="{Binding Track.Title}" />
|
||||||
<ui:GridViewColumn Width="180" Header="Urheber" DisplayMemberBinding="{Binding Track.Creator}" />
|
<ui:GridViewColumn Width="180" Header="{l:Tr Import_ColCreator}" DisplayMemberBinding="{Binding Track.Creator}" />
|
||||||
<ui:GridViewColumn Width="80" Header="Dauer" DisplayMemberBinding="{Binding Track.DurationText}" />
|
<ui:GridViewColumn Width="80" Header="{l:Tr Song_Duration}" DisplayMemberBinding="{Binding Track.DurationText}" />
|
||||||
<ui:GridViewColumn Width="130" Header="Lizenz" DisplayMemberBinding="{Binding Track.License}" />
|
<ui:GridViewColumn Width="130" Header="{l:Tr Song_License}" DisplayMemberBinding="{Binding Track.License}" />
|
||||||
|
<ui:GridViewColumn Width="130" Header="{l:Tr Import_ColSource}" DisplayMemberBinding="{Binding Source}" />
|
||||||
</ui:GridView>
|
</ui:GridView>
|
||||||
</ui:ListView.View>
|
</ui:ListView.View>
|
||||||
</ui:ListView>
|
</ui:ListView>
|
||||||
|
|
||||||
<StackPanel Grid.Row="3" Margin="0,12,0,0" Orientation="Horizontal">
|
<StackPanel Grid.Row="3" Margin="0,12,0,0" Orientation="Horizontal">
|
||||||
<ui:Button x:Name="PreviewButton" MinWidth="110" Content="Vorhören" Icon="{ui:SymbolIcon Play24}"
|
<ui:Button x:Name="PreviewButton" MinWidth="110" Content="{l:Tr Import_Preview}" Icon="{ui:SymbolIcon Play24}"
|
||||||
IsEnabled="False" Click="OnPreview" />
|
IsEnabled="False" Click="OnPreview" />
|
||||||
<ui:Button x:Name="ImportButton" ToolTipService.ShowOnDisabled="True" Margin="8,0,0,0" Appearance="Primary"
|
<ui:Button x:Name="ImportButton" ToolTipService.ShowOnDisabled="True" Margin="8,0,0,0" Appearance="Primary"
|
||||||
Content="In Bibliothek importieren" Icon="{ui:SymbolIcon ArrowDownload24}"
|
Content="{l:Tr Import_ImportButton}" Icon="{ui:SymbolIcon ArrowDownload24}"
|
||||||
IsEnabled="False" Click="OnImport" />
|
IsEnabled="False" Click="OnImport" />
|
||||||
<ui:ProgressRing x:Name="Busy"
|
<ui:ProgressRing x:Name="Busy"
|
||||||
Width="20"
|
Width="20"
|
||||||
@@ -167,20 +172,20 @@
|
|||||||
<RowDefinition Height="Auto" />
|
<RowDefinition Height="Auto" />
|
||||||
<RowDefinition Height="Auto" />
|
<RowDefinition Height="Auto" />
|
||||||
</Grid.RowDefinitions>
|
</Grid.RowDefinitions>
|
||||||
<ui:TextBlock VerticalAlignment="Center" FontTypography="BodyStrong" Text="Importiert" />
|
<ui:TextBlock VerticalAlignment="Center" FontTypography="BodyStrong" Text="{l:Tr Import_SessionTitle}" />
|
||||||
<ui:Button HorizontalAlignment="Right"
|
<ui:Button HorizontalAlignment="Right"
|
||||||
Appearance="Transparent"
|
Appearance="Transparent"
|
||||||
Content="Bibliothek öffnen"
|
Content="{l:Tr Import_OpenLibrary}"
|
||||||
Icon="{ui:SymbolIcon MusicNote224}"
|
Icon="{ui:SymbolIcon MusicNote224}"
|
||||||
Click="OnOpenLibrary" />
|
Click="OnOpenLibrary" />
|
||||||
<ui:ListView x:Name="Session"
|
<ui:ListView x:Name="Session"
|
||||||
Grid.Row="1"
|
Grid.Row="1"
|
||||||
MaxHeight="200"
|
MaxHeight="200"
|
||||||
Margin="0,8,0,0"
|
Margin="0,8,0,0"
|
||||||
AutomationProperties.Name="In dieser Sitzung importierte Songs">
|
AutomationProperties.Name="{l:Tr Import_SessionName}">
|
||||||
<ui:ListView.View>
|
<ui:ListView.View>
|
||||||
<ui:GridView>
|
<ui:GridView>
|
||||||
<ui:GridViewColumn Width="160" Header="Status">
|
<ui:GridViewColumn Width="160" Header="{l:Tr Import_ColStatus}">
|
||||||
<ui:GridViewColumn.CellTemplate>
|
<ui:GridViewColumn.CellTemplate>
|
||||||
<DataTemplate>
|
<DataTemplate>
|
||||||
<StackPanel Orientation="Horizontal">
|
<StackPanel Orientation="Horizontal">
|
||||||
@@ -188,21 +193,21 @@
|
|||||||
Symbol="CheckmarkCircle24"
|
Symbol="CheckmarkCircle24"
|
||||||
Filled="True"
|
Filled="True"
|
||||||
Foreground="{DynamicResource SystemFillColorSuccessBrush}" />
|
Foreground="{DynamicResource SystemFillColorSuccessBrush}" />
|
||||||
<ui:TextBlock x:Name="Label" Margin="6,0,0,0" Text="HinzugefĂĽgt" />
|
<ui:TextBlock x:Name="Label" Margin="6,0,0,0" Text="{l:Tr Import_StatusAdded}" />
|
||||||
</StackPanel>
|
</StackPanel>
|
||||||
<DataTemplate.Triggers>
|
<DataTemplate.Triggers>
|
||||||
<DataTrigger Binding="{Binding Success}" Value="False">
|
<DataTrigger Binding="{Binding Success}" Value="False">
|
||||||
<Setter TargetName="Icon" Property="Symbol" Value="ErrorCircle24" />
|
<Setter TargetName="Icon" Property="Symbol" Value="ErrorCircle24" />
|
||||||
<Setter TargetName="Icon" Property="Foreground" Value="{DynamicResource SystemFillColorCriticalBrush}" />
|
<Setter TargetName="Icon" Property="Foreground" Value="{DynamicResource SystemFillColorCriticalBrush}" />
|
||||||
<Setter TargetName="Label" Property="Text" Value="Fehlgeschlagen" />
|
<Setter TargetName="Label" Property="Text" Value="{l:Tr Import_StatusFailed}" />
|
||||||
</DataTrigger>
|
</DataTrigger>
|
||||||
</DataTemplate.Triggers>
|
</DataTemplate.Triggers>
|
||||||
</DataTemplate>
|
</DataTemplate>
|
||||||
</ui:GridViewColumn.CellTemplate>
|
</ui:GridViewColumn.CellTemplate>
|
||||||
</ui:GridViewColumn>
|
</ui:GridViewColumn>
|
||||||
<ui:GridViewColumn Width="240" Header="Titel" DisplayMemberBinding="{Binding Title}" />
|
<ui:GridViewColumn Width="240" Header="{l:Tr Song_Title}" DisplayMemberBinding="{Binding Title}" />
|
||||||
<ui:GridViewColumn Width="160" Header="Interpret" DisplayMemberBinding="{Binding Artist}" />
|
<ui:GridViewColumn Width="160" Header="{l:Tr Song_Artist}" DisplayMemberBinding="{Binding Artist}" />
|
||||||
<ui:GridViewColumn Width="320" Header="Details" DisplayMemberBinding="{Binding Details}" />
|
<ui:GridViewColumn Width="320" Header="{l:Tr Import_ColDetails}" DisplayMemberBinding="{Binding Details}" />
|
||||||
</ui:GridView>
|
</ui:GridView>
|
||||||
</ui:ListView.View>
|
</ui:ListView.View>
|
||||||
</ui:ListView>
|
</ui:ListView>
|
||||||
|
|||||||
@@ -7,8 +7,10 @@ using Microsoft.Win32;
|
|||||||
using NAudio.Wave;
|
using NAudio.Wave;
|
||||||
using Radiosender.Controllers;
|
using Radiosender.Controllers;
|
||||||
using Radiosender.Models;
|
using Radiosender.Models;
|
||||||
|
using Radiosender.Services.Localization;
|
||||||
using Radiosender.Services.Providers;
|
using Radiosender.Services.Providers;
|
||||||
using Wpf.Ui.Controls;
|
using Wpf.Ui.Controls;
|
||||||
|
using MenuItem = System.Windows.Controls.MenuItem;
|
||||||
|
|
||||||
namespace Radiosender.Views.Pages;
|
namespace Radiosender.Views.Pages;
|
||||||
|
|
||||||
@@ -18,6 +20,7 @@ public partial class ImportPage : Page
|
|||||||
private readonly UploadController _upload;
|
private readonly UploadController _upload;
|
||||||
|
|
||||||
private readonly ObservableCollection<SessionRow> _session = [];
|
private readonly ObservableCollection<SessionRow> _session = [];
|
||||||
|
private readonly ObservableCollection<ResultRow> _results = [];
|
||||||
// Own output: never interrupts broadcast.
|
// Own output: never interrupts broadcast.
|
||||||
private WaveOut? _previewOutput;
|
private WaveOut? _previewOutput;
|
||||||
private MediaFoundationReader? _previewReader;
|
private MediaFoundationReader? _previewReader;
|
||||||
@@ -31,13 +34,15 @@ public partial class ImportPage : Page
|
|||||||
_online = online;
|
_online = online;
|
||||||
_upload = upload;
|
_upload = upload;
|
||||||
InitializeComponent();
|
InitializeComponent();
|
||||||
var providers = _online.Providers;
|
OnlineTab.Visibility = _online.Providers.Count > 0 ? Visibility.Visible : Visibility.Collapsed;
|
||||||
ProviderBox.ItemsSource = providers;
|
Results.ItemsSource = _results;
|
||||||
ProviderBox.SelectedIndex = providers.Count > 0 ? 0 : -1;
|
foreach (var license in LicenseType.All)
|
||||||
ProviderBox.Visibility = providers.Count > 1 ? Visibility.Visible : Visibility.Collapsed;
|
{
|
||||||
OnlineTab.Visibility = providers.Count > 0 ? Visibility.Visible : Visibility.Collapsed;
|
var item = new MenuItem { Header = license.Label, Tag = license.Code, IsCheckable = true, IsChecked = true, StaysOpenOnClick = true };
|
||||||
if (providers.Count == 1)
|
item.Click += (_, _) => ShowLicenseCount();
|
||||||
OnlineTab.Header = providers[0].Name;
|
LicenseMenu.Items.Add(item);
|
||||||
|
}
|
||||||
|
ShowLicenseCount();
|
||||||
Session.ItemsSource = _session;
|
Session.ItemsSource = _session;
|
||||||
_session.CollectionChanged += (_, _) =>
|
_session.CollectionChanged += (_, _) =>
|
||||||
{
|
{
|
||||||
@@ -84,7 +89,7 @@ public partial class ImportPage : Page
|
|||||||
{
|
{
|
||||||
var path = paths[i];
|
var path = paths[i];
|
||||||
UploadProgress.Value = i;
|
UploadProgress.Value = i;
|
||||||
UploadProgressText.Text = $"Importiere {i + 1} von {paths.Count}: {Path.GetFileName(path)}";
|
UploadProgressText.Text = Loc.F("Import_Uploading", i + 1, paths.Count, Path.GetFileName(path));
|
||||||
var result = await Task.Run(() => _upload.Upload(path));
|
var result = await Task.Run(() => _upload.Upload(path));
|
||||||
_session.Insert(0, result.Song is { } song
|
_session.Insert(0, result.Song is { } song
|
||||||
? SessionRow.Added(song, Path.GetFileName(path))
|
? SessionRow.Added(song, Path.GetFileName(path))
|
||||||
@@ -101,6 +106,26 @@ public partial class ImportPage : Page
|
|||||||
|
|
||||||
private ResultRow? Selected => Results.SelectedItem as ResultRow;
|
private ResultRow? Selected => Results.SelectedItem as ResultRow;
|
||||||
|
|
||||||
|
private List<MenuItem> LicenseItems => [.. LicenseMenu.Items.OfType<MenuItem>()];
|
||||||
|
|
||||||
|
// null when all are checked: providers then also keep licenses outside LicenseType.All.
|
||||||
|
private IReadOnlySet<string>? CheckedLicenses()
|
||||||
|
{
|
||||||
|
var items = LicenseItems;
|
||||||
|
return items.All(item => item.IsChecked)
|
||||||
|
? null
|
||||||
|
: items.Where(item => item.IsChecked).Select(item => (string)item.Tag).ToHashSet();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ShowLicenseCount()
|
||||||
|
{
|
||||||
|
var items = LicenseItems;
|
||||||
|
var count = items.Count(item => item.IsChecked);
|
||||||
|
LicenseButton.Content = count == items.Count ? Loc.T("Import_AllLicenses")
|
||||||
|
: count == 1 ? items.First(item => item.IsChecked).Header
|
||||||
|
: Loc.F("Import_LicenseCount", count);
|
||||||
|
}
|
||||||
|
|
||||||
private void OnQueryKeyDown(object sender, KeyEventArgs e)
|
private void OnQueryKeyDown(object sender, KeyEventArgs e)
|
||||||
{
|
{
|
||||||
if (e.Key == Key.Enter)
|
if (e.Key == Key.Enter)
|
||||||
@@ -110,28 +135,48 @@ public partial class ImportPage : Page
|
|||||||
private async void OnSearch(object sender, RoutedEventArgs e)
|
private async void OnSearch(object sender, RoutedEventArgs e)
|
||||||
{
|
{
|
||||||
var query = QueryBox.Text.Trim();
|
var query = QueryBox.Text.Trim();
|
||||||
if (query.Length == 0 || _busy || ProviderBox.SelectedItem is not IMusicProvider provider)
|
if (query.Length == 0 || _busy)
|
||||||
return;
|
return;
|
||||||
|
var licenses = CheckedLicenses();
|
||||||
|
if (licenses is { Count: 0 })
|
||||||
|
{
|
||||||
|
Show(InfoBarSeverity.Warning, Loc.T("Import_NoLicense"), Loc.T("Import_NoLicenseHint"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
SetBusy($"Suche auf {provider.Name} nach \"{query}\"...");
|
var total = _online.Providers.Count;
|
||||||
|
var done = 0;
|
||||||
|
List<string> errors = [];
|
||||||
|
SetBusy(Loc.F("Import_Searching", query));
|
||||||
Message.IsOpen = false;
|
Message.IsOpen = false;
|
||||||
|
_results.Clear();
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var tracks = await provider.SearchAsync(query);
|
|
||||||
var imported = _online.ImportedIds();
|
var imported = _online.ImportedIds();
|
||||||
Results.ItemsSource = tracks.Select(t => ResultRow.For(t, imported)).ToList();
|
await foreach (var result in _online.SearchAllAsync(query, licenses))
|
||||||
GridColumns.Fit(Results);
|
{
|
||||||
if (tracks.Count == 0)
|
foreach (var track in result.Tracks)
|
||||||
Show(InfoBarSeverity.Informational, "Keine Ergebnisse", $"{provider.Name} hat nichts zu \"{query}\" gefunden.");
|
_results.Add(ResultRow.For(track, imported, result.Provider.Name));
|
||||||
}
|
if (result.Error is { } error)
|
||||||
catch (MusicProviderException ex)
|
errors.Add(error.Message);
|
||||||
{
|
GridColumns.Fit(Results);
|
||||||
Show(InfoBarSeverity.Error, "Suche fehlgeschlagen", ex.Message);
|
if (++done < total)
|
||||||
|
SetBusy(Loc.F("Import_SearchingProgress", query, done, total));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
SetBusy(null);
|
SetBusy(null);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (errors.Count > 0)
|
||||||
|
Show(_results.Count > 0 ? InfoBarSeverity.Warning : InfoBarSeverity.Error,
|
||||||
|
Loc.T(errors.Count == total ? "Import_SearchFailed" : "Import_SearchPartial"), string.Join(" ", errors));
|
||||||
|
else if (_results.Count == 0)
|
||||||
|
Show(InfoBarSeverity.Informational, Loc.T("Import_NoResults"),
|
||||||
|
licenses is null
|
||||||
|
? Loc.F("Import_NothingFound", query)
|
||||||
|
: Loc.F("Import_NothingFoundLicenses", query));
|
||||||
}
|
}
|
||||||
|
|
||||||
// NAudio, not WPF MediaPlayer: MediaPlayer cannot open https.
|
// NAudio, not WPF MediaPlayer: MediaPlayer cannot open https.
|
||||||
@@ -162,7 +207,7 @@ public partial class ImportPage : Page
|
|||||||
if (id != _previewId) return;
|
if (id != _previewId) return;
|
||||||
OnStop(this, new RoutedEventArgs());
|
OnStop(this, new RoutedEventArgs());
|
||||||
if (stopped.Exception is { } error)
|
if (stopped.Exception is { } error)
|
||||||
Show(InfoBarSeverity.Error, "Vorhören fehlgeschlagen", error.Message);
|
Show(InfoBarSeverity.Error, Loc.T("Import_PreviewFailed"), error.Message);
|
||||||
});
|
});
|
||||||
_previewOutput.Init(reader);
|
_previewOutput.Init(reader);
|
||||||
_previewOutput.Play();
|
_previewOutput.Play();
|
||||||
@@ -171,14 +216,14 @@ public partial class ImportPage : Page
|
|||||||
{
|
{
|
||||||
if (id != _previewId) return;
|
if (id != _previewId) return;
|
||||||
OnStop(this, new RoutedEventArgs());
|
OnStop(this, new RoutedEventArgs());
|
||||||
Show(InfoBarSeverity.Error, "Vorhören fehlgeschlagen", ex.Message);
|
Show(InfoBarSeverity.Error, Loc.T("Import_PreviewFailed"), ex.Message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void SetPreviewing(bool on)
|
private void SetPreviewing(bool on)
|
||||||
{
|
{
|
||||||
_previewing = on;
|
_previewing = on;
|
||||||
PreviewButton.Content = on ? "Stopp" : "Vorhören";
|
PreviewButton.Content = Loc.T(on ? "Import_Stop" : "Import_Preview");
|
||||||
PreviewButton.Icon = new SymbolIcon(on ? SymbolRegular.Stop24 : SymbolRegular.Play24);
|
PreviewButton.Icon = new SymbolIcon(on ? SymbolRegular.Stop24 : SymbolRegular.Play24);
|
||||||
UpdateButtons();
|
UpdateButtons();
|
||||||
}
|
}
|
||||||
@@ -220,18 +265,18 @@ public partial class ImportPage : Page
|
|||||||
{
|
{
|
||||||
var row = rows[i];
|
var row = rows[i];
|
||||||
SetBusy(rows.Count == 1
|
SetBusy(rows.Count == 1
|
||||||
? $"Lade \"{row.Track.Title}\" herunter..."
|
? Loc.F("Import_Downloading", row.Track.Title)
|
||||||
: $"Lade {i + 1} von {rows.Count} herunter: \"{row.Track.Title}\"...");
|
: Loc.F("Import_DownloadingMany", i + 1, rows.Count, row.Track.Title));
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var song = await _online.ImportAsync(row.Track);
|
var song = await _online.ImportAsync(row.Track);
|
||||||
_session.Insert(0, SessionRow.Added(song, song.License ?? ""));
|
_session.Insert(0, SessionRow.Added(song, song.License ?? ""));
|
||||||
ReplaceRow(row, row with { Status = "In Bibliothek", CanImport = false });
|
ReplaceRow(row, row with { Status = "Import_StatusInLibrary", CanImport = false });
|
||||||
}
|
}
|
||||||
catch (Exception ex) when (ex is MusicProviderException or Microsoft.EntityFrameworkCore.DbUpdateException)
|
catch (Exception ex) when (ex is MusicProviderException or Microsoft.EntityFrameworkCore.DbUpdateException)
|
||||||
{
|
{
|
||||||
// DB error text is technical English; usual cause: song already stored.
|
// DB error text is technical English; usual cause: song already stored.
|
||||||
var reason = ex is MusicProviderException ? ex.Message : "Der Song konnte nicht in der Bibliothek gespeichert werden.";
|
var reason = ex is MusicProviderException ? ex.Message : Loc.T("Import_SaveFailedSong");
|
||||||
_session.Insert(0, SessionRow.Failed(row.Track.Title, reason));
|
_session.Insert(0, SessionRow.Failed(row.Track.Title, reason));
|
||||||
failed++;
|
failed++;
|
||||||
lastError = reason;
|
lastError = reason;
|
||||||
@@ -244,16 +289,15 @@ public partial class ImportPage : Page
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (failed > 0)
|
if (failed > 0)
|
||||||
Show(InfoBarSeverity.Error, "Import fehlgeschlagen", rows.Count == 1
|
Show(InfoBarSeverity.Error, Loc.T("Import_Failed"), rows.Count == 1
|
||||||
? lastError
|
? lastError
|
||||||
: $"{failed} von {rows.Count} Songs konnten nicht importiert werden. Die GrĂĽnde stehen in der Liste \"Importiert\".");
|
: Loc.F("Import_FailedMany", failed, rows.Count));
|
||||||
}
|
}
|
||||||
|
|
||||||
private void ReplaceRow(ResultRow old, ResultRow updated)
|
private void ReplaceRow(ResultRow old, ResultRow updated)
|
||||||
{
|
{
|
||||||
if (Results.ItemsSource is not List<ResultRow> rows || rows.IndexOf(old) is var i && i < 0) return;
|
if (_results.IndexOf(old) is var i and >= 0)
|
||||||
rows[i] = updated;
|
_results[i] = updated;
|
||||||
Results.Items.Refresh();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void OnSelectionChanged(object sender, SelectionChangedEventArgs e) => UpdateButtons();
|
private void OnSelectionChanged(object sender, SelectionChangedEventArgs e) => UpdateButtons();
|
||||||
@@ -272,8 +316,8 @@ public partial class ImportPage : Page
|
|||||||
PreviewButton.IsEnabled = _previewing || Selected is not null;
|
PreviewButton.IsEnabled = _previewing || Selected is not null;
|
||||||
var importable = Importable.Count;
|
var importable = Importable.Count;
|
||||||
ImportButton.IsEnabled = !_busy && importable > 0;
|
ImportButton.IsEnabled = !_busy && importable > 0;
|
||||||
ImportButton.Content = importable > 1 ? $"{importable} in Bibliothek importieren" : "In Bibliothek importieren";
|
ImportButton.Content = importable > 1 ? Loc.F("Import_ImportCount", importable) : Loc.T("Import_ImportButton");
|
||||||
ImportButton.ToolTip = importable == 0 && Selected is { } blocked ? blocked.Status : null;
|
ImportButton.ToolTip = importable == 0 && Selected is { } blocked ? Loc.T(blocked.Status) : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void Show(InfoBarSeverity severity, string title, string message)
|
private void Show(InfoBarSeverity severity, string title, string message)
|
||||||
@@ -287,14 +331,29 @@ public partial class ImportPage : Page
|
|||||||
private void OnOpenLibrary(object sender, RoutedEventArgs e) =>
|
private void OnOpenLibrary(object sender, RoutedEventArgs e) =>
|
||||||
(Window.GetWindow(this) as MainWindow)?.RootNavigation.Navigate(typeof(LibraryPage));
|
(Window.GetWindow(this) as MainWindow)?.RootNavigation.Navigate(typeof(LibraryPage));
|
||||||
|
|
||||||
private void OnUnloaded(object sender, RoutedEventArgs e) => OnStop(sender, e);
|
private void OnLoaded(object sender, RoutedEventArgs e) => Loc.Changed += OnLanguageChanged;
|
||||||
|
|
||||||
private sealed record ResultRow(MusicTrack Track, string Status, bool CanImport)
|
private void OnUnloaded(object sender, RoutedEventArgs e)
|
||||||
{
|
{
|
||||||
public static ResultRow For(MusicTrack track, IReadOnlySet<string> imported) =>
|
Loc.Changed -= OnLanguageChanged;
|
||||||
imported.Contains(track.Id) ? new(track, "In Bibliothek", false)
|
OnStop(sender, e);
|
||||||
: !track.CanImport ? new(track, "Keine Dauer", false)
|
}
|
||||||
: new(track, "", true);
|
|
||||||
|
// Texts set in code and values computed into rows.
|
||||||
|
private void OnLanguageChanged(object? sender, EventArgs e)
|
||||||
|
{
|
||||||
|
ShowLicenseCount();
|
||||||
|
SetPreviewing(_previewing);
|
||||||
|
Results.Items.Refresh();
|
||||||
|
GridColumns.Fit(Results);
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed record ResultRow(MusicTrack Track, string Source, string Status, bool CanImport)
|
||||||
|
{
|
||||||
|
public static ResultRow For(MusicTrack track, IReadOnlySet<string> imported, string source) =>
|
||||||
|
imported.Contains(track.Id) ? new(track, source, "Import_StatusInLibrary", false)
|
||||||
|
: !track.CanImport ? new(track, source, "Import_StatusNoDuration", false)
|
||||||
|
: new(track, source, "", true);
|
||||||
}
|
}
|
||||||
|
|
||||||
private sealed record SessionRow(bool Success, string Title, string Artist, string Details)
|
private sealed record SessionRow(bool Success, string Title, string Artist, string Details)
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
using System.Net;
|
using System.Net;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
|
using Radiosender.Models;
|
||||||
using Radiosender.Services.Providers;
|
using Radiosender.Services.Providers;
|
||||||
|
|
||||||
namespace Radiosender.Tests;
|
namespace Radiosender.Tests;
|
||||||
@@ -30,6 +31,30 @@ public class MusicProviderTests
|
|||||||
private static HttpResponseMessage Json(string json, string contentType = "application/json") =>
|
private static HttpResponseMessage Json(string json, string contentType = "application/json") =>
|
||||||
new(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, contentType) };
|
new(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, contentType) };
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task InternetArchive_KeepsOnlyTheChosenLicenses()
|
||||||
|
{
|
||||||
|
var provider = new InternetArchiveProvider(Http(uri =>
|
||||||
|
Json(uri.AbsolutePath == "/advancedsearch.php" ? ArchiveSearchJson : ArchiveMetadataJson)));
|
||||||
|
|
||||||
|
var publicDomain = await provider.SearchAsync("jazz", new HashSet<string> { "pdm" });
|
||||||
|
var none = await provider.SearchAsync("jazz", new HashSet<string>());
|
||||||
|
|
||||||
|
Assert.Equal(3, publicDomain.Count);
|
||||||
|
Assert.All(publicDomain, track => Assert.Equal("Public Domain Mark 1.0", track.License));
|
||||||
|
Assert.Empty(none);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("CC BY-NC-SA 4.0", "by-nc-sa")]
|
||||||
|
[InlineData("CC BY 3.0", "by")]
|
||||||
|
[InlineData("CC0 1.0", "cc0")]
|
||||||
|
[InlineData("Public Domain Mark 1.0", "pdm")]
|
||||||
|
[InlineData("CC SAMPLING+ 1.0", null)]
|
||||||
|
[InlineData("", null)]
|
||||||
|
public void LicenseType_ReadsTheCodeFromTheLicenseName(string license, string? code) =>
|
||||||
|
Assert.Equal(code, LicenseType.CodeOf(license));
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task InternetArchive_TurnsTheMp3FilesOfEachItemIntoTracks()
|
public async Task InternetArchive_TurnsTheMp3FilesOfEachItemIntoTracks()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -91,6 +91,33 @@ public sealed class OpenverseTests : IDisposable
|
|||||||
Assert.Equal("Openverse", Assert.Single(controller.Providers).Name);
|
Assert.Equal("Openverse", Assert.Single(controller.Providers).Name);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Controller_SearchesAllProvidersInParallelAndYieldsEachWhenDone()
|
||||||
|
{
|
||||||
|
var slowGate = new TaskCompletionSource<IReadOnlyList<MusicTrack>>();
|
||||||
|
var slow = new FakeProvider("Slow", (_, _) => slowGate.Task);
|
||||||
|
var failing = new FakeProvider("Failing", (_, _) => throw new MusicProviderException("kaputt"));
|
||||||
|
IReadOnlySet<string>? seenLicenses = null;
|
||||||
|
var fast = new FakeProvider("Fast", (_, licenses) => { seenLicenses = licenses; return Task.FromResult<IReadOnlyList<MusicTrack>>([Track()]); });
|
||||||
|
var controller = new OnlineImportController([slow, failing, fast], NewClient((_, _) => Respond(HttpStatusCode.OK)), new SongRepository(Path.Combine(_directory, "test.db")));
|
||||||
|
var licenses = new HashSet<string> { "by" };
|
||||||
|
|
||||||
|
List<ProviderResult> results = [];
|
||||||
|
await foreach (var result in controller.SearchAllAsync("jazz", licenses))
|
||||||
|
{
|
||||||
|
results.Add(result);
|
||||||
|
if (results.Count == 2)
|
||||||
|
slowGate.SetResult([Track() with { Id = "slow" }]); // slow only finishes after the others were yielded
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.Equal(["Failing", "Fast", "Slow"], results.Select(r => r.Provider.Name).Order());
|
||||||
|
Assert.Equal("Slow", results[2].Provider.Name);
|
||||||
|
Assert.Equal("kaputt", Assert.Single(results, r => r.Error is not null).Error!.Message);
|
||||||
|
Assert.Empty(results.Single(r => r.Provider == failing).Tracks);
|
||||||
|
Assert.Single(results.Single(r => r.Provider == fast).Tracks);
|
||||||
|
Assert.Same(licenses, seenLicenses);
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task Search_ParsesResults()
|
public async Task Search_ParsesResults()
|
||||||
{
|
{
|
||||||
@@ -119,6 +146,23 @@ public sealed class OpenverseTests : IDisposable
|
|||||||
Assert.Equal("CC0 1.0", tracks[1].License);
|
Assert.Equal("CC0 1.0", tracks[1].License);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Search_SendsTheChosenLicenses()
|
||||||
|
{
|
||||||
|
var requested = new List<Uri>();
|
||||||
|
var client = NewProvider((request, _) =>
|
||||||
|
{
|
||||||
|
requested.Add(request.RequestUri!);
|
||||||
|
return Respond(HttpStatusCode.OK, new StringContent(SearchJson, Encoding.UTF8, "application/json"));
|
||||||
|
});
|
||||||
|
|
||||||
|
await client.SearchAsync("jazz", new HashSet<string> { "cc0", "by" });
|
||||||
|
var none = await client.SearchAsync("jazz", new HashSet<string>());
|
||||||
|
|
||||||
|
Assert.Equal("https://api.openverse.org/v1/audio/?q=jazz&page_size=20&license=by%2Ccc0", Assert.Single(requested).AbsoluteUri);
|
||||||
|
Assert.Empty(none);
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task Search_RateLimited_ThrowsReadableError()
|
public async Task Search_RateLimited_ThrowsReadableError()
|
||||||
{
|
{
|
||||||
@@ -229,6 +273,14 @@ public sealed class OpenverseTests : IDisposable
|
|||||||
Assert.Empty(songs.GetAll());
|
Assert.Empty(songs.GetAll());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private sealed class FakeProvider(string name, Func<string, IReadOnlySet<string>?, Task<IReadOnlyList<MusicTrack>>> search) : IMusicProvider
|
||||||
|
{
|
||||||
|
public string Name => name;
|
||||||
|
|
||||||
|
public Task<IReadOnlyList<MusicTrack>> SearchAsync(string query, IReadOnlySet<string>? licenses = null, CancellationToken cancellationToken = default) =>
|
||||||
|
search(query, licenses);
|
||||||
|
}
|
||||||
|
|
||||||
private sealed class FakeHandler(Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> handle) : HttpMessageHandler
|
private sealed class FakeHandler(Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> handle) : HttpMessageHandler
|
||||||
{
|
{
|
||||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) =>
|
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) =>
|
||||||
|
|||||||
Reference in new issue
Block a user