Merge remote-tracking branch 'origin/main' into j.lechner/openverse
# Conflicts: # src/Radiosender/Views/MainWindow.xaml
This commit is contained in:
commit
ba97d351b0
7 files changed
+296
No files matched your search
@@ -0,0 +1,27 @@
|
|||||||
|
using Radiosender.Services;
|
||||||
|
|
||||||
|
namespace Radiosender.Controllers;
|
||||||
|
|
||||||
|
public record UploadResult(bool Success, string Message);
|
||||||
|
|
||||||
|
public class UploadController(SongImportService importService)
|
||||||
|
{
|
||||||
|
public static string FileDialogFilter { get; } = "Audio files (*.mp3;*.wav)|*.mp3;*.wav";
|
||||||
|
|
||||||
|
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.");
|
||||||
|
}
|
||||||
|
catch (SongImportException e)
|
||||||
|
{
|
||||||
|
return new UploadResult(false, e.Message);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
return new UploadResult(false, $"The song could not be saved: {e.Message}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,6 +11,7 @@
|
|||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Microsoft.Data.Sqlite" Version="10.0.15" />
|
<PackageReference Include="Microsoft.Data.Sqlite" Version="10.0.15" />
|
||||||
<PackageReference Include="NAudio" Version="3.3.0" />
|
<PackageReference Include="NAudio" Version="3.3.0" />
|
||||||
|
<PackageReference Include="TagLibSharp" Version="2.3.0" />
|
||||||
<PackageReference Include="WPF-UI" Version="4.3.0" />
|
<PackageReference Include="WPF-UI" Version="4.3.0" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,100 @@
|
|||||||
|
using System.IO;
|
||||||
|
using NAudio.Wave;
|
||||||
|
using Radiosender.Models;
|
||||||
|
|
||||||
|
namespace Radiosender.Services;
|
||||||
|
|
||||||
|
/// <summary>An import failure with a message that can be shown to the user.</summary>
|
||||||
|
public class SongImportException(string message, Exception? innerException = null) : Exception(message, innerException);
|
||||||
|
|
||||||
|
/// <summary>Copies an uploaded MP3 or WAV file into the music folder and saves it as a song.</summary>
|
||||||
|
public class SongImportService(SongRepository songs, string musicDirectory)
|
||||||
|
{
|
||||||
|
public static string DefaultMusicDirectory { get; } = Path.Combine(
|
||||||
|
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Radiosender", "Music");
|
||||||
|
|
||||||
|
public static IReadOnlyList<string> SupportedExtensions { get; } = [".mp3", ".wav"];
|
||||||
|
|
||||||
|
/// <exception cref="SongImportException">The file is not a readable MP3 or WAV file with audio.</exception>
|
||||||
|
public Song Import(string sourcePath)
|
||||||
|
{
|
||||||
|
if (!SupportedExtensions.Contains(Path.GetExtension(sourcePath).ToLowerInvariant()))
|
||||||
|
throw new SongImportException("Only MP3 and WAV files are supported.");
|
||||||
|
|
||||||
|
Directory.CreateDirectory(musicDirectory);
|
||||||
|
var targetPath = GetUniqueTargetPath(Path.GetFileName(sourcePath));
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.Copy(sourcePath, targetPath, overwrite: false);
|
||||||
|
}
|
||||||
|
catch (Exception e) when (e is IOException or UnauthorizedAccessException)
|
||||||
|
{
|
||||||
|
throw new SongImportException($"The file could not be read: {e.Message}", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var duration = ReadDuration(targetPath);
|
||||||
|
var (title, artist) = ReadTags(targetPath);
|
||||||
|
var song = new Song
|
||||||
|
{
|
||||||
|
Title = title ?? Path.GetFileNameWithoutExtension(sourcePath),
|
||||||
|
Artist = artist ?? "",
|
||||||
|
Duration = duration,
|
||||||
|
FilePath = targetPath,
|
||||||
|
Source = SongSource.Upload,
|
||||||
|
};
|
||||||
|
songs.Add(song);
|
||||||
|
return song;
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
File.Delete(targetPath);
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private string GetUniqueTargetPath(string fileName)
|
||||||
|
{
|
||||||
|
var name = Path.GetFileNameWithoutExtension(fileName);
|
||||||
|
var extension = Path.GetExtension(fileName);
|
||||||
|
var path = Path.Combine(musicDirectory, fileName);
|
||||||
|
for (var i = 2; File.Exists(path); i++)
|
||||||
|
path = Path.Combine(musicDirectory, $"{name} ({i}){extension}");
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static TimeSpan ReadDuration(string path)
|
||||||
|
{
|
||||||
|
TimeSpan duration;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var reader = new AudioFileReader(path);
|
||||||
|
duration = reader.TotalTime;
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
// NAudio and Media Foundation throw many unrelated exception types for corrupt files.
|
||||||
|
throw new SongImportException("The file is not a readable MP3 or WAV file.", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (duration <= TimeSpan.Zero)
|
||||||
|
throw new SongImportException("The file contains no audio.");
|
||||||
|
return duration;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static (string? Title, string? Artist) ReadTags(string path)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var file = TagLib.File.Create(path);
|
||||||
|
return (NullIfBlank(file.Tag.Title), NullIfBlank(file.Tag.FirstPerformer));
|
||||||
|
}
|
||||||
|
catch (Exception e) when (e is TagLib.CorruptFileException or TagLib.UnsupportedFormatException or IOException)
|
||||||
|
{
|
||||||
|
return (null, null); // tags are optional; duration reading decides if the file is valid
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string? NullIfBlank(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim();
|
||||||
|
}
|
||||||
@@ -25,6 +25,9 @@
|
|||||||
<ui:NavigationViewItem Content="Library"
|
<ui:NavigationViewItem Content="Library"
|
||||||
Icon="{ui:SymbolIcon MusicNote224}"
|
Icon="{ui:SymbolIcon MusicNote224}"
|
||||||
TargetPageType="{x:Type pages:LibraryPage}" />
|
TargetPageType="{x:Type pages:LibraryPage}" />
|
||||||
|
<ui:NavigationViewItem Content="Upload"
|
||||||
|
Icon="{ui:SymbolIcon ArrowUpload24}"
|
||||||
|
TargetPageType="{x:Type pages:UploadPage}" />
|
||||||
<ui:NavigationViewItem Content="Openverse"
|
<ui:NavigationViewItem Content="Openverse"
|
||||||
Icon="{ui:SymbolIcon Search24}"
|
Icon="{ui:SymbolIcon Search24}"
|
||||||
TargetPageType="{x:Type pages:OpenversePage}" />
|
TargetPageType="{x:Type pages:OpenversePage}" />
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
<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>
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
using Microsoft.Data.Sqlite;
|
||||||
|
using NAudio.Wave;
|
||||||
|
using Radiosender.Models;
|
||||||
|
using Radiosender.Services;
|
||||||
|
|
||||||
|
namespace Radiosender.Tests;
|
||||||
|
|
||||||
|
public sealed class SongImportServiceTests : IDisposable
|
||||||
|
{
|
||||||
|
private readonly string _directory = Path.Combine(Path.GetTempPath(), "radiosender-tests", Guid.NewGuid().ToString("N"));
|
||||||
|
private readonly SongRepository _repository;
|
||||||
|
private readonly SongImportService _service;
|
||||||
|
|
||||||
|
private string SourceDirectory => Path.Combine(_directory, "source");
|
||||||
|
private string MusicDirectory => Path.Combine(_directory, "music");
|
||||||
|
|
||||||
|
public SongImportServiceTests()
|
||||||
|
{
|
||||||
|
Directory.CreateDirectory(SourceDirectory);
|
||||||
|
_repository = new SongRepository(Path.Combine(_directory, "test.db"));
|
||||||
|
_service = new SongImportService(_repository, MusicDirectory);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
SqliteConnection.ClearAllPools(); // pooled connections keep the file locked
|
||||||
|
Directory.Delete(_directory, recursive: true);
|
||||||
|
}
|
||||||
|
|
||||||
|
private string CreateWav(string fileName, TimeSpan duration)
|
||||||
|
{
|
||||||
|
var path = Path.Combine(SourceDirectory, fileName);
|
||||||
|
var format = new WaveFormat(8000, 16, 1);
|
||||||
|
using var writer = new WaveFileWriter(path, format);
|
||||||
|
writer.Write(new byte[(int)(format.AverageBytesPerSecond * duration.TotalSeconds)]);
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
|
||||||
|
private string[] MusicFiles() =>
|
||||||
|
Directory.Exists(MusicDirectory) ? Directory.GetFiles(MusicDirectory) : [];
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Import_Wav_CopiesFileAndSavesSong()
|
||||||
|
{
|
||||||
|
var source = CreateWav("My Song.wav", TimeSpan.FromSeconds(2));
|
||||||
|
|
||||||
|
var song = _service.Import(source);
|
||||||
|
|
||||||
|
var stored = _repository.GetById(song.Id);
|
||||||
|
Assert.NotNull(stored);
|
||||||
|
Assert.Equal("My Song", stored.Title);
|
||||||
|
Assert.Equal(TimeSpan.FromSeconds(2), stored.Duration);
|
||||||
|
Assert.Equal(SongSource.Upload, stored.Source);
|
||||||
|
Assert.Equal(Path.Combine(MusicDirectory, "My Song.wav"), stored.FilePath);
|
||||||
|
Assert.True(File.Exists(stored.FilePath));
|
||||||
|
Assert.True(File.Exists(source));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Import_SameFileTwice_DoesNotOverwrite()
|
||||||
|
{
|
||||||
|
var source = CreateWav("song.wav", TimeSpan.FromSeconds(1));
|
||||||
|
|
||||||
|
var first = _service.Import(source);
|
||||||
|
var second = _service.Import(source);
|
||||||
|
|
||||||
|
Assert.NotEqual(first.FilePath, second.FilePath);
|
||||||
|
Assert.Equal(Path.Combine(MusicDirectory, "song (2).wav"), second.FilePath);
|
||||||
|
Assert.Equal(2, MusicFiles().Length);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Import_WrongExtension_IsRejected()
|
||||||
|
{
|
||||||
|
var source = Path.Combine(SourceDirectory, "notes.txt");
|
||||||
|
File.WriteAllText(source, "not audio");
|
||||||
|
|
||||||
|
Assert.Throws<SongImportException>(() => _service.Import(source));
|
||||||
|
Assert.Empty(MusicFiles());
|
||||||
|
Assert.Empty(_repository.GetAll());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("garbage.wav")]
|
||||||
|
[InlineData("garbage.mp3")]
|
||||||
|
public void Import_GarbageFile_IsRejectedWithoutLeftoverCopy(string fileName)
|
||||||
|
{
|
||||||
|
var source = Path.Combine(SourceDirectory, fileName);
|
||||||
|
File.WriteAllBytes(source, Enumerable.Range(0, 4096).Select(i => (byte)(i * 7)).ToArray());
|
||||||
|
|
||||||
|
Assert.Throws<SongImportException>(() => _service.Import(source));
|
||||||
|
Assert.Empty(MusicFiles());
|
||||||
|
Assert.Empty(_repository.GetAll());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Import_EmptyWav_IsRejectedWithoutLeftoverCopy()
|
||||||
|
{
|
||||||
|
var source = CreateWav("silence.wav", TimeSpan.Zero);
|
||||||
|
|
||||||
|
Assert.Throws<SongImportException>(() => _service.Import(source));
|
||||||
|
Assert.Empty(MusicFiles());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Import_MissingFile_IsRejected()
|
||||||
|
{
|
||||||
|
Assert.Throws<SongImportException>(() => _service.Import(Path.Combine(SourceDirectory, "missing.mp3")));
|
||||||
|
Assert.Empty(MusicFiles());
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user