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}]
indent_style = space
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.style = all_upper_style
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.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.severity = suggestion
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_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.word_separator = _
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_kinds = field
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_kinds = field
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_kinds =
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_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_other_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;
[AttributeUsage(AttributeTargets.Class)]
sealed class NadekoModuleAttribute : GroupAttribute
internal sealed class NadekoModuleAttribute : GroupAttribute
{
public NadekoModuleAttribute(string moduleName) : base(moduleName)
{

View File

@@ -4,7 +4,7 @@ namespace NadekoBot.Common;
public class NadekoRandom : Random
{
readonly RandomNumberGenerator _rng;
private readonly RandomNumberGenerator _rng;
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
{
using (var p = new Parser(x =>
using var p = new Parser(x =>
{
x.HelpWriter = null;
}))
{
});
var res = p.ParseArguments<T>(args);
options = res.MapResult(x => x, x => options);
options.NormalizeOptions();
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)
{
using (var uow = _db.GetDbContext())
{
using var uow = _db.GetDbContext();
var conf = uow.GuildConfigsForId(guildId,
set => set.Include(x => x.DelMsgOnCmdChannels));
return (conf.DeleteMessageOnCommand, conf.DelMsgOnCmdChannels);
}
}
private Task DelMsgOnCmd_Handler(IUserMessage msg, CommandInfo cmd)
{
@@ -70,13 +68,11 @@ public class AdministrationService : INService
public bool ToggleDeleteMessageOnCommand(ulong guildId)
{
bool enabled;
using (var uow = _db.GetDbContext())
{
using var uow = _db.GetDbContext();
var conf = uow.GuildConfigsForId(guildId, set => set);
enabled = conf.DeleteMessageOnCommand = !conf.DeleteMessageOnCommand;
uow.SaveChanges();
}
return enabled;
}

View File

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

View File

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

View File

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

View File

@@ -59,8 +59,7 @@ public class GuildTimezoneService : INService
public void SetTimeZone(ulong guildId, TimeZoneInfo tz)
{
using (var uow = _db.GetDbContext())
{
using var uow = _db.GetDbContext();
var gc = uow.GuildConfigsForId(guildId, set => set);
gc.TimeZoneId = tz?.Id;
@@ -71,7 +70,6 @@ public class GuildTimezoneService : INService
else
_timezones.AddOrUpdate(guildId, tz, (key, old) => tz);
}
}
public TimeZoneInfo GetTimeZoneOrUtc(ulong guildId)
=> 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)
{
await using (var uow = _db.GetDbContext())
{
await using var uow = _db.GetDbContext();
var logSetting = uow.LogSettingsFor(guildId);
logSetting.LogOtherId =
@@ -222,7 +221,6 @@ public sealed class LogCommandService : ILogCommandService
await uow.SaveChangesAsync();
GuildLogSettings.AddOrUpdate(guildId, id => logSetting, (id, old) => logSetting);
}
}
private Task _client_UserUpdated(SocketUser before, SocketUser uAfter)
{
@@ -1193,8 +1191,7 @@ public sealed class LogCommandService : ILogCommandService
private void UnsetLogSetting(ulong guildId, LogType logChannelType)
{
using (var uow = _db.GetDbContext())
{
using var uow = _db.GetDbContext();
var newLogSetting = uow.LogSettingsFor(guildId);
switch (logChannelType)
{
@@ -1248,5 +1245,4 @@ public sealed class LogCommandService : ILogCommandService
GuildLogSettings.AddOrUpdate(guildId, newLogSetting, (gid, old) => newLogSetting);
uow.SaveChanges();
}
}
}

View File

@@ -163,14 +163,12 @@ public class MuteService : INService
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);
config.MuteRoleName = name;
GuildMuteRoles.AddOrUpdate(guildId, name, (id, old) => name);
await uow.SaveChangesAsync();
}
}
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)
{
using (var uow = _db.GetDbContext())
{
using var uow = _db.GetDbContext();
object toDelete;
if (type == TimerType.Mute)
{
@@ -464,5 +461,4 @@ public class MuteService : INService
}
uow.SaveChanges();
}
}
}

View File

