Skip to content

Commit

Permalink
Replace Efcore With Dapper + Dbup
Browse files Browse the repository at this point in the history
  • Loading branch information
xBaank committed Aug 14, 2024
1 parent ae4f403 commit 5d42964
Show file tree
Hide file tree
Showing 24 changed files with 192 additions and 1,109 deletions.
13 changes: 10 additions & 3 deletions Console/Audio/PlayerController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ internal class PlayerController(YoutubeClient youtubeClient, SettingsRepository
private readonly AsyncLock _lock = new();
private readonly YoutubeClient _youtubeClient = youtubeClient;
private readonly SettingsRepository _settingsRepository = settingsRepository;
private float _volume = settingsRepository.GetSettings().Volume / 100f;
private float _volume = -1f;
private PlayState _state = PlayState.Stopped;
private List<IVideo> _queue = [];
private int _currentSongIndex = 0;
Expand All @@ -41,7 +41,14 @@ public PlayState State
}
public int Volume
{
get { return (int)(_volume * 100); }
get
{
//Load volume if it wasnt loaded before
if (_volume < 0)
_volume = _settingsRepository.GetSettings().Volume / 100f;

return (int)(_volume * 100);
}
set
{
if (value is < 0 or > 100)
Expand Down Expand Up @@ -104,7 +111,7 @@ public async ValueTask DisposeAsync()
await _audioSender.DisposeAsync().ConfigureAwait(false);
}

await _settingsRepository.DisposeAsync();
_settingsRepository.Dispose();

// Suppress finalization
GC.SuppressFinalize(this);
Expand Down
35 changes: 23 additions & 12 deletions Console/Commands/MainCommand.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
using CliFx;
using System.Data;
using System.Reflection;
using CliFx;
using CliFx.Attributes;
using CliFx.Infrastructure;
using Console.Audio;
using Console.Cookies;
using Console.Database;
using Console.Extensions;
using Console.Repositories;
using Console.Views;
using DbUp;
using Microsoft.Data.Sqlite;
using Microsoft.Extensions.DependencyInjection;
using Terminal.Gui;
using YoutubeExplode;
Expand All @@ -24,9 +27,19 @@ internal class MainCommand : ICommand

public async ValueTask ExecuteAsync(IConsole console)
{
await Utils.ConfigurePlatformDependenciesAsync(console);
const string connectionString = "Data Source=data.db";

Application.Init();
Utils.ConfigurePlatformDependencies();
await console.Output.WriteLineAsync("Ignore any warnings above this message");
await console.Output.WriteLineAsync("[PortAudio] Initialized corretly");

var upgrader = DeployChanges
.To.SQLiteDatabase(connectionString)
.WithScriptsEmbeddedInAssembly(Assembly.GetExecutingAssembly())
.LogToConsole()
.Build();

var result = upgrader.PerformUpgrade();

var top = new Toplevel();

Expand Down Expand Up @@ -104,7 +117,7 @@ public async ValueTask ExecuteAsync(IConsole console)
videosWin.Add(tabView);

var serviceProvider = new ServiceCollection()
.AddScoped<MyDbContext>()
.AddScoped<IDbConnection>(_ => new SqliteConnection(connectionString))
.AddScoped<LocalPlaylistsRepository>()
.AddScoped<SettingsRepository>()
.AddSingleton<SharedCancellationTokenSource>()
Expand Down Expand Up @@ -190,29 +203,27 @@ public async ValueTask ExecuteAsync(IConsole console)
})
.BuildServiceProvider();

using var dbContext = serviceProvider.GetRequiredService<MyDbContext>();
var statusBarFactory = serviceProvider.GetRequiredService<StatusBarFactory>();
using var settingsRepository = serviceProvider.GetRequiredService<SettingsRepository>();
//TODO change to dapper and use fluent migrations cause this will never work
await dbContext.MigrateAOTAsync("migrations.sql");
await settingsRepository.InitializeAsync();

top.Add(queueWin, searchWin, videosWin, playerWin, statusBarFactory.Create());

Application.Init();

await using var playerController = serviceProvider.GetRequiredService<PlayerController>();
var playerView = serviceProvider.GetRequiredService<PlayerView>();
var queueView = serviceProvider.GetRequiredService<QueueView>();
var videosResultsView = serviceProvider.GetRequiredService<VideosResultsView>();
var recommendationsView = serviceProvider.GetRequiredService<RecommendationsView>();
var videoSearchView = serviceProvider.GetRequiredService<VideoSearchView>();
var localPlaylistsView = serviceProvider.GetRequiredService<LocalPlaylistsView>();
var statusBarFactory = serviceProvider.GetRequiredService<StatusBarFactory>();

videoSearchView.ShowSearch();
playerView.ShowPlayer();
queueView.ShowQueue();
recommendationsView.ShowRecommendations();
localPlaylistsView.ShowLocalPlaylists();
var statusBar = statusBarFactory.Create();

top.Add(queueWin, searchWin, videosWin, playerWin, statusBar);

Application.Run(top);
top.Dispose();
Expand Down
36 changes: 18 additions & 18 deletions Console/Console.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,21 @@
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<InterceptorsPreviewNamespaces>$(InterceptorsPreviewNamespaces);Dapper.AOT</InterceptorsPreviewNamespaces>
</PropertyGroup>
<ItemGroup>
<None Remove="scripts\migrations\2024081401_Initial.sql" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="CliFx" Version="2.3.5" />
<PackageReference Include="Concentus" Version="2.2.2" />
<PackageReference Include="Concentus.Native" Version="1.5.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.7">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="8.0.7" />
<PackageReference Include="Dapper" Version="2.1.35" />
<PackageReference Include="Dapper.AOT" Version="1.0.31" />
<PackageReference Include="Dapper.Contrib" Version="2.0.78" />
<PackageReference Include="dbup-sqlite" Version="5.0.40" />
<PackageReference Include="Lazy.Fody" Version="1.11.0" />
<PackageReference Include="Microsoft.Data.Sqlite" Version="8.0.8" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Nito.AsyncEx" Version="5.1.2" />
<PackageReference Include="PortAudioSharp" Version="0.3.0" />
Expand All @@ -29,6 +34,11 @@
<ItemGroup>
<InternalsVisibleTo Include="Tests" />
</ItemGroup>

