Using declarations and other code reformats

This commit is contained in:
Kwoth
2021-12-26 03:22:45 +01:00
parent d18f9429c6
commit b85ba177cd
64 changed files with 2349 additions and 2736 deletions

View File

@@ -1,4 +1,24 @@
[*]
charset = utf-8-bom
end_of_line = crlf
trim_trailing_whitespace = false
insert_final_newline = false
indent_style = space
indent_size = 4
[{*.har,*.inputactions,*.jsb2,*.jsb3,*.json,.babelrc,.eslintrc,.stylelintrc,bowerrc,jest.config}]
indent_style = space
indent_size = 2
[{*.yaml,*.yml}]
indent_style = space
indent_size = 2
[*.proto]
indent_style = space
indent_size = 2
[*.{appxmanifest,asax,ascx,aspx,axaml,build,cg,cginc,compute,cs,cshtml,dtd,hlsl,hlsli,hlslinc,master,nuspec,paml,razor,resw,resx,shader,skin,usf,ush,vb,xaml,xamlx,xoml,xsd}] [*.{appxmanifest,asax,ascx,aspx,axaml,build,cg,cginc,compute,cs,cshtml,dtd,hlsl,hlsli,hlslinc,master,nuspec,paml,razor,resw,resx,shader,skin,usf,ush,vb,xaml,xamlx,xoml,xsd}]
indent_style = space indent_style = space
indent_size = 4 indent_size = 4
@@ -24,28 +44,15 @@ dotnet_naming_rule.private_constants_rule.import_to_resharper = as_predefined
dotnet_naming_rule.private_constants_rule.severity = suggestion dotnet_naming_rule.private_constants_rule.severity = suggestion
dotnet_naming_rule.private_constants_rule.style = all_upper_style dotnet_naming_rule.private_constants_rule.style = all_upper_style
dotnet_naming_rule.private_constants_rule.symbols = private_constants_symbols dotnet_naming_rule.private_constants_rule.symbols = private_constants_symbols
dotnet_naming_rule.private_static_readonly_rule.import_to_resharper = as_predefined
dotnet_naming_rule.private_static_readonly_rule.resharper_style = _ + aaBb, aaBb
dotnet_naming_rule.private_static_readonly_rule.severity = suggestion
dotnet_naming_rule.private_static_readonly_rule.style = lower_camel_case_style_1
dotnet_naming_rule.private_static_readonly_rule.symbols = private_static_readonly_symbols
dotnet_naming_rule.unity_serialized_field_rule.import_to_resharper = True dotnet_naming_rule.unity_serialized_field_rule.import_to_resharper = True
dotnet_naming_rule.unity_serialized_field_rule.resharper_description = Unity serialized field dotnet_naming_rule.unity_serialized_field_rule.resharper_description = Unity serialized field
dotnet_naming_rule.unity_serialized_field_rule.resharper_guid = 5f0fdb63-c892-4d2c-9324-15c80b22a7ef dotnet_naming_rule.unity_serialized_field_rule.resharper_guid = 5f0fdb63-c892-4d2c-9324-15c80b22a7ef
dotnet_naming_rule.unity_serialized_field_rule.severity = suggestion dotnet_naming_rule.unity_serialized_field_rule.severity = suggestion
dotnet_naming_rule.unity_serialized_field_rule.style = lower_camel_case_style dotnet_naming_rule.unity_serialized_field_rule.style = lower_camel_case_style
dotnet_naming_rule.unity_serialized_field_rule.symbols = unity_serialized_field_symbols dotnet_naming_rule.unity_serialized_field_rule.symbols = unity_serialized_field_symbols
dotnet_naming_rule.unity_serialized_field_rule_1.import_to_resharper = True
dotnet_naming_rule.unity_serialized_field_rule_1.resharper_description = Unity serialized field
dotnet_naming_rule.unity_serialized_field_rule_1.resharper_guid = 5f0fdb63-c892-4d2c-9324-15c80b22a7ef
dotnet_naming_rule.unity_serialized_field_rule_1.severity = suggestion
dotnet_naming_rule.unity_serialized_field_rule_1.style = lower_camel_case_style
dotnet_naming_rule.unity_serialized_field_rule_1.symbols = unity_serialized_field_symbols_1
dotnet_naming_style.all_upper_style.capitalization = all_upper dotnet_naming_style.all_upper_style.capitalization = all_upper
dotnet_naming_style.all_upper_style.word_separator = _ dotnet_naming_style.all_upper_style.word_separator = _
dotnet_naming_style.lower_camel_case_style.capitalization = camel_case dotnet_naming_style.lower_camel_case_style.capitalization = camel_case
dotnet_naming_style.lower_camel_case_style_1.capitalization = camel_case
dotnet_naming_style.lower_camel_case_style_1.required_prefix = _
dotnet_naming_symbols.constants_symbols.applicable_accessibilities = public,internal,protected,protected_internal,private_protected dotnet_naming_symbols.constants_symbols.applicable_accessibilities = public,internal,protected,protected_internal,private_protected
dotnet_naming_symbols.constants_symbols.applicable_kinds = field dotnet_naming_symbols.constants_symbols.applicable_kinds = field
dotnet_naming_symbols.constants_symbols.required_modifiers = const dotnet_naming_symbols.constants_symbols.required_modifiers = const
@@ -55,17 +62,10 @@ dotnet_naming_symbols.local_constants_symbols.required_modifiers = const
dotnet_naming_symbols.private_constants_symbols.applicable_accessibilities = private dotnet_naming_symbols.private_constants_symbols.applicable_accessibilities = private
dotnet_naming_symbols.private_constants_symbols.applicable_kinds = field dotnet_naming_symbols.private_constants_symbols.applicable_kinds = field
dotnet_naming_symbols.private_constants_symbols.required_modifiers = const dotnet_naming_symbols.private_constants_symbols.required_modifiers = const
dotnet_naming_symbols.private_static_readonly_symbols.applicable_accessibilities = private
dotnet_naming_symbols.private_static_readonly_symbols.applicable_kinds = field
dotnet_naming_symbols.private_static_readonly_symbols.required_modifiers = static,readonly
dotnet_naming_symbols.unity_serialized_field_symbols.applicable_accessibilities = * dotnet_naming_symbols.unity_serialized_field_symbols.applicable_accessibilities = *
dotnet_naming_symbols.unity_serialized_field_symbols.applicable_kinds = dotnet_naming_symbols.unity_serialized_field_symbols.applicable_kinds =
dotnet_naming_symbols.unity_serialized_field_symbols.resharper_applicable_kinds = unity_serialised_field dotnet_naming_symbols.unity_serialized_field_symbols.resharper_applicable_kinds = unity_serialised_field
dotnet_naming_symbols.unity_serialized_field_symbols.resharper_required_modifiers = instance dotnet_naming_symbols.unity_serialized_field_symbols.resharper_required_modifiers = instance
dotnet_naming_symbols.unity_serialized_field_symbols_1.applicable_accessibilities = *
dotnet_naming_symbols.unity_serialized_field_symbols_1.applicable_kinds =
dotnet_naming_symbols.unity_serialized_field_symbols_1.resharper_applicable_kinds = unity_serialised_field
dotnet_naming_symbols.unity_serialized_field_symbols_1.resharper_required_modifiers = instance
dotnet_style_parentheses_in_arithmetic_binary_operators = never_if_unnecessary:none dotnet_style_parentheses_in_arithmetic_binary_operators = never_if_unnecessary:none
dotnet_style_parentheses_in_other_binary_operators = never_if_unnecessary:none dotnet_style_parentheses_in_other_binary_operators = never_if_unnecessary:none
dotnet_style_parentheses_in_relational_binary_operators = never_if_unnecessary:none dotnet_style_parentheses_in_relational_binary_operators = never_if_unnecessary:none

View File

@@ -1,7 +1,7 @@
namespace NadekoBot.Common.Attributes; namespace NadekoBot.Common.Attributes;
[AttributeUsage(AttributeTargets.Class)] [AttributeUsage(AttributeTargets.Class)]
sealed class NadekoModuleAttribute : GroupAttribute internal sealed class NadekoModuleAttribute : GroupAttribute
{ {
public NadekoModuleAttribute(string moduleName) : base(moduleName) public NadekoModuleAttribute(string moduleName) : base(moduleName)
{ {

View File

@@ -4,7 +4,7 @@ namespace NadekoBot.Common;
public class NadekoRandom : Random public class NadekoRandom : Random
{ {
readonly RandomNumberGenerator _rng; private readonly RandomNumberGenerator _rng;
public NadekoRandom() : base() public NadekoRandom() : base()
{ {

View File

@@ -9,15 +9,13 @@ public static class OptionsParser
public static (T, bool) ParseFrom<T>(T options, string[] args) where T : INadekoCommandOptions public static (T, bool) ParseFrom<T>(T options, string[] args) where T : INadekoCommandOptions
{ {
using (var p = new Parser(x => using var p = new Parser(x =>
{ {
x.HelpWriter = null; x.HelpWriter = null;
})) });
{
var res = p.ParseArguments<T>(args); var res = p.ParseArguments<T>(args);
options = res.MapResult(x => x, x => options); options = res.MapResult(x => x, x => options);
options.NormalizeOptions(); options.NormalizeOptions();
return (options, res.Tag == ParserResultType.Parsed); return (options, res.Tag == ParserResultType.Parsed);
} }
}
} }

View File

@@ -32,14 +32,12 @@ public class AdministrationService : INService
public (bool DelMsgOnCmd, IEnumerable<DelMsgOnCmdChannel> channels) GetDelMsgOnCmdData(ulong guildId) public (bool DelMsgOnCmd, IEnumerable<DelMsgOnCmdChannel> channels) GetDelMsgOnCmdData(ulong guildId)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var conf = uow.GuildConfigsForId(guildId, var conf = uow.GuildConfigsForId(guildId,
set => set.Include(x => x.DelMsgOnCmdChannels)); set => set.Include(x => x.DelMsgOnCmdChannels));
return (conf.DeleteMessageOnCommand, conf.DelMsgOnCmdChannels); return (conf.DeleteMessageOnCommand, conf.DelMsgOnCmdChannels);
} }
}
private Task DelMsgOnCmd_Handler(IUserMessage msg, CommandInfo cmd) private Task DelMsgOnCmd_Handler(IUserMessage msg, CommandInfo cmd)
{ {
@@ -70,13 +68,11 @@ public class AdministrationService : INService
public bool ToggleDeleteMessageOnCommand(ulong guildId) public bool ToggleDeleteMessageOnCommand(ulong guildId)
{ {
bool enabled; bool enabled;
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var conf = uow.GuildConfigsForId(guildId, set => set); var conf = uow.GuildConfigsForId(guildId, set => set);
enabled = conf.DeleteMessageOnCommand = !conf.DeleteMessageOnCommand; enabled = conf.DeleteMessageOnCommand = !conf.DeleteMessageOnCommand;
uow.SaveChanges(); uow.SaveChanges();
}
return enabled; return enabled;
} }

View File

@@ -40,10 +40,8 @@ DELETE FROM Clubs;";
public async Task<int> ExecuteSql(string sql) public async Task<int> ExecuteSql(string sql)
{ {
int res; int res;
await using (var uow = _db.GetDbContext()) await using var uow = _db.GetDbContext();
{
res = await uow.Database.ExecuteSqlRawAsync(sql); res = await uow.Database.ExecuteSqlRawAsync(sql);
}
return res; return res;
} }
@@ -61,14 +59,11 @@ DELETE FROM Clubs;";
Results = new(), Results = new(),
}; };
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var conn = uow.Database.GetDbConnection(); var conn = uow.Database.GetDbConnection();
using (var cmd = conn.CreateCommand()) using var cmd = conn.CreateCommand();
{
cmd.CommandText = sql; cmd.CommandText = sql;
using (var reader = cmd.ExecuteReader()) using var reader = cmd.ExecuteReader();
{
if (reader.HasRows) if (reader.HasRows)
{ {
for (var i = 0; i < reader.FieldCount; i++) for (var i = 0; i < reader.FieldCount; i++)
@@ -82,9 +77,7 @@ DELETE FROM Clubs;";
result.Results.Add(obj.Select(x => x.ToString()).ToArray()); result.Results.Add(obj.Select(x => x.ToString()).ToArray());
} }
} }
}
}
}
return result; return result;
} }

View File

@@ -48,8 +48,7 @@ public class DiscordPermOverrideService : INService, ILateBlocker
public async Task AddOverride(ulong guildId, string commandName, GuildPerm perm) public async Task AddOverride(ulong guildId, string commandName, GuildPerm perm)
{ {
commandName = commandName.ToLowerInvariant(); commandName = commandName.ToLowerInvariant();
await using (var uow = _db.GetDbContext()) await using var uow = _db.GetDbContext();
{
var over = await uow var over = await uow
.Set<DiscordPermOverride>() .Set<DiscordPermOverride>()
.AsQueryable() .AsQueryable()
@@ -58,12 +57,7 @@ public class DiscordPermOverrideService : INService, ILateBlocker
if (over is null) if (over is null)
{ {
uow.Set<DiscordPermOverride>() uow.Set<DiscordPermOverride>()
.Add(over = new() .Add(over = new() { Command = commandName, Perm = perm, GuildId = guildId, });
{
Command = commandName,
Perm = perm,
GuildId = guildId,
});
} }
else else
{ {
@@ -74,12 +68,10 @@ public class DiscordPermOverrideService : INService, ILateBlocker
await uow.SaveChangesAsync(); await uow.SaveChangesAsync();
} }
}
public async Task ClearAllOverrides(ulong guildId) public async Task ClearAllOverrides(ulong guildId)
{ {
await using (var uow = _db.GetDbContext()) await using var uow = _db.GetDbContext();
{
var overrides = await uow var overrides = await uow
.Set<DiscordPermOverride>() .Set<DiscordPermOverride>()
.AsQueryable() .AsQueryable()
@@ -95,14 +87,12 @@ public class DiscordPermOverrideService : INService, ILateBlocker
_overrides.TryRemove((guildId, over.Command), out _); _overrides.TryRemove((guildId, over.Command), out _);
} }
} }
}
public async Task RemoveOverride(ulong guildId, string commandName) public async Task RemoveOverride(ulong guildId, string commandName)
{ {
commandName = commandName.ToLowerInvariant(); commandName = commandName.ToLowerInvariant();
await using (var uow = _db.GetDbContext()) await using var uow = _db.GetDbContext();
{
var over = await uow var over = await uow
.Set<DiscordPermOverride>() .Set<DiscordPermOverride>()
.AsQueryable() .AsQueryable()
@@ -117,26 +107,23 @@ public class DiscordPermOverrideService : INService, ILateBlocker
_overrides.TryRemove((guildId, commandName), out _); _overrides.TryRemove((guildId, commandName), out _);
} }
}
public Task<List<DiscordPermOverride>> GetAllOverrides(ulong guildId) public async Task<List<DiscordPermOverride>> GetAllOverrides(ulong guildId)
{ {
using (var uow = _db.GetDbContext()) await using var uow = _db.GetDbContext();
{ return await uow
return uow
.Set<DiscordPermOverride>() .Set<DiscordPermOverride>()
.AsQueryable() .AsQueryable()
.AsNoTracking() .AsNoTracking()
.Where(x => x.GuildId == guildId) .Where(x => x.GuildId == guildId)
.ToListAsync(); .ToListAsync();
} }
}
public async Task<bool> TryBlockLate(ICommandContext context, string moduleName, CommandInfo command) public async Task<bool> TryBlockLate(ICommandContext context, string moduleName, CommandInfo command)
{ {
if (TryGetOverrides(context.Guild?.Id ?? 0, command.Name, out var perm) && perm is not null) if (TryGetOverrides(context.Guild?.Id ?? 0, command.Name, out var perm) && perm is not null)
{ {
var result = await new RequireUserPermissionAttribute((GuildPermission) perm) var result = await new RequireUserPermissionAttribute((GuildPermission)perm)
.CheckPermissionsAsync(context, command, _services); .CheckPermissionsAsync(context, command, _services);
return !result.IsSuccess; return !result.IsSuccess;

View File

@@ -56,8 +56,7 @@ public class GameVoiceChannelService : INService
public ulong? ToggleGameVoiceChannel(ulong guildId, ulong vchId) public ulong? ToggleGameVoiceChannel(ulong guildId, ulong vchId)
{ {
ulong? id; ulong? id;
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var gc = uow.GuildConfigsForId(guildId, set => set); var gc = uow.GuildConfigsForId(guildId, set => set);
if (gc.GameVoiceChannel == vchId) if (gc.GameVoiceChannel == vchId)
@@ -74,7 +73,6 @@ public class GameVoiceChannelService : INService
} }
uow.SaveChanges(); uow.SaveChanges();
}
return id; return id;
} }

View File

@@ -59,8 +59,7 @@ public class GuildTimezoneService : INService
public void SetTimeZone(ulong guildId, TimeZoneInfo tz) public void SetTimeZone(ulong guildId, TimeZoneInfo tz)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var gc = uow.GuildConfigsForId(guildId, set => set); var gc = uow.GuildConfigsForId(guildId, set => set);
gc.TimeZoneId = tz?.Id; gc.TimeZoneId = tz?.Id;
@@ -71,7 +70,6 @@ public class GuildTimezoneService : INService
else else
_timezones.AddOrUpdate(guildId, tz, (key, old) => tz); _timezones.AddOrUpdate(guildId, tz, (key, old) => tz);
} }
}
public TimeZoneInfo GetTimeZoneOrUtc(ulong guildId) public TimeZoneInfo GetTimeZoneOrUtc(ulong guildId)
=> GetTimeZoneOrDefault(guildId) ?? TimeZoneInfo.Utc; => GetTimeZoneOrDefault(guildId) ?? TimeZoneInfo.Utc;

View File

@@ -198,8 +198,7 @@ public sealed class LogCommandService : ILogCommandService
public async Task LogServer(ulong guildId, ulong channelId, bool value) public async Task LogServer(ulong guildId, ulong channelId, bool value)
{ {
await using (var uow = _db.GetDbContext()) await using var uow = _db.GetDbContext();
{
var logSetting = uow.LogSettingsFor(guildId); var logSetting = uow.LogSettingsFor(guildId);
logSetting.LogOtherId = logSetting.LogOtherId =
@@ -222,7 +221,6 @@ public sealed class LogCommandService : ILogCommandService
await uow.SaveChangesAsync(); await uow.SaveChangesAsync();
GuildLogSettings.AddOrUpdate(guildId, id => logSetting, (id, old) => logSetting); GuildLogSettings.AddOrUpdate(guildId, id => logSetting, (id, old) => logSetting);
} }
}
private Task _client_UserUpdated(SocketUser before, SocketUser uAfter) private Task _client_UserUpdated(SocketUser before, SocketUser uAfter)
{ {
@@ -1193,8 +1191,7 @@ public sealed class LogCommandService : ILogCommandService
private void UnsetLogSetting(ulong guildId, LogType logChannelType) private void UnsetLogSetting(ulong guildId, LogType logChannelType)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var newLogSetting = uow.LogSettingsFor(guildId); var newLogSetting = uow.LogSettingsFor(guildId);
switch (logChannelType) switch (logChannelType)
{ {
@@ -1248,5 +1245,4 @@ public sealed class LogCommandService : ILogCommandService
GuildLogSettings.AddOrUpdate(guildId, newLogSetting, (gid, old) => newLogSetting); GuildLogSettings.AddOrUpdate(guildId, newLogSetting, (gid, old) => newLogSetting);
uow.SaveChanges(); uow.SaveChanges();
} }
}
} }

View File

