chore: format with csharpier

This commit is contained in:
sam 2024-10-09 17:35:11 +02:00
parent 2f516dcb73
commit 4f54077c68
59 changed files with 2000 additions and 942 deletions

View file

@ -17,7 +17,9 @@ public static class DiscordExtensions
public static string Tag(this IPartialUser user)
{
var discriminator = user.Discriminator.OrDefault();
return discriminator == 0 ? user.Username.Value : $"{user.Username.Value}#{discriminator:0000}";
return discriminator == 0
? user.Username.Value
: $"{user.Username.Value}#{discriminator:0000}";
}
public static string AvatarUrl(this IUser user, int size = 256)
@ -28,13 +30,15 @@ public static class DiscordExtensions
return $"https://cdn.discordapp.com/avatars/{user.ID}/{user.Avatar.Value}{ext}?size={size}";
}
var avatarIndex = user.Discriminator == 0 ? (int)((user.ID.Value >> 22) % 6) : user.Discriminator % 5;
var avatarIndex =
user.Discriminator == 0 ? (int)((user.ID.Value >> 22) % 6) : user.Discriminator % 5;
return $"https://cdn.discordapp.com/embed/avatars/{avatarIndex}.png?size={size}";
}
public static string? IconUrl(this IGuild guild, int size = 256)
{
if (guild.Icon == null) return null;
if (guild.Icon == null)
return null;
var ext = guild.Icon.HasGif ? ".gif" : ".webp";
@ -45,7 +49,8 @@ public static class DiscordExtensions
public static ulong ToUlong(this Optional<Snowflake> snowflake)
{
if (!snowflake.IsDefined()) throw new Exception("ToUlong called on an undefined Snowflake");
if (!snowflake.IsDefined())
throw new Exception("ToUlong called on an undefined Snowflake");
return snowflake.Value.Value;
}
@ -58,40 +63,64 @@ public static class DiscordExtensions
return $"#{r}{g}{b}";
}
public static bool Is(this Optional<Snowflake> s1, Snowflake s2) => s1.IsDefined(out var value) && value == s2;
public static bool Is(this Optional<Snowflake> s1, ulong s2) => s1.IsDefined(out var value) && value == s2;
public static bool Is(this Optional<Snowflake> s1, Snowflake s2) =>
s1.IsDefined(out var value) && value == s2;
public static bool Is(this Optional<Snowflake> s1, ulong s2) =>
s1.IsDefined(out var value) && value == s2;
public static T GetOrThrow<T>(this Result<T> result)
{
if (result.Error != null) throw new DiscordRestException(result.Error.Message);
if (result.Error != null)
throw new DiscordRestException(result.Error.Message);
return result.Entity;
}
public static T GetOrThrow<T>(this Optional<T> optional) =>
optional.OrThrow(() => new CataloggerError("Optional<T> was unset"));
public static async Task<T> GetOrThrow<T>(this Task<Result<T>> result) => (await result).GetOrThrow();
public static async Task<T> GetOrThrow<T>(this Task<Result<T>> result) =>
(await result).GetOrThrow();
public static async Task<Result> UpdateMessageAsync(this IDiscordRestInteractionAPI interactionApi,
IInteraction interaction, InteractionMessageCallbackData data) =>
await interactionApi.CreateInteractionResponseAsync(interaction.ID,
public static async Task<Result> UpdateMessageAsync(
this IDiscordRestInteractionAPI interactionApi,
IInteraction interaction,
InteractionMessageCallbackData data
) =>
await interactionApi.CreateInteractionResponseAsync(
interaction.ID,
interaction.Token,
new InteractionResponse(InteractionCallbackType.UpdateMessage,
new Optional<OneOf<IInteractionMessageCallbackData, IInteractionAutocompleteCallbackData,
IInteractionModalCallbackData>>(data)));
new InteractionResponse(
InteractionCallbackType.UpdateMessage,
new Optional<
OneOf<
IInteractionMessageCallbackData,
IInteractionAutocompleteCallbackData,
IInteractionModalCallbackData
>
>(data)
)
);
public static string ToPrettyString(this IDiscordPermissionSet permissionSet) =>
string.Join(", ", permissionSet.GetPermissions().Select(p => p.Humanize(LetterCasing.Title)));
string.Join(
", ",
permissionSet.GetPermissions().Select(p => p.Humanize(LetterCasing.Title))
);
public static (Snowflake, Snowflake) GetUserAndGuild(this ContextInjectionService contextInjectionService)
public static (Snowflake, Snowflake) GetUserAndGuild(
this ContextInjectionService contextInjectionService
)
{
if (contextInjectionService.Context is not IInteractionCommandContext ctx)
throw new CataloggerError("No context");
if (!ctx.TryGetUserID(out var userId)) throw new CataloggerError("No user ID in context");
if (!ctx.TryGetGuildID(out var guildId)) throw new CataloggerError("No guild ID in context");
if (!ctx.TryGetUserID(out var userId))
throw new CataloggerError("No user ID in context");
if (!ctx.TryGetGuildID(out var guildId))
throw new CataloggerError("No guild ID in context");
return (userId, guildId);
}
/// <summary>
/// Sorts a list of roles by their position in the Discord interface.
/// </summary>
@ -99,12 +128,14 @@ public static class DiscordExtensions
/// <param name="filterByIds">An optional list of role IDs to return, from a member object or similar.
/// If null, the entire list is returned.</param>
/// <returns></returns>
public static IEnumerable<IRole> Sorted(this IEnumerable<IRole> roles,
IEnumerable<Snowflake>? filterByIds = null)
public static IEnumerable<IRole> Sorted(
this IEnumerable<IRole> roles,
IEnumerable<Snowflake>? filterByIds = null
)
{
var sorted = roles.OrderByDescending(r => r.Position);
return filterByIds != null ? sorted.Where(r => filterByIds.Contains(r.ID)) : sorted;
}
public class DiscordRestException(string message) : Exception(message);
}
}