@@ -290,13 +290,11 @@ public class ProtectionService : INService
_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));
gc.AntiRaidSetting = stats.AntiRaidSettings;
await uow.SaveChangesAsync();
}
return stats;
}
@@ -305,13 +303,11 @@ public class ProtectionService : INService
{
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));
gc.AntiRaidSetting = null;
uow.SaveChanges();
}
return true;
}
return false;
@@ -322,14 +318,12 @@ public class ProtectionService : INService
if (_antiSpamGuilds.TryRemove(guildId, out var removed))
{
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)
.ThenInclude(x => x.IgnoredChannels));
gc.AntiSpamSetting = null;
uow.SaveChanges();
}
return true;
}
return false;
@@ -361,8 +355,7 @@ public class ProtectionService : INService
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));
if (gc.AntiSpamSetting != null)
@@ -377,7 +370,6 @@ public class ProtectionService : INService
gc.AntiSpamSetting = stats.AntiSpamSettings;
}
await uow.SaveChangesAsync();
}
return stats;
}
@@ -388,8 +380,7 @@ public class ProtectionService : INService
ChannelId = channelId
};
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 spam = gc.AntiSpamSetting;
if (spam is null)
@@ -415,7 +406,6 @@ public class ProtectionService : INService
}
await uow.SaveChangesAsync();
}
return added;
}

View File

@@ -163,8 +163,7 @@ public class RoleCommandsService : INService
public void Remove(ulong id, int index)
{
using (var uow = _db.GetDbContext())
{
using var uow = _db.GetDbContext();
var gc = uow.GuildConfigsForId(id,
set => set.Include(x => x.ReactionRoleMessages)
.ThenInclude(x => x.ReactionRoles));
@@ -176,7 +175,6 @@ public class RoleCommandsService : INService
delegate { return gc.ReactionRoleMessages; });
uow.SaveChanges();
}
}
/// <summary>
/// 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)
{
using (var uow = _db.GetDbContext())
{
using var uow = _db.GetDbContext();
var roles = uow.SelfAssignableRoles.GetFromGuild(guildId);
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()
{
Group = group,
Group = @group,
RoleId = role.Id,
GuildId = role.Guild.Id
});
uow.SaveChanges();
}
return true;
}
public bool ToggleAdSarm(ulong guildId)
{
bool newval;
using (var uow = _db.GetDbContext())
{
using var uow = _db.GetDbContext();
var config = uow.GuildConfigsForId(guildId, set => set);
newval = config.AutoDeleteSelfAssignedRoleMessages = !config.AutoDeleteSelfAssignedRoleMessages;
uow.SaveChanges();
}
return newval;
}
@@ -129,10 +125,9 @@ public class SelfAssignedRolesService : INService
public async Task<bool> SetNameAsync(ulong guildId, int group, string name)
{
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 toUpdate = gc.SelfAssignableRoleGroupNames.FirstOrDefault(x => x.Number == group);
var toUpdate = gc.SelfAssignableRoleGroupNames.FirstOrDefault(x => x.Number == @group);
if (string.IsNullOrWhiteSpace(name))
{
@@ -144,7 +139,7 @@ public class SelfAssignedRolesService : INService
gc.SelfAssignableRoleGroupNames.Add(new()
{
Name = name,
Number = group,
Number = @group,
});
set = true;
}
@@ -155,7 +150,6 @@ public class SelfAssignedRolesService : INService
}
await uow.SaveChangesAsync();
}
return set;
}
@@ -187,18 +181,15 @@ public class SelfAssignedRolesService : INService
public bool RemoveSar(ulong guildId, ulong roleId)
{
bool success;
using (var uow = _db.GetDbContext())
{
using var uow = _db.GetDbContext();
success = uow.SelfAssignableRoles.DeleteByGuildAndRoleId(guildId, roleId);
uow.SaveChanges();
}
return success;
}
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 autoDelete = gc.AutoDeleteSelfAssignedRoleMessages;
var exclusive = gc.ExclusiveSelfAssignedRoles;
@@ -206,12 +197,10 @@ public class SelfAssignedRolesService : INService
return (autoDelete, exclusive, roles);
}
}
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 sar = roles.FirstOrDefault(x => x.RoleId == role.Id);
if (sar != null)
@@ -223,7 +212,6 @@ public class SelfAssignedRolesService : INService
{
return false;
}
}
return true;
}
@@ -231,13 +219,11 @@ public class SelfAssignedRolesService : INService
public bool ToggleEsar(ulong guildId)
{
bool areExclusive;
using (var uow = _db.GetDbContext())
{
using var uow = _db.GetDbContext();
var config = uow.GuildConfigsForId(guildId, set => set);
areExclusive = config.ExclusiveSelfAssignedRoles = !config.ExclusiveSelfAssignedRoles;
uow.SaveChanges();
}
return areExclusive;
}

