From 65743279b125098dcd021b9dda05c8f718f70764 Mon Sep 17 00:00:00 2001 From: Julian Lechner Date: Mon, 23 Nov 2026 14:40:12 +0100 Subject: [PATCH] refactor(database): access the library through EF Core SongRepository uses Entity Framework Core instead of hand-written SQL. The table and column names stay the same, so existing libraries open unchanged. The duration rule moves into the repository, and a duplicate Openverse id now surfaces as DbUpdateException. Libraries from before the Openverse import, which lack the OpenverseId column, are no longer upgraded. Co-Authored-By: Claude Fable 5.2 --- README.md | 5 +- src/Radiosender/Radiosender.csproj | 2 +- src/Radiosender/Services/SongRepository.cs | 164 +++++++----------- .../Views/Pages/ImportPage.xaml.cs | 8 +- .../Radiosender.Tests/SongRepositoryTests.cs | 49 ++++-- 5 files changed, 107 insertions(+), 121 deletions(-) diff --git a/README.md b/README.md index 5df0528..45a54d3 100644 --- a/README.md +++ b/README.md @@ -72,7 +72,7 @@ Views only handle input and display. They call a controller, and the controller Main services: -- `SongRepository`: CRUD for songs in SQLite, with parameterized queries +- `SongRepository`: CRUD for songs in SQLite through Entity Framework Core, without SQL in the code - `SongImportService`: copies an uploaded file into the music folder, reads its tags with TagLibSharp and its duration with NAudio - `OpenverseClient`: anonymous search and download through the Openverse API - `MusicPlayer`: the audio player as a singleton (`MusicPlayer.Instance`, private constructor). It plays files with NAudio. @@ -97,7 +97,7 @@ For each downloaded track the app stores the license (for example `CC BY 4.0`) a | Up to 20 minutes of ads and moderator talk per hour | Targets in the settings. The defaults are 20 minutes of ads plus 10 of moderator talk, which is 30; set them to 20 together to meet this rule | Configurable | | Ads never 20 minutes in a row | One ad item lasts at most 5 minutes and follows a moderator item | Done | | Remaining time filled with music | Songs fill each slot | Done | -| Music comes from a SQLite database | `SongRepository`, `radiosender.db` | Done | +| Music comes from a SQLite database | `SongRepository` with Entity Framework Core, `radiosender.db` | Done | | Library can be extended at any time: add, edit, delete | Library page and `SongEditWindow` | Done | | Add by simple upload | Import page, "Vom Computer" (MP3, WAV, several files, drag and drop) | Done | | Add through the Openverse API | Import page, "Openverse" | Done | @@ -114,6 +114,7 @@ For each downloaded track the app stores the license (for example `CC BY 4.0`) a - **Manual edits** shift every later item, so after moving, removing or resizing an item the news can leave :00 and :30 and the plan can end earlier or later. - **Late items**: if a song plays longer than its stored duration, the following items start late by the same amount. Nothing is cut to catch up; the delay only disappears when a later item ends early. - **Skipped songs**: a song that cannot be played (missing file, unsupported format) is skipped with a warning, and the station stays silent until the next planned item. +- **Very old libraries**: a `radiosender.db` from before the Openverse import has no `OpenverseId` column and is not upgraded. Delete the file and import the music again. - **Deleting a song** removes it from the library but keeps its file in the `Music` folder. - **Placeholders** have no audio. - **Targets** for ads and moderator talk are missed by the time the songs cannot fill, usually a few seconds per hour; a small library or only long songs make that more. diff --git a/src/Radiosender/Radiosender.csproj b/src/Radiosender/Radiosender.csproj index b8a5c75..91374ec 100644 --- a/src/Radiosender/Radiosender.csproj +++ b/src/Radiosender/Radiosender.csproj @@ -9,7 +9,7 @@ - + diff --git a/src/Radiosender/Services/SongRepository.cs b/src/Radiosender/Services/SongRepository.cs index 58928e0..831c4f6 100644 --- a/src/Radiosender/Services/SongRepository.cs +++ b/src/Radiosender/Services/SongRepository.cs @@ -1,156 +1,112 @@ using System.IO; using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; using Radiosender.Models; namespace Radiosender.Services; +/// +/// The music library in a SQLite file, accessed through Entity Framework Core. +/// Every call uses its own short-lived context, so the repository can be used from any thread. +/// 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, OpenverseId"; - - private readonly string _connectionString; + private readonly DbContextOptions _options; public SongRepository(string databasePath) { Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(databasePath))!); - _connectionString = new SqliteConnectionStringBuilder { DataSource = databasePath }.ToString(); + _options = new DbContextOptionsBuilder() + .UseSqlite(new SqliteConnectionStringBuilder { DataSource = databasePath }.ToString()) + .Options; - 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, - 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(); + // Creates the file and the table on first start; an existing database is left as it is. + using var context = Open(); + context.Database.EnsureCreated(); } /// Ids of all Openverse results that are already in the library. public IReadOnlySet 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(); - while (reader.Read()) - ids.Add(reader.GetString(0)); - return ids; + using var context = Open(); + return context.Songs.Where(s => s.OpenverseId != null).Select(s => s.OpenverseId!).ToHashSet(); } 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; + using var context = Open(); + return context.Songs.AsNoTracking().OrderBy(s => s.Artist).ThenBy(s => s.Title).ToList(); } 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; + using var context = Open(); + return context.Songs.AsNoTracking().FirstOrDefault(s => s.Id == id); } /// Inserts the song and sets its . + /// The song has no duration. + /// The database rejected the song, e.g. a second song with the same Openverse id. 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, OpenverseId) - VALUES ($title, $artist, $durationMs, $filePath, $source, $license, $attribution, $openverseId); - SELECT last_insert_rowid(); - """; - AddParameters(command, song); - song.Id = (long)command.ExecuteScalar()!; + RequireDuration(song); + using var context = Open(); + context.Songs.Add(song); + context.SaveChanges(); } + /// Stores everything except the Openverse id, which never changes after the import. /// false if no song with this id exists. + /// The song has no duration. 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; + RequireDuration(song); + using var context = Open(); + return context.Songs.Where(s => s.Id == song.Id).ExecuteUpdate(s => s + .SetProperty(x => x.Title, song.Title) + .SetProperty(x => x.Artist, song.Artist) + .SetProperty(x => x.Duration, song.Duration) + .SetProperty(x => x.FilePath, song.FilePath) + .SetProperty(x => x.Source, song.Source) + .SetProperty(x => x.License, song.License) + .SetProperty(x => x.Attribution, song.Attribution)) == 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; + using var context = Open(); + return context.Songs.Where(s => s.Id == id).ExecuteDelete() == 1; } - private SqliteConnection Open() + private LibraryContext Open() => new(_options); + + // Songs need a length for scheduling. Checked here, so the rule does not depend on the database schema. + private static void RequireDuration(Song song) { - var connection = new SqliteConnection(_connectionString); - connection.Open(); - return connection; + if (song.Duration <= TimeSpan.Zero) + throw new ArgumentException("A song needs a duration longer than zero.", nameof(song)); } - private static void AddParameters(SqliteCommand command, Song song) + /// Maps to the table Songs. + private sealed class LibraryContext(DbContextOptions options) : DbContext(options) { - 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); - command.Parameters.AddWithValue("$openverseId", (object?)song.OpenverseId ?? DBNull.Value); - } + public DbSet Songs => Set(); - 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), - OpenverseId = reader.IsDBNull(8) ? null : reader.GetString(8), - }; + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + var song = modelBuilder.Entity(); + song.ToTable("Songs"); + // Stored as whole milliseconds in the column the first version of the app created. + song.Property(s => s.Duration) + .HasColumnName("DurationMs") + .HasConversion(duration => (long)duration.TotalMilliseconds, milliseconds => TimeSpan.FromMilliseconds(milliseconds)); + // One song per Openverse result, also if two imports of the same track race. + // SQLite allows any number of rows without an id in a unique index. + song.HasIndex(s => s.OpenverseId).IsUnique(); + } + } } diff --git a/src/Radiosender/Views/Pages/ImportPage.xaml.cs b/src/Radiosender/Views/Pages/ImportPage.xaml.cs index a58aba0..ffec4c9 100644 --- a/src/Radiosender/Views/Pages/ImportPage.xaml.cs +++ b/src/Radiosender/Views/Pages/ImportPage.xaml.cs @@ -232,11 +232,13 @@ public partial class ImportPage : Page _session.Insert(0, SessionRow.Added(song, song.License ?? "")); ReplaceRow(row, row with { Status = "In Bibliothek", CanImport = false }); } - catch (Exception ex) when (ex is OpenverseException or Microsoft.Data.Sqlite.SqliteException) + catch (Exception ex) when (ex is OpenverseException or Microsoft.EntityFrameworkCore.DbUpdateException) { - _session.Insert(0, SessionRow.Failed(row.Track.Title, ex.Message)); + // The database error text is technical and English; the usual cause is a song that is already stored. + var reason = ex is OpenverseException ? ex.Message : "Der Song konnte nicht in der Bibliothek gespeichert werden."; + _session.Insert(0, SessionRow.Failed(row.Track.Title, reason)); failed++; - lastError = ex.Message; + lastError = reason; } } } diff --git a/tests/Radiosender.Tests/SongRepositoryTests.cs b/tests/Radiosender.Tests/SongRepositoryTests.cs index e7fd748..8519607 100644 --- a/tests/Radiosender.Tests/SongRepositoryTests.cs +++ b/tests/Radiosender.Tests/SongRepositoryTests.cs @@ -1,4 +1,5 @@ using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; using Radiosender.Models; using Radiosender.Services; @@ -122,7 +123,8 @@ public sealed class SongRepositoryTests : IDisposable var song = NewSong(); song.Duration = TimeSpan.Zero; - Assert.Throws(() => repository.Add(song)); + Assert.Throws(() => repository.Add(song)); + Assert.Empty(repository.GetAll()); } [Fact] @@ -144,12 +146,30 @@ public sealed class SongRepositoryTests : IDisposable var repository = new SongRepository(DatabasePath); repository.Add(new Song { Title = "A", Artist = "", Duration = TimeSpan.FromSeconds(1), FilePath = "a", OpenverseId = "ov-1" }); - Assert.Throws(() => + Assert.Throws(() => repository.Add(new Song { Title = "B", Artist = "", Duration = TimeSpan.FromSeconds(1), FilePath = "b", OpenverseId = "ov-1" })); } [Fact] - public void Constructor_AddsOpenverseIdColumnToOlderDatabase() + public void Update_RejectsZeroDurationAndKeepsTheOpenverseId() + { + var repository = new SongRepository(DatabasePath); + var song = NewSong(); + song.OpenverseId = "ov-1"; + repository.Add(song); + + song.Title = "Renamed"; + song.OpenverseId = "changed"; + Assert.True(repository.Update(song)); + Assert.Equal("ov-1", repository.GetById(song.Id)!.OpenverseId); + + song.Duration = TimeSpan.Zero; + Assert.Throws(() => repository.Update(song)); + } + + // The schema below is what the app created before it used Entity Framework Core; libraries from then must keep working. + [Fact] + public void Constructor_OpensADatabaseFromBeforeEntityFramework() { Directory.CreateDirectory(_directory); using (var connection = new SqliteConnection($"Data Source={DatabasePath}")) @@ -160,18 +180,25 @@ public sealed class SongRepositoryTests : IDisposable CREATE TABLE 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); - INSERT INTO Songs (Title, Artist, DurationMs, FilePath, Source) VALUES ('Old', 'Artist', 1000, 'old.mp3', 0); + Source INTEGER NOT NULL, License TEXT, Attribution TEXT, OpenverseId TEXT); + CREATE UNIQUE INDEX IX_Songs_OpenverseId ON Songs (OpenverseId) WHERE OpenverseId IS NOT NULL; + INSERT INTO Songs (Title, Artist, DurationMs, FilePath, Source, License, OpenverseId) + VALUES ('Old', 'Artist', 185500, 'old.mp3', 1, 'CC BY 4.0', 'ov-old'); """; command.ExecuteNonQuery(); } var repository = new SongRepository(DatabasePath); - var song = NewSong(); - song.OpenverseId = "ov-1"; - repository.Add(song); + var old = Assert.Single(repository.GetAll()); + Assert.Equal("Old", old.Title); + Assert.Equal(TimeSpan.FromSeconds(185.5), old.Duration); + Assert.Equal(SongSource.Openverse, old.Source); + Assert.Equal("ov-old", old.OpenverseId); - Assert.Null(Assert.Single(repository.GetAll(), s => s.Title == "Old").OpenverseId); - Assert.Equal("ov-1", repository.GetById(song.Id)!.OpenverseId); - _ = new SongRepository(DatabasePath); // second start must not try to add the column again + var added = NewSong("New"); + repository.Add(added); + old.Title = "Renamed"; + Assert.True(repository.Update(old)); + Assert.Equal(["New", "Renamed"], repository.GetAll().Select(s => s.Title).Order()); + Assert.True(repository.Delete(added.Id)); }}