View file

@ -27,7 +27,10 @@ public static class StartupExtensions
/// <summary>
/// Adds Serilog to this service collection. This method also initializes Serilog, so it should be called as early as possible, before any log calls.
/// </summary>
public static WebApplicationBuilder AddSerilog(this WebApplicationBuilder builder, Config config)
public static WebApplicationBuilder AddSerilog(
this WebApplicationBuilder builder,
Config config
)
{
var logCfg = new LoggerConfiguration()
.Enrich.FromLogContext()
@ -35,8 +38,10 @@ public static class StartupExtensions
// ASP.NET's built in request logs are extremely verbose, so we use Serilog's instead.
// Serilog doesn't disable the built-in logs, so we do it here.
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.MinimumLevel.Override("Microsoft.EntityFrameworkCore.Database.Command",
config.Logging.LogQueries ? LogEventLevel.Information : LogEventLevel.Fatal)
.MinimumLevel.Override(
"Microsoft.EntityFrameworkCore.Database.Command",
config.Logging.LogQueries ? LogEventLevel.Information : LogEventLevel.Fatal
)
.MinimumLevel.Override("Microsoft.AspNetCore.Hosting", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.AspNetCore.Mvc", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.AspNetCore.Routing", LogEventLevel.Warning)
@ -69,32 +74,43 @@ public static class StartupExtensions
.AddEnvironmentVariables();
}
public static IServiceCollection AddCustomServices(this IServiceCollection services) => services
.AddSingleton<IClock>(SystemClock.Instance)
.AddSingleton<GuildCache>()
.AddSingleton<RoleCache>()
.AddSingleton<ChannelCache>()
.AddSingleton<UserCache>()
.AddSingleton<AuditLogCache>()
.AddSingleton<PluralkitApiService>()
.AddScoped<IEncryptionService, EncryptionService>()
.AddSingleton<MetricsCollectionService>()
.AddSingleton<AuditLogEnrichedResponderService>()
.AddScoped<MessageRepository>()
.AddSingleton<WebhookExecutorService>()
.AddSingleton<PkMessageHandler>()
.AddSingleton(InMemoryDataService<Snowflake, ChannelCommandData>.Instance)
.AddSingleton<GuildFetchService>()
.AddHostedService(serviceProvider => serviceProvider.GetRequiredService<GuildFetchService>());
public static IServiceCollection AddCustomServices(this IServiceCollection services) =>
services
.AddSingleton<IClock>(SystemClock.Instance)
.AddSingleton<GuildCache>()
.AddSingleton<RoleCache>()
.AddSingleton<ChannelCache>()
.AddSingleton<UserCache>()
.AddSingleton<AuditLogCache>()
.AddSingleton<PluralkitApiService>()
.AddScoped<IEncryptionService, EncryptionService>()
.AddSingleton<MetricsCollectionService>()
.AddSingleton<AuditLogEnrichedResponderService>()
.AddScoped<MessageRepository>()
.AddSingleton<WebhookExecutorService>()
.AddSingleton<PkMessageHandler>()
.AddSingleton(InMemoryDataService<Snowflake, ChannelCommandData>.Instance)
.AddSingleton<GuildFetchService>()
.AddHostedService(serviceProvider =>
serviceProvider.GetRequiredService<GuildFetchService>()
);
public static IHostBuilder AddShardedDiscordService(this IHostBuilder builder,
Func<IServiceProvider, string> tokenFactory) =>
builder.ConfigureServices((_, services) => services
.AddDiscordGateway(tokenFactory)
.AddSingleton<ShardedGatewayClient>()
.AddHostedService<ShardedDiscordService>());
public static IHostBuilder AddShardedDiscordService(
this IHostBuilder builder,
Func<IServiceProvider, string> tokenFactory
) =>
builder.ConfigureServices(
(_, services) =>
services
.AddDiscordGateway(tokenFactory)
.AddSingleton<ShardedGatewayClient>()
.AddHostedService<ShardedDiscordService>()
);
public static IServiceCollection MaybeAddRedisCaches(this IServiceCollection services, Config config)
public static IServiceCollection MaybeAddRedisCaches(
this IServiceCollection services,
Config config
)
{
if (config.Database.Redis == null)
{
@ -104,7 +120,8 @@ public static class StartupExtensions
.AddSingleton<IInviteCache, InMemoryInviteCache>();
}
return services.AddSingleton<RedisService>()
return services
.AddSingleton<RedisService>()
.AddSingleton<IWebhookCache, RedisWebhookCache>()
.AddSingleton<IMemberCache, RedisMemberCache>()
.AddSingleton<IInviteCache, RedisInviteCache>();
@ -116,7 +133,9 @@ public static class StartupExtensions
var logger = scope.ServiceProvider.GetRequiredService<ILogger>().ForContext<Program>();
logger.Information("Starting Catalogger.NET");
CataloggerMetrics.Startup = scope.ServiceProvider.GetRequiredService<IClock>().GetCurrentInstant();
CataloggerMetrics.Startup = scope
.ServiceProvider.GetRequiredService<IClock>()
.GetCurrentInstant();
await using (var db = scope.ServiceProvider.GetRequiredService<DatabaseContext>())
{
@ -126,7 +145,8 @@ public static class StartupExtensions
logger.Information("Applying {Count} database migrations", migrationCount);
await db.Database.MigrateAsync();
}
else logger.Information("There are no pending migrations");
else
logger.Information("There are no pending migrations");
}
var config = scope.ServiceProvider.GetRequiredService<Config>();
@ -135,20 +155,28 @@ public static class StartupExtensions
if (config.Discord.ApplicationId == 0)
{
logger.Warning(
"Application ID not set in config. Fetching and setting it now, but for future restarts, please add it to config.ini as Discord.ApplicationId.");
"Application ID not set in config. Fetching and setting it now, but for future restarts, please add it to config.ini as Discord.ApplicationId."
);
var restApi = scope.ServiceProvider.GetRequiredService<IDiscordRestApplicationAPI>();
var application = await restApi.GetCurrentApplicationAsync().GetOrThrow();
config.Discord.ApplicationId = application.ID.ToUlong();
logger.Information("Current application ID is {ApplicationId}", config.Discord.ApplicationId);
logger.Information(
"Current application ID is {ApplicationId}",
config.Discord.ApplicationId
);
}
if (config.Discord.SyncCommands)
{
if (config.Discord.CommandsGuildId != null)
{
logger.Information("Syncing application commands with guild {GuildId}", config.Discord.CommandsGuildId);
logger.Information(
"Syncing application commands with guild {GuildId}",
config.Discord.CommandsGuildId
);
await slashService.UpdateSlashCommandsAsync(
guildID: DiscordSnowflake.New(config.Discord.CommandsGuildId.Value));
guildID: DiscordSnowflake.New(config.Discord.CommandsGuildId.Value)
);
}
else
{
@ -156,6 +184,9 @@ public static class StartupExtensions
await slashService.UpdateSlashCommandsAsync();
}
}
else logger.Information("Not syncing slash commands, Discord.SyncCommands is false or unset");
else
logger.Information(
"Not syncing slash commands, Discord.SyncCommands is false or unset"
);
}
}
}

View file

@ -12,9 +12,11 @@ public static class TimeExtensions
public static string Prettify(this Duration duration, TimeUnit minUnit = TimeUnit.Minute) =>
duration.ToTimeSpan().Prettify(minUnit);
public static string Prettify(this DateTimeOffset datetime, TimeUnit minUnit = TimeUnit.Minute) =>
(datetime - DateTimeOffset.Now).Prettify(minUnit);
public static string Prettify(
this DateTimeOffset datetime,
TimeUnit minUnit = TimeUnit.Minute
) => (datetime - DateTimeOffset.Now).Prettify(minUnit);
public static string Prettify(this Instant instant, TimeUnit minUnit = TimeUnit.Minute) =>
(instant - SystemClock.Instance.GetCurrentInstant()).Prettify(minUnit);
}
}