View File

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

View File

@@ -198,8 +198,7 @@ public class UserPunishService : INService
public async Task CheckAllWarnExpiresAsync()
{
await using (var uow = _db.GetDbContext())
{
await using var uow = _db.GetDbContext();
var cleared = await uow.Database.ExecuteSqlRawAsync($@"UPDATE Warnings
SET Forgiven = 1,
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.");
}
}
}
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);
if (config.WarnExpireHours == 0)
@@ -246,7 +243,6 @@ WHERE GuildId={guildId}
await uow.SaveChangesAsync();
}
}
public Task<int> GetWarnExpire(ulong guildId)
{
@@ -275,25 +271,20 @@ WHERE GuildId={guildId}
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();
}
}
public Warning[] UserWarnings(ulong gid, ulong userId)
{
using (var uow = _db.GetDbContext())
{
using var uow = _db.GetDbContext();
return uow.Warnings.ForId(gid, userId);
}
}
public async Task<bool> WarnClearAsync(ulong guildId, ulong userId, int index, string moderator)
{
var toReturn = true;
await using (var uow = _db.GetDbContext())
{
await using var uow = _db.GetDbContext();
if (index == 0)
{
await uow.Warnings.ForgiveAll(guildId, userId, moderator);
@@ -303,7 +294,6 @@ WHERE GuildId={guildId}
toReturn = uow.Warnings.Forgive(guildId, userId, moderator, index - 1);
}
uow.SaveChanges();
}
return toReturn;
}
@@ -315,8 +305,7 @@ WHERE GuildId={guildId}
if (number <= 0 || (time != null && time.Time > TimeSpan.FromDays(49)))
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 toDelete = ps.Where(x => x.Count == number);
@@ -330,7 +319,6 @@ WHERE GuildId={guildId}
RoleId = punish == PunishmentAction.AddRole ? role.Id : default(ulong?),
});
uow.SaveChanges();
}
return true;
}
@@ -339,8 +327,7 @@ WHERE GuildId={guildId}
if (number <= 0)
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 p = ps.FirstOrDefault(x => x.Count == number);
@@ -349,20 +336,18 @@ WHERE GuildId={guildId}
uow.Remove(p);
uow.SaveChanges();
}
}
return true;
}
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))
.WarnPunishments
.OrderBy(x => x.Count)
.ToArray();
}
}
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)
{
using (var uow = _db.GetDbContext())
{
using var uow = _db.GetDbContext();
var template = uow.BanTemplates
.AsQueryable()
.FirstOrDefault(x => x.GuildId == guildId);
return template?.Text;
}
}
public void SetBanTemplate(ulong guildId, string text)
{
using (var uow = _db.GetDbContext())
{
using var uow = _db.GetDbContext();
var template = uow.BanTemplates
.AsQueryable()
.FirstOrDefault(x => x.GuildId == guildId);
@@ -442,7 +424,6 @@ WHERE GuildId={guildId}
uow.SaveChanges();
}
}
public SmartText GetBanUserDmEmbed(ICommandContext context, IGuildUser target, string defaultMessage,
string banReason, TimeSpan? duration)

View File

@@ -117,14 +117,12 @@ public class VcRoleService : INService
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)}");
uow.RemoveRange(missingRoles);
await uow.SaveChangesAsync();
}
}
}
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>());
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 toDelete = conf.VcRoleInfos.FirstOrDefault(x => x.VoiceChannelId == vcId); // remove old one
if(toDelete != null)
@@ -149,7 +146,6 @@ public class VcRoleService : INService
}); // add new one
uow.SaveChanges();
}
}
public bool RemoveVcRole(ulong guildId, ulong vcId)
{
@@ -159,13 +155,11 @@ public class VcRoleService : INService
if (!guildVcRoles.TryRemove(vcId, out _))
return false;
using (var uow = _db.GetDbContext())
{
using var uow = _db.GetDbContext();
var conf = uow.GuildConfigsForId(guildId, set => set.Include(x => x.VcRoleInfos));
var toRemove = conf.VcRoleInfos.Where(x => x.VoiceChannelId == vcId).ToList();
uow.RemoveRange(toRemove);
uow.SaveChanges();
}
return true;
}

View File

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

View File

