Skip to content

Commit

Permalink
refactor: Various refactors
Browse files Browse the repository at this point in the history
- Made the `ConsoleRunnerContext` class sealed.
- Renamed the `SerilogConfiguration` variable to `_serilogConfiguration`.
- Updated the `Main` method in the `Program.cs` file to accept command line arguments.
- Renamed the `CreateHostBuilder` method parameter from `_` to `args`.
- Added a new extension method, `AddYumeCoreServices`, to configure custom services for running the YumeCore application.
- Updated the constructor of the `ComponentActivator` class to use field initialization syntax.
- Made the `NetRunnerContext` class sealed.
- Renamed the `_loggerConfiguration` variable in the `Program.cs` file to `_loggerConfiguration`.
- Removed commented out code related to container configuration in the `CreateHostBuilder` method.
- Removed unused using statements in various files.
  • Loading branch information
SakuraIsayeki committed Sep 22, 2023
1 parent 1e58e0d commit 4941c2a
Show file tree
Hide file tree
Showing 10 changed files with 46 additions and 31 deletions.
2 changes: 1 addition & 1 deletion src/YumeChan.ConsoleRunner/ConsoleRunnerContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@

namespace YumeChan.ConsoleRunner;

internal record ConsoleRunnerContext(RunnerType RunnerType, string RunnerName, string RunnerVersion) : IRunnerContext;
internal sealed record ConsoleRunnerContext(RunnerType RunnerType, string RunnerName, string RunnerVersion) : IRunnerContext;
10 changes: 5 additions & 5 deletions src/YumeChan.ConsoleRunner/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ namespace YumeChan.ConsoleRunner;

