feat: combine upload and Openverse into one import page

Adding music took two navigation items that each did half the job.
The new Import page has both sources as tabs and one shared list of
what was added in this session, with the reason for every failure and
a link to the library.

From computer: drop several MP3 or WAV files or pick them with a
multi-select dialog. Files are imported one by one on a background
thread with a progress bar, and a failing file does not stop the rest.

Openverse: search and download show a progress ring with a status
text. Results that are already in the library or have no duration are
marked in their row and cannot be imported; a double-click imports.

To detect duplicates, songs now store the Openverse result id. The
repository adds the column to existing databases and a unique index
keeps one song per Openverse result.

Refs #13

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
fraujulianandClaude Opus 5.5 committed 2026-11-23 11:34:35 +01:00
1 parent a762a2f571
commit 0a0d8e1d4c
17 files changed
+582 -266

No files matched your search

@@ -9,11 +9,16 @@ public class OpenverseController(OpenverseClient client, SongRepository songs)
public Task<IReadOnlyList<OpenverseTrack>> SearchAsync(string query, CancellationToken cancellationToken = default) =>
client.SearchAsync(query, cancellationToken);
/// <summary>Ids of the Openverse results that are already in the library.</summary>
public IReadOnlySet<string> ImportedIds() => songs.GetOpenverseIds();
/// <summary>Downloads the track and stores it as a song with its license and attribution.</summary>
public async Task<Song> ImportAsync(OpenverseTrack track, CancellationToken cancellationToken = default)
{
if (track.Duration is not { } duration)
throw new OpenverseException("This result has no duration and cannot be imported.");
if (track.Id.Length > 0 && ImportedIds().Contains(track.Id))
throw new OpenverseException($"\"{track.Title}\" is already in the library.");
var path = await client.DownloadAsync(track, cancellationToken);
var song = new Song
@@ -25,6 +30,7 @@ public class OpenverseController(OpenverseClient client, SongRepository songs)
Source = SongSource.Openverse,
License = track.LicenseName,
Attribution = track.Attribution,
OpenverseId = track.Id.Length > 0 ? track.Id : null,
};
try
{
@@ -1,19 +1,22 @@
using Radiosender.Models;
using Radiosender.Services;
namespace Radiosender.Controllers;
public record UploadResult(bool Success, string Message);
/// <param name="Song">The saved song, or <c>null</c> when the upload failed.</param>
public record UploadResult(bool Success, string Message, Song? Song = null);
public class UploadController(SongImportService importService)
{
public static string FileDialogFilter { get; } = "Audio files (*.mp3;*.wav)|*.mp3;*.wav";
/// <summary>Imports one file; failures come back as a result, so a batch can go on with the next file.</summary>
public UploadResult Upload(string filePath)
{
try
{
var song = importService.Import(filePath);
return new UploadResult(true, $"\"{song.Title}\" ({(int)song.Duration.TotalMinutes}:{song.Duration.Seconds:00}) was added to the library.");
return new UploadResult(true, $"\"{song.Title}\" ({(int)song.Duration.TotalMinutes}:{song.Duration.Seconds:00}) was added to the library.", song);
}
catch (SongImportException e)
{
+1
View File
@@ -5,6 +5,7 @@ namespace Radiosender.Models;
/// <summary>One audio result of the Openverse search API (fields as documented at api.openverse.org/v1).</summary>
public class OpenverseTrack
{
public string Id { get; init; } = "";
public string Title { get; init; } = "";
public string? Creator { get; init; }
public string Url { get; init; } = "";
+3
View File
@@ -16,4 +16,7 @@ public class Song
public SongSource Source { get; set; }
public string? License { get; set; }
public string? Attribution { get; set; }
/// <summary>Id of the Openverse result the song was imported from, so it is not imported twice.</summary>
public string? OpenverseId { get; set; }
}
+32 -4
View File
@@ -9,7 +9,7 @@ public class SongRepository
public static string DefaultDatabasePath { get; } = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Radiosender", "radiosender.db");
private const string Columns = "Id, Title, Artist, DurationMs, FilePath, Source, License, Attribution";
private const string Columns = "Id, Title, Artist, DurationMs, FilePath, Source, License, Attribution, OpenverseId";
private readonly string _connectionString;
@@ -29,10 +29,36 @@ public class SongRepository
FilePath TEXT NOT NULL,
Source INTEGER NOT NULL,
License TEXT,
Attribution TEXT
Attribution TEXT,
OpenverseId TEXT
)
""";
command.ExecuteNonQuery();
// Databases from before the Openverse id get the column added.
command.CommandText = "SELECT COUNT(*) FROM pragma_table_info('Songs') WHERE name = 'OpenverseId'";
if ((long)command.ExecuteScalar()! == 0)
{
command.CommandText = "ALTER TABLE Songs ADD COLUMN OpenverseId TEXT";
command.ExecuteNonQuery();
}
// One song per Openverse result, also if two imports of the same track race.
command.CommandText = "CREATE UNIQUE INDEX IF NOT EXISTS IX_Songs_OpenverseId ON Songs (OpenverseId) WHERE OpenverseId IS NOT NULL";
command.ExecuteNonQuery();
}
/// <summary>Ids of all Openverse results that are already in the library.</summary>
public IReadOnlySet<string> GetOpenverseIds()
{
using var connection = Open();
using var command = connection.CreateCommand();
command.CommandText = "SELECT OpenverseId FROM Songs WHERE OpenverseId IS NOT NULL";
using var reader = command.ExecuteReader();
var ids = new HashSet<string>();
while (reader.Read())
ids.Add(reader.GetString(0));
return ids;
}
public IReadOnlyList<Song> GetAll()
@@ -63,8 +89,8 @@ public class SongRepository
using var connection = Open();
using var command = connection.CreateCommand();
command.CommandText = """
INSERT INTO Songs (Title, Artist, DurationMs, FilePath, Source, License, Attribution)
VALUES ($title, $artist, $durationMs, $filePath, $source, $license, $attribution);
INSERT INTO Songs (Title, Artist, DurationMs, FilePath, Source, License, Attribution, OpenverseId)
VALUES ($title, $artist, $durationMs, $filePath, $source, $license, $attribution, $openverseId);
SELECT last_insert_rowid();
""";
AddParameters(command, song);
@@ -112,6 +138,7 @@ public class SongRepository
command.Parameters.AddWithValue("$source", (int)song.Source);
command.Parameters.AddWithValue("$license", (object?)song.License ?? DBNull.Value);
command.Parameters.AddWithValue("$attribution", (object?)song.Attribution ?? DBNull.Value);
command.Parameters.AddWithValue("$openverseId", (object?)song.OpenverseId ?? DBNull.Value);
}
private static Song Read(SqliteDataReader reader) => new()
@@ -124,5 +151,6 @@ public class SongRepository
Source = (SongSource)reader.GetInt32(5),
License = reader.IsDBNull(6) ? null : reader.GetString(6),
Attribution = reader.IsDBNull(7) ? null : reader.GetString(7),
OpenverseId = reader.IsDBNull(8) ? null : reader.GetString(8),
};
}
+3 -6
View File
@@ -28,12 +28,9 @@
<ui:NavigationViewItem Content="Library"
Icon="{ui:SymbolIcon MusicNote224}"
TargetPageType="{x:Type pages:LibraryPage}" />
<ui:NavigationViewItem Content="Upload"
Icon="{ui:SymbolIcon ArrowUpload24}"
TargetPageType="{x:Type pages:UploadPage}" />
<ui:NavigationViewItem Content="Openverse"
Icon="{ui:SymbolIcon Search24}"
TargetPageType="{x:Type pages:OpenversePage}" />
<ui:NavigationViewItem Content="Import"
Icon="{ui:SymbolIcon ArrowDownload24}"
TargetPageType="{x:Type pages:ImportPage}" />
</ui:NavigationView.MenuItems>
</ui:NavigationView>
</Grid>
+1 -1
View File
@@ -6,6 +6,6 @@
<StackPanel Margin="24">
<ui:TextBlock FontTypography="Title" Text="Radiosender" />
<ui:TextBlock Margin="0,8,0,0" TextWrapping="Wrap"
Text="Add music under Library, Upload or Openverse, then plan and start a broadcast on the Schedule page." />
Text="Add music on the Import page, then plan and start a broadcast on the Schedule page." />
</StackPanel>
</Page>
+198
View File
@@ -0,0 +1,198 @@
<Page x:Class="Radiosender.Views.Pages.ImportPage"
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"
Unloaded="OnUnloaded">
<Grid Margin="24">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="3*" MinHeight="260" />
<RowDefinition Height="Auto" />
<RowDefinition Height="2*" MinHeight="120" />
</Grid.RowDefinitions>
<ui:TextBlock Grid.Row="0" FontTypography="Title" Text="Import" />
<TabControl x:Name="Sources" Grid.Row="1" Margin="0,12,0,0">
<!-- From computer -->
<TabItem Header="From computer">
<Grid Margin="0,12,0,0">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid x:Name="DropZone"
Background="Transparent"
AllowDrop="True"
AutomationProperties.Name="Drop zone for MP3 and WAV files"
DragEnter="OnDragOver"
DragOver="OnDragOver"
DragLeave="OnDragLeave"
Drop="OnDrop">
<Rectangle x:Name="DropBorder"
RadiusX="8"
RadiusY="8"
StrokeThickness="2"
StrokeDashArray="4 3"
Stroke="{DynamicResource TextFillColorTertiaryBrush}" />
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
<ui:SymbolIcon HorizontalAlignment="Center" FontSize="40" Symbol="ArrowUpload24" />
<ui:TextBlock Margin="0,8,0,0"
HorizontalAlignment="Center"
FontTypography="BodyStrong"
Text="Drop MP3 or WAV files here" />
<ui:TextBlock Margin="0,4,0,12"
HorizontalAlignment="Center"
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
Text="You can add several files at once." />
<ui:Button x:Name="ChooseFilesButton"
HorizontalAlignment="Center"
Appearance="Primary"
Content="Choose files..."
Icon="{ui:SymbolIcon FolderOpen24}"
Click="OnChooseFiles" />
</StackPanel>
</Grid>
<StackPanel x:Name="UploadProgressPanel" Grid.Row="1" Margin="0,12,0,0" Visibility="Collapsed">
<ui:TextBlock x:Name="UploadProgressText" />
<ProgressBar x:Name="UploadProgress"
Margin="0,6,0,0"
AutomationProperties.Name="Upload progress" />
</StackPanel>
</Grid>
</TabItem>
<!-- Openverse -->
<TabItem Header="Openverse">
<Grid Margin="0,12,0,0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid Grid.Row="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ui:TextBox x:Name="QueryBox"
PlaceholderText="Search free audio, for example &quot;jazz piano&quot;"
AutomationProperties.Name="Search term"
KeyDown="OnQueryKeyDown" />
<ui:Button x:Name="SearchButton"
Grid.Column="1"
Margin="8,0,0,0"
Appearance="Primary"
Content="Search"
Icon="{ui:SymbolIcon Search24}"
Click="OnSearch" />
</Grid>
<ui:InfoBar x:Name="Message" Grid.Row="1" Margin="0,12,0,0" IsClosable="True" />
<ui:ListView x:Name="Results"
Grid.Row="2"
Margin="0,12,0,0"
SelectionMode="Single"
AutomationProperties.Name="Search results"
SelectionChanged="OnSelectionChanged"
MouseDoubleClick="OnResultDoubleClick">
<ui:ListView.View>
<ui:GridView>
<ui:GridViewColumn Width="300" Header="Title" DisplayMemberBinding="{Binding Track.Title}" />
<ui:GridViewColumn Width="180" Header="Creator" DisplayMemberBinding="{Binding Track.Creator}" />
<ui:GridViewColumn Width="80" Header="Duration" DisplayMemberBinding="{Binding Track.DurationText}" />
<ui:GridViewColumn Width="130" Header="License" DisplayMemberBinding="{Binding Track.LicenseName}" />
<ui:GridViewColumn Width="150" Header="Status">
<ui:GridViewColumn.CellTemplate>
<DataTemplate>
<ui:TextBlock Text="{Binding Status}" Foreground="{DynamicResource TextFillColorSecondaryBrush}" />
</DataTemplate>
</ui:GridViewColumn.CellTemplate>
</ui:GridViewColumn>
</ui:GridView>
</ui:ListView.View>
</ui:ListView>
<StackPanel Grid.Row="3" Margin="0,12,0,0" Orientation="Horizontal">
<ui:Button x:Name="PreviewButton" Content="Preview" Icon="{ui:SymbolIcon Play24}"
IsEnabled="False" Click="OnPreview" />
<ui:Button x:Name="StopButton" Margin="8,0,0,0" Content="Stop" Icon="{ui:SymbolIcon Stop24}"
IsEnabled="False" Click="OnStop" />
<ui:Button x:Name="ImportButton" Margin="8,0,0,0" Appearance="Primary"
Content="Import to library" Icon="{ui:SymbolIcon ArrowDownload24}"
IsEnabled="False" Click="OnImport" />
<ui:ProgressRing x:Name="Busy"
Width="20"
Height="20"
Margin="12,0,0,0"
IsIndeterminate="True"
Visibility="Collapsed" />
<ui:TextBlock x:Name="BusyText"
Margin="8,0,0,0"
VerticalAlignment="Center"
Foreground="{DynamicResource TextFillColorSecondaryBrush}" />
</StackPanel>
</Grid>
</TabItem>
</TabControl>
<!-- Added in this session, from both sources -->
<Grid Grid.Row="2" Margin="0,16,0,0">
<ui:TextBlock VerticalAlignment="Center" FontTypography="Subtitle" Text="Added in this session" />
<ui:Button HorizontalAlignment="Right"
Appearance="Transparent"
Content="Open library"
Icon="{ui:SymbolIcon MusicNote224}"
Click="OnOpenLibrary" />
</Grid>
<ui:ListView x:Name="Session"
Grid.Row="3"
Margin="0,8,0,0"
AutomationProperties.Name="Songs added in this session">
<ui:ListView.View>
<ui:GridView>
<ui:GridViewColumn Width="110" Header="Status">
<ui:GridViewColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<ui:SymbolIcon x:Name="Icon"
Symbol="CheckmarkCircle24"
Filled="True"
Foreground="{DynamicResource SystemFillColorSuccessBrush}" />
<ui:TextBlock x:Name="Label" Margin="6,0,0,0" Text="Added" />
</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="Failed" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ui:GridViewColumn.CellTemplate>
</ui:GridViewColumn>
<ui:GridViewColumn Width="240" Header="Title" DisplayMemberBinding="{Binding Title}" />
<ui:GridViewColumn Width="160" Header="Artist" DisplayMemberBinding="{Binding Artist}" />
<ui:GridViewColumn Width="80" Header="Duration" DisplayMemberBinding="{Binding Duration}" />
<ui:GridViewColumn Width="100" Header="Source" DisplayMemberBinding="{Binding Source}" />
<ui:GridViewColumn Width="320" Header="Details" DisplayMemberBinding="{Binding Details}" />
</ui:GridView>
</ui:ListView.View>
</ui:ListView>
<ui:TextBlock x:Name="SessionEmpty"
Grid.Row="3"
Margin="0,32,0,0"
HorizontalAlignment="Center"
VerticalAlignment="Top"
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
Text="Songs you import appear here." />
</Grid>
</Page>
@@ -0,0 +1,233 @@
using System.Collections.ObjectModel;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using Microsoft.Win32;
using Radiosender.Controllers;
using Radiosender.Models;
using Radiosender.Services;
using Wpf.Ui.Controls;
namespace Radiosender.Views.Pages;
/// <summary>Adds music to the library from local files or from Openverse; both list their results in one place.</summary>
public partial class ImportPage : Page
{
// One Openverse controller (and HttpClient) for the app lifetime; created on first use, after App.Songs exists.
private static OpenverseController? _openverse;
private static OpenverseController Openverse => _openverse ??= new(OpenverseClient.CreateDefault(), App.Songs);
private readonly UploadController _upload =
new(new SongImportService(App.Songs, SongImportService.DefaultMusicDirectory));
private readonly ObservableCollection<SessionRow> _session = [];
private readonly MediaPlayer _preview = new();
private bool _uploading;
private bool _busy;
public ImportPage()
{
InitializeComponent();
Session.ItemsSource = _session;
_session.CollectionChanged += (_, _) =>
SessionEmpty.Visibility = _session.Count == 0 ? Visibility.Visible : Visibility.Collapsed;
_preview.MediaEnded += (_, _) => OnStop(this, new RoutedEventArgs());
_preview.MediaFailed += (_, e) =>
{
OnStop(this, new RoutedEventArgs());
Show(InfoBarSeverity.Error, "Preview failed", e.ErrorException.Message);
};
}
// ---- From computer ----
private async void OnChooseFiles(object sender, RoutedEventArgs e)
{
var dialog = new OpenFileDialog { Filter = UploadController.FileDialogFilter, Multiselect = true };
if (dialog.ShowDialog() == true)
await UploadAsync(dialog.FileNames);
}
private void OnDragOver(object sender, DragEventArgs e)
{
var ok = !_uploading && e.Data.GetDataPresent(DataFormats.FileDrop);
e.Effects = ok ? DragDropEffects.Copy : DragDropEffects.None;
DropBorder.SetResourceReference(System.Windows.Shapes.Shape.StrokeProperty, ok ? "AccentTextFillColorPrimaryBrush" : "TextFillColorTertiaryBrush");
e.Handled = true;
}
private void OnDragLeave(object sender, DragEventArgs e) =>
DropBorder.SetResourceReference(System.Windows.Shapes.Shape.StrokeProperty, "TextFillColorTertiaryBrush");
private async void OnDrop(object sender, DragEventArgs e)
{
OnDragLeave(sender, e);
if (!_uploading && e.Data.GetData(DataFormats.FileDrop) is string[] paths)
await UploadAsync(paths);
}
// Files are imported one by one on a pool thread; each result shows up as soon as it is known.
private async Task UploadAsync(IReadOnlyList<string> paths)
{
if (paths.Count == 0) return;
_uploading = true;
ChooseFilesButton.IsEnabled = false;
UploadProgressPanel.Visibility = Visibility.Visible;
UploadProgress.Maximum = paths.Count;
try
{
for (var i = 0; i < paths.Count; i++)
{
var path = paths[i];
UploadProgress.Value = i;
UploadProgressText.Text = $"Importing {i + 1} of {paths.Count}: {Path.GetFileName(path)}";
var result = await Task.Run(() => _upload.Upload(path));
_session.Insert(0, result.Song is { } song
? SessionRow.Added(song, "Upload", Path.GetFileName(path))
: SessionRow.Failed(Path.GetFileName(path), "Upload", result.Message));
}
}
finally
{
_uploading = false;
ChooseFilesButton.IsEnabled = true;
UploadProgressPanel.Visibility = Visibility.Collapsed;
}
}
// ---- Openverse ----
private ResultRow? Selected => Results.SelectedItem as ResultRow;
private void OnQueryKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
OnSearch(sender, e);
}
private async void OnSearch(object sender, RoutedEventArgs e)
{
var query = QueryBox.Text.Trim();
if (query.Length == 0 || _busy)
return;
SetBusy($"Searching Openverse for \"{query}\"...");
Message.IsOpen = false;
try
{
var tracks = await Openverse.SearchAsync(query);
var imported = Openverse.ImportedIds();
Results.ItemsSource = tracks.Select(t => ResultRow.For(t, imported)).ToList();
if (tracks.Count == 0)
Show(InfoBarSeverity.Informational, "No results", $"Openverse found no audio for \"{query}\".");
}
catch (OpenverseException ex)
{
Show(InfoBarSeverity.Error, "Search failed", ex.Message);
}
finally
{
SetBusy(null);
}
}
private void OnPreview(object sender, RoutedEventArgs e)
{
if (Selected is not { } row || !Uri.TryCreate(row.Track.Url, UriKind.Absolute, out var uri) || uri.Scheme != Uri.UriSchemeHttps)
return;
_preview.Open(uri); // streams the file, nothing is saved
_preview.Play();
StopButton.IsEnabled = true;
}
private void OnStop(object sender, RoutedEventArgs e)
{
_preview.Stop();
_preview.Close();
StopButton.IsEnabled = false;
}
private void OnResultDoubleClick(object sender, MouseButtonEventArgs e) => OnImport(sender, e);
private async void OnImport(object sender, RoutedEventArgs e)
{
if (Selected is not { CanImport: true } row || _busy)
return;
SetBusy($"Downloading \"{row.Track.Title}\"...");
Message.IsOpen = false;
try
{
var song = await Openverse.ImportAsync(row.Track);
_session.Insert(0, SessionRow.Added(song, "Openverse", song.License ?? ""));
ReplaceRow(row, row with { Status = "In library", CanImport = false });
}
catch (Exception ex) when (ex is OpenverseException or Microsoft.Data.Sqlite.SqliteException)
{
_session.Insert(0, SessionRow.Failed(row.Track.Title, "Openverse", ex.Message));
Show(InfoBarSeverity.Error, "Import failed", ex.Message);
}
finally
{
SetBusy(null);
}
}
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();
Results.SelectedIndex = i;
}
private void OnSelectionChanged(object sender, SelectionChangedEventArgs e) => UpdateButtons();
private void SetBusy(string? text)
{
_busy = text is not null;
Busy.Visibility = _busy ? Visibility.Visible : Visibility.Collapsed;
BusyText.Text = text ?? "";
SearchButton.IsEnabled = !_busy;
UpdateButtons();
}
private void UpdateButtons()
{
PreviewButton.IsEnabled = Selected is not null;
ImportButton.IsEnabled = !_busy && Selected is { CanImport: true };
}
private void Show(InfoBarSeverity severity, string title, string message)
{
Message.Severity = severity;
Message.Title = title;
Message.Message = message;
Message.IsOpen = true;
}
// ---- Shared ----
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 sealed record ResultRow(OpenverseTrack Track, string Status, bool CanImport)
{
public static ResultRow For(OpenverseTrack track, IReadOnlySet<string> imported) =>
imported.Contains(track.Id) ? new(track, "In library", false)
: !track.CanImport ? new(track, "No duration", false)
: new(track, "", true);
}
private sealed record SessionRow(bool Success, string Title, string Artist, string Duration, string Source, string Details)
{
public static SessionRow Added(Song song, string source, string details) =>
new(true, song.Title, song.Artist, $"{(int)song.Duration.TotalMinutes}:{song.Duration.Seconds:00}", source, details);
public static SessionRow Failed(string name, string source, string error) => new(false, name, "", "", source, error);
}
}
@@ -1,62 +0,0 @@
<Page x:Class="Radiosender.Views.Pages.OpenversePage"
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="Openverse"
Unloaded="OnUnloaded">
<Grid Margin="24">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<ui:TextBlock Grid.Row="0" FontTypography="Title" Text="Openverse" />
<Grid Grid.Row="1" Margin="0,12,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ui:TextBox x:Name="QueryBox"
PlaceholderText="Search free audio, for example &quot;jazz piano&quot;"
AutomationProperties.Name="Search term"
KeyDown="OnQueryKeyDown" />
<ui:Button x:Name="SearchButton" Grid.Column="1" Margin="8,0,0,0"
Appearance="Primary" Content="Search"
Icon="{ui:SymbolIcon Search24}"
Click="OnSearch" />
</Grid>
<ui:InfoBar x:Name="Message" Grid.Row="2" Margin="0,12,0,0" IsClosable="True" />
<ui:ListView x:Name="Results" Grid.Row="3" Margin="0,12,0,0"
SelectionMode="Single"
AutomationProperties.Name="Search results"
SelectionChanged="OnSelectionChanged">
<ui:ListView.View>
<ui:GridView>
<GridViewColumn Header="Title" Width="320" DisplayMemberBinding="{Binding Title}" />
<GridViewColumn Header="Creator" Width="200" DisplayMemberBinding="{Binding Creator}" />
<GridViewColumn Header="Duration" Width="90" DisplayMemberBinding="{Binding DurationText}" />
<GridViewColumn Header="License" Width="150" DisplayMemberBinding="{Binding LicenseName}" />
</ui:GridView>
</ui:ListView.View>
</ui:ListView>
<StackPanel Grid.Row="4" Margin="0,12,0,0" Orientation="Horizontal">
<ui:Button x:Name="PreviewButton" Content="Preview" Icon="{ui:SymbolIcon Play24}"
IsEnabled="False" Click="OnPreview" />
<ui:Button x:Name="StopButton" Margin="8,0,0,0" Content="Stop" Icon="{ui:SymbolIcon Stop24}"
IsEnabled="False" Click="OnStop" />
<ui:Button x:Name="ImportButton" Margin="8,0,0,0" Appearance="Primary"
Content="Import to library" Icon="{ui:SymbolIcon ArrowDownload24}"
IsEnabled="False" Click="OnImport" />
<ui:TextBlock x:Name="ImportHint" Margin="12,0,0,0" VerticalAlignment="Center"
Visibility="Collapsed"
Text="This result has no duration and cannot be imported." />
</StackPanel>
</Grid>
</Page>
@@ -1,128 +0,0 @@
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using Radiosender.Controllers;
using Radiosender.Models;
using Radiosender.Services;
using Wpf.Ui.Controls;
namespace Radiosender.Views.Pages;
public partial class OpenversePage : Page
{
// One controller (and HttpClient) for the app lifetime; created on first use, after App.Songs exists.
private static OpenverseController? _controller;
private static OpenverseController Controller => _controller ??= new(OpenverseClient.CreateDefault(), App.Songs);
private readonly MediaPlayer _preview = new();
private bool _busy;
public OpenversePage()
{
InitializeComponent();
_preview.MediaEnded += (_, _) => OnStop(this, new RoutedEventArgs());
_preview.MediaFailed += (_, e) =>
{
OnStop(this, new RoutedEventArgs());
Show(InfoBarSeverity.Error, "Preview failed", e.ErrorException.Message);
};
}
private OpenverseTrack? Selected => Results.SelectedItem as OpenverseTrack;
private void OnQueryKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
OnSearch(sender, e);
}
private async void OnSearch(object sender, RoutedEventArgs e)
{
var query = QueryBox.Text.Trim();
if (query.Length == 0 || _busy)
return;
SetBusy(true);
Message.IsOpen = false;
try
{
var tracks = await Controller.SearchAsync(query);
Results.ItemsSource = tracks;
if (tracks.Count == 0)
Show(InfoBarSeverity.Informational, "No results", $"Openverse found no audio for \"{query}\".");
}
catch (OpenverseException ex)
{
Show(InfoBarSeverity.Error, "Search failed", ex.Message);
}
finally
{
SetBusy(false);
}
}
private void OnPreview(object sender, RoutedEventArgs e)
{
if (Selected is not { } track || !Uri.TryCreate(track.Url, UriKind.Absolute, out var uri) || uri.Scheme != Uri.UriSchemeHttps)
return;
_preview.Open(uri); // streams the file, nothing is saved
_preview.Play();
StopButton.IsEnabled = true;
}
private void OnStop(object sender, RoutedEventArgs e)
{
_preview.Stop();
_preview.Close();
StopButton.IsEnabled = false;
}
private async void OnImport(object sender, RoutedEventArgs e)
{
if (Selected is not { CanImport: true } track || _busy)
return;
SetBusy(true);
Message.IsOpen = false;
try
{
var song = await Controller.ImportAsync(track);
Show(InfoBarSeverity.Success, "Imported", $"\"{song.Title}\" was added to the library.");
}
catch (Exception ex) when (ex is OpenverseException or Microsoft.Data.Sqlite.SqliteException)
{
Show(InfoBarSeverity.Error, "Import failed", ex.Message);
}
finally
{
SetBusy(false);
}
}
private void OnSelectionChanged(object sender, SelectionChangedEventArgs e) => UpdateButtons();
private void OnUnloaded(object sender, RoutedEventArgs e) => OnStop(sender, e);
private void SetBusy(bool busy)
{
_busy = busy;
SearchButton.IsEnabled = !busy;
UpdateButtons();
}
private void UpdateButtons()
{
PreviewButton.IsEnabled = Selected is not null;
ImportButton.IsEnabled = !_busy && Selected is { CanImport: true };
ImportHint.Visibility = Selected is { CanImport: false } ? Visibility.Visible : Visibility.Collapsed;
}
private void Show(InfoBarSeverity severity, string title, string message)
{
Message.Severity = severity;
Message.Title = title;
Message.Message = message;
Message.IsOpen = true;
}
}
@@ -1,19 +0,0 @@
<Page x:Class="Radiosender.Views.Pages.UploadPage"
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="Upload">
<Grid>
<StackPanel Margin="24">
<ui:TextBlock FontTypography="Title" Text="Upload" />
<ui:TextBlock Margin="0,8,0,0" Text="Add an MP3 or WAV file from your computer to the library." />
<ui:Button x:Name="ChooseFileButton"
Margin="0,16,0,0"
Appearance="Primary"
Content="Choose file..."
Icon="{ui:SymbolIcon ArrowUpload24}"
Click="ChooseFileButton_Click" />
</StackPanel>
<ui:SnackbarPresenter x:Name="SnackbarPresenter" VerticalAlignment="Bottom" />
</Grid>
</Page>
@@ -1,35 +0,0 @@
using System.Windows;
using Microsoft.Win32;
using Radiosender.Controllers;
using Radiosender.Services;
using Wpf.Ui.Controls;
namespace Radiosender.Views.Pages;
public partial class UploadPage
{
private readonly UploadController _controller =
new(new SongImportService(App.Songs, SongImportService.DefaultMusicDirectory));
public UploadPage()
{
InitializeComponent();
}
private void ChooseFileButton_Click(object sender, RoutedEventArgs e)
{
var dialog = new OpenFileDialog { Filter = UploadController.FileDialogFilter };
if (dialog.ShowDialog() != true)
return;
var result = _controller.Upload(dialog.FileName);
new Snackbar(SnackbarPresenter)
{
Title = result.Success ? "Song uploaded" : "Upload failed",
Content = result.Message,
Appearance = result.Success ? ControlAppearance.Success : ControlAppearance.Danger,
Icon = new SymbolIcon(result.Success ? SymbolRegular.CheckmarkCircle24 : SymbolRegular.ErrorCircle24),
Timeout = TimeSpan.FromSeconds(5),
}.Show();
}
}