@@ -44,8 +44,8 @@ public partial class Gambling
cardObjects.Add(currentCard);
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)
{
i.Dispose();
@@ -60,7 +60,6 @@ public partial class Gambling
return (img.ToStream(), toSend);
}
}
[NadekoCommand, Aliases]
[RequireContext(ContextType.Guild)]

View File

@@ -47,9 +47,9 @@ public partial class Gambling
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)
{
i.Dispose();
@@ -61,7 +61,6 @@ public partial class Gambling
: Format.Bold(GetText(strs.tails))));
await ctx.Channel.SendFileAsync(stream, $"{count} coins.{format.FileExtensions.First()}", msg).ConfigureAwait(false);
}
}
public enum BetFlipGuess
{

View File

@@ -538,11 +538,9 @@ public partial class Gambling : GamblingModule<GamblingService>
}
else
{
await using (var uow = _db.GetDbContext())
{
await using var uow = _db.GetDbContext();
cleanRichest = uow.DiscordUser.GetTopRichest(_client.CurrentUser.Id, 9, page).ToList();
}
}
await ctx.SendPaginatedConfirmAsync(page, curPage =>
{
@@ -553,11 +551,9 @@ public partial class Gambling : GamblingModule<GamblingService>
List<DiscordUser> toSend;
if (!opts.Clean)
{
using (var uow = _db.GetDbContext())
{
using var uow = _db.GetDbContext();
toSend = uow.DiscordUser.GetTopRichest(_client.CurrentUser.Id, 9, curPage);
}
}
else
{
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)
return;
using (var uow = _db.GetDbContext())
{
using var uow = _db.GetDbContext();
var lastCurrencyDecay = _cache.GetLastCurrencyDecay();
if (DateTime.UtcNow - lastCurrencyDecay < TimeSpan.FromHours(config.Decay.HourInterval))
@@ -69,7 +68,6 @@ WHERE CurrencyAmount > {config.Decay.MinThreshold} AND UserId!={_client.CurrentU
_cache.SetLastCurrencyDecay();
uow.SaveChanges();
}
}, null, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(5));
}
}

View File

@@ -44,8 +44,7 @@ public class PlantPickService : INService
_gss = gss;
cmd.OnMessageNoTrigger += PotentialFlowerGeneration;
using (var uow = db.GetDbContext())
{
using var uow = db.GetDbContext();
var guildIds = client.Guilds.Select(x => x.Id).ToList();
var configs = uow.Set<GuildConfig>()
.AsQueryable()
@@ -56,7 +55,6 @@ public class PlantPickService : INService
_generationChannels = new(configs
.SelectMany(c => c.GenerateCurrencyChannelIds.Select(obj => obj.ChannelId)));
}
}
private string GetText(ulong gid, LocStr str)
=> _strings.GetText(str, gid);
@@ -64,8 +62,7 @@ public class PlantPickService : INService
public bool ToggleCurrencyGeneration(ulong gid, ulong cid)
{
bool enabled;
using (var uow = _db.GetDbContext())
{
using var uow = _db.GetDbContext();
var guildConfig = uow.GuildConfigsForId(gid, set => set.Include(gc => gc.GenerateCurrencyChannelIds));
var toAdd = new GCChannelId() { ChannelId = cid };
@@ -86,18 +83,15 @@ public class PlantPickService : INService
enabled = false;
}
uow.SaveChanges();
}
return enabled;
}
public IEnumerable<GuildConfigExtensions.GeneratingChannel> GetAllGeneratingChannels()
{
using (var uow = _db.GetDbContext())
{
using var uow = _db.GetDbContext();
var chs = uow.GuildConfigs.GetGeneratingChannels();
return chs;
}
}
/// <summary>
/// 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
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
var font = _fonts.NotoSans.CreateFont(img.Height / 12, FontStyle.Bold);
img.Mutate(x =>
@@ -164,7 +157,6 @@ public class PlantPickService : INService
// return image as a stream for easy sending
return (img.ToStream(format), format.FileExtensions.FirstOrDefault() ?? "png");
}
}
private Task PotentialFlowerGeneration(IUserMessage imsg)
{
@@ -309,14 +301,12 @@ public class PlantPickService : INService
msgToSend += " " + GetText(gid, strs.pick_sn(prefix));
//get the image
await using (var stream = GetRandomCurrencyImage(pass, out var ext))
{
await using var stream = GetRandomCurrencyImage(pass, out var ext);
// send it
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 msg.Id;
}
}
catch
{
// 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)
{
await using (var uow = _db.GetDbContext())
{
await using var uow = _db.GetDbContext();
uow.PlantedCurrency.Add(new()
{
Amount = amount,
@@ -366,5 +355,4 @@ public class PlantPickService : INService
});
await uow.SaveChangesAsync();
}
}
}