@@ -163,14 +163,12 @@ public class MuteService : INService
public async Task SetMuteRoleAsync(ulong guildId, string name) public async Task SetMuteRoleAsync(ulong guildId, string name)
{ {
await using (var uow = _db.GetDbContext()) await using var uow = _db.GetDbContext();
{
var config = uow.GuildConfigsForId(guildId, set => set); var config = uow.GuildConfigsForId(guildId, set => set);
config.MuteRoleName = name; config.MuteRoleName = name;
GuildMuteRoles.AddOrUpdate(guildId, name, (id, old) => name); GuildMuteRoles.AddOrUpdate(guildId, name, (id, old) => name);
await uow.SaveChangesAsync(); await uow.SaveChangesAsync();
} }
}
public async Task MuteUser(IGuildUser usr, IUser mod, MuteType type = MuteType.All, string reason = "") public async Task MuteUser(IGuildUser usr, IUser mod, MuteType type = MuteType.All, string reason = "")
{ {
@@ -445,8 +443,7 @@ public class MuteService : INService
private void RemoveTimerFromDb(ulong guildId, ulong userId, TimerType type) private void RemoveTimerFromDb(ulong guildId, ulong userId, TimerType type)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
object toDelete; object toDelete;
if (type == TimerType.Mute) if (type == TimerType.Mute)
{ {
@@ -464,5 +461,4 @@ public class MuteService : INService
} }
uow.SaveChanges(); uow.SaveChanges();
} }
}
} }

View File

@@ -290,13 +290,11 @@ public class ProtectionService : INService
_antiRaidGuilds.AddOrUpdate(guildId, stats, (key, old) => stats); _antiRaidGuilds.AddOrUpdate(guildId, stats, (key, old) => stats);
await using (var uow = _db.GetDbContext()) await using var uow = _db.GetDbContext();
{
var gc = uow.GuildConfigsForId(guildId, set => set.Include(x => x.AntiRaidSetting)); var gc = uow.GuildConfigsForId(guildId, set => set.Include(x => x.AntiRaidSetting));
gc.AntiRaidSetting = stats.AntiRaidSettings; gc.AntiRaidSetting = stats.AntiRaidSettings;
await uow.SaveChangesAsync(); await uow.SaveChangesAsync();
}
return stats; return stats;
} }
@@ -305,13 +303,11 @@ public class ProtectionService : INService
{ {
if (_antiRaidGuilds.TryRemove(guildId, out _)) if (_antiRaidGuilds.TryRemove(guildId, out _))
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var gc = uow.GuildConfigsForId(guildId, set => set.Include(x => x.AntiRaidSetting)); var gc = uow.GuildConfigsForId(guildId, set => set.Include(x => x.AntiRaidSetting));
gc.AntiRaidSetting = null; gc.AntiRaidSetting = null;
uow.SaveChanges(); uow.SaveChanges();
}
return true; return true;
} }
return false; return false;
@@ -322,14 +318,12 @@ public class ProtectionService : INService
if (_antiSpamGuilds.TryRemove(guildId, out var removed)) if (_antiSpamGuilds.TryRemove(guildId, out var removed))
{ {
removed.UserStats.ForEach(x => x.Value.Dispose()); removed.UserStats.ForEach(x => x.Value.Dispose());
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var gc = uow.GuildConfigsForId(guildId, set => set.Include(x => x.AntiSpamSetting) var gc = uow.GuildConfigsForId(guildId, set => set.Include(x => x.AntiSpamSetting)
.ThenInclude(x => x.IgnoredChannels)); .ThenInclude(x => x.IgnoredChannels));
gc.AntiSpamSetting = null; gc.AntiSpamSetting = null;
uow.SaveChanges(); uow.SaveChanges();
}
return true; return true;
} }
return false; return false;
@@ -361,8 +355,7 @@ public class ProtectionService : INService
return stats; return stats;
}); });
await using (var uow = _db.GetDbContext()) await using var uow = _db.GetDbContext();
{
var gc = uow.GuildConfigsForId(guildId, set => set.Include(x => x.AntiSpamSetting)); var gc = uow.GuildConfigsForId(guildId, set => set.Include(x => x.AntiSpamSetting));
if (gc.AntiSpamSetting != null) if (gc.AntiSpamSetting != null)
@@ -377,7 +370,6 @@ public class ProtectionService : INService
gc.AntiSpamSetting = stats.AntiSpamSettings; gc.AntiSpamSetting = stats.AntiSpamSettings;
} }
await uow.SaveChangesAsync(); await uow.SaveChangesAsync();
}
return stats; return stats;
} }
@@ -388,8 +380,7 @@ public class ProtectionService : INService
ChannelId = channelId ChannelId = channelId
}; };
bool added; bool added;
await using (var uow = _db.GetDbContext()) await using var uow = _db.GetDbContext();
{
var gc = uow.GuildConfigsForId(guildId, set => set.Include(x => x.AntiSpamSetting).ThenInclude(x => x.IgnoredChannels)); var gc = uow.GuildConfigsForId(guildId, set => set.Include(x => x.AntiSpamSetting).ThenInclude(x => x.IgnoredChannels));
var spam = gc.AntiSpamSetting; var spam = gc.AntiSpamSetting;
if (spam is null) if (spam is null)
@@ -415,7 +406,6 @@ public class ProtectionService : INService
} }
await uow.SaveChangesAsync(); await uow.SaveChangesAsync();
}
return added; return added;
} }

View File

@@ -163,8 +163,7 @@ public class RoleCommandsService : INService
public void Remove(ulong id, int index) public void Remove(ulong id, int index)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var gc = uow.GuildConfigsForId(id, var gc = uow.GuildConfigsForId(id,
set => set.Include(x => x.ReactionRoleMessages) set => set.Include(x => x.ReactionRoleMessages)
.ThenInclude(x => x.ReactionRoles)); .ThenInclude(x => x.ReactionRoles));
@@ -176,7 +175,6 @@ public class RoleCommandsService : INService
delegate { return gc.ReactionRoleMessages; }); delegate { return gc.ReactionRoleMessages; });
uow.SaveChanges(); uow.SaveChanges();
} }
}
/// <summary> /// <summary>
/// Adds a reaction role to the specified user. /// Adds a reaction role to the specified user.

View File

@@ -33,8 +33,7 @@ public class SelfAssignedRolesService : INService
public bool AddNew(ulong guildId, IRole role, int group) public bool AddNew(ulong guildId, IRole role, int group)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var roles = uow.SelfAssignableRoles.GetFromGuild(guildId); var roles = uow.SelfAssignableRoles.GetFromGuild(guildId);
if (roles.Any(s => s.RoleId == role.Id && s.GuildId == role.Guild.Id)) if (roles.Any(s => s.RoleId == role.Id && s.GuildId == role.Guild.Id))
{ {
@@ -43,24 +42,21 @@ public class SelfAssignedRolesService : INService
uow.SelfAssignableRoles.Add(new() uow.SelfAssignableRoles.Add(new()
{ {
Group = group, Group = @group,
RoleId = role.Id, RoleId = role.Id,
GuildId = role.Guild.Id GuildId = role.Guild.Id
}); });
uow.SaveChanges(); uow.SaveChanges();
}
return true; return true;
} }
public bool ToggleAdSarm(ulong guildId) public bool ToggleAdSarm(ulong guildId)
{ {
bool newval; bool newval;
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var config = uow.GuildConfigsForId(guildId, set => set); var config = uow.GuildConfigsForId(guildId, set => set);
newval = config.AutoDeleteSelfAssignedRoleMessages = !config.AutoDeleteSelfAssignedRoleMessages; newval = config.AutoDeleteSelfAssignedRoleMessages = !config.AutoDeleteSelfAssignedRoleMessages;
uow.SaveChanges(); uow.SaveChanges();
}
return newval; return newval;
} }
@@ -129,10 +125,9 @@ public class SelfAssignedRolesService : INService
public async Task<bool> SetNameAsync(ulong guildId, int group, string name) public async Task<bool> SetNameAsync(ulong guildId, int group, string name)
{ {
var set = false; var set = false;
await using (var uow = _db.GetDbContext()) await using var uow = _db.GetDbContext();
{
var gc = uow.GuildConfigsForId(guildId, y => y.Include(x => x.SelfAssignableRoleGroupNames)); var gc = uow.GuildConfigsForId(guildId, y => y.Include(x => x.SelfAssignableRoleGroupNames));
var toUpdate = gc.SelfAssignableRoleGroupNames.FirstOrDefault(x => x.Number == group); var toUpdate = gc.SelfAssignableRoleGroupNames.FirstOrDefault(x => x.Number == @group);
if (string.IsNullOrWhiteSpace(name)) if (string.IsNullOrWhiteSpace(name))
{ {
@@ -144,7 +139,7 @@ public class SelfAssignedRolesService : INService
gc.SelfAssignableRoleGroupNames.Add(new() gc.SelfAssignableRoleGroupNames.Add(new()
{ {
Name = name, Name = name,
Number = group, Number = @group,
}); });
set = true; set = true;
} }
@@ -155,7 +150,6 @@ public class SelfAssignedRolesService : INService
} }
await uow.SaveChangesAsync(); await uow.SaveChangesAsync();
}
return set; return set;
} }
@@ -187,18 +181,15 @@ public class SelfAssignedRolesService : INService
public bool RemoveSar(ulong guildId, ulong roleId) public bool RemoveSar(ulong guildId, ulong roleId)
{ {
bool success; bool success;
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
success = uow.SelfAssignableRoles.DeleteByGuildAndRoleId(guildId, roleId); success = uow.SelfAssignableRoles.DeleteByGuildAndRoleId(guildId, roleId);
uow.SaveChanges(); uow.SaveChanges();
}
return success; return success;
} }
public (bool AutoDelete, bool Exclusive, IEnumerable<SelfAssignedRole>) GetAdAndRoles(ulong guildId) public (bool AutoDelete, bool Exclusive, IEnumerable<SelfAssignedRole>) GetAdAndRoles(ulong guildId)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var gc = uow.GuildConfigsForId(guildId, set => set); var gc = uow.GuildConfigsForId(guildId, set => set);
var autoDelete = gc.AutoDeleteSelfAssignedRoleMessages; var autoDelete = gc.AutoDeleteSelfAssignedRoleMessages;
var exclusive = gc.ExclusiveSelfAssignedRoles; var exclusive = gc.ExclusiveSelfAssignedRoles;
@@ -206,12 +197,10 @@ public class SelfAssignedRolesService : INService
return (autoDelete, exclusive, roles); return (autoDelete, exclusive, roles);
} }
}
public bool SetLevelReq(ulong guildId, IRole role, int level) public bool SetLevelReq(ulong guildId, IRole role, int level)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var roles = uow.SelfAssignableRoles.GetFromGuild(guildId); var roles = uow.SelfAssignableRoles.GetFromGuild(guildId);
var sar = roles.FirstOrDefault(x => x.RoleId == role.Id); var sar = roles.FirstOrDefault(x => x.RoleId == role.Id);
if (sar != null) if (sar != null)
@@ -223,7 +212,6 @@ public class SelfAssignedRolesService : INService
{ {
return false; return false;
} }
}
return true; return true;
} }
@@ -231,13 +219,11 @@ public class SelfAssignedRolesService : INService
public bool ToggleEsar(ulong guildId) public bool ToggleEsar(ulong guildId)
{ {
bool areExclusive; bool areExclusive;
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var config = uow.GuildConfigsForId(guildId, set => set); var config = uow.GuildConfigsForId(guildId, set => set);
areExclusive = config.ExclusiveSelfAssignedRoles = !config.ExclusiveSelfAssignedRoles; areExclusive = config.ExclusiveSelfAssignedRoles = !config.ExclusiveSelfAssignedRoles;
uow.SaveChanges(); uow.SaveChanges();
}
return areExclusive; return areExclusive;
} }

View File

@@ -273,8 +273,7 @@ public sealed class SelfService : ILateExecutor, IReadyExecutor, INService
public bool RemoveStartupCommand(int index, out AutoCommand cmd) public bool RemoveStartupCommand(int index, out AutoCommand cmd)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
cmd = uow.AutoCommands cmd = uow.AutoCommands
.AsNoTracking() .AsNoTracking()
.Where(x => x.Interval == 0) .Where(x => x.Interval == 0)
@@ -287,15 +286,13 @@ public sealed class SelfService : ILateExecutor, IReadyExecutor, INService
uow.SaveChanges(); uow.SaveChanges();
return true; return true;
} }
}
return false; return false;
} }
public bool RemoveAutoCommand(int index, out AutoCommand cmd) public bool RemoveAutoCommand(int index, out AutoCommand cmd)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
cmd = uow.AutoCommands cmd = uow.AutoCommands
.AsNoTracking() .AsNoTracking()
.Where(x => x.Interval >= 5) .Where(x => x.Interval >= 5)
@@ -311,7 +308,6 @@ public sealed class SelfService : ILateExecutor, IReadyExecutor, INService
uow.SaveChanges(); uow.SaveChanges();
return true; return true;
} }
}
return false; return false;
} }
@@ -326,27 +322,22 @@ public sealed class SelfService : ILateExecutor, IReadyExecutor, INService
var uri = new Uri(img); var uri = new Uri(img);
using (var http = _httpFactory.CreateClient()) using var http = _httpFactory.CreateClient();
using (var sr = await http.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false)) using var sr = await http.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);
{
if (!sr.IsImage()) if (!sr.IsImage())
return false; return false;
// i can't just do ReadAsStreamAsync because dicord.net's image poops itself // i can't just do ReadAsStreamAsync because dicord.net's image poops itself
var imgData = await sr.Content.ReadAsByteArrayAsync().ConfigureAwait(false); var imgData = await sr.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
await using (var imgStream = imgData.ToStream()) await using var imgStream = imgData.ToStream();
{
await _client.CurrentUser.ModifyAsync(u => u.Avatar = new Image(imgStream)).ConfigureAwait(false); await _client.CurrentUser.ModifyAsync(u => u.Avatar = new Image(imgStream)).ConfigureAwait(false);
}
}
return true; return true;
} }
public void ClearStartupCommands() public void ClearStartupCommands()
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var toRemove = uow var toRemove = uow
.AutoCommands .AutoCommands
.AsNoTracking() .AsNoTracking()
@@ -355,7 +346,6 @@ public sealed class SelfService : ILateExecutor, IReadyExecutor, INService
uow.AutoCommands.RemoveRange(toRemove); uow.AutoCommands.RemoveRange(toRemove);
uow.SaveChanges(); uow.SaveChanges();
} }
}
public Task ReloadImagesAsync() public Task ReloadImagesAsync()
=> _pubSub.Pub(_imagesReloadKey, true); => _pubSub.Pub(_imagesReloadKey, true);

View File

@@ -198,8 +198,7 @@ public class UserPunishService : INService
public async Task CheckAllWarnExpiresAsync() public async Task CheckAllWarnExpiresAsync()
{ {
await using (var uow = _db.GetDbContext()) await using var uow = _db.GetDbContext();
{
var cleared = await uow.Database.ExecuteSqlRawAsync($@"UPDATE Warnings var cleared = await uow.Database.ExecuteSqlRawAsync($@"UPDATE Warnings
SET Forgiven = 1, SET Forgiven = 1,
ForgivenBy = 'Expiry' ForgivenBy = 'Expiry'
@@ -216,12 +215,10 @@ WHERE GuildId in (SELECT GuildId FROM GuildConfigs WHERE WarnExpireHours > 0 AND
Log.Information($"Cleared {cleared} warnings and deleted {deleted} warnings due to expiry."); Log.Information($"Cleared {cleared} warnings and deleted {deleted} warnings due to expiry.");
} }
} }
}
public async Task CheckWarnExpiresAsync(ulong guildId) public async Task CheckWarnExpiresAsync(ulong guildId)
{ {
await using (var uow = _db.GetDbContext()) await using var uow = _db.GetDbContext();
{
var config = uow.GuildConfigsForId(guildId, inc => inc); var config = uow.GuildConfigsForId(guildId, inc => inc);
if (config.WarnExpireHours == 0) if (config.WarnExpireHours == 0)
@@ -246,7 +243,6 @@ WHERE GuildId={guildId}
await uow.SaveChangesAsync(); await uow.SaveChangesAsync();
} }
}
public Task<int> GetWarnExpire(ulong guildId) public Task<int> GetWarnExpire(ulong guildId)
{ {
@@ -275,25 +271,20 @@ WHERE GuildId={guildId}
public IGrouping<ulong, Warning>[] WarnlogAll(ulong gid) public IGrouping<ulong, Warning>[] WarnlogAll(ulong gid)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
return uow.Warnings.GetForGuild(gid).GroupBy(x => x.UserId).ToArray(); return uow.Warnings.GetForGuild(gid).GroupBy(x => x.UserId).ToArray();
} }
}
public Warning[] UserWarnings(ulong gid, ulong userId) public Warning[] UserWarnings(ulong gid, ulong userId)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
return uow.Warnings.ForId(gid, userId); return uow.Warnings.ForId(gid, userId);
} }
}
public async Task<bool> WarnClearAsync(ulong guildId, ulong userId, int index, string moderator) public async Task<bool> WarnClearAsync(ulong guildId, ulong userId, int index, string moderator)
{ {
var toReturn = true; var toReturn = true;
await using (var uow = _db.GetDbContext()) await using var uow = _db.GetDbContext();
{
if (index == 0) if (index == 0)
{ {
await uow.Warnings.ForgiveAll(guildId, userId, moderator); await uow.Warnings.ForgiveAll(guildId, userId, moderator);
@@ -303,7 +294,6 @@ WHERE GuildId={guildId}
toReturn = uow.Warnings.Forgive(guildId, userId, moderator, index - 1); toReturn = uow.Warnings.Forgive(guildId, userId, moderator, index - 1);
} }
uow.SaveChanges(); uow.SaveChanges();
}
return toReturn; return toReturn;
} }
@@ -315,8 +305,7 @@ WHERE GuildId={guildId}
if (number <= 0 || (time != null && time.Time > TimeSpan.FromDays(49))) if (number <= 0 || (time != null && time.Time > TimeSpan.FromDays(49)))
return false; return false;
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var ps = uow.GuildConfigsForId(guildId, set => set.Include(x => x.WarnPunishments)).WarnPunishments; var ps = uow.GuildConfigsForId(guildId, set => set.Include(x => x.WarnPunishments)).WarnPunishments;
var toDelete = ps.Where(x => x.Count == number); var toDelete = ps.Where(x => x.Count == number);
@@ -330,7 +319,6 @@ WHERE GuildId={guildId}
RoleId = punish == PunishmentAction.AddRole ? role.Id : default(ulong?), RoleId = punish == PunishmentAction.AddRole ? role.Id : default(ulong?),
}); });
uow.SaveChanges(); uow.SaveChanges();
}
return true; return true;
} }
@@ -339,8 +327,7 @@ WHERE GuildId={guildId}
if (number <= 0) if (number <= 0)
return false; return false;
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var ps = uow.GuildConfigsForId(guildId, set => set.Include(x => x.WarnPunishments)).WarnPunishments; var ps = uow.GuildConfigsForId(guildId, set => set.Include(x => x.WarnPunishments)).WarnPunishments;
var p = ps.FirstOrDefault(x => x.Count == number); var p = ps.FirstOrDefault(x => x.Count == number);
@@ -349,20 +336,18 @@ WHERE GuildId={guildId}
uow.Remove(p); uow.Remove(p);
uow.SaveChanges(); uow.SaveChanges();
} }
}
return true; return true;
} }
public WarningPunishment[] WarnPunishList(ulong guildId) public WarningPunishment[] WarnPunishList(ulong guildId)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
return uow.GuildConfigsForId(guildId, gc => gc.Include(x => x.WarnPunishments)) return uow.GuildConfigsForId(guildId, gc => gc.Include(x => x.WarnPunishments))
.WarnPunishments .WarnPunishments
.OrderBy(x => x.Count) .OrderBy(x => x.Count)
.ToArray(); .ToArray();
} }
}
public (IEnumerable<(string Original, ulong? Id, string Reason)> Bans, int Missing) MassKill(SocketGuild guild, string people) public (IEnumerable<(string Original, ulong? Id, string Reason)> Bans, int Missing) MassKill(SocketGuild guild, string people)
{ {
@@ -403,19 +388,16 @@ WHERE GuildId={guildId}
public string GetBanTemplate(ulong guildId) public string GetBanTemplate(ulong guildId)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var template = uow.BanTemplates var template = uow.BanTemplates
.AsQueryable() .AsQueryable()
.FirstOrDefault(x => x.GuildId == guildId); .FirstOrDefault(x => x.GuildId == guildId);
return template?.Text; return template?.Text;
} }
}
public void SetBanTemplate(ulong guildId, string text) public void SetBanTemplate(ulong guildId, string text)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var template = uow.BanTemplates var template = uow.BanTemplates
.AsQueryable() .AsQueryable()
.FirstOrDefault(x => x.GuildId == guildId); .FirstOrDefault(x => x.GuildId == guildId);
@@ -442,7 +424,6 @@ WHERE GuildId={guildId}
uow.SaveChanges(); uow.SaveChanges();
} }
}
public SmartText GetBanUserDmEmbed(ICommandContext context, IGuildUser target, string defaultMessage, public SmartText GetBanUserDmEmbed(ICommandContext context, IGuildUser target, string defaultMessage,
string banReason, TimeSpan? duration) string banReason, TimeSpan? duration)

