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.Runtime.CompilerServices;
|
||||
using Radiosender.Models;
|
||||
using Radiosender.Services.Library;
|
||||
using Radiosender.Services.Localization;
|
||||
using Radiosender.Services.Providers;
|
||||
|
||||
namespace Radiosender.Controllers;
|
||||
|
||||
public class OnlineImportController(IEnumerable<IMusicProvider> providers, TrackDownloader downloader, SongRepository songs)
|
||||
{
|
||||
private readonly IReadOnlyList<IMusicProvider> _providers = [.. providers];
|
||||
|
||||
public IReadOnlyList<IMusicProvider> Providers => [.. _providers.Where(provider => provider.IsAvailable)];
|
||||
public IReadOnlyList<IMusicProvider> Providers { get; } = [.. providers];
|
||||
|
||||
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>
|
||||
public async Task<Song> ImportAsync(MusicTrack track, CancellationToken cancellationToken = default)
|
||||
{
|
||||
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))
|
||||
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 song = new Song
|
||||
|
||||
@@ -7,8 +7,7 @@ public interface IMusicProvider
|
||||
{
|
||||
string Name { get; }
|
||||
|
||||
bool IsAvailable => true;
|
||||
|
||||
// licenses: LicenseType codes to keep; null = all.
|
||||
/// <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.RegularExpressions;
|
||||
using Radiosender.Models;
|
||||
using Radiosender.Services.Localization;
|
||||
|
||||
namespace Radiosender.Services.Providers;
|
||||
|
||||
@@ -18,8 +19,10 @@ public partial class InternetArchiveProvider(HttpClient http) : IMusicProvider
|
||||
|
||||
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.
|
||||
var words = string.Join(' ', LuceneSyntax().Replace(query, " ").Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries));
|
||||
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);
|
||||
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.");
|
||||
throw new MusicProviderException(Loc.F("Provider_SearchUnexpected", Name));
|
||||
|
||||
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)
|
||||
|
||||
@@ -3,6 +3,7 @@ using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using Radiosender.Models;
|
||||
using Radiosender.Services.Localization;
|
||||
|
||||
namespace Radiosender.Services.Providers;
|
||||
|
||||
@@ -15,16 +16,21 @@ public class OpenverseProvider(HttpClient http) : IMusicProvider
|
||||
|
||||
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}";
|
||||
// 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
|
||||
{
|
||||
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.");
|
||||
throw new MusicProviderException(Loc.F("Provider_RateLimit", Name));
|
||||
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);
|
||||
return page?.Results?.Select(result => result.ToMusicTrack()).ToList() ?? [];
|
||||
}
|
||||
@@ -32,9 +38,9 @@ public class OpenverseProvider(HttpClient http) : IMusicProvider
|
||||
{
|
||||
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),
|
||||
OperationCanceledException => new MusicProviderException(Loc.F("Provider_SearchTimeout", Name), e),
|
||||
JsonException => new MusicProviderException(Loc.F("Provider_SearchUnexpected", Name), e),
|
||||
_ => new MusicProviderException(Loc.F("Provider_SearchError", Name, e.Message), e),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,24 +3,20 @@ using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using Radiosender.Services.Localization;
|
||||
|
||||
namespace Radiosender.Services.Providers;
|
||||
|
||||
internal static partial class ProviderParsing
|
||||
{
|
||||
/// <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
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, url);
|
||||
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.");
|
||||
using var response = await http.GetAsync(url, cancellationToken);
|
||||
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.
|
||||
return JsonDocument.Parse(await response.Content.ReadAsStringAsync(cancellationToken));
|
||||
}
|
||||
@@ -28,9 +24,9 @@ internal static partial class ProviderParsing
|
||||
{
|
||||
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),
|
||||
OperationCanceledException => new MusicProviderException(Loc.F("Provider_SearchTimeout", provider), e),
|
||||
JsonException => new MusicProviderException(Loc.F("Provider_SearchUnexpected", provider), 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:x="http://schemas.microsoft.com/winfx/2006/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}"
|
||||
ScrollViewer.CanContentScroll="False"
|
||||
Loaded="OnLoaded"
|
||||
Unloaded="OnUnloaded">
|
||||
<Grid Margin="24">
|
||||
<Grid.RowDefinitions>
|
||||
@@ -39,7 +41,7 @@
|
||||
</Style>
|
||||
</TabControl.Resources>
|
||||
<!-- From computer -->
|
||||
<TabItem Header="Vom Computer">
|
||||
<TabItem Header="{l:Tr Import_TabComputer}">
|
||||
<Grid Margin="0,12,0,0">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="*" />
|
||||
@@ -49,7 +51,7 @@
|
||||
<Grid x:Name="DropZone"
|
||||
Background="Transparent"
|
||||
AllowDrop="True"
|
||||
AutomationProperties.Name="Ablagebereich fĂĽr MP3- und WAV-Dateien"
|
||||
AutomationProperties.Name="{l:Tr Import_DropZoneName}"
|
||||
DragEnter="OnDragOver"
|
||||
DragOver="OnDragOver"
|
||||
DragLeave="OnDragLeave"
|
||||
@@ -65,11 +67,11 @@
|
||||
<ui:TextBlock Margin="0,8,0,12"
|
||||
HorizontalAlignment="Center"
|
||||
FontTypography="BodyStrong"
|
||||
Text="MP3- oder WAV-Dateien hier ablegen" />
|
||||
Text="{l:Tr Import_DropHint}" />
|
||||
<ui:Button x:Name="ChooseFilesButton"
|
||||
HorizontalAlignment="Center"
|
||||
Appearance="Primary"
|
||||
Content="Dateien auswählen..."
|
||||
Content="{l:Tr Import_ChooseFiles}"
|
||||
Icon="{ui:SymbolIcon FolderOpen24}"
|
||||
Click="OnChooseFiles" />
|
||||
</StackPanel>
|
||||
@@ -79,13 +81,13 @@
|
||||
<ui:TextBlock x:Name="UploadProgressText" />
|
||||
<ProgressBar x:Name="UploadProgress"
|
||||
Margin="0,6,0,0"
|
||||
AutomationProperties.Name="Import-Fortschritt" />
|
||||
AutomationProperties.Name="{l:Tr Import_ProgressName}" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</TabItem>
|
||||
|
||||
<!-- Online providers; the header is the provider name when there is only one -->
|
||||
<TabItem x:Name="OnlineTab" Header="Online">
|
||||
<!-- Searches all providers in parallel -->
|
||||
<TabItem x:Name="OnlineTab" Header="{l:Tr Import_TabOnline}">
|
||||
<Grid Margin="0,12,0,0">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
@@ -100,23 +102,25 @@
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<!-- Only shown when more than one provider is registered -->
|
||||
<ComboBox x:Name="ProviderBox"
|
||||
MinWidth="140"
|
||||
Margin="0,0,8,0"
|
||||
AutomationProperties.Name="Musikquelle"
|
||||
DisplayMemberPath="Name"
|
||||
Visibility="Collapsed" />
|
||||
<!-- Multiselect: checkable items filled from LicenseType.All in code -->
|
||||
<ui:DropDownButton x:Name="LicenseButton"
|
||||
MinWidth="150"
|
||||
Margin="0,0,8,0"
|
||||
AutomationProperties.Name="{l:Tr Import_LicensesName}">
|
||||
<ui:DropDownButton.Flyout>
|
||||
<ContextMenu x:Name="LicenseMenu" />
|
||||
</ui:DropDownButton.Flyout>
|
||||
</ui:DropDownButton>
|
||||
<ui:TextBox x:Name="QueryBox"
|
||||
Grid.Column="1"
|
||||
PlaceholderText="Freie Musik suchen, zum Beispiel "jazz piano""
|
||||
AutomationProperties.Name="Suchbegriff"
|
||||
PlaceholderText="{l:Tr Import_SearchPlaceholder}"
|
||||
AutomationProperties.Name="{l:Tr Import_QueryName}"
|
||||
KeyDown="OnQueryKeyDown" />
|
||||
<ui:Button x:Name="SearchButton"
|
||||
Grid.Column="2"
|
||||
Margin="8,0,0,0"
|
||||
Appearance="Primary"
|
||||
Content="Suchen"
|
||||
Content="{l:Tr Import_Search}"
|
||||
Icon="{ui:SymbolIcon Search24}"
|
||||
Click="OnSearch" />
|
||||
</Grid>
|
||||
@@ -127,24 +131,25 @@
|
||||
Grid.Row="2"
|
||||
Margin="0,12,0,0"
|
||||
SelectionMode="Extended"
|
||||
AutomationProperties.Name="Suchergebnisse"
|
||||
AutomationProperties.Name="{l:Tr Import_ResultsName}"
|
||||
SelectionChanged="OnSelectionChanged"
|
||||
MouseDoubleClick="OnResultDoubleClick">
|
||||
<ui:ListView.View>
|
||||
<ui:GridView>
|
||||
<ui:GridViewColumn Width="300" Header="Titel" DisplayMemberBinding="{Binding Track.Title}" />
|
||||
<ui:GridViewColumn Width="180" Header="Urheber" DisplayMemberBinding="{Binding Track.Creator}" />
|
||||
<ui:GridViewColumn Width="80" Header="Dauer" DisplayMemberBinding="{Binding Track.DurationText}" />
|
||||
<ui:GridViewColumn Width="130" Header="Lizenz" DisplayMemberBinding="{Binding Track.License}" />
|
||||
<ui:GridViewColumn Width="300" Header="{l:Tr Song_Title}" DisplayMemberBinding="{Binding Track.Title}" />
|
||||
<ui:GridViewColumn Width="180" Header="{l:Tr Import_ColCreator}" DisplayMemberBinding="{Binding Track.Creator}" />
|
||||
<ui:GridViewColumn Width="80" Header="{l:Tr Song_Duration}" DisplayMemberBinding="{Binding Track.DurationText}" />
|
||||
<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:ListView.View>
|
||||
</ui:ListView>
|
||||
|
||||
<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" />
|
||||
<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" />
|
||||
<ui:ProgressRing x:Name="Busy"
|
||||
Width="20"
|
||||
@@ -167,20 +172,20 @@
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</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"
|
||||
Appearance="Transparent"
|
||||
Content="Bibliothek öffnen"
|
||||
Content="{l:Tr Import_OpenLibrary}"
|
||||
Icon="{ui:SymbolIcon MusicNote224}"
|
||||
Click="OnOpenLibrary" />
|
||||
<ui:ListView x:Name="Session"
|
||||
Grid.Row="1"
|
||||
MaxHeight="200"
|
||||
Margin="0,8,0,0"
|
||||
AutomationProperties.Name="In dieser Sitzung importierte Songs">
|
||||
AutomationProperties.Name="{l:Tr Import_SessionName}">
|
||||
<ui:ListView.View>
|
||||
<ui:GridView>
|
||||
<ui:GridViewColumn Width="160" Header="Status">
|
||||
<ui:GridViewColumn Width="160" Header="{l:Tr Import_ColStatus}">
|
||||
<ui:GridViewColumn.CellTemplate>
|
||||
<DataTemplate>
|
||||
<StackPanel Orientation="Horizontal">
|
||||
@@ -188,21 +193,21 @@
|
||||
Symbol="CheckmarkCircle24"
|
||||
Filled="True"
|
||||
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>
|
||||
<DataTemplate.Triggers>
|
||||
<DataTrigger Binding="{Binding Success}" Value="False">
|
||||
<Setter TargetName="Icon" Property="Symbol" Value="ErrorCircle24" />
|
||||
<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>
|
||||
</DataTemplate.Triggers>
|
||||
</DataTemplate>
|
||||
</ui:GridViewColumn.CellTemplate>
|
||||
</ui:GridViewColumn>
|
||||
<ui:GridViewColumn Width="240" Header="Titel" DisplayMemberBinding="{Binding Title}" />
|
||||
<ui:GridViewColumn Width="160" Header="Interpret" DisplayMemberBinding="{Binding Artist}" />
|
||||
<ui:GridViewColumn Width="320" Header="Details" DisplayMemberBinding="{Binding Details}" />
|
||||
<ui:GridViewColumn Width="240" Header="{l:Tr Song_Title}" DisplayMemberBinding="{Binding Title}" />
|
||||
<ui:GridViewColumn Width="160" Header="{l:Tr Song_Artist}" DisplayMemberBinding="{Binding Artist}" />
|
||||
<ui:GridViewColumn Width="320" Header="{l:Tr Import_ColDetails}" DisplayMemberBinding="{Binding Details}" />
|
||||
</ui:GridView>
|
||||
</ui:ListView.View>
|
||||
</ui:ListView>
|
||||
|
||||
@@ -7,8 +7,10 @@ using Microsoft.Win32;
|
||||
using NAudio.Wave;
|
||||
using Radiosender.Controllers;
|
||||
using Radiosender.Models;
|
||||
using Radiosender.Services.Localization;
|
||||
using Radiosender.Services.Providers;
|
||||
using Wpf.Ui.Controls;
|
||||
using MenuItem = System.Windows.Controls.MenuItem;
|
||||
|
||||
namespace Radiosender.Views.Pages;
|
||||
|
||||
@@ -18,6 +20,7 @@ public partial class ImportPage : Page
|
||||
private readonly UploadController _upload;
|
||||
|
||||
private readonly ObservableCollection<SessionRow> _session = [];
|
||||
private readonly ObservableCollection<ResultRow> _results = [];
|
||||
// Own output: never interrupts broadcast.
|
||||
private WaveOut? _previewOutput;
|
||||
private MediaFoundationReader? _previewReader;
|
||||
@@ -31,13 +34,15 @@ public partial class ImportPage : Page
|
||||
_online = online;
|
||||
_upload = upload;
|
||||
InitializeComponent();
|
||||
var providers = _online.Providers;
|
||||
ProviderBox.ItemsSource = providers;
|
||||
ProviderBox.SelectedIndex = providers.Count > 0 ? 0 : -1;
|
||||
ProviderBox.Visibility = providers.Count > 1 ? Visibility.Visible : Visibility.Collapsed;
|
||||
OnlineTab.Visibility = providers.Count > 0 ? Visibility.Visible : Visibility.Collapsed;
|
||||
if (providers.Count == 1)
|
||||
OnlineTab.Header = providers[0].Name;
|
||||
OnlineTab.Visibility = _online.Providers.Count > 0 ? Visibility.Visible : Visibility.Collapsed;
|
||||
Results.ItemsSource = _results;
|
||||
foreach (var license in LicenseType.All)
|
||||
{
|
||||
var item = new MenuItem { Header = license.Label, Tag = license.Code, IsCheckable = true, IsChecked = true, StaysOpenOnClick = true };
|
||||
item.Click += (_, _) => ShowLicenseCount();
|
||||
LicenseMenu.Items.Add(item);
|
||||
}
|
||||
ShowLicenseCount();
|
||||
Session.ItemsSource = _session;
|
||||
_session.CollectionChanged += (_, _) =>
|
||||
{
|
||||
@@ -84,7 +89,7 @@ public partial class ImportPage : Page
|
||||
{
|
||||
var path = paths[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));
|
||||
_session.Insert(0, result.Song is { } song
|
||||
? SessionRow.Added(song, Path.GetFileName(path))
|
||||
@@ -101,6 +106,26 @@ public partial class ImportPage : Page
|
||||
|
||||
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)
|
||||
{
|
||||
if (e.Key == Key.Enter)
|
||||
@@ -110,28 +135,48 @@ public partial class ImportPage : Page
|
||||
private async void OnSearch(object sender, RoutedEventArgs e)
|
||||
{
|
||||
var query = QueryBox.Text.Trim();
|
||||
if (query.Length == 0 || _busy || ProviderBox.SelectedItem is not IMusicProvider provider)
|
||||
if (query.Length == 0 || _busy)
|
||||
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;
|
||||
_results.Clear();
|
||||
try
|
||||
{
|
||||
var tracks = await provider.SearchAsync(query);
|
||||
var imported = _online.ImportedIds();
|
||||
Results.ItemsSource = tracks.Select(t => ResultRow.For(t, imported)).ToList();
|
||||
GridColumns.Fit(Results);
|
||||
if (tracks.Count == 0)
|
||||
Show(InfoBarSeverity.Informational, "Keine Ergebnisse", $"{provider.Name} hat nichts zu \"{query}\" gefunden.");
|
||||
}
|
||||
catch (MusicProviderException ex)
|
||||
{
|
||||
Show(InfoBarSeverity.Error, "Suche fehlgeschlagen", ex.Message);
|
||||
await foreach (var result in _online.SearchAllAsync(query, licenses))
|
||||
{
|
||||
foreach (var track in result.Tracks)
|
||||
_results.Add(ResultRow.For(track, imported, result.Provider.Name));
|
||||
if (result.Error is { } error)
|
||||
errors.Add(error.Message);
|
||||
GridColumns.Fit(Results);
|
||||
if (++done < total)
|
||||
SetBusy(Loc.F("Import_SearchingProgress", query, done, total));
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
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.
|
||||
@@ -162,7 +207,7 @@ public partial class ImportPage : Page
|
||||
if (id != _previewId) return;
|
||||
OnStop(this, new RoutedEventArgs());
|
||||
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.Play();
|
||||
@@ -171,14 +216,14 @@ public partial class ImportPage : Page
|
||||
{
|
||||
if (id != _previewId) return;
|
||||
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)
|
||||
{
|
||||
_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);
|
||||
UpdateButtons();
|
||||
}
|
||||
@@ -220,18 +265,18 @@ public partial class ImportPage : Page
|
||||
{
|
||||
var row = rows[i];
|
||||
SetBusy(rows.Count == 1
|
||||
? $"Lade \"{row.Track.Title}\" herunter..."
|
||||
: $"Lade {i + 1} von {rows.Count} herunter: \"{row.Track.Title}\"...");
|
||||
? Loc.F("Import_Downloading", row.Track.Title)
|
||||
: Loc.F("Import_DownloadingMany", i + 1, rows.Count, row.Track.Title));
|
||||
try
|
||||
{
|
||||
var song = await _online.ImportAsync(row.Track);
|
||||
_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)
|
||||
{
|
||||
// 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));
|
||||
failed++;
|
||||
lastError = reason;
|
||||
@@ -244,16 +289,15 @@ public partial class ImportPage : Page
|
||||
}
|
||||
|
||||
if (failed > 0)
|
||||
Show(InfoBarSeverity.Error, "Import fehlgeschlagen", rows.Count == 1
|
||||
Show(InfoBarSeverity.Error, Loc.T("Import_Failed"), rows.Count == 1
|
||||
? 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)
|
||||
{
|
||||
if (Results.ItemsSource is not List<ResultRow> rows || rows.IndexOf(old) is var i && i < 0) return;
|
||||
rows[i] = updated;
|
||||
Results.Items.Refresh();
|
||||
if (_results.IndexOf(old) is var i and >= 0)
|
||||
_results[i] = updated;
|
||||
}
|
||||
|
||||
private void OnSelectionChanged(object sender, SelectionChangedEventArgs e) => UpdateButtons();
|
||||
@@ -272,8 +316,8 @@ public partial class ImportPage : Page
|
||||
PreviewButton.IsEnabled = _previewing || Selected is not null;
|
||||
var importable = Importable.Count;
|
||||
ImportButton.IsEnabled = !_busy && importable > 0;
|
||||
ImportButton.Content = importable > 1 ? $"{importable} in Bibliothek importieren" : "In Bibliothek importieren";
|
||||
ImportButton.ToolTip = importable == 0 && Selected is { } blocked ? blocked.Status : null;
|
||||
ImportButton.Content = importable > 1 ? Loc.F("Import_ImportCount", importable) : Loc.T("Import_ImportButton");
|
||||
ImportButton.ToolTip = importable == 0 && Selected is { } blocked ? Loc.T(blocked.Status) : null;
|
||||
}
|
||||
|
||||
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) =>
|
||||
(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) =>
|
||||
imported.Contains(track.Id) ? new(track, "In Bibliothek", false)
|
||||
: !track.CanImport ? new(track, "Keine Dauer", false)
|
||||
: new(track, "", true);
|
||||
Loc.Changed -= OnLanguageChanged;
|
||||
OnStop(sender, e);
|
||||
}
|
||||
|
||||
// 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)
|
||||
|
||||
Reference in new issue
Block a user