View File

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

View File

@@ -41,18 +41,18 @@ public partial class Gambling
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
arr => arr.All(a=>a==MaxValue) ? 30 : 0,
arr => arr.All(a=>a==MAX_VALUE) ? 30 : 0,
//three of the same
arr => !arr.Any(a => a != arr[0]) ? 10 : 0,
//two flowers
arr => arr.Count(a => a == MaxValue) == 2 ? 4 : 0,
arr => arr.Count(a => a == MAX_VALUE) == 2 ? 4 : 0,
//one flower
arr => arr.Any(a => a == MaxValue) ? 1 : 0,
arr => arr.Any(a => a == MAX_VALUE) ? 1 : 0,
};
public static SlotResult Pull()
@@ -60,7 +60,7 @@ public partial class Gambling
var numbers = new int[3];
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;
foreach (var t in _winningCombos)
@@ -85,6 +85,8 @@ public partial class Gambling
}
}
public Task Test() => Task.CompletedTask;
[NadekoCommand, Aliases]
[OwnerOnly]
public async Task SlotStats()
@@ -124,7 +126,6 @@ public partial class Gambling
}
var sb = new StringBuilder();
const int bet = 1;
var payout = 0;
foreach (var key in dict.Keys.OrderByDescending(x => x))
{
@@ -132,7 +133,7 @@ public partial class Gambling
payout += key * dict[key];
}
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]
@@ -216,22 +217,20 @@ public partial class Gambling
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));
}
}
var msg = GetText(strs.better_luck);
if (result.Multiplier > 0)
{
if (result.Multiplier == 1f)
if (Math.Abs(result.Multiplier - 1f) <= float.Epsilon)
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));
else if (result.Multiplier == 10f)
else if (Math.Abs(result.Multiplier - 10f) <= float.Epsilon)
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));
}

View File

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

View File

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

View File

@@ -51,12 +51,10 @@ public class PollRunner
}
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);
trackedPoll.Votes.Add(voteObj);
uow.SaveChanges();
}
return true;
}

View File

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

View File

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

View File

@@ -76,12 +76,10 @@ public class GamesService : INService
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");
return JsonConvert.DeserializeObject<RatingTexts>(text);
}
}
public void AddTypingArticle(IUser user, string text)
{

View File

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

View File

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

View File

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

View File

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

View File

@@ -29,8 +29,7 @@ public class PermissionService : ILateBlocker, INService
_strings = strings;
_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)
.ToList()))
{
@@ -42,7 +41,6 @@ public class PermissionService : ILateBlocker, INService
});
}
}
}
public PermissionCache GetCacheFor(ulong guildId)
{
@@ -63,8 +61,7 @@ public class PermissionService : ILateBlocker, INService
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 orderedPerms = new PermissionsCollection<Permissionv2>(config.Permissions);
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();
UpdateCache(config);
}
}
public void UpdateCache(GuildConfig config)
{
@@ -170,12 +166,10 @@ public class PermissionService : ILateBlocker, INService
public async Task Reset(ulong guildId)
{
await using (var uow = _db.GetDbContext())
{
await using var uow = _db.GetDbContext();
var config = uow.GcWithPermissionsv2For(guildId);
config.Permissions = Permissionv2.GetDefaultPermlist;
await uow.SaveChangesAsync();
UpdateCache(config);
}
}
}

View File