View File

@@ -117,14 +117,12 @@ public class VcRoleService : INService
if (missingRoles.Any()) if (missingRoles.Any())
{ {
await using (var uow = _db.GetDbContext()) await using var uow = _db.GetDbContext();
{
Log.Warning($"Removing {missingRoles.Count} missing roles from {nameof(VcRoleService)}"); Log.Warning($"Removing {missingRoles.Count} missing roles from {nameof(VcRoleService)}");
uow.RemoveRange(missingRoles); uow.RemoveRange(missingRoles);
await uow.SaveChangesAsync(); await uow.SaveChangesAsync();
} }
} }
}
public void AddVcRole(ulong guildId, IRole role, ulong vcId) public void AddVcRole(ulong guildId, IRole role, ulong vcId)
{ {
@@ -134,8 +132,7 @@ public class VcRoleService : INService
var guildVcRoles = VcRoles.GetOrAdd(guildId, new ConcurrentDictionary<ulong, IRole>()); var guildVcRoles = VcRoles.GetOrAdd(guildId, new ConcurrentDictionary<ulong, IRole>());
guildVcRoles.AddOrUpdate(vcId, role, (key, old) => role); guildVcRoles.AddOrUpdate(vcId, role, (key, old) => role);
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var conf = uow.GuildConfigsForId(guildId, set => set.Include(x => x.VcRoleInfos)); var conf = uow.GuildConfigsForId(guildId, set => set.Include(x => x.VcRoleInfos));
var toDelete = conf.VcRoleInfos.FirstOrDefault(x => x.VoiceChannelId == vcId); // remove old one var toDelete = conf.VcRoleInfos.FirstOrDefault(x => x.VoiceChannelId == vcId); // remove old one
if(toDelete != null) if(toDelete != null)
@@ -149,7 +146,6 @@ public class VcRoleService : INService
}); // add new one }); // add new one
uow.SaveChanges(); uow.SaveChanges();
} }
}
public bool RemoveVcRole(ulong guildId, ulong vcId) public bool RemoveVcRole(ulong guildId, ulong vcId)
{ {
@@ -159,13 +155,11 @@ public class VcRoleService : INService
if (!guildVcRoles.TryRemove(vcId, out _)) if (!guildVcRoles.TryRemove(vcId, out _))
return false; return false;
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var conf = uow.GuildConfigsForId(guildId, set => set.Include(x => x.VcRoleInfos)); var conf = uow.GuildConfigsForId(guildId, set => set.Include(x => x.VcRoleInfos));
var toRemove = conf.VcRoleInfos.Where(x => x.VoiceChannelId == vcId).ToList(); var toRemove = conf.VcRoleInfos.Where(x => x.VoiceChannelId == vcId).ToList();
uow.RemoveRange(toRemove); uow.RemoveRange(toRemove);
uow.SaveChanges(); uow.SaveChanges();
}
return true; return true;
} }

View File

@@ -30,16 +30,14 @@ public partial class Gambling
var num1 = gen / 10; var num1 = gen / 10;
var num2 = gen % 10; var num2 = gen % 10;
using (var img1 = GetDice(num1)) using var img1 = GetDice(num1);
using (var img2 = GetDice(num2)) using var img2 = GetDice(num2);
using (var img = new[] { img1, img2 }.Merge(out var format)) using var img = new[] { img1, img2 }.Merge(out var format);
await using (var ms = img.ToStream(format)) await using var ms = img.ToStream(format);
{
await ctx.Channel.SendFileAsync(ms, await ctx.Channel.SendFileAsync(ms,
$"dice.{format.FileExtensions.First()}", $"dice.{format.FileExtensions.First()}",
Format.Bold(ctx.User.ToString()) + " " + GetText(strs.dice_rolled(Format.Code(gen.ToString())))); Format.Bold(ctx.User.ToString()) + " " + GetText(strs.dice_rolled(Format.Code(gen.ToString()))));
} }
}
[NadekoCommand, Aliases] [NadekoCommand, Aliases]
[Priority(1)] [Priority(1)]
@@ -108,9 +106,8 @@ public partial class Gambling
values.Insert(toInsert, randomNumber); values.Insert(toInsert, randomNumber);
} }
using (var bitmap = dice.Merge(out var format)) using var bitmap = dice.Merge(out var format);
await using (var ms = bitmap.ToStream(format)) await using var ms = bitmap.ToStream(format);
{
foreach (var d in dice) foreach (var d in dice)
{ {
d.Dispose(); d.Dispose();
@@ -123,7 +120,6 @@ public partial class Gambling
Format.Bold(values.Sum().ToString()), Format.Bold(values.Sum().ToString()),
Format.Bold((values.Sum() / (1.0f * values.Count)).ToString("N2"))))); Format.Bold((values.Sum() / (1.0f * values.Count)).ToString("N2")))));
} }
}
private async Task InternallDndRoll(string arg, bool ordered) private async Task InternallDndRoll(string arg, bool ordered)
{ {
@@ -211,12 +207,10 @@ public partial class Gambling
if (num == 10) if (num == 10)
{ {
var images = _images.Dice; var images = _images.Dice;
using (var imgOne = Image.Load(images[1])) using var imgOne = Image.Load(images[1]);
using (var imgZero = Image.Load(images[0])) using var imgZero = Image.Load(images[0]);
{
return new[] { imgOne, imgZero }.Merge(); return new[] { imgOne, imgZero }.Merge();
} }
}
return Image.Load(_images.Dice[num]); return Image.Load(_images.Dice[num]);
} }
} }

View File

@@ -44,8 +44,8 @@ public partial class Gambling
cardObjects.Add(currentCard); cardObjects.Add(currentCard);
images.Add(Image.Load(_images.GetCard(currentCard.ToString().ToLowerInvariant().Replace(' ', '_')))); images.Add(Image.Load(_images.GetCard(currentCard.ToString().ToLowerInvariant().Replace(' ', '_'))));
} }
using (var img = images.Merge())
{ using var img = images.Merge();
foreach (var i in images) foreach (var i in images)
{ {
i.Dispose(); i.Dispose();
@@ -60,7 +60,6 @@ public partial class Gambling
return (img.ToStream(), toSend); return (img.ToStream(), toSend);
} }
}
[NadekoCommand, Aliases] [NadekoCommand, Aliases]
[RequireContext(ContextType.Guild)] [RequireContext(ContextType.Guild)]

View File

@@ -47,9 +47,9 @@ public partial class Gambling
tailCount++; tailCount++;
} }
} }
using (var img = imgs.Merge(out var format))
await using (var stream = img.ToStream(format)) using var img = imgs.Merge(out var format);
{ await using var stream = img.ToStream(format);
foreach (var i in imgs) foreach (var i in imgs)
{ {
i.Dispose(); i.Dispose();
@@ -61,7 +61,6 @@ public partial class Gambling
: Format.Bold(GetText(strs.tails)))); : Format.Bold(GetText(strs.tails))));
await ctx.Channel.SendFileAsync(stream, $"{count} coins.{format.FileExtensions.First()}", msg).ConfigureAwait(false); await ctx.Channel.SendFileAsync(stream, $"{count} coins.{format.FileExtensions.First()}", msg).ConfigureAwait(false);
} }
}
public enum BetFlipGuess public enum BetFlipGuess
{ {

View File

@@ -538,11 +538,9 @@ public partial class Gambling : GamblingModule<GamblingService>
} }
else else
{ {
await using (var uow = _db.GetDbContext()) await using var uow = _db.GetDbContext();
{
cleanRichest = uow.DiscordUser.GetTopRichest(_client.CurrentUser.Id, 9, page).ToList(); cleanRichest = uow.DiscordUser.GetTopRichest(_client.CurrentUser.Id, 9, page).ToList();
} }
}
await ctx.SendPaginatedConfirmAsync(page, curPage => await ctx.SendPaginatedConfirmAsync(page, curPage =>
{ {
@@ -553,11 +551,9 @@ public partial class Gambling : GamblingModule<GamblingService>
List<DiscordUser> toSend; List<DiscordUser> toSend;
if (!opts.Clean) if (!opts.Clean)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
toSend = uow.DiscordUser.GetTopRichest(_client.CurrentUser.Id, 9, curPage); toSend = uow.DiscordUser.GetTopRichest(_client.CurrentUser.Id, 9, curPage);
} }
}
else else
{ {
toSend = cleanRichest.Skip(curPage * 9).Take(9).ToList(); toSend = cleanRichest.Skip(curPage * 9).Take(9).ToList();

View File

@@ -41,8 +41,7 @@ public class GamblingService : INService
if (config.Decay.Percent <= 0 || config.Decay.Percent > 1 || maxDecay < 0) if (config.Decay.Percent <= 0 || config.Decay.Percent > 1 || maxDecay < 0)
return; return;
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var lastCurrencyDecay = _cache.GetLastCurrencyDecay(); var lastCurrencyDecay = _cache.GetLastCurrencyDecay();
if (DateTime.UtcNow - lastCurrencyDecay < TimeSpan.FromHours(config.Decay.HourInterval)) if (DateTime.UtcNow - lastCurrencyDecay < TimeSpan.FromHours(config.Decay.HourInterval))
@@ -69,7 +68,6 @@ WHERE CurrencyAmount > {config.Decay.MinThreshold} AND UserId!={_client.CurrentU
_cache.SetLastCurrencyDecay(); _cache.SetLastCurrencyDecay();
uow.SaveChanges(); uow.SaveChanges();
}
}, null, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(5)); }, null, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(5));
} }
} }

View File

@@ -44,8 +44,7 @@ public class PlantPickService : INService
_gss = gss; _gss = gss;
cmd.OnMessageNoTrigger += PotentialFlowerGeneration; cmd.OnMessageNoTrigger += PotentialFlowerGeneration;
using (var uow = db.GetDbContext()) using var uow = db.GetDbContext();
{
var guildIds = client.Guilds.Select(x => x.Id).ToList(); var guildIds = client.Guilds.Select(x => x.Id).ToList();
var configs = uow.Set<GuildConfig>() var configs = uow.Set<GuildConfig>()
.AsQueryable() .AsQueryable()
@@ -56,7 +55,6 @@ public class PlantPickService : INService
_generationChannels = new(configs _generationChannels = new(configs
.SelectMany(c => c.GenerateCurrencyChannelIds.Select(obj => obj.ChannelId))); .SelectMany(c => c.GenerateCurrencyChannelIds.Select(obj => obj.ChannelId)));
} }
}
private string GetText(ulong gid, LocStr str) private string GetText(ulong gid, LocStr str)
=> _strings.GetText(str, gid); => _strings.GetText(str, gid);
@@ -64,8 +62,7 @@ public class PlantPickService : INService
public bool ToggleCurrencyGeneration(ulong gid, ulong cid) public bool ToggleCurrencyGeneration(ulong gid, ulong cid)
{ {
bool enabled; bool enabled;
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var guildConfig = uow.GuildConfigsForId(gid, set => set.Include(gc => gc.GenerateCurrencyChannelIds)); var guildConfig = uow.GuildConfigsForId(gid, set => set.Include(gc => gc.GenerateCurrencyChannelIds));
var toAdd = new GCChannelId() { ChannelId = cid }; var toAdd = new GCChannelId() { ChannelId = cid };
@@ -86,18 +83,15 @@ public class PlantPickService : INService
enabled = false; enabled = false;
} }
uow.SaveChanges(); uow.SaveChanges();
}
return enabled; return enabled;
} }
public IEnumerable<GuildConfigExtensions.GeneratingChannel> GetAllGeneratingChannels() public IEnumerable<GuildConfigExtensions.GeneratingChannel> GetAllGeneratingChannels()
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var chs = uow.GuildConfigs.GetGeneratingChannels(); var chs = uow.GuildConfigs.GetGeneratingChannels();
return chs; return chs;
} }
}
/// <summary> /// <summary>
/// Get a random currency image stream, with an optional password sticked onto it. /// Get a random currency image stream, with an optional password sticked onto it.
@@ -139,8 +133,7 @@ public class PlantPickService : INService
{ {
// draw lower, it looks better // draw lower, it looks better
pass = pass.TrimTo(10, true).ToLowerInvariant(); pass = pass.TrimTo(10, true).ToLowerInvariant();
using (var img = Image.Load<Rgba32>(curImg, out var format)) using var img = Image.Load<Rgba32>(curImg, out var format);
{
// choose font size based on the image height, so that it's visible // choose font size based on the image height, so that it's visible
var font = _fonts.NotoSans.CreateFont(img.Height / 12, FontStyle.Bold); var font = _fonts.NotoSans.CreateFont(img.Height / 12, FontStyle.Bold);
img.Mutate(x => img.Mutate(x =>
@@ -164,7 +157,6 @@ public class PlantPickService : INService
// return image as a stream for easy sending // return image as a stream for easy sending
return (img.ToStream(format), format.FileExtensions.FirstOrDefault() ?? "png"); return (img.ToStream(format), format.FileExtensions.FirstOrDefault() ?? "png");
} }
}
private Task PotentialFlowerGeneration(IUserMessage imsg) private Task PotentialFlowerGeneration(IUserMessage imsg)
{ {
@@ -309,14 +301,12 @@ public class PlantPickService : INService
msgToSend += " " + GetText(gid, strs.pick_sn(prefix)); msgToSend += " " + GetText(gid, strs.pick_sn(prefix));
//get the image //get the image
await using (var stream = GetRandomCurrencyImage(pass, out var ext)) await using var stream = GetRandomCurrencyImage(pass, out var ext);
{
// send it // send it
var msg = await ch.SendFileAsync(stream, $"img.{ext}", msgToSend).ConfigureAwait(false); var msg = await ch.SendFileAsync(stream, $"img.{ext}", msgToSend).ConfigureAwait(false);
// return sent message's id (in order to be able to delete it when it's picked) // return sent message's id (in order to be able to delete it when it's picked)
return msg.Id; return msg.Id;
} }
}
catch catch
{ {
// if sending fails, return null as message id // if sending fails, return null as message id
@@ -353,8 +343,7 @@ public class PlantPickService : INService
private async Task AddPlantToDatabase(ulong gid, ulong cid, ulong uid, ulong mid, long amount, string pass) private async Task AddPlantToDatabase(ulong gid, ulong cid, ulong uid, ulong mid, long amount, string pass)
{ {
await using (var uow = _db.GetDbContext()) await using var uow = _db.GetDbContext();
{
uow.PlantedCurrency.Add(new() uow.PlantedCurrency.Add(new()
{ {
Amount = amount, Amount = amount,
@@ -366,5 +355,4 @@ public class PlantPickService : INService
}); });
await uow.SaveChangesAsync(); await uow.SaveChangesAsync();
} }
}
} }

View File

@@ -37,8 +37,7 @@ public class WaifuService : INService
var settings = _gss.Data; var settings = _gss.Data;
await using (var uow = _db.GetDbContext()) await using var uow = _db.GetDbContext();
{
var waifu = uow.WaifuInfo.ByWaifuUserId(waifuId); var waifu = uow.WaifuInfo.ByWaifuUserId(waifuId);
var ownerUser = uow.GetOrCreateUser(owner); var ownerUser = uow.GetOrCreateUser(owner);
@@ -79,7 +78,6 @@ public class WaifuService : INService
waifu.ClaimerId = newOwnerUser.Id; waifu.ClaimerId = newOwnerUser.Id;
await uow.SaveChangesAsync(); await uow.SaveChangesAsync();
}
return true; return true;
} }
@@ -87,8 +85,7 @@ public class WaifuService : INService
public int GetResetPrice(IUser user) public int GetResetPrice(IUser user)
{ {
var settings = _gss.Data; var settings = _gss.Data;
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var waifu = uow.WaifuInfo.ByWaifuUserId(user.Id); var waifu = uow.WaifuInfo.ByWaifuUserId(user.Id);
if (waifu is null) if (waifu is null)
@@ -109,12 +106,10 @@ public class WaifuService : INService
return (int) Math.Ceiling(waifu.Price * 1.25f) + return (int) Math.Ceiling(waifu.Price * 1.25f) +
((divorces + affs + 2) * settings.Waifu.Multipliers.WaifuReset); ((divorces + affs + 2) * settings.Waifu.Multipliers.WaifuReset);
} }
}
public async Task<bool> TryReset(IUser user) public async Task<bool> TryReset(IUser user)
{ {
await using (var uow = _db.GetDbContext()) await using var uow = _db.GetDbContext();
{
var price = GetResetPrice(user); var price = GetResetPrice(user);
if (!await _cs.RemoveAsync(user.Id, "Waifu Reset", price, gamble: true)) if (!await _cs.RemoveAsync(user.Id, "Waifu Reset", price, gamble: true))
return false; return false;
@@ -147,7 +142,6 @@ public class WaifuService : INService
//wives stay though //wives stay though
uow.SaveChanges(); uow.SaveChanges();
}
return true; return true;
} }
@@ -302,11 +296,9 @@ public class WaifuService : INService
public IEnumerable<WaifuLbResult> GetTopWaifusAtPage(int page) public IEnumerable<WaifuLbResult> GetTopWaifusAtPage(int page)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
return uow.WaifuInfo.GetTop(9, page * 9); return uow.WaifuInfo.GetTop(9, page * 9);
} }
}
public ulong GetWaifuUserId(ulong ownerId, string name) public ulong GetWaifuUserId(ulong ownerId, string name)
{ {
@@ -372,8 +364,7 @@ public class WaifuService : INService
return false; return false;
} }
await using (var uow = _db.GetDbContext()) await using var uow = _db.GetDbContext();
{
var w = uow.WaifuInfo.ByWaifuUserId(giftedWaifu.Id, var w = uow.WaifuInfo.ByWaifuUserId(giftedWaifu.Id,
set => set.Include(x => x.Items) set => set.Include(x => x.Items)
.Include(x => x.Claimer)); .Include(x => x.Claimer));
@@ -396,7 +387,7 @@ public class WaifuService : INService
ItemEmoji = itemObj.ItemEmoji, ItemEmoji = itemObj.ItemEmoji,
}); });
if (w.Claimer?.UserId == from.Id) if (w.Claimer?.UserId == @from.Id)
{ {
w.Price += (int)(itemObj.Price * _gss.Data.Waifu.Multipliers.GiftEffect); w.Price += (int)(itemObj.Price * _gss.Data.Waifu.Multipliers.GiftEffect);
} }
@@ -413,15 +404,13 @@ public class WaifuService : INService
} }
await uow.SaveChangesAsync(); await uow.SaveChangesAsync();
}
return true; return true;
} }
public WaifuInfoStats GetFullWaifuInfoAsync(ulong targetId) public WaifuInfoStats GetFullWaifuInfoAsync(ulong targetId)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var wi = uow.GetWaifuInfo(targetId); var wi = uow.GetWaifuInfo(targetId);
if (wi is null) if (wi is null)
{ {
@@ -442,16 +431,13 @@ public class WaifuService : INService
return wi; return wi;
} }
}
public WaifuInfoStats GetFullWaifuInfoAsync(IGuildUser target) public WaifuInfoStats GetFullWaifuInfoAsync(IGuildUser target)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var du = uow.GetOrCreateUser(target); var du = uow.GetOrCreateUser(target);
return GetFullWaifuInfoAsync(target.Id); return GetFullWaifuInfoAsync(target.Id);
} }
}
public string GetClaimTitle(int count) public string GetClaimTitle(int count)
{ {

View File

@@ -41,18 +41,18 @@ public partial class Gambling
public sealed class SlotMachine public sealed class SlotMachine
{ {
public const int MaxValue = 5; public const int MAX_VALUE = 5;
static readonly List<Func<int[], int>> _winningCombos = new() private static readonly List<Func<int[], int>> _winningCombos = new()
{ {
//three flowers //three flowers
arr => arr.All(a=>a==MaxValue) ? 30 : 0, arr => arr.All(a=>a==MAX_VALUE) ? 30 : 0,
//three of the same //three of the same
arr => !arr.Any(a => a != arr[0]) ? 10 : 0, arr => !arr.Any(a => a != arr[0]) ? 10 : 0,
//two flowers //two flowers
arr => arr.Count(a => a == MaxValue) == 2 ? 4 : 0, arr => arr.Count(a => a == MAX_VALUE) == 2 ? 4 : 0,
//one flower //one flower
arr => arr.Any(a => a == MaxValue) ? 1 : 0, arr => arr.Any(a => a == MAX_VALUE) ? 1 : 0,
}; };
public static SlotResult Pull() public static SlotResult Pull()
@@ -60,7 +60,7 @@ public partial class Gambling
var numbers = new int[3]; var numbers = new int[3];
for (var i = 0; i < numbers.Length; i++) for (var i = 0; i < numbers.Length; i++)
{ {
numbers[i] = new NadekoRandom().Next(0, MaxValue + 1); numbers[i] = new NadekoRandom().Next(0, MAX_VALUE + 1);
} }
var multi = 0; var multi = 0;
foreach (var t in _winningCombos) foreach (var t in _winningCombos)
@@ -85,6 +85,8 @@ public partial class Gambling
} }
} }
public Task Test() => Task.CompletedTask;
[NadekoCommand, Aliases] [NadekoCommand, Aliases]
[OwnerOnly] [OwnerOnly]
public async Task SlotStats() public async Task SlotStats()
@@ -124,7 +126,6 @@ public partial class Gambling
} }
var sb = new StringBuilder(); var sb = new StringBuilder();
const int bet = 1;
var payout = 0; var payout = 0;
foreach (var key in dict.Keys.OrderByDescending(x => x)) foreach (var key in dict.Keys.OrderByDescending(x => x))
{ {
@@ -132,7 +133,7 @@ public partial class Gambling
payout += key * dict[key]; payout += key * dict[key];
} }
await SendConfirmAsync("Slot Test Results", sb.ToString(), await SendConfirmAsync("Slot Test Results", sb.ToString(),
footer: $"Total Bet: {tests * bet} | Payout: {payout * bet} | {payout * 1.0f / tests * 100}%").ConfigureAwait(false); footer: $"Total Bet: {tests} | Payout: {payout} | {payout * 1.0f / tests * 100}%").ConfigureAwait(false);
} }
[NadekoCommand, Aliases] [NadekoCommand, Aliases]
@@ -216,22 +217,20 @@ public partial class Gambling
for (var i = 0; i < 3; i++) for (var i = 0; i < 3; i++)
{ {
using (var img = Image.Load(_images.SlotEmojis[numbers[i]])) using var img = Image.Load(_images.SlotEmojis[numbers[i]]);
{
bgImage.Mutate(x => x.DrawImage(img, new Point(148 + (105 * i), 217), 1f)); bgImage.Mutate(x => x.DrawImage(img, new Point(148 + (105 * i), 217), 1f));
} }
}
var msg = GetText(strs.better_luck); var msg = GetText(strs.better_luck);
if (result.Multiplier > 0) if (result.Multiplier > 0)
{ {
if (result.Multiplier == 1f) if (Math.Abs(result.Multiplier - 1f) <= float.Epsilon)
msg = GetText(strs.slot_single(CurrencySign, 1)); msg = GetText(strs.slot_single(CurrencySign, 1));
else if (result.Multiplier == 4f) else if (Math.Abs(result.Multiplier - 4f) < float.Epsilon)
msg = GetText(strs.slot_two(CurrencySign, 4)); msg = GetText(strs.slot_two(CurrencySign, 4));
else if (result.Multiplier == 10f) else if (Math.Abs(result.Multiplier - 10f) <= float.Epsilon)
msg = GetText(strs.slot_three(10)); msg = GetText(strs.slot_three(10));
else if (result.Multiplier == 30f) else if (Math.Abs(result.Multiplier - 30f) <= float.Epsilon)
msg = GetText(strs.slot_jackpot(30)); msg = GetText(strs.slot_jackpot(30));
} }

