diff --git a/README.md b/README.md index b3a644f..71c8a3e 100644 --- a/README.md +++ b/README.md @@ -12,8 +12,11 @@ WPF desktop app that plans and plays a radio program: random music from a SQLite ```powershell dotnet build Radiosender.slnx dotnet run --project src/Radiosender +dotnet test Radiosender.slnx ``` +The app creates its SQLite database on first start at `%LOCALAPPDATA%\Radiosender\radiosender.db`. + ## Structure The app uses the MVC pattern and [WPF UI](https://github.com/lepoco/wpfui) for the interface. diff --git a/Radiosender.slnx b/Radiosender.slnx index 0b7230e..5bf2a16 100644 --- a/Radiosender.slnx +++ b/Radiosender.slnx @@ -2,4 +2,7 @@ + + + diff --git a/src/Radiosender/App.xaml.cs b/src/Radiosender/App.xaml.cs index 6323b09..1a339b1 100644 --- a/src/Radiosender/App.xaml.cs +++ b/src/Radiosender/App.xaml.cs @@ -1,7 +1,16 @@ using System.Windows; +using Radiosender.Services; namespace Radiosender; public partial class App : Application { + public static SongRepository Songs { get; private set; } = null!; + + protected override void OnStartup(StartupEventArgs e) + { + // Creates the database file and table on first start. + Songs = new SongRepository(SongRepository.DefaultDatabasePath); + base.OnStartup(e); + } } diff --git a/src/Radiosender/Models/.gitkeep b/src/Radiosender/Models/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/src/Radiosender/Models/Song.cs b/src/Radiosender/Models/Song.cs new file mode 100644 index 0000000..db91d7f --- /dev/null +++ b/src/Radiosender/Models/Song.cs @@ -0,0 +1,19 @@ +namespace Radiosender.Models; + +public enum SongSource +{ + Upload, + Openverse, +} + +public class Song +{ + public long Id { get; set; } + public string Title { get; set; } = ""; + public string Artist { get; set; } = ""; + public TimeSpan Duration { get; set; } + public string FilePath { get; set; } = ""; + public SongSource Source { get; set; } + public string? License { get; set; } + public string? Attribution { get; set; } +} diff --git a/src/Radiosender/Radiosender.csproj b/src/Radiosender/Radiosender.csproj index 26a66e9..c78ea43 100644 --- a/src/Radiosender/Radiosender.csproj +++ b/src/Radiosender/Radiosender.csproj @@ -9,6 +9,7 @@ + diff --git a/src/Radiosender/Services/.gitkeep b/src/Radiosender/Services/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/src/Radiosender/Services/SongRepository.cs b/src/Radiosender/Services/SongRepository.cs new file mode 100644 index 0000000..dbb8bf1 --- /dev/null +++ b/src/Radiosender/Services/SongRepository.cs @@ -0,0 +1,128 @@ +using System.IO; +using Microsoft.Data.Sqlite; +using Radiosender.Models; + +namespace Radiosender.Services; + +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 readonly string _connectionString; + + public SongRepository(string databasePath) + { + Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(databasePath))!); + _connectionString = new SqliteConnectionStringBuilder { DataSource = databasePath }.ToString(); + + using var connection = Open(); + using var command = connection.CreateCommand(); + command.CommandText = """ + CREATE TABLE IF NOT EXISTS Songs ( + Id INTEGER PRIMARY KEY AUTOINCREMENT, + Title TEXT NOT NULL, + Artist TEXT NOT NULL, + DurationMs INTEGER NOT NULL CHECK (DurationMs > 0), + FilePath TEXT NOT NULL, + Source INTEGER NOT NULL, + License TEXT, + Attribution TEXT + ) + """; + command.ExecuteNonQuery(); + } + + public IReadOnlyList GetAll() + { + using var connection = Open(); + using var command = connection.CreateCommand(); + command.CommandText = $"SELECT {Columns} FROM Songs ORDER BY Artist, Title"; + using var reader = command.ExecuteReader(); + var songs = new List(); + while (reader.Read()) + songs.Add(Read(reader)); + return songs; + } + + public Song? GetById(long id) + { + using var connection = Open(); + using var command = connection.CreateCommand(); + command.CommandText = $"SELECT {Columns} FROM Songs WHERE Id = $id"; + command.Parameters.AddWithValue("$id", id); + using var reader = command.ExecuteReader(); + return reader.Read() ? Read(reader) : null; + } + + /// Inserts the song and sets its . + public void Add(Song song) + { + 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); + SELECT last_insert_rowid(); + """; + AddParameters(command, song); + song.Id = (long)command.ExecuteScalar()!; + } + + /// false if no song with this id exists. + public bool Update(Song song) + { + using var connection = Open(); + using var command = connection.CreateCommand(); + command.CommandText = """ + UPDATE Songs SET Title = $title, Artist = $artist, DurationMs = $durationMs, FilePath = $filePath, + Source = $source, License = $license, Attribution = $attribution + WHERE Id = $id + """; + AddParameters(command, song); + command.Parameters.AddWithValue("$id", song.Id); + return command.ExecuteNonQuery() == 1; + } + + /// false if no song with this id exists. + public bool Delete(long id) + { + using var connection = Open(); + using var command = connection.CreateCommand(); + command.CommandText = "DELETE FROM Songs WHERE Id = $id"; + command.Parameters.AddWithValue("$id", id); + return command.ExecuteNonQuery() == 1; + } + + private SqliteConnection Open() + { + var connection = new SqliteConnection(_connectionString); + connection.Open(); + return connection; + } + + private static void AddParameters(SqliteCommand command, Song song) + { + command.Parameters.AddWithValue("$title", song.Title); + command.Parameters.AddWithValue("$artist", song.Artist); + command.Parameters.AddWithValue("$durationMs", (long)song.Duration.TotalMilliseconds); + command.Parameters.AddWithValue("$filePath", song.FilePath); + 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); + } + + private static Song Read(SqliteDataReader reader) => new() + { + Id = reader.GetInt64(0), + Title = reader.GetString(1), + Artist = reader.GetString(2), + Duration = TimeSpan.FromMilliseconds(reader.GetInt64(3)), + FilePath = reader.GetString(4), + Source = (SongSource)reader.GetInt32(5), + License = reader.IsDBNull(6) ? null : reader.GetString(6), + Attribution = reader.IsDBNull(7) ? null : reader.GetString(7), + }; +} diff --git a/tests/Radiosender.Tests/Radiosender.Tests.csproj b/tests/Radiosender.Tests/Radiosender.Tests.csproj new file mode 100644 index 0000000..0dac77b --- /dev/null +++ b/tests/Radiosender.Tests/Radiosender.Tests.csproj @@ -0,0 +1,25 @@ + + + + net10.0-windows + enable + enable + false + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tests/Radiosender.Tests/SongRepositoryTests.cs b/tests/Radiosender.Tests/SongRepositoryTests.cs new file mode 100644 index 0000000..a41967f --- /dev/null +++ b/tests/Radiosender.Tests/SongRepositoryTests.cs @@ -0,0 +1,127 @@ +using Microsoft.Data.Sqlite; +using Radiosender.Models; +using Radiosender.Services; + +namespace Radiosender.Tests; + +public sealed class SongRepositoryTests : IDisposable +{ + private readonly string _directory = Path.Combine(Path.GetTempPath(), "radiosender-tests", Guid.NewGuid().ToString("N")); + private string DatabasePath => Path.Combine(_directory, "test.db"); + + public void Dispose() + { + SqliteConnection.ClearAllPools(); // pooled connections keep the file locked + Directory.Delete(_directory, recursive: true); + } + + private static Song NewSong(string title = "Song") => new() + { + Title = title, + Artist = "Artist", + Duration = TimeSpan.FromSeconds(185.5), + FilePath = @"C:\music\song.mp3", + Source = SongSource.Openverse, + License = "CC BY 4.0", + Attribution = null, + }; + + [Fact] + public void Constructor_CreatesDatabaseFileAndDirectory() + { + _ = new SongRepository(DatabasePath); + + Assert.True(File.Exists(DatabasePath)); + } + + [Fact] + public void Add_ThenGetById_ReturnsSameValues() + { + var repository = new SongRepository(DatabasePath); + var song = NewSong(); + + repository.Add(song); + var loaded = repository.GetById(song.Id); + + Assert.True(song.Id > 0); + Assert.NotNull(loaded); + Assert.Equal(song.Title, loaded.Title); + Assert.Equal(song.Artist, loaded.Artist); + Assert.Equal(song.Duration, loaded.Duration); + Assert.Equal(song.FilePath, loaded.FilePath); + Assert.Equal(song.Source, loaded.Source); + Assert.Equal(song.License, loaded.License); + Assert.Null(loaded.Attribution); + } + + [Fact] + public void Data_SurvivesNewRepositoryInstance() + { + new SongRepository(DatabasePath).Add(NewSong("A")); + + var songs = new SongRepository(DatabasePath).GetAll(); + + Assert.Equal("A", Assert.Single(songs).Title); + } + + [Fact] + public void Update_ChangesStoredSong() + { + var repository = new SongRepository(DatabasePath); + var song = NewSong(); + repository.Add(song); + + song.Title = "Renamed"; + song.Attribution = "by someone"; + + Assert.True(repository.Update(song)); + var loaded = repository.GetById(song.Id)!; + Assert.Equal("Renamed", loaded.Title); + Assert.Equal("by someone", loaded.Attribution); + } + + [Fact] + public void Delete_RemovesSong() + { + var repository = new SongRepository(DatabasePath); + var song = NewSong(); + repository.Add(song); + + Assert.True(repository.Delete(song.Id)); + Assert.Null(repository.GetById(song.Id)); + Assert.Empty(repository.GetAll()); + } + + [Fact] + public void UpdateAndDelete_ReturnFalseForUnknownId() + { + var repository = new SongRepository(DatabasePath); + + var unknown = NewSong(); + unknown.Id = 42; + + Assert.False(repository.Update(unknown)); + Assert.False(repository.Delete(42)); + } + + [Fact] + public void Add_StoresTitleWithSqlCharactersAsText() + { + var repository = new SongRepository(DatabasePath); + var song = NewSong("x'); DROP TABLE Songs; --"); + + repository.Add(song); + + Assert.Equal(song.Title, Assert.Single(repository.GetAll()).Title); + } + + [Fact] + public void Add_RejectsZeroDuration() + { + var repository = new SongRepository(DatabasePath); + var song = NewSong(); + song.Duration = TimeSpan.Zero; + + Assert.Throws(() => repository.Add(song)); + } +}