@@ -47,8 +47,7 @@ public partial class Searches
var fullQueryLink = "https://myanimelist.net/profile/" + name;
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 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);
}
}
private static string MalInfoToEmoji(string info)
{

View File

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

View File

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

View File

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

View File

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

View File

@@ -41,12 +41,10 @@ public partial class Searches
try
{
using (var http = _httpFactory.CreateClient())
{
using var http = _httpFactory.CreateClient();
var res = await http.GetStringAsync($"{_poeURL}{usr}").ConfigureAwait(false);
characters = JsonConvert.DeserializeObject<List<Account>>(res);
}
}
catch
{
var embed = _eb.Create()
@@ -102,12 +100,10 @@ public partial class Searches
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);
leagues = JsonConvert.DeserializeObject<List<Leagues>>(res);
}
}
catch
{
var eembed = _eb.Create()
@@ -159,8 +155,7 @@ public partial class Searches
try
{
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 chaosEquivalent = 0.0F;
@@ -201,7 +196,6 @@ public partial class Searches
await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
}
}
catch
{
var embed = _eb.Create()

View File

@@ -39,8 +39,7 @@ public partial class Searches : NadekoModule<SearchesService>
var av = usr.RealAvatarUrl();
if (av is null)
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(
picStream,
"rip.png",
@@ -48,7 +47,6 @@ public partial class Searches : NadekoModule<SearchesService>
Format.Italics(ctx.User.ToString()))
.ConfigureAwait(false);
}
}
[NadekoCommand, Aliases]
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 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();
if (!elems.Any())
@@ -249,7 +246,6 @@ public partial class Searches : NadekoModule<SearchesService>
await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
}
}
}
[NadekoCommand, Aliases]
public async Task Lmgtfy([Leftover] string ffs = null)
@@ -280,17 +276,15 @@ public partial class Searches : NadekoModule<SearchesService>
{
try
{
using (var _http = _httpFactory.CreateClient())
using (var req = new HttpRequestMessage(HttpMethod.Post, "https://goolnk.com/api/v1/shorten"))
{
using var _http = _httpFactory.CreateClient();
using var req = new HttpRequestMessage(HttpMethod.Post, "https://goolnk.com/api/v1/shorten");
var formData = new MultipartFormDataContent
{
{ new StringContent(query), "url" }
};
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 data = JsonConvert.DeserializeObject<ShortenData>(content);
@@ -301,8 +295,6 @@ public partial class Searches : NadekoModule<SearchesService>
shortLink = data.ResultUrl;
}
}
}
catch (Exception ex)
{
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))
return;
using (var _http = _httpFactory.CreateClient())
{
using var _http = _httpFactory.CreateClient();
string res;
try
{
@@ -535,13 +526,11 @@ public partial class Searches : NadekoModule<SearchesService>
Log.Error(ex, "Error retrieving definition data for: {Word}", word);
}
}
}
[NadekoCommand, Aliases]
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);
if (response is null)
return;
@@ -549,7 +538,6 @@ public partial class Searches : NadekoModule<SearchesService>
var fact = JObject.Parse(response)["fact"].ToString();
await SendConfirmAsync("🐈" + GetText(strs.catfact), fact).ConfigureAwait(false);
}
}
//done in 3.0
[NadekoCommand, Aliases]
@@ -585,8 +573,7 @@ public partial class Searches : NadekoModule<SearchesService>
if (!await ValidateQuery(query).ConfigureAwait(false))
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 data = JsonConvert.DeserializeObject<WikipediaApiModel>(result);
if (data.Query.Pages[0].Missing || string.IsNullOrWhiteSpace(data.Query.Pages[0].FullUrl))
@@ -594,7 +581,6 @@ public partial class Searches : NadekoModule<SearchesService>
else
await ctx.Channel.SendMessageAsync(data.Query.Pages[0].FullUrl).ConfigureAwait(false);
}
}
[NadekoCommand, Aliases]
public async Task Color(params SixLabors.ImageSharp.Color[] colors)
@@ -605,8 +591,7 @@ public partial class Searches : NadekoModule<SearchesService>
var colorObjects = colors.Take(10)
.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++)
{
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);
}
}
}
[NadekoCommand, Aliases]
[RequireContext(ContextType.Guild)]
@@ -655,8 +637,7 @@ public partial class Searches : NadekoModule<SearchesService>
return;
}
await ctx.Channel.TriggerTypingAsync().ConfigureAwait(false);
using (var http = _httpFactory.CreateClient())
{
using var http = _httpFactory.CreateClient();
http.DefaultRequestHeaders.Clear();
try
{
@@ -685,7 +666,6 @@ public partial class Searches : NadekoModule<SearchesService>
await ReplyErrorLocalizedAsync(strs.wikia_error).ConfigureAwait(false);
}
}
}
[NadekoCommand, Aliases]
[RequireContext(ContextType.Guild)]
@@ -694,14 +674,12 @@ public partial class Searches : NadekoModule<SearchesService>
var obj = new BibleVerses();
try
{
using (var http = _httpFactory.CreateClient())
{
using var http = _httpFactory.CreateClient();
var res = await http
.GetStringAsync("https://bible-api.com/" + book + " " + chapterAndVerse).ConfigureAwait(false);
obj = JsonConvert.DeserializeObject<BibleVerses>(res);
}
}
catch
{
}