View File

@@ -24,11 +24,9 @@ public class ChatterBotSession : IChatterBotSession
public async Task<string> Think(string message) public async Task<string> Think(string message)
{ {
using (var http = _httpFactory.CreateClient()) using var http = _httpFactory.CreateClient();
{
var res = await http.GetStringAsync(string.Format(ApiEndpoint, message)).ConfigureAwait(false); var res = await http.GetStringAsync(string.Format(ApiEndpoint, message)).ConfigureAwait(false);
var cbr = JsonConvert.DeserializeObject<ChatterBotResponse>(res); var cbr = JsonConvert.DeserializeObject<ChatterBotResponse>(res);
return cbr.BotSay.Replace("<br/>", "\n", StringComparison.InvariantCulture); return cbr.BotSay.Replace("<br/>", "\n", StringComparison.InvariantCulture);
} }
}
} }

View File

@@ -21,8 +21,7 @@ public class OfficialCleverbotSession : IChatterBotSession
public async Task<string> Think(string input) public async Task<string> Think(string input)
{ {
using (var http = _httpFactory.CreateClient()) using var http = _httpFactory.CreateClient();
{
var dataString = await http.GetStringAsync(string.Format(QueryString, input, _cs ?? "")).ConfigureAwait(false); var dataString = await http.GetStringAsync(string.Format(QueryString, input, _cs ?? "")).ConfigureAwait(false);
try try
{ {
@@ -38,7 +37,6 @@ public class OfficialCleverbotSession : IChatterBotSession
return null; return null;
} }
} }
}
} }
public class CleverbotIOSession : IChatterBotSession public class CleverbotIOSession : IChatterBotSession
@@ -62,14 +60,13 @@ public class CleverbotIOSession : IChatterBotSession
private async Task<string> GetNick() private async Task<string> GetNick()
{ {
using (var _http = _httpFactory.CreateClient()) using var _http = _httpFactory.CreateClient();
using (var msg = new FormUrlEncodedContent(new[] using var msg = new FormUrlEncodedContent(new[]
{ {
new KeyValuePair<string, string>("user", _user), new KeyValuePair<string, string>("user", _user),
new KeyValuePair<string, string>("key", _key), new KeyValuePair<string, string>("key", _key),
})) });
using (var data = await _http.PostAsync(_createEndpoint, msg).ConfigureAwait(false)) using var data = await _http.PostAsync(_createEndpoint, msg).ConfigureAwait(false);
{
var str = await data.Content.ReadAsStringAsync().ConfigureAwait(false); var str = await data.Content.ReadAsStringAsync().ConfigureAwait(false);
var obj = JsonConvert.DeserializeObject<CleverbotIOCreateResponse>(str); var obj = JsonConvert.DeserializeObject<CleverbotIOCreateResponse>(str);
if (obj.Status != "success") if (obj.Status != "success")
@@ -77,20 +74,18 @@ public class CleverbotIOSession : IChatterBotSession
return obj.Nick; return obj.Nick;
} }
}
public async Task<string> Think(string input) public async Task<string> Think(string input)
{ {
using (var _http = _httpFactory.CreateClient()) using var _http = _httpFactory.CreateClient();
using (var msg = new FormUrlEncodedContent(new[] using var msg = new FormUrlEncodedContent(new[]
{ {
new KeyValuePair<string, string>("user", _user), new KeyValuePair<string, string>("user", _user),
new KeyValuePair<string, string>("key", _key), new KeyValuePair<string, string>("key", _key),
new KeyValuePair<string, string>("nick", await _nick), new KeyValuePair<string, string>("nick", await _nick),
new KeyValuePair<string, string>("text", input), new KeyValuePair<string, string>("text", input),
})) });
using (var data = await _http.PostAsync(_askEndpoint, msg).ConfigureAwait(false)) using var data = await _http.PostAsync(_askEndpoint, msg).ConfigureAwait(false);
{
var str = await data.Content.ReadAsStringAsync().ConfigureAwait(false); var str = await data.Content.ReadAsStringAsync().ConfigureAwait(false);
var obj = JsonConvert.DeserializeObject<CleverbotIOAskResponse>(str); var obj = JsonConvert.DeserializeObject<CleverbotIOAskResponse>(str);
if (obj.Status != "success") if (obj.Status != "success")
@@ -98,5 +93,4 @@ public class CleverbotIOSession : IChatterBotSession
return obj.Response; return obj.Response;
} }
}
} }

View File

@@ -30,8 +30,7 @@ public class GirlRating
{ {
try try
{ {
using (var img = Image.Load(_images.RategirlMatrix)) using var img = Image.Load(_images.RategirlMatrix);
{
const int minx = 35; const int minx = 35;
const int miny = 385; const int miny = 385;
const int length = 345; const int length = 345;
@@ -57,7 +56,6 @@ public class GirlRating
// } // }
//} //}
} }
}
catch (Exception ex) catch (Exception ex)
{ {
Log.Warning(ex, "Error getting RateGirl image"); Log.Warning(ex, "Error getting RateGirl image");

View File

@@ -51,12 +51,10 @@ public class PollRunner
} }
finally { _locker.Release(); } finally { _locker.Release(); }
await using (var uow = _db.GetDbContext()) await using var uow = _db.GetDbContext();
{
var trackedPoll = uow.Poll.FirstOrDefault(x => x.Id == Poll.Id); var trackedPoll = uow.Poll.FirstOrDefault(x => x.Id == Poll.Id);
trackedPoll.Votes.Add(voteObj); trackedPoll.Votes.Add(voteObj);
uow.SaveChanges(); uow.SaveChanges();
}
return true; return true;
} }

View File

@@ -17,7 +17,7 @@ public class TicTacToe
public int TurnTimer { get; set; } = 15; public int TurnTimer { get; set; } = 15;
} }
enum Phase private enum Phase
{ {
Starting, Starting,
Started, Started,

View File

@@ -57,8 +57,7 @@ public partial class Games : NadekoModule<GamesService>
return; return;
} }
await using (var imgStream = new MemoryStream()) await using var imgStream = new MemoryStream();
{
lock (gr) lock (gr)
{ {
originalStream.Position = 0; originalStream.Position = 0;
@@ -75,7 +74,6 @@ public partial class Games : NadekoModule<GamesService>
.AddField("Advice", gr.Advice, false) .AddField("Advice", gr.Advice, false)
.Build()).ConfigureAwait(false); .Build()).ConfigureAwait(false);
} }
}
private double NextDouble(double x, double y) private double NextDouble(double x, double y)
{ {

View File

@@ -76,12 +76,10 @@ public class GamesService : INService
private async Task<RatingTexts> GetRatingTexts() private async Task<RatingTexts> GetRatingTexts()
{ {
using (var http = _httpFactory.CreateClient()) using var http = _httpFactory.CreateClient();
{
var text = await http.GetStringAsync("https://nadeko-pictures.nyc3.digitaloceanspaces.com/other/rategirl/rates.json"); var text = await http.GetStringAsync("https://nadeko-pictures.nyc3.digitaloceanspaces.com/other/rategirl/rates.json");
return JsonConvert.DeserializeObject<RatingTexts>(text); return JsonConvert.DeserializeObject<RatingTexts>(text);
} }
}
public void AddTypingArticle(IUser user, string text) public void AddTypingArticle(IUser user, string text)
{ {

View File

@@ -22,8 +22,7 @@ public class PollService : IEarlyBehavior
_strs = strs; _strs = strs;
_eb = eb; _eb = eb;
using (var uow = db.GetDbContext()) using var uow = db.GetDbContext();
{
ActivePolls = uow.Poll.GetAllPolls() ActivePolls = uow.Poll.GetAllPolls()
.ToDictionary(x => x.GuildId, x => .ToDictionary(x => x.GuildId, x =>
{ {
@@ -33,7 +32,6 @@ public class PollService : IEarlyBehavior
}) })
.ToConcurrent(); .ToConcurrent();
} }
}
public Poll CreatePoll(ulong guildId, ulong channelId, string input) public Poll CreatePoll(ulong guildId, ulong channelId, string input)
{ {

View File

@@ -42,11 +42,9 @@ public class RadioResolver : IRadioResolver
string file = null; string file = null;
try try
{ {
using (var http = new HttpClient()) using var http = new HttpClient();
{
file = await http.GetStringAsync(query).ConfigureAwait(false); file = await http.GetStringAsync(query).ConfigureAwait(false);
} }
}
catch catch
{ {
return query; return query;

View File

@@ -64,8 +64,7 @@ public sealed partial class Music
var success = false; var success = false;
try try
{ {
await using (var uow = _db.GetDbContext()) await using var uow = _db.GetDbContext();
{
var pl = uow.MusicPlaylists.FirstOrDefault(x => x.Id == id); var pl = uow.MusicPlaylists.FirstOrDefault(x => x.Id == id);
if (pl != null) if (pl != null)
@@ -78,7 +77,6 @@ public sealed partial class Music
} }
} }
} }
}
catch (Exception ex) catch (Exception ex)
{ {
Log.Warning(ex, "Error deleting playlist"); Log.Warning(ex, "Error deleting playlist");

View File

@@ -34,8 +34,7 @@ public sealed class FilterService : IEarlyBehavior
public void ClearFilteredWords(ulong guildId) public void ClearFilteredWords(ulong guildId)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var gc = uow.GuildConfigsForId(guildId, var gc = uow.GuildConfigsForId(guildId,
set => set.Include(x => x.FilteredWords) set => set.Include(x => x.FilteredWords)
.Include(x => x.FilterWordsChannelIds)); .Include(x => x.FilterWordsChannelIds));
@@ -54,7 +53,6 @@ public sealed class FilterService : IEarlyBehavior
uow.SaveChanges(); uow.SaveChanges();
} }
}
public ConcurrentHashSet<string> FilteredWordsForServer(ulong guildId) public ConcurrentHashSet<string> FilteredWordsForServer(ulong guildId)
{ {

View File

@@ -29,8 +29,7 @@ public class PermissionService : ILateBlocker, INService
_strings = strings; _strings = strings;
_eb = eb; _eb = eb;
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
foreach (var x in uow.GuildConfigs.Permissionsv2ForAll(client.Guilds.ToArray().Select(x => x.Id) foreach (var x in uow.GuildConfigs.Permissionsv2ForAll(client.Guilds.ToArray().Select(x => x.Id)
.ToList())) .ToList()))
{ {
@@ -42,7 +41,6 @@ public class PermissionService : ILateBlocker, INService
}); });
} }
} }
}
public PermissionCache GetCacheFor(ulong guildId) public PermissionCache GetCacheFor(ulong guildId)
{ {
@@ -63,8 +61,7 @@ public class PermissionService : ILateBlocker, INService
public async Task AddPermissions(ulong guildId, params Permissionv2[] perms) public async Task AddPermissions(ulong guildId, params Permissionv2[] perms)
{ {
await using (var uow = _db.GetDbContext()) await using var uow = _db.GetDbContext();
{
var config = uow.GcWithPermissionsv2For(guildId); var config = uow.GcWithPermissionsv2For(guildId);
//var orderedPerms = new PermissionsCollection<Permissionv2>(config.Permissions); //var orderedPerms = new PermissionsCollection<Permissionv2>(config.Permissions);
var max = config.Permissions.Max(x => x.Index); //have to set its index to be the highest var max = config.Permissions.Max(x => x.Index); //have to set its index to be the highest
@@ -76,7 +73,6 @@ public class PermissionService : ILateBlocker, INService
await uow.SaveChangesAsync(); await uow.SaveChangesAsync();
UpdateCache(config); UpdateCache(config);
} }
}
public void UpdateCache(GuildConfig config) public void UpdateCache(GuildConfig config)
{ {
@@ -170,12 +166,10 @@ public class PermissionService : ILateBlocker, INService
public async Task Reset(ulong guildId) public async Task Reset(ulong guildId)
{ {
await using (var uow = _db.GetDbContext()) await using var uow = _db.GetDbContext();
{
var config = uow.GcWithPermissionsv2For(guildId); var config = uow.GcWithPermissionsv2For(guildId);
config.Permissions = Permissionv2.GetDefaultPermlist; config.Permissions = Permissionv2.GetDefaultPermlist;
await uow.SaveChangesAsync(); await uow.SaveChangesAsync();
UpdateCache(config); UpdateCache(config);
} }
}
} }

View File

@@ -47,8 +47,7 @@ public partial class Searches
var fullQueryLink = "https://myanimelist.net/profile/" + name; var fullQueryLink = "https://myanimelist.net/profile/" + name;
var config = Configuration.Default.WithDefaultLoader(); var config = Configuration.Default.WithDefaultLoader();
using (var document = await BrowsingContext.New(config).OpenAsync(fullQueryLink).ConfigureAwait(false)) using var document = await BrowsingContext.New(config).OpenAsync(fullQueryLink).ConfigureAwait(false);
{
var imageElem = document.QuerySelector("body > div#myanimelist > div.wrapper > div#contentWrapper > div#content > div.content-container > div.container-left > div.user-profile > div.user-image > img"); var imageElem = document.QuerySelector("body > div#myanimelist > div.wrapper > div#contentWrapper > div#content > div.content-container > div.container-left > div.user-profile > div.user-image > img");
var imageUrl = ((IHtmlImageElement)imageElem)?.Source ?? "http://icecream.me/uploads/870b03f36b59cc16ebfe314ef2dde781.png"; var imageUrl = ((IHtmlImageElement)imageElem)?.Source ?? "http://icecream.me/uploads/870b03f36b59cc16ebfe314ef2dde781.png";
@@ -105,7 +104,6 @@ public partial class Searches
await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false); await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
} }
}
private static string MalInfoToEmoji(string info) private static string MalInfoToEmoji(string info)
{ {

View File

@@ -53,8 +53,7 @@ public class PicartoProvider : Provider
if (logins.Count == 0) if (logins.Count == 0)
return new(); return new();
using (var http = _httpClientFactory.CreateClient()) using var http = _httpClientFactory.CreateClient();
{
var toReturn = new List<StreamData>(); var toReturn = new List<StreamData>();
foreach (var login in logins) foreach (var login in logins)
{ {
@@ -81,7 +80,6 @@ public class PicartoProvider : Provider
return toReturn; return toReturn;
} }
}
private StreamData ToStreamData(PicartoChannelResponse stream) private StreamData ToStreamData(PicartoChannelResponse stream)
{ {

View File

@@ -53,8 +53,7 @@ public class TwitchProvider : Provider
if (logins.Count == 0) if (logins.Count == 0)
return new(); return new();
using (var http = _httpClientFactory.CreateClient()) using var http = _httpClientFactory.CreateClient();
{
http.DefaultRequestHeaders.Add("Client-Id", "67w6z9i09xv2uoojdm9l0wsyph4hxo6"); http.DefaultRequestHeaders.Add("Client-Id", "67w6z9i09xv2uoojdm9l0wsyph4hxo6");
http.DefaultRequestHeaders.Add("Accept", "application/vnd.twitchtv.v5+json"); http.DefaultRequestHeaders.Add("Accept", "application/vnd.twitchtv.v5+json");
@@ -110,7 +109,6 @@ public class TwitchProvider : Provider
return toReturn; return toReturn;
} }
}
private StreamData ToStreamData(TwitchResponseV5.Stream stream) private StreamData ToStreamData(TwitchResponseV5.Stream stream)
{ {

View File

@@ -39,8 +39,7 @@ public partial class Searches
if (--page < 0) if (--page < 0)
return; return;
using (var http = _httpFactory.CreateClient("memelist")) using var http = _httpFactory.CreateClient("memelist");
{
var res = await http.GetAsync("https://api.memegen.link/templates/") var res = await http.GetAsync("https://api.memegen.link/templates/")
.ConfigureAwait(false); .ConfigureAwait(false);
@@ -62,7 +61,6 @@ public partial class Searches
return embed; return embed;
}, data.Count, 15).ConfigureAwait(false); }, data.Count, 15).ConfigureAwait(false);
} }
}
[NadekoCommand, Aliases] [NadekoCommand, Aliases]
public async Task Memegen(string meme, [Leftover] string memeText = null) public async Task Memegen(string meme, [Leftover] string memeText = null)

