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 <noreply@anthropic.com>
This commit is contained in:
fraujulianandClaude Fable 5.2 committed 2026-11-23 14:40:12 +01:00
1 parent 7cdc3b3a41
commit 65743279b1
5 files changed
+106 -120

No files matched your search

+3 -2
View File
@@ -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.
+1 -1
View File
@@ -9,7 +9,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Data.Sqlite" Version="10.0.15" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.15" />
<PackageReference Include="NAudio" Version="3.3.0" />
<PackageReference Include="TagLibSharp" Version="2.3.0" />
<PackageReference Include="WPF-UI" Version="4.3.0" />
+59 -103
View File
@@ -1,156 +1,112 @@
using System.IO;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Radiosender.Models;
namespace Radiosender.Services;
/// <summary>
/// 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.
/// </summary>
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<LibraryContext> _options;
public SongRepository(string databasePath)
{
Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(databasePath))!);
_connectionString = new SqliteConnectionStringBuilder { DataSource = databasePath }.ToString();
_options = new DbContextOptionsBuilder<LibraryContext>()
.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();
}
/// <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;
using var context = Open();
return context.Songs.Where(s => s.OpenverseId != null).Select(s => s.OpenverseId!).ToHashSet();
}
public IReadOnlyList<Song> 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<Song>();
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);
}
/// <summary>Inserts the song and sets its <see cref="Song.Id"/>.</summary>
/// <exception cref="ArgumentException">The song has no duration.</exception>
/// <exception cref="DbUpdateException">The database rejected the song, e.g. a second song with the same Openverse id.</exception>
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();
}
/// <summary>Stores everything except the Openverse id, which never changes after the import.</summary>
/// <returns><c>false</c> if no song with this id exists.</returns>
/// <exception cref="ArgumentException">The song has no duration.</exception>
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;
}
/// <returns><c>false</c> if no song with this id exists.</returns>
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)
/// <summary>Maps <see cref="Song"/> to the table <c>Songs</c>.</summary>
private sealed class LibraryContext(DbContextOptions<LibraryContext> 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<Song> Songs => Set<Song>();
private static Song Read(SqliteDataReader reader) => new()
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
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),
};
var song = modelBuilder.Entity<Song>();
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();
}
}
}
@@ -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;
}
}
}
+38 -11
View File
@@ -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<SqliteException>(() => repository.Add(song));
Assert.Throws<ArgumentException>(() => 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<SqliteException>(() =>
Assert.Throws<DbUpdateException>(() =>
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<ArgumentException>(() => 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));
}}