View File

@@ -61,8 +61,7 @@ public class AnimeSearchService : INService
if (!ok)
{
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");
if (imageElem is null)
return null;
@@ -113,7 +112,6 @@ public class AnimeSearchService : INService
return obj;
}
}
return JsonConvert.DeserializeObject<NovelResult>(data);
}

View File

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

View File

@@ -85,13 +85,11 @@ public class SearchesService : INService
public async Task<byte[]> GetRipPictureFactory((string text, Uri 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);
if (!succ)
{
using (var http = _httpFactory.CreateClient())
{
using var http = _httpFactory.CreateClient();
data = await http.GetByteArrayAsync(avatarUrl);
using (var avatarImg = Image.Load<Rgba32>(data))
{
@@ -103,14 +101,11 @@ public class SearchesService : INService
}
await _cache.SetImageDataAsync(avatarUrl, data);
}
}
else
{
using (var avatarImg = Image.Load<Rgba32>(data))
{
using var avatarImg = Image.Load<Rgba32>(data);
DrawAvatar(bg, avatarImg);
}
}
bg.Mutate(x => x.DrawText(
new()
@@ -134,7 +129,6 @@ public class SearchesService : INService
return bg.ToStream().ToArray();
}
}
public Task<WeatherData> GetWeatherDataAsync(string query)
{
@@ -148,8 +142,7 @@ public class SearchesService : INService
private async Task<WeatherData> GetWeatherDataFactory(string query)
{
using (var http = _httpFactory.CreateClient())
{
using var http = _httpFactory.CreateClient();
try
{
var data = await http.GetStringAsync($"http://api.openweathermap.org/data/2.5/weather?" +
@@ -168,7 +161,6 @@ public class SearchesService : INService
return null;
}
}
}
public Task<((string Address, DateTime Time, string TimeZoneName), TimeErrors?)> GetTimeDataAsync(string arg)
{
@@ -195,8 +187,7 @@ public class SearchesService : INService
try
{
using (var _http = _httpFactory.CreateClient())
{
using var _http = _httpFactory.CreateClient();
var res = await _cache.GetOrAddCachedDataAsync($"geo_{query}", _ =>
{
var url = "https://eu1.locationiq.com/v1/search.php?" +
@@ -217,14 +208,11 @@ public class SearchesService : INService
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&" +
"by=position&" +
$"lat={geoData.Lat}&lng={geoData.Lon}"))
{
using (var geoRes = await _http.SendAsync(req))
{
$"lat={geoData.Lat}&lng={geoData.Lon}");
using var geoRes = await _http.SendAsync(req);
var resString = await geoRes.Content.ReadAsStringAsync();
var timeObj = JsonConvert.DeserializeObject<TimeZoneResult>(resString);
@@ -236,9 +224,6 @@ public class SearchesService : INService
TimeZoneName: timeObj.TimezoneName
), default);
}
}
}
}
catch (Exception ex)
{
Log.Error(ex, "Weather error: {Message}", ex.Message);
@@ -310,22 +295,18 @@ public class SearchesService : INService
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 resObj = JsonConvert.DeserializeAnonymousType(res, new {setup = "", punchline = ""});
return (resObj.setup, resObj.punchline);
}
}
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);
return JObject.Parse(response)["value"]["joke"].ToString() + " 😆";
}
}
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();
var response = await http.GetStringAsync($"https://api.magicthegathering.io/v1/cards?name={Uri.EscapeDataString(search)}")
.ConfigureAwait(false);
@@ -391,7 +371,6 @@ public class SearchesService : INService
return await Task.WhenAll(tasks).ConfigureAwait(false);
}
}
public Task<HearthstoneCardData> GetHearthstoneCardDataAsync(string name)
{
@@ -404,8 +383,7 @@ public class SearchesService : INService
private async Task<HearthstoneCardData> HearthstoneCardDataFactory(string name)
{
using (var http = _httpFactory.CreateClient())
{
using var http = _httpFactory.CreateClient();
http.DefaultRequestHeaders.Clear();
http.DefaultRequestHeaders.Add("x-rapidapi-key", _creds.RapidApiKey);
try
@@ -437,7 +415,6 @@ public class SearchesService : INService
return null;
}
}
}
public Task<OmdbMovie> GetMovieDataAsync(string name)
{
@@ -450,8 +427,7 @@ public class SearchesService : INService
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",
name.Trim().Replace(' ', '+'))).ConfigureAwait(false);
var movie = JsonConvert.DeserializeObject<OmdbMovie>(res);
@@ -460,7 +436,6 @@ public class SearchesService : INService
movie.Poster = await _google.ShortenUrl(movie.Poster).ConfigureAwait(false);
return movie;
}
}
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 _ =>
{
using (var http = _httpFactory.CreateClient())
{
using var http = _httpFactory.CreateClient();
// https://api.steampowered.com/ISteamApps/GetAppList/v2/
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;
@@ -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.StringSetAsync("steam_game_ids", gamesStr, TimeSpan.FromHours(24));
//await db.KeyExpireAsync("steam_game_ids", TimeSpan.FromHours(24), CommandFlags.FireAndForget).ConfigureAwait(false);
}
}, default(string), TimeSpan.FromHours(24));
if (gamesMap is null)