View File

@@ -23,8 +23,7 @@ public partial class Searches
if (string.IsNullOrWhiteSpace(user)) if (string.IsNullOrWhiteSpace(user))
return; return;
using (var http = _httpFactory.CreateClient()) using var http = _httpFactory.CreateClient();
{
var modeNumber = string.IsNullOrWhiteSpace(mode) var modeNumber = string.IsNullOrWhiteSpace(mode)
? 0 ? 0
: ResolveGameMode(mode); : ResolveGameMode(mode);
@@ -75,13 +74,11 @@ public partial class Searches
Log.Warning(ex, "Osu command failed"); Log.Warning(ex, "Osu command failed");
} }
} }
}
[NadekoCommand, Aliases] [NadekoCommand, Aliases]
public async Task Gatari(string user, [Leftover] string mode = null) public async Task Gatari(string user, [Leftover] string mode = null)
{ {
using (var http = _httpFactory.CreateClient()) using var http = _httpFactory.CreateClient();
{
var modeNumber = string.IsNullOrWhiteSpace(mode) var modeNumber = string.IsNullOrWhiteSpace(mode)
? 0 ? 0
: ResolveGameMode(mode); : ResolveGameMode(mode);
@@ -118,7 +115,6 @@ public partial class Searches
await ctx.Channel.EmbedAsync(embed); await ctx.Channel.EmbedAsync(embed);
} }
}
[NadekoCommand, Aliases] [NadekoCommand, Aliases]
public async Task Osu5(string user, [Leftover] string mode = null) public async Task Osu5(string user, [Leftover] string mode = null)
@@ -135,8 +131,7 @@ public partial class Searches
return; return;
} }
using (var http = _httpFactory.CreateClient()) using var http = _httpFactory.CreateClient();
{
var m = 0; var m = 0;
if (!string.IsNullOrWhiteSpace(mode)) if (!string.IsNullOrWhiteSpace(mode))
{ {
@@ -191,7 +186,6 @@ public partial class Searches
await ctx.Channel.EmbedAsync(eb).ConfigureAwait(false); await ctx.Channel.EmbedAsync(eb).ConfigureAwait(false);
} }
}
//https://osu.ppy.sh/wiki/Accuracy //https://osu.ppy.sh/wiki/Accuracy
private static double CalculateAcc(OsuUserBests play, int mode) private static double CalculateAcc(OsuUserBests play, int mode)

View File

@@ -41,12 +41,10 @@ public partial class Searches
try try
{ {
using (var http = _httpFactory.CreateClient()) using var http = _httpFactory.CreateClient();
{
var res = await http.GetStringAsync($"{_poeURL}{usr}").ConfigureAwait(false); var res = await http.GetStringAsync($"{_poeURL}{usr}").ConfigureAwait(false);
characters = JsonConvert.DeserializeObject<List<Account>>(res); characters = JsonConvert.DeserializeObject<List<Account>>(res);
} }
}
catch catch
{ {
var embed = _eb.Create() var embed = _eb.Create()
@@ -102,12 +100,10 @@ public partial class Searches
try try
{ {
using (var http = _httpFactory.CreateClient()) using var http = _httpFactory.CreateClient();
{
var res = await http.GetStringAsync("http://api.pathofexile.com/leagues?type=main&compact=1").ConfigureAwait(false); var res = await http.GetStringAsync("http://api.pathofexile.com/leagues?type=main&compact=1").ConfigureAwait(false);
leagues = JsonConvert.DeserializeObject<List<Leagues>>(res); leagues = JsonConvert.DeserializeObject<List<Leagues>>(res);
} }
}
catch catch
{ {
var eembed = _eb.Create() var eembed = _eb.Create()
@@ -159,8 +155,7 @@ public partial class Searches
try try
{ {
var res = $"{_ponURL}{leagueName}"; var res = $"{_ponURL}{leagueName}";
using (var http = _httpFactory.CreateClient()) using var http = _httpFactory.CreateClient();
{
var obj = JObject.Parse(await http.GetStringAsync(res).ConfigureAwait(false)); var obj = JObject.Parse(await http.GetStringAsync(res).ConfigureAwait(false));
var chaosEquivalent = 0.0F; var chaosEquivalent = 0.0F;
@@ -201,7 +196,6 @@ public partial class Searches
await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false); await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
} }
}
catch catch
{ {
var embed = _eb.Create() var embed = _eb.Create()

View File

@@ -39,8 +39,7 @@ public partial class Searches : NadekoModule<SearchesService>
var av = usr.RealAvatarUrl(); var av = usr.RealAvatarUrl();
if (av is null) if (av is null)
return; return;
await using (var picStream = await _service.GetRipPictureAsync(usr.Nickname ?? usr.Username, av).ConfigureAwait(false)) await using var picStream = await _service.GetRipPictureAsync(usr.Nickname ?? usr.Username, av).ConfigureAwait(false);
{
await ctx.Channel.SendFileAsync( await ctx.Channel.SendFileAsync(
picStream, picStream,
"rip.png", "rip.png",
@@ -48,7 +47,6 @@ public partial class Searches : NadekoModule<SearchesService>
Format.Italics(ctx.User.ToString())) Format.Italics(ctx.User.ToString()))
.ConfigureAwait(false); .ConfigureAwait(false);
} }
}
[NadekoCommand, Aliases] [NadekoCommand, Aliases]
public async Task Weather([Leftover] string query) public async Task Weather([Leftover] string query)
@@ -224,8 +222,7 @@ public partial class Searches : NadekoModule<SearchesService>
var fullQueryLink = $"http://imgur.com/search?q={ query }"; var fullQueryLink = $"http://imgur.com/search?q={ query }";
var config = Configuration.Default.WithDefaultLoader(); var config = Configuration.Default.WithDefaultLoader();
using (var document = await BrowsingContext.New(config).OpenAsync(fullQueryLink).ConfigureAwait(false)) using var document = await BrowsingContext.New(config).OpenAsync(fullQueryLink).ConfigureAwait(false);
{
var elems = document.QuerySelectorAll("a.image-list-link").ToList(); var elems = document.QuerySelectorAll("a.image-list-link").ToList();
if (!elems.Any()) if (!elems.Any())
@@ -249,7 +246,6 @@ public partial class Searches : NadekoModule<SearchesService>
await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false); await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
} }
} }
}
[NadekoCommand, Aliases] [NadekoCommand, Aliases]
public async Task Lmgtfy([Leftover] string ffs = null) public async Task Lmgtfy([Leftover] string ffs = null)
@@ -280,17 +276,15 @@ public partial class Searches : NadekoModule<SearchesService>
{ {
try try
{ {
using (var _http = _httpFactory.CreateClient()) using var _http = _httpFactory.CreateClient();
using (var req = new HttpRequestMessage(HttpMethod.Post, "https://goolnk.com/api/v1/shorten")) using var req = new HttpRequestMessage(HttpMethod.Post, "https://goolnk.com/api/v1/shorten");
{
var formData = new MultipartFormDataContent var formData = new MultipartFormDataContent
{ {
{ new StringContent(query), "url" } { new StringContent(query), "url" }
}; };
req.Content = formData; req.Content = formData;
using (var res = await _http.SendAsync(req).ConfigureAwait(false)) using var res = await _http.SendAsync(req).ConfigureAwait(false);
{
var content = await res.Content.ReadAsStringAsync(); var content = await res.Content.ReadAsStringAsync();
var data = JsonConvert.DeserializeObject<ShortenData>(content); var data = JsonConvert.DeserializeObject<ShortenData>(content);
@@ -301,8 +295,6 @@ public partial class Searches : NadekoModule<SearchesService>
shortLink = data.ResultUrl; shortLink = data.ResultUrl;
} }
}
}
catch (Exception ex) catch (Exception ex)
{ {
Log.Error(ex, "Error shortening a link: {Message}", ex.Message); Log.Error(ex, "Error shortening a link: {Message}", ex.Message);
@@ -477,8 +469,7 @@ public partial class Searches : NadekoModule<SearchesService>
if (!await ValidateQuery(word).ConfigureAwait(false)) if (!await ValidateQuery(word).ConfigureAwait(false))
return; return;
using (var _http = _httpFactory.CreateClient()) using var _http = _httpFactory.CreateClient();
{
string res; string res;
try try
{ {
@@ -535,13 +526,11 @@ public partial class Searches : NadekoModule<SearchesService>
Log.Error(ex, "Error retrieving definition data for: {Word}", word); Log.Error(ex, "Error retrieving definition data for: {Word}", word);
} }
} }
}
[NadekoCommand, Aliases] [NadekoCommand, Aliases]
public async Task Catfact() public async Task Catfact()
{ {
using (var http = _httpFactory.CreateClient()) using var http = _httpFactory.CreateClient();
{
var response = await http.GetStringAsync("https://catfact.ninja/fact").ConfigureAwait(false); var response = await http.GetStringAsync("https://catfact.ninja/fact").ConfigureAwait(false);
if (response is null) if (response is null)
return; return;
@@ -549,7 +538,6 @@ public partial class Searches : NadekoModule<SearchesService>
var fact = JObject.Parse(response)["fact"].ToString(); var fact = JObject.Parse(response)["fact"].ToString();
await SendConfirmAsync("🐈" + GetText(strs.catfact), fact).ConfigureAwait(false); await SendConfirmAsync("🐈" + GetText(strs.catfact), fact).ConfigureAwait(false);
} }
}
//done in 3.0 //done in 3.0
[NadekoCommand, Aliases] [NadekoCommand, Aliases]
@@ -585,8 +573,7 @@ public partial class Searches : NadekoModule<SearchesService>
if (!await ValidateQuery(query).ConfigureAwait(false)) if (!await ValidateQuery(query).ConfigureAwait(false))
return; return;
using (var http = _httpFactory.CreateClient()) using var http = _httpFactory.CreateClient();
{
var result = await http.GetStringAsync("https://en.wikipedia.org//w/api.php?action=query&format=json&prop=info&redirects=1&formatversion=2&inprop=url&titles=" + Uri.EscapeDataString(query)).ConfigureAwait(false); var result = await http.GetStringAsync("https://en.wikipedia.org//w/api.php?action=query&format=json&prop=info&redirects=1&formatversion=2&inprop=url&titles=" + Uri.EscapeDataString(query)).ConfigureAwait(false);
var data = JsonConvert.DeserializeObject<WikipediaApiModel>(result); var data = JsonConvert.DeserializeObject<WikipediaApiModel>(result);
if (data.Query.Pages[0].Missing || string.IsNullOrWhiteSpace(data.Query.Pages[0].FullUrl)) if (data.Query.Pages[0].Missing || string.IsNullOrWhiteSpace(data.Query.Pages[0].FullUrl))
@@ -594,7 +581,6 @@ public partial class Searches : NadekoModule<SearchesService>
else else
await ctx.Channel.SendMessageAsync(data.Query.Pages[0].FullUrl).ConfigureAwait(false); await ctx.Channel.SendMessageAsync(data.Query.Pages[0].FullUrl).ConfigureAwait(false);
} }
}
[NadekoCommand, Aliases] [NadekoCommand, Aliases]
public async Task Color(params SixLabors.ImageSharp.Color[] colors) public async Task Color(params SixLabors.ImageSharp.Color[] colors)
@@ -605,8 +591,7 @@ public partial class Searches : NadekoModule<SearchesService>
var colorObjects = colors.Take(10) var colorObjects = colors.Take(10)
.ToArray(); .ToArray();
using (var img = new Image<Rgba32>(colorObjects.Length * 50, 50)) using var img = new Image<Rgba32>(colorObjects.Length * 50, 50);
{
for (var i = 0; i < colorObjects.Length; i++) for (var i = 0; i < colorObjects.Length; i++)
{ {
var x = i * 50; var x = i * 50;
@@ -618,12 +603,9 @@ public partial class Searches : NadekoModule<SearchesService>
})); }));
} }
await using (var ms = img.ToStream()) await using var ms = img.ToStream();
{
await ctx.Channel.SendFileAsync(ms, $"colors.png").ConfigureAwait(false); await ctx.Channel.SendFileAsync(ms, $"colors.png").ConfigureAwait(false);
} }
}
}
[NadekoCommand, Aliases] [NadekoCommand, Aliases]
[RequireContext(ContextType.Guild)] [RequireContext(ContextType.Guild)]
@@ -655,8 +637,7 @@ public partial class Searches : NadekoModule<SearchesService>
return; return;
} }
await ctx.Channel.TriggerTypingAsync().ConfigureAwait(false); await ctx.Channel.TriggerTypingAsync().ConfigureAwait(false);
using (var http = _httpFactory.CreateClient()) using var http = _httpFactory.CreateClient();
{
http.DefaultRequestHeaders.Clear(); http.DefaultRequestHeaders.Clear();
try try
{ {
@@ -685,7 +666,6 @@ public partial class Searches : NadekoModule<SearchesService>
await ReplyErrorLocalizedAsync(strs.wikia_error).ConfigureAwait(false); await ReplyErrorLocalizedAsync(strs.wikia_error).ConfigureAwait(false);
} }
} }
}
[NadekoCommand, Aliases] [NadekoCommand, Aliases]
[RequireContext(ContextType.Guild)] [RequireContext(ContextType.Guild)]
@@ -694,14 +674,12 @@ public partial class Searches : NadekoModule<SearchesService>
var obj = new BibleVerses(); var obj = new BibleVerses();
try try
{ {
using (var http = _httpFactory.CreateClient()) using var http = _httpFactory.CreateClient();
{
var res = await http var res = await http
.GetStringAsync("https://bible-api.com/" + book + " " + chapterAndVerse).ConfigureAwait(false); .GetStringAsync("https://bible-api.com/" + book + " " + chapterAndVerse).ConfigureAwait(false);
obj = JsonConvert.DeserializeObject<BibleVerses>(res); obj = JsonConvert.DeserializeObject<BibleVerses>(res);
} }
}
catch catch
{ {
} }

View File

@@ -61,8 +61,7 @@ public class AnimeSearchService : INService
if (!ok) if (!ok)
{ {
var config = Configuration.Default.WithDefaultLoader(); var config = Configuration.Default.WithDefaultLoader();
using (var document = await BrowsingContext.New(config).OpenAsync(link).ConfigureAwait(false)) using var document = await BrowsingContext.New(config).OpenAsync(link).ConfigureAwait(false);
{
var imageElem = document.QuerySelector("div.seriesimg > img"); var imageElem = document.QuerySelector("div.seriesimg > img");
if (imageElem is null) if (imageElem is null)
return null; return null;
@@ -113,7 +112,6 @@ public class AnimeSearchService : INService
return obj; return obj;
} }
}
return JsonConvert.DeserializeObject<NovelResult>(data); return JsonConvert.DeserializeObject<NovelResult>(data);
} }

View File

@@ -156,8 +156,7 @@ public class FeedsService : INService
public List<FeedSub> GetFeeds(ulong guildId) public List<FeedSub> GetFeeds(ulong guildId)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
return uow.GuildConfigsForId(guildId, return uow.GuildConfigsForId(guildId,
set => set.Include(x => x.FeedSubs) set => set.Include(x => x.FeedSubs)
.ThenInclude(x => x.GuildConfig)) .ThenInclude(x => x.GuildConfig))
@@ -165,7 +164,6 @@ public class FeedsService : INService
.OrderBy(x => x.Id) .OrderBy(x => x.Id)
.ToList(); .ToList();
} }
}
public bool AddFeed(ulong guildId, ulong channelId, string rssFeed) public bool AddFeed(ulong guildId, ulong channelId, string rssFeed)
{ {
@@ -177,8 +175,7 @@ public class FeedsService : INService
Url = rssFeed.Trim(), Url = rssFeed.Trim(),
}; };
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var gc = uow.GuildConfigsForId(guildId, var gc = uow.GuildConfigsForId(guildId,
set => set.Include(x => x.FeedSubs) set => set.Include(x => x.FeedSubs)
.ThenInclude(x => x.GuildConfig)); .ThenInclude(x => x.GuildConfig));
@@ -203,7 +200,6 @@ public class FeedsService : INService
return old; return old;
}); });
} }
}
return true; return true;
} }
@@ -213,8 +209,7 @@ public class FeedsService : INService
if (index < 0) if (index < 0)
return false; return false;
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var items = uow.GuildConfigsForId(guildId, set => set.Include(x => x.FeedSubs)) var items = uow.GuildConfigsForId(guildId, set => set.Include(x => x.FeedSubs))
.FeedSubs .FeedSubs
.OrderBy(x => x.Id) .OrderBy(x => x.Id)
@@ -230,7 +225,6 @@ public class FeedsService : INService
}); });
uow.Remove(toRemove); uow.Remove(toRemove);
uow.SaveChanges(); uow.SaveChanges();
}
return true; return true;
} }

View File