<ItemGroup>
<EmbeddedResource Include="Scripts/Migrations/*.sql" />
</ItemGroup>


<PropertyGroup>
<PortAudioPlatform>$(RuntimeIdentifier)</PortAudioPlatform>
Expand All @@ -41,20 +51,10 @@
<PortAudioPlatform Condition="'$(PortAudioPlatform)' == '' AND $([MSBuild]::IsOsPlatform('OSX')) AND '$([System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture)' == 'Arm64'">osx-arm64</PortAudioPlatform>
<PortAudioPlatform Condition="'$(PortAudioPlatform)' == '' AND $([MSBuild]::IsOsPlatform('OSX')) AND '$([System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture)' == 'X64'">osx-x64</PortAudioPlatform>
<PortAudioFileName Condition="$(PortAudioPlatform.StartsWith('win-'))">portaudio.dll</PortAudioFileName>
<PortAudioFileName Condition="$(PortAudioPlatform.StartsWith('linux-'))">libportaudio.so</PortAudioFileName>
<PortAudioFileName Condition="'$(PortAudioFileName)' == ''">libportaudio.dylib</PortAudioFileName>
<PortAudioFileName Condition="$(PortAudioPlatform.StartsWith('linux-x'))">libportaudio.so</PortAudioFileName>
<PortAudioFileName Condition="$(PortAudioPlatform.StartsWith('linux-arm'))">libportaudio.a</PortAudioFileName>
<PortAudioFileName Condition="$(PortAudioPlatform.StartsWith('osx-'))">libportaudio.dylib</PortAudioFileName>
</PropertyGroup>

<Target Name="GenerateMigrationsAfterBuild" AfterTargets="Build">
<Exec Command="dotnet ef migrations script -o migrations.sql --no-build" LogStandardErrorAsError="true" />
<Copy SourceFiles="$(ProjectDir)/migrations.sql" DestinationFolder="$(OutDir)" SkipUnchangedFiles="true" />
</Target>

<!-- Generate migrations after publish -->
<Target Name="GenerateMigrationsAfterPublish" AfterTargets="Publish">
<Exec Command="dotnet ef migrations script -o migrations.sql --no-build" LogStandardErrorAsError="true" />
<Copy SourceFiles="$(ProjectDir)/migrations.sql" DestinationFolder="$(PublishDir)" SkipUnchangedFiles="true" />
</Target>

<Target Name="Download PortAudio before build" BeforeTargets="PreBuildEvent">
<Exec Command="powershell -ExecutionPolicy Bypass -File &quot;$(ProjectDir)/DownloadPortAudioBin.ps1&quot; -Platform $(PortAudioPlatform) -OutputPath &quot;$(ProjectDir)/$(PortAudioFileName)&quot;" LogStandardErrorAsError="true" />
Expand Down
5 changes: 3 additions & 2 deletions Console/Database/LocalPlaylist.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
using Microsoft.EntityFrameworkCore;
using Dapper.Contrib.Extensions;

namespace Console.Database;

[PrimaryKey("PlaylistId")]
internal class LocalPlaylist
{
[Key]
public int PlaylistId { get; set; }
public required string Name { get; set; }

// Navigation property for the many-to-many relationship
[Computed]
public ICollection<LocalPlaylistSong> PlaylistSongs { get; set; } = [];

public override string ToString() => Name ?? "";
Expand Down
22 changes: 17 additions & 5 deletions Console/Database/LocalSong.cs
Original file line number Diff line number Diff line change
@@ -1,24 +1,36 @@
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.EntityFrameworkCore;
using Dapper.Contrib.Extensions;
using Lazy;
using YoutubeExplode.Common;
using YoutubeExplode.Videos;

namespace Console.Database;

[PrimaryKey("Id")]
internal class LocalSong : IVideo
{
[Key]
public required string Id { get; set; }
public required string Url { get; set; }
public required string Title { get; set; }
public required string ChannelId { get; set; }
public required string ChannelTitle { get; set; }
public required TimeSpan? Duration { get; set; }
public required double DurationMiliseconds { get; set; }

[NotMapped]
[Computed]
[Lazy]
public TimeSpan? Duration => TimeSpan.FromMilliseconds(DurationMiliseconds);

[Computed]
//Not saved for now, only to satisfy IVideo
public IReadOnlyList<Thumbnail> Thumbnails { get; } = [];

[Computed]
public ICollection<LocalPlaylistSong>? PlaylistSongs { get; set; }

[Computed]
[Lazy]
VideoId IVideo.Id => new(Id);

[Computed]
[Lazy]
Author IVideo.Author => new(ChannelId, ChannelTitle);
}
41 changes: 0 additions & 41 deletions Console/Database/MyDbContext.cs

This file was deleted.

4 changes: 2 additions & 2 deletions Console/Database/Setting.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
using Microsoft.EntityFrameworkCore;
using Dapper.Contrib.Extensions;

namespace Console.Database;

[PrimaryKey("Id")]
internal class Setting
{
[Key]
public int Id { get; set; }
public int Volume { get; set; }
}
15 changes: 0 additions & 15 deletions Console/Extensions/MyDbContextExtensions.cs

This file was deleted.

Loading

0 comments on commit 5d42964

Please sign in to comment.