View File

@@ -130,8 +130,7 @@ public sealed class StreamNotificationService : INService
var deleteGroups = failingStreams.GroupBy(x => x.Type)
.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)
{
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));
}
}
}
catch (Exception ex)
{
Log.Error("Error cleaning up FollowedStreams");
@@ -461,8 +459,7 @@ public sealed class StreamNotificationService : INService
public bool ToggleStreamOffline(ulong guildId)
{
bool newValue;
using (var uow = _db.GetDbContext())
{
using var uow = _db.GetDbContext();
var gc = uow.GuildConfigsForId(guildId, set => set);
newValue = gc.NotifyStreamOffline = !gc.NotifyStreamOffline;
uow.SaveChanges();
@@ -475,7 +472,6 @@ public sealed class StreamNotificationService : INService
{
_offlineNotificationServers.TryRemove(guildId);
}
}
return newValue;
}
@@ -510,8 +506,7 @@ public sealed class StreamNotificationService : INService
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>()
.AsQueryable()
.Where(x => x.GuildId == guildId)
@@ -537,7 +532,6 @@ public sealed class StreamNotificationService : INService
}
uow.SaveChanges();
}
return true;
}

View File

@@ -23,8 +23,7 @@ public partial class Searches
{
try
{
using (var http = _httpFactory.CreateClient())
{
using var http = _httpFactory.CreateClient();
var res = await http.GetStringAsync($"{_xkcdUrl}/info.0.json").ConfigureAwait(false);
var comic = JsonConvert.DeserializeObject<XkcdComic>(res);
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);
}
}
catch (HttpRequestException)
{
await ReplyErrorLocalizedAsync(strs.comic_not_found).ConfigureAwait(false);
@@ -57,8 +55,7 @@ public partial class Searches
return;
try
{
using (var http = _httpFactory.CreateClient())
{
using var http = _httpFactory.CreateClient();
var res = await http.GetStringAsync($"{_xkcdUrl}/{num}/info.0.json").ConfigureAwait(false);
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);
}
}
catch (HttpRequestException)
{
await ReplyErrorLocalizedAsync(strs.comic_not_found).ConfigureAwait(false);

View File

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

View File

@@ -35,12 +35,10 @@ public class ConverterService : INService
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);
return JsonConvert.DeserializeObject<Rates>(res);
}
}
private async Task UpdateCurrency(bool shouldLoad)
{

View File

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

View File

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

View File

@@ -431,11 +431,9 @@ public partial class Utility : NadekoModule
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);
}
}
private static SemaphoreSlim sem = new(1, 1);
[NadekoCommand, Aliases]

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,4 +1,5 @@
using NadekoBot.Db.Models;
using Discord;
using NadekoBot.Db.Models;
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)
{
await using (var file = File.Open(filePath, FileMode.Open))
{
return await user.SendFileAsync(file, caption ?? "x", text, isTTS).ConfigureAwait(false);
}
await using var file = File.Open(filePath, FileMode.Open);
return await UserExtensions.SendFileAsync(user, 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) =>
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
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))
{
using (var reader = new StringReader(stdout))
{
using var reader = new StringReader(stdout);
while (true)
{
var text = reader.ReadLine();
@@ -68,7 +67,6 @@ public static class ProcessExtensions
}
}
}
}
private static void KillProcessUnix(int processId, TimeSpan timeout)
{