@@ -85,13 +85,11 @@ public class SearchesService : INService
public async Task<byte[]> GetRipPictureFactory((string text, Uri avatarUrl) arg) public async Task<byte[]> GetRipPictureFactory((string text, Uri avatarUrl) arg)
{ {
var (text, avatarUrl) = arg; var (text, avatarUrl) = arg;
using (var bg = Image.Load<Rgba32>(_imgs.Rip.ToArray())) using var bg = Image.Load<Rgba32>(_imgs.Rip.ToArray());
{
var (succ, data) = (false, (byte[])null); //await _cache.TryGetImageDataAsync(avatarUrl); var (succ, data) = (false, (byte[])null); //await _cache.TryGetImageDataAsync(avatarUrl);
if (!succ) if (!succ)
{ {
using (var http = _httpFactory.CreateClient()) using var http = _httpFactory.CreateClient();
{
data = await http.GetByteArrayAsync(avatarUrl); data = await http.GetByteArrayAsync(avatarUrl);
using (var avatarImg = Image.Load<Rgba32>(data)) using (var avatarImg = Image.Load<Rgba32>(data))
{ {
@@ -103,14 +101,11 @@ public class SearchesService : INService
} }
await _cache.SetImageDataAsync(avatarUrl, data); await _cache.SetImageDataAsync(avatarUrl, data);
} }
}
else else
{ {
using (var avatarImg = Image.Load<Rgba32>(data)) using var avatarImg = Image.Load<Rgba32>(data);
{
DrawAvatar(bg, avatarImg); DrawAvatar(bg, avatarImg);
} }
}
bg.Mutate(x => x.DrawText( bg.Mutate(x => x.DrawText(
new() new()
@@ -134,7 +129,6 @@ public class SearchesService : INService
return bg.ToStream().ToArray(); return bg.ToStream().ToArray();
} }
}
public Task<WeatherData> GetWeatherDataAsync(string query) public Task<WeatherData> GetWeatherDataAsync(string query)
{ {
@@ -148,8 +142,7 @@ public class SearchesService : INService
private async Task<WeatherData> GetWeatherDataFactory(string query) private async Task<WeatherData> GetWeatherDataFactory(string query)
{ {
using (var http = _httpFactory.CreateClient()) using var http = _httpFactory.CreateClient();
{
try try
{ {
var data = await http.GetStringAsync($"http://api.openweathermap.org/data/2.5/weather?" + var data = await http.GetStringAsync($"http://api.openweathermap.org/data/2.5/weather?" +
@@ -168,7 +161,6 @@ public class SearchesService : INService
return null; return null;
} }
} }
}
public Task<((string Address, DateTime Time, string TimeZoneName), TimeErrors?)> GetTimeDataAsync(string arg) public Task<((string Address, DateTime Time, string TimeZoneName), TimeErrors?)> GetTimeDataAsync(string arg)
{ {
@@ -195,8 +187,7 @@ public class SearchesService : INService
try try
{ {
using (var _http = _httpFactory.CreateClient()) using var _http = _httpFactory.CreateClient();
{
var res = await _cache.GetOrAddCachedDataAsync($"geo_{query}", _ => var res = await _cache.GetOrAddCachedDataAsync($"geo_{query}", _ =>
{ {
var url = "https://eu1.locationiq.com/v1/search.php?" + var url = "https://eu1.locationiq.com/v1/search.php?" +
@@ -217,14 +208,11 @@ public class SearchesService : INService
var geoData = responses[0]; var geoData = responses[0];
using (var req = new HttpRequestMessage(HttpMethod.Get, "http://api.timezonedb.com/v2.1/get-time-zone?" + using var req = new HttpRequestMessage(HttpMethod.Get, "http://api.timezonedb.com/v2.1/get-time-zone?" +
$"key={_creds.TimezoneDbApiKey}&format=json&" + $"key={_creds.TimezoneDbApiKey}&format=json&" +
"by=position&" + "by=position&" +
$"lat={geoData.Lat}&lng={geoData.Lon}")) $"lat={geoData.Lat}&lng={geoData.Lon}");
{ using var geoRes = await _http.SendAsync(req);
using (var geoRes = await _http.SendAsync(req))
{
var resString = await geoRes.Content.ReadAsStringAsync(); var resString = await geoRes.Content.ReadAsStringAsync();
var timeObj = JsonConvert.DeserializeObject<TimeZoneResult>(resString); var timeObj = JsonConvert.DeserializeObject<TimeZoneResult>(resString);
@@ -236,9 +224,6 @@ public class SearchesService : INService
TimeZoneName: timeObj.TimezoneName TimeZoneName: timeObj.TimezoneName
), default); ), default);
} }
}
}
}
catch (Exception ex) catch (Exception ex)
{ {
Log.Error(ex, "Weather error: {Message}", ex.Message); Log.Error(ex, "Weather error: {Message}", ex.Message);
@@ -310,22 +295,18 @@ public class SearchesService : INService
public async Task<(string Setup, string Punchline)> GetRandomJoke() public async Task<(string Setup, string Punchline)> GetRandomJoke()
{ {
using (var http = _httpFactory.CreateClient()) using var http = _httpFactory.CreateClient();
{
var res = await http.GetStringAsync("https://official-joke-api.appspot.com/random_joke"); var res = await http.GetStringAsync("https://official-joke-api.appspot.com/random_joke");
var resObj = JsonConvert.DeserializeAnonymousType(res, new {setup = "", punchline = ""}); var resObj = JsonConvert.DeserializeAnonymousType(res, new {setup = "", punchline = ""});
return (resObj.setup, resObj.punchline); return (resObj.setup, resObj.punchline);
} }
}
public async Task<string> GetChuckNorrisJoke() public async Task<string> GetChuckNorrisJoke()
{ {
using (var http = _httpFactory.CreateClient()) using var http = _httpFactory.CreateClient();
{
var response = await http.GetStringAsync(new Uri("http://api.icndb.com/jokes/random/")).ConfigureAwait(false); var response = await http.GetStringAsync(new Uri("http://api.icndb.com/jokes/random/")).ConfigureAwait(false);
return JObject.Parse(response)["value"]["joke"].ToString() + " 😆"; return JObject.Parse(response)["value"]["joke"].ToString() + " 😆";
} }
}
public async Task<MtgData> GetMtgCardAsync(string search) public async Task<MtgData> GetMtgCardAsync(string search)
{ {
@@ -367,8 +348,7 @@ public class SearchesService : INService
}; };
} }
using (var http = _httpFactory.CreateClient()) using var http = _httpFactory.CreateClient();
{
http.DefaultRequestHeaders.Clear(); http.DefaultRequestHeaders.Clear();
var response = await http.GetStringAsync($"https://api.magicthegathering.io/v1/cards?name={Uri.EscapeDataString(search)}") var response = await http.GetStringAsync($"https://api.magicthegathering.io/v1/cards?name={Uri.EscapeDataString(search)}")
.ConfigureAwait(false); .ConfigureAwait(false);
@@ -391,7 +371,6 @@ public class SearchesService : INService
return await Task.WhenAll(tasks).ConfigureAwait(false); return await Task.WhenAll(tasks).ConfigureAwait(false);
} }
}
public Task<HearthstoneCardData> GetHearthstoneCardDataAsync(string name) public Task<HearthstoneCardData> GetHearthstoneCardDataAsync(string name)
{ {
@@ -404,8 +383,7 @@ public class SearchesService : INService
private async Task<HearthstoneCardData> HearthstoneCardDataFactory(string name) private async Task<HearthstoneCardData> HearthstoneCardDataFactory(string name)
{ {
using (var http = _httpFactory.CreateClient()) using var http = _httpFactory.CreateClient();
{
http.DefaultRequestHeaders.Clear(); http.DefaultRequestHeaders.Clear();
http.DefaultRequestHeaders.Add("x-rapidapi-key", _creds.RapidApiKey); http.DefaultRequestHeaders.Add("x-rapidapi-key", _creds.RapidApiKey);
try try
@@ -437,7 +415,6 @@ public class SearchesService : INService
return null; return null;
} }
} }
}
public Task<OmdbMovie> GetMovieDataAsync(string name) public Task<OmdbMovie> GetMovieDataAsync(string name)
{ {
@@ -450,8 +427,7 @@ public class SearchesService : INService
private async Task<OmdbMovie> GetMovieDataFactory(string name) private async Task<OmdbMovie> GetMovieDataFactory(string name)
{ {
using (var http = _httpFactory.CreateClient()) using var http = _httpFactory.CreateClient();
{
var res = await http.GetStringAsync(string.Format("https://omdbapi.nadeko.bot/?t={0}&y=&plot=full&r=json", var res = await http.GetStringAsync(string.Format("https://omdbapi.nadeko.bot/?t={0}&y=&plot=full&r=json",
name.Trim().Replace(' ', '+'))).ConfigureAwait(false); name.Trim().Replace(' ', '+'))).ConfigureAwait(false);
var movie = JsonConvert.DeserializeObject<OmdbMovie>(res); var movie = JsonConvert.DeserializeObject<OmdbMovie>(res);
@@ -460,7 +436,6 @@ public class SearchesService : INService
movie.Poster = await _google.ShortenUrl(movie.Poster).ConfigureAwait(false); movie.Poster = await _google.ShortenUrl(movie.Poster).ConfigureAwait(false);
return movie; return movie;
} }
}
public async Task<int> GetSteamAppIdByName(string query) public async Task<int> GetSteamAppIdByName(string query)
{ {
@@ -486,8 +461,7 @@ public class SearchesService : INService
var gamesMap = await _cache.GetOrAddCachedDataAsync(STEAM_GAME_IDS_KEY, async _ => var gamesMap = await _cache.GetOrAddCachedDataAsync(STEAM_GAME_IDS_KEY, async _ =>
{ {
using (var http = _httpFactory.CreateClient()) using var http = _httpFactory.CreateClient();
{
// https://api.steampowered.com/ISteamApps/GetAppList/v2/ // https://api.steampowered.com/ISteamApps/GetAppList/v2/
var gamesStr = await http.GetStringAsync("https://api.steampowered.com/ISteamApps/GetAppList/v2/").ConfigureAwait(false); var gamesStr = await http.GetStringAsync("https://api.steampowered.com/ISteamApps/GetAppList/v2/").ConfigureAwait(false);
var apps = JsonConvert.DeserializeAnonymousType(gamesStr, new { applist = new { apps = new List<SteamGameId>() } }).applist.apps; var apps = JsonConvert.DeserializeAnonymousType(gamesStr, new { applist = new { apps = new List<SteamGameId>() } }).applist.apps;
@@ -499,7 +473,6 @@ public class SearchesService : INService
//await db.HashSetAsync("steam_game_ids", apps.Select(app => new HashEntry(app.Name.Trim().ToLowerInvariant(), app.AppId)).ToArray()).ConfigureAwait(false); //await db.HashSetAsync("steam_game_ids", apps.Select(app => new HashEntry(app.Name.Trim().ToLowerInvariant(), app.AppId)).ToArray()).ConfigureAwait(false);
//await db.StringSetAsync("steam_game_ids", gamesStr, TimeSpan.FromHours(24)); //await db.StringSetAsync("steam_game_ids", gamesStr, TimeSpan.FromHours(24));
//await db.KeyExpireAsync("steam_game_ids", TimeSpan.FromHours(24), CommandFlags.FireAndForget).ConfigureAwait(false); //await db.KeyExpireAsync("steam_game_ids", TimeSpan.FromHours(24), CommandFlags.FireAndForget).ConfigureAwait(false);
}
}, default(string), TimeSpan.FromHours(24)); }, default(string), TimeSpan.FromHours(24));
if (gamesMap is null) if (gamesMap is null)

View File

@@ -130,8 +130,7 @@ public sealed class StreamNotificationService : INService
var deleteGroups = failingStreams.GroupBy(x => x.Type) var deleteGroups = failingStreams.GroupBy(x => x.Type)
.ToDictionary(x => x.Key, x => x.Select(x => x.Name).ToList()); .ToDictionary(x => x.Key, x => x.Select(x => x.Name).ToList());
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
foreach (var kvp in deleteGroups) foreach (var kvp in deleteGroups)
{ {
Log.Information($"Deleting {kvp.Value.Count} {kvp.Key} streams because " + Log.Information($"Deleting {kvp.Value.Count} {kvp.Key} streams because " +
@@ -149,7 +148,6 @@ public sealed class StreamNotificationService : INService
_streamTracker.UntrackStreamByKey(new(kvp.Key, loginToDelete)); _streamTracker.UntrackStreamByKey(new(kvp.Key, loginToDelete));
} }
} }
}
catch (Exception ex) catch (Exception ex)
{ {
Log.Error("Error cleaning up FollowedStreams"); Log.Error("Error cleaning up FollowedStreams");
@@ -461,8 +459,7 @@ public sealed class StreamNotificationService : INService
public bool ToggleStreamOffline(ulong guildId) public bool ToggleStreamOffline(ulong guildId)
{ {
bool newValue; bool newValue;
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var gc = uow.GuildConfigsForId(guildId, set => set); var gc = uow.GuildConfigsForId(guildId, set => set);
newValue = gc.NotifyStreamOffline = !gc.NotifyStreamOffline; newValue = gc.NotifyStreamOffline = !gc.NotifyStreamOffline;
uow.SaveChanges(); uow.SaveChanges();
@@ -475,7 +472,6 @@ public sealed class StreamNotificationService : INService
{ {
_offlineNotificationServers.TryRemove(guildId); _offlineNotificationServers.TryRemove(guildId);
} }
}
return newValue; return newValue;
} }
@@ -510,8 +506,7 @@ public sealed class StreamNotificationService : INService
public bool SetStreamMessage(ulong guildId, int index, string message, out FollowedStream fs) public bool SetStreamMessage(ulong guildId, int index, string message, out FollowedStream fs)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var fss = uow.Set<FollowedStream>() var fss = uow.Set<FollowedStream>()
.AsQueryable() .AsQueryable()
.Where(x => x.GuildId == guildId) .Where(x => x.GuildId == guildId)
@@ -537,7 +532,6 @@ public sealed class StreamNotificationService : INService
} }
uow.SaveChanges(); uow.SaveChanges();
}
return true; return true;
} }

View File

@@ -23,8 +23,7 @@ public partial class Searches
{ {
try try
{ {
using (var http = _httpFactory.CreateClient()) using var http = _httpFactory.CreateClient();
{
var res = await http.GetStringAsync($"{_xkcdUrl}/info.0.json").ConfigureAwait(false); var res = await http.GetStringAsync($"{_xkcdUrl}/info.0.json").ConfigureAwait(false);
var comic = JsonConvert.DeserializeObject<XkcdComic>(res); var comic = JsonConvert.DeserializeObject<XkcdComic>(res);
var embed = _eb.Create().WithOkColor() var embed = _eb.Create().WithOkColor()
@@ -39,7 +38,6 @@ public partial class Searches
await sent.ModifyAsync(m => m.Embed = embed.AddField("Alt", comic.Alt.ToString(), false).Build()).ConfigureAwait(false); await sent.ModifyAsync(m => m.Embed = embed.AddField("Alt", comic.Alt.ToString(), false).Build()).ConfigureAwait(false);
} }
}
catch (HttpRequestException) catch (HttpRequestException)
{ {
await ReplyErrorLocalizedAsync(strs.comic_not_found).ConfigureAwait(false); await ReplyErrorLocalizedAsync(strs.comic_not_found).ConfigureAwait(false);
@@ -57,8 +55,7 @@ public partial class Searches
return; return;
try try
{ {
using (var http = _httpFactory.CreateClient()) using var http = _httpFactory.CreateClient();
{
var res = await http.GetStringAsync($"{_xkcdUrl}/{num}/info.0.json").ConfigureAwait(false); var res = await http.GetStringAsync($"{_xkcdUrl}/{num}/info.0.json").ConfigureAwait(false);
var comic = JsonConvert.DeserializeObject<XkcdComic>(res); var comic = JsonConvert.DeserializeObject<XkcdComic>(res);
@@ -76,7 +73,6 @@ public partial class Searches
await sent.ModifyAsync(m => m.Embed = embed.AddField("Alt", comic.Alt.ToString(), false).Build()).ConfigureAwait(false); await sent.ModifyAsync(m => m.Embed = embed.AddField("Alt", comic.Alt.ToString(), false).Build()).ConfigureAwait(false);
} }
}
catch (HttpRequestException) catch (HttpRequestException)
{ {
await ReplyErrorLocalizedAsync(strs.comic_not_found).ConfigureAwait(false); await ReplyErrorLocalizedAsync(strs.comic_not_found).ConfigureAwait(false);

View File

@@ -18,8 +18,7 @@ public class CommandMapService : IInputTransformer, INService
{ {
_eb = eb; _eb = eb;
using (var uow = db.GetDbContext()) using var uow = db.GetDbContext();
{
var guildIds = client.Guilds.Select(x => x.Id).ToList(); var guildIds = client.Guilds.Select(x => x.Id).ToList();
var configs = uow.Set<GuildConfig>() var configs = uow.Set<GuildConfig>()
.Include(gc => gc.CommandAliases) .Include(gc => gc.CommandAliases)
@@ -35,20 +34,17 @@ public class CommandMapService : IInputTransformer, INService
_db = db; _db = db;
} }
}
public int ClearAliases(ulong guildId) public int ClearAliases(ulong guildId)
{ {
AliasMaps.TryRemove(guildId, out _); AliasMaps.TryRemove(guildId, out _);
int count; int count;
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var gc = uow.GuildConfigsForId(guildId, set => set.Include(x => x.CommandAliases)); var gc = uow.GuildConfigsForId(guildId, set => set.Include(x => x.CommandAliases));
count = gc.CommandAliases.Count; count = gc.CommandAliases.Count;
gc.CommandAliases.Clear(); gc.CommandAliases.Clear();
uow.SaveChanges(); uow.SaveChanges();
}
return count; return count;
} }

View File

@@ -35,12 +35,10 @@ public class ConverterService : INService
private async Task<Rates> GetCurrencyRates() private async Task<Rates> GetCurrencyRates()
{ {
using (var http = _httpFactory.CreateClient()) using var http = _httpFactory.CreateClient();
{
var res = await http.GetStringAsync("https://convertapi.nadeko.bot/latest").ConfigureAwait(false); var res = await http.GetStringAsync("https://convertapi.nadeko.bot/latest").ConfigureAwait(false);
return JsonConvert.DeserializeObject<Rates>(res); return JsonConvert.DeserializeObject<Rates>(res);
} }
}
private async Task UpdateCurrency(bool shouldLoad) private async Task UpdateCurrency(bool shouldLoad)
{ {

View File

@@ -224,8 +224,7 @@ public class PatreonRewardsService : INService
{ {
var eligibleFor = (int)(cents * settings.PatreonCurrencyPerCent); var eligibleFor = (int)(cents * settings.PatreonCurrencyPerCent);
await using (var uow = _db.GetDbContext()) await using var uow = _db.GetDbContext();
{
var users = uow.Set<RewardedUser>(); var users = uow.Set<RewardedUser>();
var usr = await users.FirstOrDefaultAsyncEF(x => x.PatreonUserId == patreonUserId); var usr = await users.FirstOrDefaultAsyncEF(x => x.PatreonUserId == patreonUserId);
@@ -282,7 +281,6 @@ public class PatreonRewardsService : INService
return 0; return 0;
} }
}
finally finally
{ {
claimLockJustInCase.Release(); claimLockJustInCase.Release();

View File

@@ -56,24 +56,20 @@ public class RemindService : INService
private async Task RemoveReminders(List<Reminder> reminders) private async Task RemoveReminders(List<Reminder> reminders)
{ {
await using (var uow = _db.GetDbContext()) await using var uow = _db.GetDbContext();
{
uow.Set<Reminder>() uow.Set<Reminder>()
.RemoveRange(reminders); .RemoveRange(reminders);
await uow.SaveChangesAsync(); await uow.SaveChangesAsync();
} }
}
private Task<List<Reminder>> GetRemindersBeforeAsync(DateTime now) private Task<List<Reminder>> GetRemindersBeforeAsync(DateTime now)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
return uow.Reminders return uow.Reminders
.FromSqlInterpolated($"select * from reminders where ((serverid >> 22) % {_creds.TotalShards}) == {_client.ShardId} and \"when\" < {now};") .FromSqlInterpolated($"select * from reminders where ((serverid >> 22) % {_creds.TotalShards}) == {_client.ShardId} and \"when\" < {now};")
.ToListAsync(); .ToListAsync();
} }
}
public struct RemindObject public struct RemindObject
{ {

View File

@@ -431,11 +431,9 @@ public partial class Utility : NadekoModule
return msg; return msg;
}) })
}); });
await using (var stream = await JsonConvert.SerializeObject(grouping, Formatting.Indented).ToStream().ConfigureAwait(false)) await using var stream = await JsonConvert.SerializeObject(grouping, Formatting.Indented).ToStream().ConfigureAwait(false);
{
await ctx.User.SendFileAsync(stream, title, title, false).ConfigureAwait(false); await ctx.User.SendFileAsync(stream, title, title, false).ConfigureAwait(false);
} }
}
private static SemaphoreSlim sem = new(1, 1); private static SemaphoreSlim sem = new(1, 1);
[NadekoCommand, Aliases] [NadekoCommand, Aliases]

View File

@@ -52,13 +52,12 @@ public class ClubService : INService
public ClubInfo TransferClub(IUser from, IUser newOwner) public ClubInfo TransferClub(IUser from, IUser newOwner)
{ {
ClubInfo club; ClubInfo club;
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{ club = uow.Clubs.GetByOwner(@from.Id);
club = uow.Clubs.GetByOwner(from.Id);
var newOwnerUser = uow.GetOrCreateUser(newOwner); var newOwnerUser = uow.GetOrCreateUser(newOwner);
if (club is null || if (club is null ||
club.Owner.UserId != from.Id || club.Owner.UserId != @from.Id ||
!club.Users.Contains(newOwnerUser)) !club.Users.Contains(newOwnerUser))
return null; return null;
@@ -66,15 +65,13 @@ public class ClubService : INService
newOwnerUser.IsClubAdmin = true; newOwnerUser.IsClubAdmin = true;
club.Owner = newOwnerUser; club.Owner = newOwnerUser;
uow.SaveChanges(); uow.SaveChanges();
}
return club; return club;
} }
public bool ToggleAdmin(IUser owner, IUser toAdmin) public bool ToggleAdmin(IUser owner, IUser toAdmin)
{ {
bool newState; bool newState;
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var club = uow.Clubs.GetByOwner(owner.Id); var club = uow.Clubs.GetByOwner(owner.Id);
var adminUser = uow.GetOrCreateUser(toAdmin); var adminUser = uow.GetOrCreateUser(toAdmin);
@@ -87,7 +84,6 @@ public class ClubService : INService
newState = adminUser.IsClubAdmin = !adminUser.IsClubAdmin; newState = adminUser.IsClubAdmin = !adminUser.IsClubAdmin;
uow.SaveChanges(); uow.SaveChanges();
}
return newState; return newState;
} }
@@ -102,16 +98,13 @@ public class ClubService : INService
{ {
if (url != null) if (url != null)
{ {
using (var http = _httpFactory.CreateClient()) using var http = _httpFactory.CreateClient();
using (var temp = await http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false)) using var temp = await http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);
{
if (!temp.IsImage() || temp.GetImageSize() > 11) if (!temp.IsImage() || temp.GetImageSize() > 11)
return false; return false;
} }
}
await using (var uow = _db.GetDbContext()) await using var uow = _db.GetDbContext();
{
var club = uow.Clubs.GetByOwner(ownerUserId); var club = uow.Clubs.GetByOwner(ownerUserId);
if (club is null) if (club is null)
@@ -119,7 +112,6 @@ public class ClubService : INService
club.ImageUrl = url.ToString(); club.ImageUrl = url.ToString();
uow.SaveChanges(); uow.SaveChanges();
}
return true; return true;
} }
@@ -137,20 +129,17 @@ public class ClubService : INService
if (string.IsNullOrWhiteSpace(name)) if (string.IsNullOrWhiteSpace(name))
return false; return false;
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
club = uow.Clubs.GetByName(name, discrim); club = uow.Clubs.GetByName(name, discrim);
if (club is null) if (club is null)
return false; return false;
else else
return true; return true;
} }
}
public bool ApplyToClub(IUser user, ClubInfo club) public bool ApplyToClub(IUser user, ClubInfo club)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var du = uow.GetOrCreateUser(user); var du = uow.GetOrCreateUser(user);
uow.SaveChanges(); uow.SaveChanges();
@@ -173,15 +162,13 @@ public class ClubService : INService
uow.Set<ClubApplicants>().Add(app); uow.Set<ClubApplicants>().Add(app);
uow.SaveChanges(); uow.SaveChanges();
}
return true; return true;
} }
public bool AcceptApplication(ulong clubOwnerUserId, string userName, out DiscordUser discordUser) public bool AcceptApplication(ulong clubOwnerUserId, string userName, out DiscordUser discordUser)
{ {
discordUser = null; discordUser = null;
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var club = uow.Clubs.GetByOwnerOrAdmin(clubOwnerUserId); var club = uow.Clubs.GetByOwnerOrAdmin(clubOwnerUserId);
if (club is null) if (club is null)
return false; return false;
@@ -202,22 +189,18 @@ public class ClubService : INService
discordUser = applicant.User; discordUser = applicant.User;
uow.SaveChanges(); uow.SaveChanges();
}
return true; return true;
} }
public ClubInfo GetClubWithBansAndApplications(ulong ownerUserId) public ClubInfo GetClubWithBansAndApplications(ulong ownerUserId)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
return uow.Clubs.GetByOwnerOrAdmin(ownerUserId); return uow.Clubs.GetByOwnerOrAdmin(ownerUserId);
} }
}
public bool LeaveClub(IUser user) public bool LeaveClub(IUser user)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var du = uow.GetOrCreateUser(user); var du = uow.GetOrCreateUser(user);
if (du.Club is null || du.Club.OwnerId == du.Id) if (du.Club is null || du.Club.OwnerId == du.Id)
return false; return false;
@@ -225,7 +208,6 @@ public class ClubService : INService
du.Club = null; du.Club = null;
du.IsClubAdmin = false; du.IsClubAdmin = false;
uow.SaveChanges(); uow.SaveChanges();
}
return true; return true;
} }
@@ -234,52 +216,45 @@ public class ClubService : INService
if (level < 5) if (level < 5)
return false; return false;
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var club = uow.Clubs.GetByOwner(userId); var club = uow.Clubs.GetByOwner(userId);
if (club is null) if (club is null)
return false; return false;
club.MinimumLevelReq = level; club.MinimumLevelReq = level;
uow.SaveChanges(); uow.SaveChanges();
}
return true; return true;
} }
public bool ChangeClubDescription(ulong userId, string desc) public bool ChangeClubDescription(ulong userId, string desc)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var club = uow.Clubs.GetByOwner(userId); var club = uow.Clubs.GetByOwner(userId);
if (club is null) if (club is null)
return false; return false;
club.Description = desc?.TrimTo(150, true); club.Description = desc?.TrimTo(150, true);
uow.SaveChanges(); uow.SaveChanges();
}
return true; return true;
} }
public bool Disband(ulong userId, out ClubInfo club) public bool Disband(ulong userId, out ClubInfo club)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
club = uow.Clubs.GetByOwner(userId); club = uow.Clubs.GetByOwner(userId);
if (club is null) if (club is null)
return false; return false;
uow.Clubs.Remove(club); uow.Clubs.Remove(club);
uow.SaveChanges(); uow.SaveChanges();
}
return true; return true;
} }
public bool Ban(ulong bannerId, string userName, out ClubInfo club) public bool Ban(ulong bannerId, string userName, out ClubInfo club)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
club = uow.Clubs.GetByOwnerOrAdmin(bannerId); club = uow.Clubs.GetByOwnerOrAdmin(bannerId);
if (club is null) if (club is null)
return false; return false;
@@ -304,15 +279,13 @@ public class ClubService : INService
club.Applicants.Remove(app); club.Applicants.Remove(app);
uow.SaveChanges(); uow.SaveChanges();
}
return true; return true;
} }
public bool UnBan(ulong ownerUserId, string userName, out ClubInfo club) public bool UnBan(ulong ownerUserId, string userName, out ClubInfo club)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
club = uow.Clubs.GetByOwnerOrAdmin(ownerUserId); club = uow.Clubs.GetByOwnerOrAdmin(ownerUserId);
if (club is null) if (club is null)
return false; return false;
@@ -323,15 +296,13 @@ public class ClubService : INService
club.Bans.Remove(ban); club.Bans.Remove(ban);
uow.SaveChanges(); uow.SaveChanges();
}
return true; return true;
} }
public bool Kick(ulong kickerId, string userName, out ClubInfo club) public bool Kick(ulong kickerId, string userName, out ClubInfo club)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
club = uow.Clubs.GetByOwnerOrAdmin(kickerId); club = uow.Clubs.GetByOwnerOrAdmin(kickerId);
if (club is null) if (club is null)
return false; return false;
@@ -348,7 +319,6 @@ public class ClubService : INService
if (app != null) if (app != null)
club.Applicants.Remove(app); club.Applicants.Remove(app);
uow.SaveChanges(); uow.SaveChanges();
}
return true; return true;
} }