public static class Program
{
private static readonly LoggerConfiguration SerilogConfiguration = new LoggerConfiguration()
private static readonly LoggerConfiguration _serilogConfiguration = new LoggerConfiguration()
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.MinimumLevel.Override("DSharpPlus", LogEventLevel.Information)
Expand All @@ -24,13 +24,13 @@ public static class Program

private static readonly string _informationalVersion = Assembly.GetEntryAssembly()?.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;

public static async Task Main(string[] _)
public static async Task Main(string[] args)
{


Log.Logger = SerilogConfiguration.CreateLogger();
Log.Logger = _serilogConfiguration.CreateLogger();

IHost host = CreateHostBuilder().Build();
IHost host = CreateHostBuilder(args).Build();

await using AsyncServiceScope scope = host.Services.CreateAsyncScope();
IServiceProvider services = scope.ServiceProvider;
Expand All @@ -46,7 +46,7 @@ public static async Task Main(string[] _)
await host.WaitForShutdownAsync();
}

public static IHostBuilder CreateHostBuilder() => new HostBuilder()
public static IHostBuilder CreateHostBuilder(string[] args) => new HostBuilder()
.UseServiceProviderFactory(new DryIocServiceProviderFactory())
.ConfigureLogging(static x => x.ClearProviders())
.UseSerilog()
Expand Down
2 changes: 1 addition & 1 deletion src/YumeChan.Core/CommandHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,7 @@ private async Task OnSlashCommandErroredAsync(SlashCommandsExtension _, SlashCom
SlashRequireGuildAttribute => "Sorry, not here. Please send this command in a server.",
// SlashRequireNsfwAttribute => "Sorry. As much as I'd love to, I've gotta keep the hot stuff to the right channels.",
// SlashCooldownAttribute cd => $"Sorry. This command is on Cooldown. You can use it {cd.MaxUses} time(s) every {cd.Reset.TotalSeconds} seconds.",
SlashRequireUserPermissionsAttribute p => $"Sorry. You need to have permission(s) ``{p.Permissions}`` to run this.",
SlashRequireUserPermissionsAttribute p => $"Sorry. You need to have permission(s) {p.Permissions:F} (``0x{p.Permissions:X}``) to run this.",
_ => null
}).ToArray();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,26 @@ namespace Microsoft.Extensions.DependencyInjection;
/// </summary>
public static class YumeCoreDependencyInjectionExtensions
{
/// <summary>
/// Extension method for <see cref="IServiceCollection"/> to add custom services necessary for running the YumeCore application.
/// This method configures a comprehensive service pipeline including various singleton services, database providers, configuration providers, and an HTTP client.
/// </summary>
/// <param name="services">An instance of <see cref="IServiceCollection"/>.</param>
/// <returns>The same service collection passed in, enabling chained configuration calls.</returns>
///
/// <remarks>
/// <para>Components added to the DI pipeline:</para>
/// <list type="bullet">
/// <item><description><see cref="YumeCore"/> - a singleton service instance for the application.</description></item>
/// <item><description><see cref="DiscordClient"/> - a singleton service with initial settings for intents, token type, token, logger factory, and minimum log level.</description></item>
/// <item><description><see cref="PluginsLoader"/> - a singleton that loads plugins from the path specified in <see cref="ICoreProperties"/>.</description></item>
/// <item><description>Singleton instances of <see cref="PluginLifetimeListener.Instance"/>, <see cref="CommandHandler"/>, <see cref="LavalinkHandler"/>, <see cref="NuGetPluginsFetcher"/>, and <see cref="DiscordBotTokenProvider"/>.</description></item>
/// <item><description>Services for MongoDB and Postgres are set up using a class <see cref="UnifiedDatabaseProvider"/>, which implements <see cref="IMongoDatabaseProvider"/> and <see cref="IPostgresDatabaseProvider"/>.</description></item>
/// <item><description><see cref="InterfaceConfigProvider"/> and <see cref="JsonConfigProvider"/> generic services provide configuration data.</description></item>
/// <item><description><see cref="ICoreProperties"/> and <see cref="IPluginLoaderProperties"/> instances are added with configurations loaded from 'coreconfig.json' and 'plugins.json' respectively.</description></item>
/// <item><description>An <see cref="HttpClient"/> is registered and configured via the HttpClientFactory for making HTTP requests, and the <see cref="NuGetPluginsFetcher"/> is added to the client.</description></item>
/// </list>
/// </remarks>
public static IServiceCollection AddYumeCoreServices(this IServiceCollection services)
{
services.AddSingleton<YumeCore>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ public sealed class ComponentActivator : IComponentActivator

public ComponentActivator(IContainer container)
{
this._container = container;
_container = container;
}

public IComponent CreateInstance(Type type)
Expand Down
2 changes: 1 addition & 1 deletion src/YumeChan.NetRunner/NetRunnerContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@

namespace YumeChan.NetRunner;

internal record NetRunnerContext(RunnerType RunnerType, string RunnerName, string RunnerVersion) : IRunnerContext;
internal sealed record NetRunnerContext(RunnerType RunnerType, string RunnerName, string RunnerVersion) : IRunnerContext;
24 changes: 10 additions & 14 deletions src/YumeChan.NetRunner/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,16 @@ namespace YumeChan.NetRunner;
public static class Program
{
private static Container _container = new();
private static readonly LoggerConfiguration _loggerConfiguration = new LoggerConfiguration()
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.Hosting.Lifetime", LogEventLevel.Information)
.Enrich.FromLogContext()
.WriteTo.Console();

public static async Task Main(string[] args)
{


Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.Hosting.Lifetime", LogEventLevel.Information)
.Enrich.FromLogContext()
.WriteTo.Console()
.CreateLogger();
Log.Logger = _loggerConfiguration.CreateLogger();

using IHost host = CreateHostBuilder(args).Build();
IServiceProvider services = host.Services;
Expand All @@ -34,15 +32,13 @@ public static async Task Main(string[] args)
yumeCore.StartBotAsync(),
host.RunAsync()
);

await host.WaitForShutdownAsync();
}
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new DryIocServiceProviderFactory())
.ConfigureLogging(x => x.ClearProviders())
.ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup<Startup>())
// .ConfigureContainer<Container>((_, container) => container
// .WithDependencyInjectionAdapter()
// )
.ConfigureContainer<Container>((_, container) => container
.WithDependencyInjectionAdapter()
)
;
}
4 changes: 1 addition & 3 deletions src/YumeChan.NetRunner/Services/Authentication/UserRoles.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,5 @@

public static class UserRoles
{
public const string
Admin = "Admin"
;
public const string Admin = "Admin";
}
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
using DSharpPlus;
using Microsoft.AspNetCore.Authentication;
using System.Security.Claims;
using Microsoft.Extensions.Configuration;

namespace YumeChan.NetRunner.Services.Authentication;

public class WebAppClaims : IClaimsTransformation
public sealed class WebAppClaims : IClaimsTransformation
{
private readonly DiscordClient _client;

public WebAppClaims(DiscordClient client, IConfiguration config)
public WebAppClaims(DiscordClient client)
{
_client = client;
}
Expand Down
6 changes: 4 additions & 2 deletions src/YumeChan.NetRunner/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,10 @@ public void ConfigureServices(IServiceCollection services)
})
.AddDiscord(options =>
{
options.ClientId = Configuration["DiscordAuth:ClientId"];
options.ClientSecret = Configuration["DiscordAuth:ClientSecret"];
Configuration.GetSection("DiscordAuth").Bind(options);
// options.ClientId = Configuration["DiscordAuth:ClientId"];
// options.ClientSecret = Configuration["DiscordAuth:ClientSecret"];
options.CallbackPath = "/signin-oauth2";
options.Scope.Add("identify");
Expand Down

0 comments on commit 4941c2a

Please sign in to comment.