View File

@@ -32,7 +32,7 @@ public class XpService : INService
private readonly FontProvider _fonts; private readonly FontProvider _fonts;
private readonly IBotCredentials _creds; private readonly IBotCredentials _creds;
private readonly ICurrencyService _cs; private readonly ICurrencyService _cs;
private readonly Task updateXpTask; private readonly Task _updateXpTask;
private readonly IHttpClientFactory _httpFactory; private readonly IHttpClientFactory _httpFactory;
private readonly XpConfigService _xpConfig; private readonly XpConfigService _xpConfig;
private readonly IPubSub _pubSub; private readonly IPubSub _pubSub;
@@ -124,19 +124,19 @@ public class XpService : INService
allGuildConfigs.Where(x => x.XpSettings.ServerExcluded) allGuildConfigs.Where(x => x.XpSettings.ServerExcluded)
.Select(x => x.GuildId)); .Select(x => x.GuildId));
_cmd.OnMessageNoTrigger += _cmd_OnMessageNoTrigger; _cmd.OnMessageNoTrigger += Cmd_OnMessageNoTrigger;
#if !GLOBAL_NADEKO #if !GLOBAL_NADEKO
_client.UserVoiceStateUpdated += _client_OnUserVoiceStateUpdated; _client.UserVoiceStateUpdated += Client_OnUserVoiceStateUpdated;
// Scan guilds on startup. // Scan guilds on startup.
_client.GuildAvailable += _client_OnGuildAvailable; _client.GuildAvailable += Client_OnGuildAvailable;
foreach (var guild in _client.Guilds) foreach (var guild in _client.Guilds)
{ {
_client_OnGuildAvailable(guild); Client_OnGuildAvailable(guild);
} }
#endif #endif
updateXpTask = Task.Run(UpdateLoop); _updateXpTask = Task.Run(UpdateLoop);
} }
private async Task UpdateLoop() private async Task UpdateLoop()
@@ -318,8 +318,7 @@ public class XpService : INService
public void SetCurrencyReward(ulong guildId, int level, int amount) public void SetCurrencyReward(ulong guildId, int level, int amount)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var settings = uow.XpSettingsFor(guildId); var settings = uow.XpSettingsFor(guildId);
if (amount <= 0) if (amount <= 0)
@@ -347,17 +346,14 @@ public class XpService : INService
uow.SaveChanges(); uow.SaveChanges();
} }
}
public IEnumerable<XpCurrencyReward> GetCurrencyRewards(ulong id) public IEnumerable<XpCurrencyReward> GetCurrencyRewards(ulong id)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
return uow.XpSettingsFor(id) return uow.XpSettingsFor(id)
.CurrencyRewards .CurrencyRewards
.ToArray(); .ToArray();
} }
}
public IEnumerable<XpRoleReward> GetRoleRewards(ulong id) public IEnumerable<XpRoleReward> GetRoleRewards(ulong id)
{ {
@@ -410,66 +406,52 @@ public class XpService : INService
public List<UserXpStats> GetUserXps(ulong guildId, int page) public List<UserXpStats> GetUserXps(ulong guildId, int page)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
return uow.UserXpStats.GetUsersFor(guildId, page); return uow.UserXpStats.GetUsersFor(guildId, page);
} }
}
public List<UserXpStats> GetTopUserXps(ulong guildId, int count) public List<UserXpStats> GetTopUserXps(ulong guildId, int count)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
return uow.UserXpStats.GetTopUserXps(guildId, count); return uow.UserXpStats.GetTopUserXps(guildId, count);
} }
}
public DiscordUser[] GetUserXps(int page) public DiscordUser[] GetUserXps(int page)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
return uow.DiscordUser.GetUsersXpLeaderboardFor(page); return uow.DiscordUser.GetUsersXpLeaderboardFor(page);
} }
}
public async Task ChangeNotificationType(ulong userId, ulong guildId, XpNotificationLocation type) public async Task ChangeNotificationType(ulong userId, ulong guildId, XpNotificationLocation type)
{ {
await using (var uow = _db.GetDbContext()) await using var uow = _db.GetDbContext();
{
var user = uow.GetOrCreateUserXpStats(guildId, userId); var user = uow.GetOrCreateUserXpStats(guildId, userId);
user.NotifyOnLevelUp = type; user.NotifyOnLevelUp = type;
await uow.SaveChangesAsync(); await uow.SaveChangesAsync();
} }
}
public XpNotificationLocation GetNotificationType(ulong userId, ulong guildId) public XpNotificationLocation GetNotificationType(ulong userId, ulong guildId)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var user = uow.GetOrCreateUserXpStats(guildId, userId); var user = uow.GetOrCreateUserXpStats(guildId, userId);
return user.NotifyOnLevelUp; return user.NotifyOnLevelUp;
} }
}
public XpNotificationLocation GetNotificationType(IUser user) public XpNotificationLocation GetNotificationType(IUser user)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
return uow.GetOrCreateUser(user).NotifyOnLevelUp; return uow.GetOrCreateUser(user).NotifyOnLevelUp;
} }
}
public async Task ChangeNotificationType(IUser user, XpNotificationLocation type) public async Task ChangeNotificationType(IUser user, XpNotificationLocation type)
{ {
await using (var uow = _db.GetDbContext()) await using var uow = _db.GetDbContext();
{
var du = uow.GetOrCreateUser(user); var du = uow.GetOrCreateUser(user);
du.NotifyOnLevelUp = type; du.NotifyOnLevelUp = type;
await uow.SaveChangesAsync(); await uow.SaveChangesAsync();
} }
}
private Task _client_OnGuildAvailable(SocketGuild guild) private Task Client_OnGuildAvailable(SocketGuild guild)
{ {
Task.Run(() => Task.Run(() =>
{ {
@@ -482,7 +464,7 @@ public class XpService : INService
return Task.CompletedTask; return Task.CompletedTask;
} }
private Task _client_OnUserVoiceStateUpdated(SocketUser socketUser, SocketVoiceState before, SocketVoiceState after) private Task Client_OnUserVoiceStateUpdated(SocketUser socketUser, SocketVoiceState before, SocketVoiceState after)
{ {
if (socketUser is not SocketGuildUser user || user.IsBot) if (socketUser is not SocketGuildUser user || user.IsBot)
return Task.CompletedTask; return Task.CompletedTask;
@@ -605,7 +587,7 @@ public class XpService : INService
return true; return true;
} }
private Task _cmd_OnMessageNoTrigger(IUserMessage arg) private Task Cmd_OnMessageNoTrigger(IUserMessage arg)
{ {
if (arg.Author is not SocketGuildUser user || user.IsBot) if (arg.Author is not SocketGuildUser user || user.IsBot)
return Task.CompletedTask; return Task.CompletedTask;
@@ -659,15 +641,13 @@ public class XpService : INService
public void AddXp(ulong userId, ulong guildId, int amount) public void AddXp(ulong userId, ulong guildId, int amount)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var usr = uow.GetOrCreateUserXpStats(guildId, userId); var usr = uow.GetOrCreateUserXpStats(guildId, userId);
usr.AwardedXp += amount; usr.AwardedXp += amount;
uow.SaveChanges(); uow.SaveChanges();
} }
}
public bool IsServerExcluded(ulong id) public bool IsServerExcluded(ulong id)
{ {
@@ -728,8 +708,7 @@ public class XpService : INService
public bool ToggleExcludeServer(ulong id) public bool ToggleExcludeServer(ulong id)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var xpSetting = uow.XpSettingsFor(id); var xpSetting = uow.XpSettingsFor(id);
if (_excludedServers.Add(id)) if (_excludedServers.Add(id))
{ {
@@ -743,13 +722,11 @@ public class XpService : INService
uow.SaveChanges(); uow.SaveChanges();
return false; return false;
} }
}
public bool ToggleExcludeRole(ulong guildId, ulong rId) public bool ToggleExcludeRole(ulong guildId, ulong rId)
{ {
var roles = _excludedRoles.GetOrAdd(guildId, _ => new()); var roles = _excludedRoles.GetOrAdd(guildId, _ => new());
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var xpSetting = uow.XpSettingsFor(guildId); var xpSetting = uow.XpSettingsFor(guildId);
var excludeObj = new ExcludedItem var excludeObj = new ExcludedItem
{ {
@@ -780,13 +757,11 @@ public class XpService : INService
return false; return false;
} }
} }
}
public bool ToggleExcludeChannel(ulong guildId, ulong chId) public bool ToggleExcludeChannel(ulong guildId, ulong chId)
{ {
var channels = _excludedChannels.GetOrAdd(guildId, _ => new()); var channels = _excludedChannels.GetOrAdd(guildId, _ => new());
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var xpSetting = uow.XpSettingsFor(guildId); var xpSetting = uow.XpSettingsFor(guildId);
var excludeObj = new ExcludedItem var excludeObj = new ExcludedItem
{ {
@@ -815,7 +790,6 @@ public class XpService : INService
return false; return false;
} }
} }
}
public async Task<(Stream Image, IImageFormat Format)> GenerateXpImageAsync(IGuildUser user) public async Task<(Stream Image, IImageFormat Format)> GenerateXpImageAsync(IGuildUser user)
{ {
@@ -845,8 +819,7 @@ public class XpService : INService
} }
}.WithFallbackFonts(_fonts.FallBackFonts); }.WithFallbackFonts(_fonts.FallBackFonts);
using (var img = Image.Load<Rgba32>(_images.XpBackground, out var imageFormat)) using var img = Image.Load<Rgba32>(_images.XpBackground, out var imageFormat);
{
if (_template.User.Name.Show) if (_template.User.Name.Show)
{ {
var fontSize = (int)(_template.User.Name.FontSize * 0.9); var fontSize = (int)(_template.User.Name.FontSize * 0.9);
@@ -1038,8 +1011,7 @@ public class XpService : INService
await _cache.SetImageDataAsync(avatarUrl, data); await _cache.SetImageDataAsync(avatarUrl, data);
} }
using (var toDraw = Image.Load(data)) using var toDraw = Image.Load(data);
{
if (toDraw.Size() != new Size(_template.User.Icon.Size.X, _template.User.Icon.Size.Y)) if (toDraw.Size() != new Size(_template.User.Icon.Size.X, _template.User.Icon.Size.Y))
{ {
toDraw.Mutate(x => toDraw.Mutate(x =>
@@ -1049,7 +1021,6 @@ public class XpService : INService
img.Mutate(x => x.DrawImage(toDraw, img.Mutate(x => x.DrawImage(toDraw,
new Point(_template.User.Icon.Pos.X, _template.User.Icon.Pos.Y), 1)); new Point(_template.User.Icon.Pos.X, _template.User.Icon.Pos.Y), 1));
} }
}
catch (Exception ex) catch (Exception ex)
{ {
Log.Warning(ex, "Error drawing avatar image"); Log.Warning(ex, "Error drawing avatar image");
@@ -1064,10 +1035,9 @@ public class XpService : INService
img.Mutate(x => x.Resize(_template.OutputSize.X, _template.OutputSize.Y)); img.Mutate(x => x.Resize(_template.OutputSize.X, _template.OutputSize.Y));
return ((Stream) img.ToStream(imageFormat), imageFormat); return ((Stream) img.ToStream(imageFormat), imageFormat);
}
}); });
void DrawXpBar(float percent, XpBar info, Image<Rgba32> img) private void DrawXpBar(float percent, XpBar info, Image<Rgba32> img)
{ {
var x1 = info.PointA.X; var x1 = info.PointA.X;
var y1 = info.PointA.Y; var y1 = info.PointA.Y;
@@ -1151,8 +1121,7 @@ public class XpService : INService
await _cache.SetImageDataAsync(imgUrl, data); await _cache.SetImageDataAsync(imgUrl, data);
} }
using (var toDraw = Image.Load(data)) using var toDraw = Image.Load(data);
{
if (toDraw.Size() != new Size(_template.Club.Icon.Size.X, _template.Club.Icon.Size.Y)) if (toDraw.Size() != new Size(_template.Club.Icon.Size.X, _template.Club.Icon.Size.Y))
{ {
toDraw.Mutate(x => x.Resize(_template.Club.Icon.Size.X, _template.Club.Icon.Size.Y)); toDraw.Mutate(x => x.Resize(_template.Club.Icon.Size.X, _template.Club.Icon.Size.Y));
@@ -1163,7 +1132,6 @@ public class XpService : INService
new Point(_template.Club.Icon.Pos.X, _template.Club.Icon.Pos.Y), new Point(_template.Club.Icon.Pos.X, _template.Club.Icon.Pos.Y),
1)); 1));
} }
}
catch (Exception ex) catch (Exception ex)
{ {
Log.Warning(ex, "Error drawing club image"); Log.Warning(ex, "Error drawing club image");
@@ -1173,21 +1141,17 @@ public class XpService : INService
public void XpReset(ulong guildId, ulong userId) public void XpReset(ulong guildId, ulong userId)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
uow.UserXpStats.ResetGuildUserXp(userId, guildId); uow.UserXpStats.ResetGuildUserXp(userId, guildId);
uow.SaveChanges(); uow.SaveChanges();
} }
}
public void XpReset(ulong guildId) public void XpReset(ulong guildId)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
uow.UserXpStats.ResetGuildXp(guildId); uow.UserXpStats.ResetGuildXp(guildId);
uow.SaveChanges(); uow.SaveChanges();
} }
}
public async Task ResetXpRewards(ulong guildId) public async Task ResetXpRewards(ulong guildId)
{ {

View File

@@ -8,6 +8,7 @@
<RunWorkingDirectory>$(MSBuildProjectDirectory)</RunWorkingDirectory> <RunWorkingDirectory>$(MSBuildProjectDirectory)</RunWorkingDirectory>
<OutputType>exe</OutputType> <OutputType>exe</OutputType>
<ApplicationIcon>nadeko_icon.ico</ApplicationIcon> <ApplicationIcon>nadeko_icon.ico</ApplicationIcon>
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>

View File

@@ -28,8 +28,7 @@ public class DbService
public void Setup() public void Setup()
{ {
using (var context = new NadekoContext(options)) using var context = new NadekoContext(options);
{
if (context.Database.GetPendingMigrations().Any()) if (context.Database.GetPendingMigrations().Any())
{ {
var mContext = new NadekoContext(migrateOptions); var mContext = new NadekoContext(migrateOptions);
@@ -40,7 +39,6 @@ public class DbService
context.Database.ExecuteSqlRaw("PRAGMA journal_mode=WAL"); context.Database.ExecuteSqlRaw("PRAGMA journal_mode=WAL");
context.SaveChanges(); context.SaveChanges();
} }
}
private NadekoContext GetDbContextInternal() private NadekoContext GetDbContextInternal()
{ {
@@ -48,11 +46,9 @@ public class DbService
context.Database.SetCommandTimeout(60); context.Database.SetCommandTimeout(60);
var conn = context.Database.GetDbConnection(); var conn = context.Database.GetDbConnection();
conn.Open(); conn.Open();
using (var com = conn.CreateCommand()) using var com = conn.CreateCommand();
{
com.CommandText = "PRAGMA journal_mode=WAL; PRAGMA synchronous=OFF"; com.CommandText = "PRAGMA journal_mode=WAL; PRAGMA synchronous=OFF";
com.ExecuteNonQuery(); com.ExecuteNonQuery();
}
return context; return context;
} }

View File

@@ -148,19 +148,15 @@ public class GreetSettingsService : INService
public string GetDmGreetMsg(ulong id) public string GetDmGreetMsg(ulong id)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
return uow.GuildConfigsForId(id, set => set)?.DmGreetMessageText; return uow.GuildConfigsForId(id, set => set)?.DmGreetMessageText;
} }
}
public string GetGreetMsg(ulong gid) public string GetGreetMsg(ulong gid)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
return uow.GuildConfigsForId(gid, set => set).ChannelGreetMessageText; return uow.GuildConfigsForId(gid, set => set).ChannelGreetMessageText;
} }
}
public string GetBoostMessage(ulong gid) public string GetBoostMessage(ulong gid)
{ {
@@ -308,11 +304,9 @@ public class GreetSettingsService : INService
public string GetByeMessage(ulong gid) public string GetByeMessage(ulong gid)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
return uow.GuildConfigsForId(gid, set => set).ChannelByeMessageText; return uow.GuildConfigsForId(gid, set => set).ChannelByeMessageText;
} }
}
public GreetSettings GetOrAddSettingsForGuild(ulong guildId) public GreetSettings GetOrAddSettingsForGuild(ulong guildId)
{ {
@@ -340,8 +334,7 @@ public class GreetSettingsService : INService
return false; return false;
} }
await using (var uow = _db.GetDbContext()) await using var uow = _db.GetDbContext();
{
var conf = uow.GuildConfigsForId(guildId, set => set); var conf = uow.GuildConfigsForId(guildId, set => set);
conf.DmGreetMessageText = settings.DmGreetMessageText?.SanitizeMentions(); conf.DmGreetMessageText = settings.DmGreetMessageText?.SanitizeMentions();
conf.ChannelGreetMessageText = settings.ChannelGreetMessageText?.SanitizeMentions(); conf.ChannelGreetMessageText = settings.ChannelGreetMessageText?.SanitizeMentions();
@@ -363,7 +356,6 @@ public class GreetSettingsService : INService
var toAdd = GreetSettings.Create(conf); var toAdd = GreetSettings.Create(conf);
GuildConfigsCache.AddOrUpdate(guildId, toAdd, (key, old) => toAdd); GuildConfigsCache.AddOrUpdate(guildId, toAdd, (key, old) => toAdd);
}
return true; return true;
} }
@@ -371,8 +363,7 @@ public class GreetSettingsService : INService
public async Task<bool> SetGreet(ulong guildId, ulong channelId, bool? value = null) public async Task<bool> SetGreet(ulong guildId, ulong channelId, bool? value = null)
{ {
bool enabled; bool enabled;
await using (var uow = _db.GetDbContext()) await using var uow = _db.GetDbContext();
{
var conf = uow.GuildConfigsForId(guildId, set => set); var conf = uow.GuildConfigsForId(guildId, set => set);
enabled = conf.SendChannelGreetMessage = value ?? !conf.SendChannelGreetMessage; enabled = conf.SendChannelGreetMessage = value ?? !conf.SendChannelGreetMessage;
conf.GreetMessageChannelId = channelId; conf.GreetMessageChannelId = channelId;
@@ -381,7 +372,6 @@ public class GreetSettingsService : INService
GuildConfigsCache.AddOrUpdate(guildId, toAdd, (key, old) => toAdd); GuildConfigsCache.AddOrUpdate(guildId, toAdd, (key, old) => toAdd);
await uow.SaveChangesAsync(); await uow.SaveChangesAsync();
}
return enabled; return enabled;
} }
@@ -393,8 +383,7 @@ public class GreetSettingsService : INService
throw new ArgumentNullException(nameof(message)); throw new ArgumentNullException(nameof(message));
bool greetMsgEnabled; bool greetMsgEnabled;
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var conf = uow.GuildConfigsForId(guildId, set => set); var conf = uow.GuildConfigsForId(guildId, set => set);
conf.ChannelGreetMessageText = message; conf.ChannelGreetMessageText = message;
greetMsgEnabled = conf.SendChannelGreetMessage; greetMsgEnabled = conf.SendChannelGreetMessage;
@@ -403,15 +392,13 @@ public class GreetSettingsService : INService
GuildConfigsCache.AddOrUpdate(guildId, toAdd, (key, old) => toAdd); GuildConfigsCache.AddOrUpdate(guildId, toAdd, (key, old) => toAdd);
uow.SaveChanges(); uow.SaveChanges();
}
return greetMsgEnabled; return greetMsgEnabled;
} }
public async Task<bool> SetGreetDm(ulong guildId, bool? value = null) public async Task<bool> SetGreetDm(ulong guildId, bool? value = null)
{ {
bool enabled; bool enabled;
await using (var uow = _db.GetDbContext()) await using var uow = _db.GetDbContext();
{
var conf = uow.GuildConfigsForId(guildId, set => set); var conf = uow.GuildConfigsForId(guildId, set => set);
enabled = conf.SendDmGreetMessage = value ?? !conf.SendDmGreetMessage; enabled = conf.SendDmGreetMessage = value ?? !conf.SendDmGreetMessage;
@@ -419,37 +406,30 @@ public class GreetSettingsService : INService
GuildConfigsCache.AddOrUpdate(guildId, toAdd, (key, old) => toAdd); GuildConfigsCache.AddOrUpdate(guildId, toAdd, (key, old) => toAdd);
await uow.SaveChangesAsync(); await uow.SaveChangesAsync();
}
return enabled; return enabled;
} }
#region Get Enabled Status #region Get Enabled Status
public bool GetGreetDmEnabled(ulong guildId) public bool GetGreetDmEnabled(ulong guildId)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var conf = uow.GuildConfigsForId(guildId, set => set); var conf = uow.GuildConfigsForId(guildId, set => set);
return conf.SendDmGreetMessage; return conf.SendDmGreetMessage;
} }
}
public bool GetGreetEnabled(ulong guildId) public bool GetGreetEnabled(ulong guildId)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var conf = uow.GuildConfigsForId(guildId, set => set); var conf = uow.GuildConfigsForId(guildId, set => set);
return conf.SendChannelGreetMessage; return conf.SendChannelGreetMessage;
} }
}
public bool GetByeEnabled(ulong guildId) public bool GetByeEnabled(ulong guildId)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var conf = uow.GuildConfigsForId(guildId, set => set); var conf = uow.GuildConfigsForId(guildId, set => set);
return conf.SendChannelByeMessage; return conf.SendChannelByeMessage;
} }
}
#endregion #endregion
#region Test Messages #region Test Messages
@@ -481,8 +461,7 @@ public class GreetSettingsService : INService
throw new ArgumentNullException(nameof(message)); throw new ArgumentNullException(nameof(message));
bool greetMsgEnabled; bool greetMsgEnabled;
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var conf = uow.GuildConfigsForId(guildId, set => set); var conf = uow.GuildConfigsForId(guildId, set => set);
conf.DmGreetMessageText = message; conf.DmGreetMessageText = message;
greetMsgEnabled = conf.SendDmGreetMessage; greetMsgEnabled = conf.SendDmGreetMessage;
@@ -491,15 +470,13 @@ public class GreetSettingsService : INService
GuildConfigsCache.AddOrUpdate(guildId, toAdd, (key, old) => toAdd); GuildConfigsCache.AddOrUpdate(guildId, toAdd, (key, old) => toAdd);
uow.SaveChanges(); uow.SaveChanges();
}
return greetMsgEnabled; return greetMsgEnabled;
} }
public async Task<bool> SetBye(ulong guildId, ulong channelId, bool? value = null) public async Task<bool> SetBye(ulong guildId, ulong channelId, bool? value = null)
{ {
bool enabled; bool enabled;
await using (var uow = _db.GetDbContext()) await using var uow = _db.GetDbContext();
{
var conf = uow.GuildConfigsForId(guildId, set => set); var conf = uow.GuildConfigsForId(guildId, set => set);
enabled = conf.SendChannelByeMessage = value ?? !conf.SendChannelByeMessage; enabled = conf.SendChannelByeMessage = value ?? !conf.SendChannelByeMessage;
conf.ByeMessageChannelId = channelId; conf.ByeMessageChannelId = channelId;
@@ -508,7 +485,6 @@ public class GreetSettingsService : INService
GuildConfigsCache.AddOrUpdate(guildId, toAdd, (key, old) => toAdd); GuildConfigsCache.AddOrUpdate(guildId, toAdd, (key, old) => toAdd);
await uow.SaveChangesAsync(); await uow.SaveChangesAsync();
}
return enabled; return enabled;
} }
@@ -520,8 +496,7 @@ public class GreetSettingsService : INService
throw new ArgumentNullException(nameof(message)); throw new ArgumentNullException(nameof(message));
bool byeMsgEnabled; bool byeMsgEnabled;
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var conf = uow.GuildConfigsForId(guildId, set => set); var conf = uow.GuildConfigsForId(guildId, set => set);
conf.ChannelByeMessageText = message; conf.ChannelByeMessageText = message;
byeMsgEnabled = conf.SendChannelByeMessage; byeMsgEnabled = conf.SendChannelByeMessage;
@@ -530,7 +505,6 @@ public class GreetSettingsService : INService
GuildConfigsCache.AddOrUpdate(guildId, toAdd, (key, old) => toAdd); GuildConfigsCache.AddOrUpdate(guildId, toAdd, (key, old) => toAdd);
uow.SaveChanges(); uow.SaveChanges();
}
return byeMsgEnabled; return byeMsgEnabled;
} }
@@ -539,8 +513,7 @@ public class GreetSettingsService : INService
if (timer < 0 || timer > 600) if (timer < 0 || timer > 600)
return; return;
await using (var uow = _db.GetDbContext()) await using var uow = _db.GetDbContext();
{
var conf = uow.GuildConfigsForId(guildId, set => set); var conf = uow.GuildConfigsForId(guildId, set => set);
conf.AutoDeleteByeMessagesTimer = timer; conf.AutoDeleteByeMessagesTimer = timer;
@@ -549,15 +522,13 @@ public class GreetSettingsService : INService
await uow.SaveChangesAsync(); await uow.SaveChangesAsync();
} }
}
public async Task SetGreetDel(ulong id, int timer) public async Task SetGreetDel(ulong id, int timer)
{ {
if (timer < 0 || timer > 600) if (timer < 0 || timer > 600)
return; return;
await using (var uow = _db.GetDbContext()) await using var uow = _db.GetDbContext();
{
var conf = uow.GuildConfigsForId(id, set => set); var conf = uow.GuildConfigsForId(id, set => set);
conf.AutoDeleteGreetMessagesTimer = timer; conf.AutoDeleteGreetMessagesTimer = timer;
@@ -566,7 +537,6 @@ public class GreetSettingsService : INService
await uow.SaveChangesAsync(); await uow.SaveChangesAsync();
} }
}
public bool SetBoostMessage(ulong guildId, ref string message) public bool SetBoostMessage(ulong guildId, ref string message)
{ {

View File

@@ -54,12 +54,10 @@ public class CurrencyService : ICurrencyService, INService
throw new ArgumentException("You can't add negative amounts. Use RemoveAsync method for that.", nameof(amount)); throw new ArgumentException("You can't add negative amounts. Use RemoveAsync method for that.", nameof(amount));
} }
await using (var uow = _db.GetDbContext()) await using var uow = _db.GetDbContext();
{
InternalChange(userId, userName, discrim, avatar, reason, amount, gamble, uow); InternalChange(userId, userName, discrim, avatar, reason, amount, gamble, uow);
await uow.SaveChangesAsync(); await uow.SaveChangesAsync();
} }
}
public Task AddAsync(ulong userId, string reason, long amount, bool gamble = false) public Task AddAsync(ulong userId, string reason, long amount, bool gamble = false)
{ {
@@ -98,8 +96,7 @@ public class CurrencyService : ICurrencyService, INService
throw new ArgumentException("Cannot perform bulk operation. Arrays are not of equal length."); throw new ArgumentException("Cannot perform bulk operation. Arrays are not of equal length.");
var userIdHashSet = new HashSet<ulong>(idArray.Length); var userIdHashSet = new HashSet<ulong>(idArray.Length);
await using (var uow = _db.GetDbContext()) await using var uow = _db.GetDbContext();
{
for (var i = 0; i < idArray.Length; i++) for (var i = 0; i < idArray.Length; i++)
{ {
// i have to prevent same user changing more than once as it will cause db error // i have to prevent same user changing more than once as it will cause db error
@@ -108,7 +105,6 @@ public class CurrencyService : ICurrencyService, INService
} }
await uow.SaveChangesAsync(); await uow.SaveChangesAsync();
} }
}
public async Task RemoveBulkAsync(IEnumerable<ulong> userIds, IEnumerable<string> reasons, IEnumerable<long> amounts, bool gamble = false) public async Task RemoveBulkAsync(IEnumerable<ulong> userIds, IEnumerable<string> reasons, IEnumerable<long> amounts, bool gamble = false)
{ {
@@ -120,8 +116,7 @@ public class CurrencyService : ICurrencyService, INService
throw new ArgumentException("Cannot perform bulk operation. Arrays are not of equal length."); throw new ArgumentException("Cannot perform bulk operation. Arrays are not of equal length.");
var userIdHashSet = new HashSet<ulong>(idArray.Length); var userIdHashSet = new HashSet<ulong>(idArray.Length);
await using (var uow = _db.GetDbContext()) await using var uow = _db.GetDbContext();
{
for (var i = 0; i < idArray.Length; i++) for (var i = 0; i < idArray.Length; i++)
{ {
// i have to prevent same user changing more than once as it will cause db error // i have to prevent same user changing more than once as it will cause db error
@@ -130,7 +125,6 @@ public class CurrencyService : ICurrencyService, INService
} }
await uow.SaveChangesAsync(); await uow.SaveChangesAsync();
} }
}
private async Task<bool> InternalRemoveAsync(ulong userId, string userName, string userDiscrim, string avatar, string reason, long amount, bool gamble = false) private async Task<bool> InternalRemoveAsync(ulong userId, string userName, string userDiscrim, string avatar, string reason, long amount, bool gamble = false)
{ {
@@ -140,11 +134,9 @@ public class CurrencyService : ICurrencyService, INService
} }
bool result; bool result;
await using (var uow = _db.GetDbContext()) await using var uow = _db.GetDbContext();
{
result = InternalChange(userId, userName, userDiscrim, avatar, reason, -amount, gamble, uow); result = InternalChange(userId, userName, userDiscrim, avatar, reason, -amount, gamble, uow);
await uow.SaveChangesAsync(); await uow.SaveChangesAsync();
}
return result; return result;
} }

View File

@@ -66,14 +66,12 @@ public class Localization : ILocalization, INService
if (GuildCultureInfos.TryRemove(guildId, out var _)) if (GuildCultureInfos.TryRemove(guildId, out var _))
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{
var gc = uow.GuildConfigsForId(guildId, set => set); var gc = uow.GuildConfigsForId(guildId, set => set);
gc.Locale = null; gc.Locale = null;
uow.SaveChanges(); uow.SaveChanges();
} }
} }
}
public void SetDefaultCulture(CultureInfo ci) public void SetDefaultCulture(CultureInfo ci)
{ {

View File

@@ -120,23 +120,19 @@ public class StatsService : IStatsService, IReadyExecutor, INService, IDisposabl
return; return;
try try
{ {
using (var http = _httpFactory.CreateClient()) using var http = _httpFactory.CreateClient();
{ using var content = new FormUrlEncodedContent(
using (var content = new FormUrlEncodedContent(
new Dictionary<string, string> { new Dictionary<string, string> {
{ "shard_count", _creds.TotalShards.ToString()}, { "shard_count", _creds.TotalShards.ToString()},
{ "shard_id", client.ShardId.ToString() }, { "shard_id", client.ShardId.ToString() },
{ "server_count", client.Guilds.Count().ToString() } { "server_count", client.Guilds.Count().ToString() }
})) });
{
content.Headers.Clear(); content.Headers.Clear();
content.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
http.DefaultRequestHeaders.Add("Authorization", _creds.BotListToken); http.DefaultRequestHeaders.Add("Authorization", _creds.BotListToken);
using (await http.PostAsync(new Uri($"https://discordbots.org/api/bots/{client.CurrentUser.Id}/stats"), content).ConfigureAwait(false)) { } using (await http.PostAsync(new Uri($"https://discordbots.org/api/bots/{client.CurrentUser.Id}/stats"), content).ConfigureAwait(false)) { }
} }
}
}
catch (Exception ex) catch (Exception ex)
{ {
Log.Error(ex, "Error "); Log.Error(ex, "Error ");

View File

@@ -1,4 +1,5 @@
using NadekoBot.Db.Models; using Discord;
using NadekoBot.Db.Models;
namespace NadekoBot.Extensions; namespace NadekoBot.Extensions;
@@ -55,14 +56,12 @@ public static class IUserExtensions
public static async Task<IUserMessage> SendFileAsync(this IUser user, string filePath, string caption = null, string text = null, bool isTTS = false) public static async Task<IUserMessage> SendFileAsync(this IUser user, string filePath, string caption = null, string text = null, bool isTTS = false)
{ {
await using (var file = File.Open(filePath, FileMode.Open)) await using var file = File.Open(filePath, FileMode.Open);
{ return await UserExtensions.SendFileAsync(user, file, caption ?? "x", text, isTTS).ConfigureAwait(false);
return await user.SendFileAsync(file, caption ?? "x", text, isTTS).ConfigureAwait(false);
}
} }
public static async Task<IUserMessage> SendFileAsync(this IUser user, Stream fileStream, string fileName, string caption = null, bool isTTS = false) => public static async Task<IUserMessage> SendFileAsync(this IUser user, Stream fileStream, string fileName, string caption = null, bool isTTS = false) =>
await user.SendFileAsync(fileStream, fileName, caption, isTTS).ConfigureAwait(false); await UserExtensions.SendFileAsync(user, fileStream, fileName, caption, isTTS).ConfigureAwait(false);
// This method is used by everything that fetches the avatar from a user // This method is used by everything that fetches the avatar from a user
public static Uri RealAvatarUrl(this IUser usr, ushort size = 128) public static Uri RealAvatarUrl(this IUser usr, ushort size = 128)

View File

@@ -49,8 +49,7 @@ public static class ProcessExtensions
if (exitCode == 0 && !string.IsNullOrEmpty(stdout)) if (exitCode == 0 && !string.IsNullOrEmpty(stdout))
{ {
using (var reader = new StringReader(stdout)) using var reader = new StringReader(stdout);
{
while (true) while (true)
{ {
var text = reader.ReadLine(); var text = reader.ReadLine();
@@ -68,7 +67,6 @@ public static class ProcessExtensions
} }
} }
} }
}
private static void KillProcessUnix(int processId, TimeSpan timeout) private static void KillProcessUnix(int processId, TimeSpan timeout)
{ {