Applied codestyle to all .cs files

This commit is contained in:
Kwoth
2021-12-29 06:07:16 +01:00
parent 723447c7d4
commit 82000c97a4
543 changed files with 13221 additions and 14059 deletions

View File

@@ -1,7 +1,6 @@
#nullable disable
using NadekoBot.Common.TypeReaders;
using NadekoBot.Services.Database.Models;
using NadekoBot.Modules.Permissions.Services;
using NadekoBot.Services.Database.Models;
namespace NadekoBot.Modules.Permissions;
@@ -19,107 +18,113 @@ public partial class Permissions
{
if (page < 0)
throw new ArgumentOutOfRangeException(nameof(page));
var list = _service.GetBlacklist();
var items = await list
.Where(x => x.Type == type)
.Select(async i =>
{
try
{
return i.Type switch
{
BlacklistType.Channel => Format.Code(i.ItemId.ToString())
+ " " + (_client.GetChannel(i.ItemId)?.ToString() ?? ""),
BlacklistType.User => Format.Code(i.ItemId.ToString())
+ " " +
((await _client.Rest.GetUserAsync(i.ItemId))?.ToString() ?? ""),
BlacklistType.Server => Format.Code(i.ItemId.ToString())
+ " " + (_client.GetGuild(i.ItemId)?.ToString() ?? ""),
_ => Format.Code(i.ItemId.ToString())
};
}
catch
{
Log.Warning("Can't get {BlacklistType} [{BlacklistItemId}]", i.Type, i.ItemId);
return Format.Code(i.ItemId.ToString());
}
})
.WhenAll();
await ctx.SendPaginatedConfirmAsync(page, (int curPage) =>
{
var pageItems = items
.Skip(10 * curPage)
.Take(10)
.ToList();
if (pageItems.Count == 0)
var list = _service.GetBlacklist();
var items = await list.Where(x => x.Type == type)
.Select(async i =>
{
try
{
return i.Type switch
{
BlacklistType.Channel => Format.Code(i.ItemId.ToString())
+ " "
+ (_client.GetChannel(i.ItemId)?.ToString()
?? ""),
BlacklistType.User => Format.Code(i.ItemId.ToString())
+ " "
+ ((await _client.Rest.GetUserAsync(i.ItemId))
?.ToString()
?? ""),
BlacklistType.Server => Format.Code(i.ItemId.ToString())
+ " "
+ (_client.GetGuild(i.ItemId)?.ToString() ?? ""),
_ => Format.Code(i.ItemId.ToString())
};
}
catch
{
Log.Warning("Can't get {BlacklistType} [{BlacklistItemId}]",
i.Type,
i.ItemId);
return Format.Code(i.ItemId.ToString());
}
})
.WhenAll();
await ctx.SendPaginatedConfirmAsync(page,
curPage =>
{
return _eb.Create()
.WithOkColor()
.WithTitle(title)
.WithDescription(GetText(strs.empty_page));
}
return _eb.Create()
.WithTitle(title)
.WithDescription(pageItems.Join('\n'))
.WithOkColor();
}, items.Length, 10);
var pageItems = items.Skip(10 * curPage).Take(10).ToList();
if (pageItems.Count == 0)
return _eb.Create().WithOkColor().WithTitle(title).WithDescription(GetText(strs.empty_page));
return _eb.Create().WithTitle(title).WithDescription(pageItems.Join('\n')).WithOkColor();
},
items.Length,
10);
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[OwnerOnly]
public Task UserBlacklist(int page = 1)
{
if (--page < 0)
return Task.CompletedTask;
return ListBlacklistInternal(GetText(strs.blacklisted_users), BlacklistType.User, page);
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[OwnerOnly]
public Task ChannelBlacklist(int page = 1)
{
if (--page < 0)
return Task.CompletedTask;
return ListBlacklistInternal(GetText(strs.blacklisted_channels), BlacklistType.Channel, page);
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[OwnerOnly]
public Task ServerBlacklist(int page = 1)
{
if (--page < 0)
return Task.CompletedTask;
return ListBlacklistInternal(GetText(strs.blacklisted_servers), BlacklistType.Server, page);
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[OwnerOnly]
public Task UserBlacklist(AddRemove action, ulong id)
=> Blacklist(action, id, BlacklistType.User);
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[OwnerOnly]
public Task UserBlacklist(AddRemove action, IUser usr)
=> Blacklist(action, usr.Id, BlacklistType.User);
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[OwnerOnly]
public Task ChannelBlacklist(AddRemove action, ulong id)
=> Blacklist(action, id, BlacklistType.Channel);
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[OwnerOnly]
public Task ServerBlacklist(AddRemove action, ulong id)
=> Blacklist(action, id, BlacklistType.Server);
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[OwnerOnly]
public Task ServerBlacklist(AddRemove action, IGuild guild)
=> Blacklist(action, guild.Id, BlacklistType.Server);
@@ -127,13 +132,9 @@ public partial class Permissions
private async Task Blacklist(AddRemove action, ulong id, BlacklistType type)
{
if (action == AddRemove.Add)
{
_service.Blacklist(type, id);
}
else
{
_service.UnBlacklist(type, id);
}
if (action == AddRemove.Add)
await ReplyConfirmLocalizedAsync(strs.blacklisted(Format.Code(type.ToString()),
@@ -143,4 +144,4 @@ public partial class Permissions
Format.Code(id.ToString())));
}
}
}
}

View File

@@ -1,9 +1,9 @@
#nullable disable
using Microsoft.EntityFrameworkCore;
using NadekoBot.Services.Database.Models;
using NadekoBot.Common.TypeReaders;
using NadekoBot.Db;
using NadekoBot.Modules.Permissions.Services;
using NadekoBot.Services.Database.Models;
namespace NadekoBot.Modules.Permissions;
@@ -12,21 +12,23 @@ public partial class Permissions
[Group]
public class CmdCdsCommands : NadekoSubmodule
{
private readonly DbService _db;
private readonly CmdCdService _service;
private ConcurrentDictionary<ulong, ConcurrentHashSet<CommandCooldown>> CommandCooldowns
=> _service.CommandCooldowns;
private ConcurrentDictionary<ulong, ConcurrentHashSet<ActiveCooldown>> ActiveCooldowns
=> _service.ActiveCooldowns;
private readonly DbService _db;
private readonly CmdCdService _service;
public CmdCdsCommands(CmdCdService service, DbService db)
{
_service = service;
_db = db;
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
public async Task CmdCooldown(CommandOrCrInfo command, int secs)
{
@@ -49,16 +51,14 @@ public partial class Permissions
localSet.RemoveWhere(cc => cc.CommandName == name);
if (secs != 0)
{
var cc = new CommandCooldown()
{
CommandName = name,
Seconds = secs,
};
var cc = new CommandCooldown { CommandName = name, Seconds = secs };
config.CommandCooldowns.Add(cc);
localSet.Add(cc);
}
await uow.SaveChangesAsync();
}
if (secs == 0)
{
var activeCds = ActiveCooldowns.GetOrAdd(channel.Guild.Id, new ConcurrentHashSet<ActiveCooldown>());
@@ -67,13 +67,12 @@ public partial class Permissions
}
else
{
await ReplyConfirmLocalizedAsync(strs.cmdcd_add(
Format.Bold(name),
Format.Bold(secs.ToString())));
await ReplyConfirmLocalizedAsync(strs.cmdcd_add(Format.Bold(name), Format.Bold(secs.ToString())));
}
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
public async Task AllCmdCooldowns()
{
@@ -83,7 +82,10 @@ public partial class Permissions
if (!localSet.Any())
await ReplyConfirmLocalizedAsync(strs.cmdcd_none);
else
await channel.SendTableAsync("", localSet.Select(c => c.CommandName + ": " + c.Seconds + GetText(strs.sec)), s => $"{s,-30}", 2);
await channel.SendTableAsync("",
localSet.Select(c => c.CommandName + ": " + c.Seconds + GetText(strs.sec)),
s => $"{s,-30}",
2);
}
}
}
}

View File

@@ -8,4 +8,4 @@ public class PermissionCache
public string PermRole { get; set; }
public bool Verbose { get; set; } = true;
public PermissionsCollection<Permissionv2> Permissions { get; set; }
}
}

View File

@@ -5,8 +5,12 @@ namespace NadekoBot.Modules.Permissions.Common;
public static class PermissionExtensions
{
public static bool CheckPermissions(this IEnumerable<Permissionv2> permsEnumerable, IUserMessage message,
string commandName, string moduleName, out int permIndex)
public static bool CheckPermissions(
this IEnumerable<Permissionv2> permsEnumerable,
IUserMessage message,
string commandName,
string moduleName,
out int permIndex)
{
var perms = permsEnumerable as List<Permissionv2> ?? permsEnumerable.ToList();
@@ -16,13 +20,11 @@ public static class PermissionExtensions
var result = perm.CheckPermission(message, commandName, moduleName);
if (result is null)
{
continue;
}
if (result is null) continue;
permIndex = i;
return result.Value;
}
permIndex = -1; //defaut behaviour
return true;
}
@@ -30,13 +32,17 @@ public static class PermissionExtensions
//null = not applicable
//true = applicable, allowed
//false = applicable, not allowed
public static bool? CheckPermission(this Permissionv2 perm, IUserMessage message, string commandName, string moduleName)
public static bool? CheckPermission(
this Permissionv2 perm,
IUserMessage message,
string commandName,
string moduleName)
{
if (!((perm.SecondaryTarget == SecondaryPermissionType.Command &&
perm.SecondaryTargetName.ToLowerInvariant() == commandName.ToLowerInvariant()) ||
(perm.SecondaryTarget == SecondaryPermissionType.Module &&
perm.SecondaryTargetName.ToLowerInvariant() == moduleName.ToLowerInvariant()) ||
perm.SecondaryTarget == SecondaryPermissionType.AllModules))
if (!((perm.SecondaryTarget == SecondaryPermissionType.Command
&& perm.SecondaryTargetName.ToLowerInvariant() == commandName.ToLowerInvariant())
|| (perm.SecondaryTarget == SecondaryPermissionType.Module
&& perm.SecondaryTargetName.ToLowerInvariant() == moduleName.ToLowerInvariant())
|| perm.SecondaryTarget == SecondaryPermissionType.AllModules))
return null;
var guildUser = message.Author as IGuildUser;
@@ -51,7 +57,7 @@ public static class PermissionExtensions
if (perm.PrimaryTargetId == message.Channel.Id)
return perm.State;
break;
case PrimaryPermissionType.Role:
case PrimaryPermissionType.Role:
if (guildUser is null)
break;
if (guildUser.RoleIds.Contains(perm.PrimaryTargetId))
@@ -62,6 +68,7 @@ public static class PermissionExtensions
break;
return perm.State;
}
return null;
}
@@ -97,8 +104,9 @@ public static class PermissionExtensions
break;
}
var secName = perm.SecondaryTarget == SecondaryPermissionType.Command && !perm.IsCustomCommand ?
prefix + perm.SecondaryTargetName : perm.SecondaryTargetName;
var secName = perm.SecondaryTarget == SecondaryPermissionType.Command && !perm.IsCustomCommand
? prefix + perm.SecondaryTargetName
: perm.SecondaryTargetName;
com += " " + (perm.SecondaryTargetName != "*" ? secName + " " : "") + (perm.State ? "enable" : "disable") + " ";
switch (perm.PrimaryTarget)
@@ -118,4 +126,4 @@ public static class PermissionExtensions
return prefix + com;
}
}
}

View File

@@ -4,15 +4,32 @@ using NadekoBot.Services.Database.Models;
namespace NadekoBot.Modules.Permissions.Common;
public class PermissionsCollection<T> : IndexedCollection<T> where T : class, IIndexed
public class PermissionsCollection<T> : IndexedCollection<T>
where T : class, IIndexed
{
public override T this[int index]
{
get => Source[index];
set
{
lock (_localLocker)
{
if (index == 0) // can't set first element. It's always allow all
throw new IndexOutOfRangeException(nameof(index));
base[index] = value;
}
}
}
private readonly object _localLocker = new();
public PermissionsCollection(IEnumerable<T> source) : base(source)
public PermissionsCollection(IEnumerable<T> source)
: base(source)
{
}
public static implicit operator List<T>(PermissionsCollection<T> x) =>
x.Source;
public static implicit operator List<T>(PermissionsCollection<T> x)
=> x.Source;
public override void Clear()
{
@@ -29,10 +46,11 @@ public class PermissionsCollection<T> : IndexedCollection<T> where T : class, II
bool removed;
lock (_localLocker)
{
if(Source.IndexOf(item) == 0)
if (Source.IndexOf(item) == 0)
throw new ArgumentException("You can't remove first permsission (allow all)");
removed = base.Remove(item);
}
return removed;
}
@@ -40,7 +58,7 @@ public class PermissionsCollection<T> : IndexedCollection<T> where T : class, II
{
lock (_localLocker)
{
if(index == 0) // can't insert on first place. Last item is always allow all.
if (index == 0) // can't insert on first place. Last item is always allow all.
throw new IndexOutOfRangeException(nameof(index));
base.Insert(index, item);
}
@@ -50,22 +68,10 @@ public class PermissionsCollection<T> : IndexedCollection<T> where T : class, II
{
lock (_localLocker)
{
if(index == 0) // you can't remove first permission (allow all)
if (index == 0) // you can't remove first permission (allow all)
throw new IndexOutOfRangeException(nameof(index));
base.RemoveAt(index);
}
}
public override T this[int index] {
get => Source[index];
set {
lock (_localLocker)
{
if(index == 0) // can't set first element. It's always allow all
throw new IndexOutOfRangeException(nameof(index));
base[index] = value;
}
}
}
}
}

View File

@@ -1,8 +1,8 @@
#nullable disable
using Microsoft.EntityFrameworkCore;
using NadekoBot.Db;
using NadekoBot.Modules.Permissions.Services;
using NadekoBot.Services.Database.Models;
using NadekoBot.Db;
namespace NadekoBot.Modules.Permissions;
@@ -16,7 +16,8 @@ public partial class Permissions
public FilterCommands(DbService db)
=> _db = db;
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
[UserPerm(GuildPerm.Administrator)]
public async Task FwClear()
@@ -25,7 +26,8 @@ public partial class Permissions
await ReplyConfirmLocalizedAsync(strs.fw_cleared);
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
public async Task SrvrFilterInv()
{
@@ -51,7 +53,8 @@ public partial class Permissions
}
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
public async Task ChnlFilterInv()
{
@@ -60,21 +63,15 @@ public partial class Permissions
FilterChannelId removed;
await using (var uow = _db.GetDbContext())
{
var config = uow.GuildConfigsForId(channel.Guild.Id, set => set.Include(gc => gc.FilterInvitesChannelIds));
var match = new FilterChannelId()
{
ChannelId = channel.Id
};
var config = uow.GuildConfigsForId(channel.Guild.Id,
set => set.Include(gc => gc.FilterInvitesChannelIds));
var match = new FilterChannelId { ChannelId = channel.Id };
removed = config.FilterInvitesChannelIds.FirstOrDefault(fc => fc.Equals(match));
if (removed is null)
{
config.FilterInvitesChannelIds.Add(match);
}
else
{
uow.Remove(removed);
}
await uow.SaveChangesAsync();
}
@@ -90,7 +87,8 @@ public partial class Permissions
}
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
public async Task SrvrFilterLin()
{
@@ -116,7 +114,8 @@ public partial class Permissions
}
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
public async Task ChnlFilterLin()
{
@@ -125,21 +124,15 @@ public partial class Permissions
FilterLinksChannelId removed;
await using (var uow = _db.GetDbContext())
{
var config = uow.GuildConfigsForId(channel.Guild.Id, set => set.Include(gc => gc.FilterLinksChannelIds));
var match = new FilterLinksChannelId()
{
ChannelId = channel.Id
};
var config =
uow.GuildConfigsForId(channel.Guild.Id, set => set.Include(gc => gc.FilterLinksChannelIds));
var match = new FilterLinksChannelId { ChannelId = channel.Id };
removed = config.FilterLinksChannelIds.FirstOrDefault(fc => fc.Equals(match));
if (removed is null)
{
config.FilterLinksChannelIds.Add(match);
}
else
{
uow.Remove(removed);
}
await uow.SaveChangesAsync();
}
@@ -155,7 +148,8 @@ public partial class Permissions
}
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
public async Task SrvrFilterWords()
{
@@ -181,7 +175,8 @@ public partial class Permissions
}
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
public async Task ChnlFilterWords()
{
@@ -190,21 +185,15 @@ public partial class Permissions
FilterChannelId removed;
await using (var uow = _db.GetDbContext())
{
var config = uow.GuildConfigsForId(channel.Guild.Id, set => set.Include(gc => gc.FilterWordsChannelIds));
var config =
uow.GuildConfigsForId(channel.Guild.Id, set => set.Include(gc => gc.FilterWordsChannelIds));
var match = new FilterChannelId()
{
ChannelId = channel.Id
};
var match = new FilterChannelId { ChannelId = channel.Id };
removed = config.FilterWordsChannelIds.FirstOrDefault(fc => fc.Equals(match));
if (removed is null)
{
config.FilterWordsChannelIds.Add(match);
}
else
{
uow.Remove(removed);
}
await uow.SaveChangesAsync();
}
@@ -220,7 +209,8 @@ public partial class Permissions
}
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
public async Task FilterWord([Leftover] string word)
{
@@ -241,14 +231,13 @@ public partial class Permissions
if (removed is null)
config.FilteredWords.Add(new() { Word = word });
else
{
uow.Remove(removed);
}
await uow.SaveChangesAsync();
}
var filteredWords = _service.ServerFilteredWords.GetOrAdd(channel.Guild.Id, new ConcurrentHashSet<string>());
var filteredWords =
_service.ServerFilteredWords.GetOrAdd(channel.Guild.Id, new ConcurrentHashSet<string>());
if (removed is null)
{
@@ -262,7 +251,8 @@ public partial class Permissions
}
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
public async Task LstFilterWords(int page = 1)
{
@@ -278,10 +268,11 @@ public partial class Permissions
await ctx.SendPaginatedConfirmAsync(page,
curPage => _eb.Create()
.WithTitle(GetText(strs.filter_word_list))
.WithDescription(string.Join("\n", fws.Skip(curPage * 10).Take(10)))
.WithOkColor()
, fws.Length, 10);
.WithTitle(GetText(strs.filter_word_list))
.WithDescription(string.Join("\n", fws.Skip(curPage * 10).Take(10)))
.WithOkColor(),
fws.Length,
10);
}
}
}
}

View File

@@ -18,7 +18,8 @@ public partial class Permissions
_db = db;
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[OwnerOnly]
public async Task GlobalPermList()
{
@@ -33,49 +34,47 @@ public partial class Permissions
var embed = _eb.Create().WithOkColor();
if (blockedModule.Any())
embed.AddField(GetText(strs.blocked_modules)
, string.Join("\n", _service.BlockedModules)
, false);
embed.AddField(GetText(strs.blocked_modules), string.Join("\n", _service.BlockedModules));
if (blockedCommands.Any())
embed.AddField(GetText(strs.blocked_commands)
, string.Join("\n", _service.BlockedCommands)
, false);
embed.AddField(GetText(strs.blocked_commands), string.Join("\n", _service.BlockedCommands));
await ctx.Channel.EmbedAsync(embed);
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[OwnerOnly]
public async Task GlobalModule(ModuleOrCrInfo module)
{
var moduleName = module.Name.ToLowerInvariant();
var added = _service.ToggleModule(moduleName);
if (added)
{
await ReplyConfirmLocalizedAsync(strs.gmod_add(Format.Bold(module.Name)));
return;
}
await ReplyConfirmLocalizedAsync(strs.gmod_remove(Format.Bold(module.Name)));
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[OwnerOnly]
public async Task GlobalCommand(CommandOrCrInfo cmd)
{
var commandName = cmd.Name.ToLowerInvariant();
var added = _service.ToggleCommand(commandName);
if (added)
{
await ReplyConfirmLocalizedAsync(strs.gcmd_add(Format.Bold(cmd.Name)));
return;
}
await ReplyConfirmLocalizedAsync(strs.gcmd_remove(Format.Bold(cmd.Name)));
}
}
}
}

View File

@@ -1,21 +1,24 @@
#nullable disable
using NadekoBot.Services.Database.Models;
using NadekoBot.Common.TypeReaders;
using NadekoBot.Common.TypeReaders.Models;
using NadekoBot.Db;
using NadekoBot.Modules.Permissions.Common;
using NadekoBot.Modules.Permissions.Services;
using NadekoBot.Services.Database.Models;
namespace NadekoBot.Modules.Permissions;
public partial class Permissions : NadekoModule<PermissionService>
{
public enum Reset { Reset }
private readonly DbService _db;
public Permissions(DbService db)
=> _db = db;
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
public async Task Verbose(PermissionAction action = null)
{
@@ -27,17 +30,15 @@ public partial class Permissions : NadekoModule<PermissionService>
await uow.SaveChangesAsync();
_service.UpdateCache(config);
}
if (action.Value)
{
await ReplyConfirmLocalizedAsync(strs.verbose_true);
}
else
{
await ReplyConfirmLocalizedAsync(strs.verbose_false);
}
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
[UserPerm(GuildPerm.Administrator)]
[Priority(0)]
@@ -45,19 +46,15 @@ public partial class Permissions : NadekoModule<PermissionService>
{
if (role != null && role == role.Guild.EveryoneRole)
return;
if (role is null)
{
var cache = _service.GetCacheFor(ctx.Guild.Id);
if (!ulong.TryParse(cache.PermRole, out var roleId) ||
(role = ((SocketGuild)ctx.Guild).GetRole(roleId)) is null)
{
if (!ulong.TryParse(cache.PermRole, out var roleId)
|| (role = ((SocketGuild)ctx.Guild).GetRole(roleId)) is null)
await ReplyConfirmLocalizedAsync(strs.permrole_not_set);
}
else
{
await ReplyConfirmLocalizedAsync(strs.permrole(Format.Bold(role.ToString())));
}
return;
}
@@ -72,9 +69,8 @@ public partial class Permissions : NadekoModule<PermissionService>
await ReplyConfirmLocalizedAsync(strs.permrole_changed(Format.Bold(role.Name)));
}
public enum Reset { Reset };
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
[UserPerm(GuildPerm.Administrator)]
[Priority(1)]
@@ -91,7 +87,8 @@ public partial class Permissions : NadekoModule<PermissionService>
await ReplyConfirmLocalizedAsync(strs.permrole_reset);
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
public async Task ListPerms(int page = 1)
{
@@ -101,32 +98,31 @@ public partial class Permissions : NadekoModule<PermissionService>
IList<Permissionv2> perms;
if (_service.Cache.TryGetValue(ctx.Guild.Id, out var permCache))
{
perms = permCache.Permissions.Source.ToList();
}
else
{
perms = Permissionv2.GetDefaultPermlist;
}
var startPos = 20 * (page - 1);
var toSend = Format.Bold(GetText(strs.page(page))) + "\n\n" + string.Join("\n",
perms.Reverse()
.Skip(startPos)
.Take(20)
.Select(p =>
{
var str =
$"`{p.Index + 1}.` {Format.Bold(p.GetCommand(Prefix, (SocketGuild)ctx.Guild))}";
if (p.Index == 0)
str += $" [{GetText(strs.uneditable)}]";
return str;
}));
var toSend = Format.Bold(GetText(strs.page(page)))
+ "\n\n"
+ string.Join("\n",
perms.Reverse()
.Skip(startPos)
.Take(20)
.Select(p =>
{
var str =
$"`{p.Index + 1}.` {Format.Bold(p.GetCommand(Prefix, (SocketGuild)ctx.Guild))}";
if (p.Index == 0)
str += $" [{GetText(strs.uneditable)}]";
return str;
}));
await ctx.Channel.SendMessageAsync(toSend);
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
public async Task RemovePerm(int index)
{
@@ -147,8 +143,7 @@ public partial class Permissions : NadekoModule<PermissionService>
_service.UpdateCache(config);
}
await ReplyConfirmLocalizedAsync(strs.removed(
index + 1,
await ReplyConfirmLocalizedAsync(strs.removed(index + 1,
Format.Code(p.GetCommand(Prefix, (SocketGuild)ctx.Guild))));
}
catch (IndexOutOfRangeException)
@@ -157,14 +152,14 @@ public partial class Permissions : NadekoModule<PermissionService>
}
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
public async Task MovePerm(int from, int to)
{
from -= 1;
to -= 1;
if (!(from == to || from < 0 || to < 0))
{
try
{
Permissionv2 fromPerm;
@@ -187,6 +182,7 @@ public partial class Permissions : NadekoModule<PermissionService>
await ReplyErrorLocalizedAsync(strs.perm_not_found(++to));
return;
}
fromPerm = permsCol[from];
permsCol.RemoveAt(from);
@@ -199,334 +195,287 @@ public partial class Permissions : NadekoModule<PermissionService>
Format.Code(fromPerm.GetCommand(Prefix, (SocketGuild)ctx.Guild)),
++from,
++to));
return;
}
catch (Exception e) when (e is ArgumentOutOfRangeException or IndexOutOfRangeException)
{
}
}
await ReplyConfirmLocalizedAsync(strs.perm_out_of_range);
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
public async Task SrvrCmd(CommandOrCrInfo command, PermissionAction action)
{
await _service.AddPermissions(ctx.Guild.Id, new Permissionv2
{
PrimaryTarget = PrimaryPermissionType.Server,
PrimaryTargetId = 0,
SecondaryTarget = SecondaryPermissionType.Command,
SecondaryTargetName = command.Name.ToLowerInvariant(),
State = action.Value,
IsCustomCommand = command.IsCustom,
});
await _service.AddPermissions(ctx.Guild.Id,
new Permissionv2
{
PrimaryTarget = PrimaryPermissionType.Server,
PrimaryTargetId = 0,
SecondaryTarget = SecondaryPermissionType.Command,
SecondaryTargetName = command.Name.ToLowerInvariant(),
State = action.Value,
IsCustomCommand = command.IsCustom
});
if (action.Value)
{
await ReplyConfirmLocalizedAsync(strs.sx_enable(
Format.Code(command.Name),
GetText(strs.of_command)));
}
await ReplyConfirmLocalizedAsync(strs.sx_enable(Format.Code(command.Name), GetText(strs.of_command)));
else
{
await ReplyConfirmLocalizedAsync(strs.sx_disable(
Format.Code(command.Name),
GetText(strs.of_command)));
}
await ReplyConfirmLocalizedAsync(strs.sx_disable(Format.Code(command.Name), GetText(strs.of_command)));
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
public async Task SrvrMdl(ModuleOrCrInfo module, PermissionAction action)
{
await _service.AddPermissions(ctx.Guild.Id, new Permissionv2
{
PrimaryTarget = PrimaryPermissionType.Server,
PrimaryTargetId = 0,
SecondaryTarget = SecondaryPermissionType.Module,
SecondaryTargetName = module.Name.ToLowerInvariant(),
State = action.Value,
});
await _service.AddPermissions(ctx.Guild.Id,
new Permissionv2
{
PrimaryTarget = PrimaryPermissionType.Server,
PrimaryTargetId = 0,
SecondaryTarget = SecondaryPermissionType.Module,
SecondaryTargetName = module.Name.ToLowerInvariant(),
State = action.Value
});
if (action.Value)
{
await ReplyConfirmLocalizedAsync(strs.sx_enable(
Format.Code(module.Name),
GetText(strs.of_module)));
}
await ReplyConfirmLocalizedAsync(strs.sx_enable(Format.Code(module.Name), GetText(strs.of_module)));
else
{
await ReplyConfirmLocalizedAsync(strs.sx_disable(
Format.Code(module.Name),
GetText(strs.of_module)));
}
await ReplyConfirmLocalizedAsync(strs.sx_disable(Format.Code(module.Name), GetText(strs.of_module)));
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
public async Task UsrCmd(CommandOrCrInfo command, PermissionAction action, [Leftover] IGuildUser user)
{
await _service.AddPermissions(ctx.Guild.Id, new Permissionv2
{
PrimaryTarget = PrimaryPermissionType.User,
PrimaryTargetId = user.Id,
SecondaryTarget = SecondaryPermissionType.Command,
SecondaryTargetName = command.Name.ToLowerInvariant(),
State = action.Value,
IsCustomCommand = command.IsCustom,
});
await _service.AddPermissions(ctx.Guild.Id,
new Permissionv2
{
PrimaryTarget = PrimaryPermissionType.User,
PrimaryTargetId = user.Id,
SecondaryTarget = SecondaryPermissionType.Command,
SecondaryTargetName = command.Name.ToLowerInvariant(),
State = action.Value,
IsCustomCommand = command.IsCustom
});
if (action.Value)
{
await ReplyConfirmLocalizedAsync(strs.ux_enable(
Format.Code(command.Name),
await ReplyConfirmLocalizedAsync(strs.ux_enable(Format.Code(command.Name),
GetText(strs.of_command),
Format.Code(user.ToString())));
}
else
{
await ReplyConfirmLocalizedAsync(strs.ux_disable(
Format.Code(command.Name),
await ReplyConfirmLocalizedAsync(strs.ux_disable(Format.Code(command.Name),
GetText(strs.of_command),
Format.Code(user.ToString())));
}
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
public async Task UsrMdl(ModuleOrCrInfo module, PermissionAction action, [Leftover] IGuildUser user)
{
await _service.AddPermissions(ctx.Guild.Id, new Permissionv2
{
PrimaryTarget = PrimaryPermissionType.User,
PrimaryTargetId = user.Id,
SecondaryTarget = SecondaryPermissionType.Module,
SecondaryTargetName = module.Name.ToLowerInvariant(),
State = action.Value,
});
await _service.AddPermissions(ctx.Guild.Id,
new Permissionv2
{
PrimaryTarget = PrimaryPermissionType.User,
PrimaryTargetId = user.Id,
SecondaryTarget = SecondaryPermissionType.Module,
SecondaryTargetName = module.Name.ToLowerInvariant(),
State = action.Value
});
if (action.Value)
{
await ReplyConfirmLocalizedAsync(strs.ux_enable(
Format.Code(module.Name),
await ReplyConfirmLocalizedAsync(strs.ux_enable(Format.Code(module.Name),
GetText(strs.of_module),
Format.Code(user.ToString())));
}
else
{
await ReplyConfirmLocalizedAsync(strs.ux_disable(
Format.Code(module.Name),
await ReplyConfirmLocalizedAsync(strs.ux_disable(Format.Code(module.Name),
GetText(strs.of_module),
Format.Code(user.ToString())));
}
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
public async Task RoleCmd(CommandOrCrInfo command, PermissionAction action, [Leftover] IRole role)
{
if (role == role.Guild.EveryoneRole)
return;
await _service.AddPermissions(ctx.Guild.Id, new Permissionv2
{
PrimaryTarget = PrimaryPermissionType.Role,
PrimaryTargetId = role.Id,
SecondaryTarget = SecondaryPermissionType.Command,
SecondaryTargetName = command.Name.ToLowerInvariant(),
State = action.Value,
IsCustomCommand = command.IsCustom,
});
await _service.AddPermissions(ctx.Guild.Id,
new Permissionv2
{
PrimaryTarget = PrimaryPermissionType.Role,
PrimaryTargetId = role.Id,
SecondaryTarget = SecondaryPermissionType.Command,
SecondaryTargetName = command.Name.ToLowerInvariant(),
State = action.Value,
IsCustomCommand = command.IsCustom
});
if (action.Value)
{
await ReplyConfirmLocalizedAsync(strs.rx_enable(
Format.Code(command.Name),
await ReplyConfirmLocalizedAsync(strs.rx_enable(Format.Code(command.Name),
GetText(strs.of_command),
Format.Code(role.Name)));
}
else
{
await ReplyConfirmLocalizedAsync(strs.rx_disable(
Format.Code(command.Name),
await ReplyConfirmLocalizedAsync(strs.rx_disable(Format.Code(command.Name),
GetText(strs.of_command),
Format.Code(role.Name)));
}
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
public async Task RoleMdl(ModuleOrCrInfo module, PermissionAction action, [Leftover] IRole role)
{
if (role == role.Guild.EveryoneRole)
return;
await _service.AddPermissions(ctx.Guild.Id, new Permissionv2
{
PrimaryTarget = PrimaryPermissionType.Role,
PrimaryTargetId = role.Id,
SecondaryTarget = SecondaryPermissionType.Module,
SecondaryTargetName = module.Name.ToLowerInvariant(),
State = action.Value,
});
await _service.AddPermissions(ctx.Guild.Id,
new Permissionv2
{
PrimaryTarget = PrimaryPermissionType.Role,
PrimaryTargetId = role.Id,
SecondaryTarget = SecondaryPermissionType.Module,
SecondaryTargetName = module.Name.ToLowerInvariant(),
State = action.Value
});
if (action.Value)
{
await ReplyConfirmLocalizedAsync(strs.rx_enable(
Format.Code(module.Name),
await ReplyConfirmLocalizedAsync(strs.rx_enable(Format.Code(module.Name),
GetText(strs.of_module),
Format.Code(role.Name)));
}
else
{
await ReplyConfirmLocalizedAsync(strs.rx_disable(
Format.Code(module.Name),
await ReplyConfirmLocalizedAsync(strs.rx_disable(Format.Code(module.Name),
GetText(strs.of_module),
Format.Code(role.Name)));
}
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
public async Task ChnlCmd(CommandOrCrInfo command, PermissionAction action, [Leftover] ITextChannel chnl)
{
await _service.AddPermissions(ctx.Guild.Id, new Permissionv2
{
PrimaryTarget = PrimaryPermissionType.Channel,
PrimaryTargetId = chnl.Id,
SecondaryTarget = SecondaryPermissionType.Command,
SecondaryTargetName = command.Name.ToLowerInvariant(),
State = action.Value,
IsCustomCommand = command.IsCustom,
});
await _service.AddPermissions(ctx.Guild.Id,
new Permissionv2
{
PrimaryTarget = PrimaryPermissionType.Channel,
PrimaryTargetId = chnl.Id,
SecondaryTarget = SecondaryPermissionType.Command,
SecondaryTargetName = command.Name.ToLowerInvariant(),
State = action.Value,
IsCustomCommand = command.IsCustom
});
if (action.Value)
{
await ReplyConfirmLocalizedAsync(strs.cx_enable(
Format.Code(command.Name),
await ReplyConfirmLocalizedAsync(strs.cx_enable(Format.Code(command.Name),
GetText(strs.of_command),
Format.Code(chnl.Name)));
}
else
{
await ReplyConfirmLocalizedAsync(strs.cx_disable(
Format.Code(command.Name),
await ReplyConfirmLocalizedAsync(strs.cx_disable(Format.Code(command.Name),
GetText(strs.of_command),
Format.Code(chnl.Name)));
}
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
public async Task ChnlMdl(ModuleOrCrInfo module, PermissionAction action, [Leftover] ITextChannel chnl)
{
await _service.AddPermissions(ctx.Guild.Id, new Permissionv2
{
PrimaryTarget = PrimaryPermissionType.Channel,
PrimaryTargetId = chnl.Id,
SecondaryTarget = SecondaryPermissionType.Module,
SecondaryTargetName = module.Name.ToLowerInvariant(),
State = action.Value,
});
await _service.AddPermissions(ctx.Guild.Id,
new Permissionv2
{
PrimaryTarget = PrimaryPermissionType.Channel,
PrimaryTargetId = chnl.Id,
SecondaryTarget = SecondaryPermissionType.Module,
SecondaryTargetName = module.Name.ToLowerInvariant(),
State = action.Value
});
if (action.Value)
{
await ReplyConfirmLocalizedAsync(strs.cx_enable(
Format.Code(module.Name),
await ReplyConfirmLocalizedAsync(strs.cx_enable(Format.Code(module.Name),
GetText(strs.of_module),
Format.Code(chnl.Name)));
}
else
{
await ReplyConfirmLocalizedAsync(strs.cx_disable(
Format.Code(module.Name),
await ReplyConfirmLocalizedAsync(strs.cx_disable(Format.Code(module.Name),
GetText(strs.of_module),
Format.Code(chnl.Name)));
}
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
public async Task AllChnlMdls(PermissionAction action, [Leftover] ITextChannel chnl)
{
await _service.AddPermissions(ctx.Guild.Id, new Permissionv2
{
PrimaryTarget = PrimaryPermissionType.Channel,
PrimaryTargetId = chnl.Id,
SecondaryTarget = SecondaryPermissionType.AllModules,
SecondaryTargetName = "*",
State = action.Value,
});
await _service.AddPermissions(ctx.Guild.Id,
new Permissionv2
{
PrimaryTarget = PrimaryPermissionType.Channel,
PrimaryTargetId = chnl.Id,
SecondaryTarget = SecondaryPermissionType.AllModules,
SecondaryTargetName = "*",
State = action.Value
});
if (action.Value)
{
await ReplyConfirmLocalizedAsync(strs.acm_enable(
Format.Code(chnl.Name)));
}
await ReplyConfirmLocalizedAsync(strs.acm_enable(Format.Code(chnl.Name)));
else
{
await ReplyConfirmLocalizedAsync(strs.acm_disable(
Format.Code(chnl.Name)));
}
await ReplyConfirmLocalizedAsync(strs.acm_disable(Format.Code(chnl.Name)));
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
public async Task AllRoleMdls(PermissionAction action, [Leftover] IRole role)
{
if (role == role.Guild.EveryoneRole)
return;
await _service.AddPermissions(ctx.Guild.Id, new Permissionv2
{
PrimaryTarget = PrimaryPermissionType.Role,
PrimaryTargetId = role.Id,
SecondaryTarget = SecondaryPermissionType.AllModules,
SecondaryTargetName = "*",
State = action.Value,
});
await _service.AddPermissions(ctx.Guild.Id,
new Permissionv2
{
PrimaryTarget = PrimaryPermissionType.Role,
PrimaryTargetId = role.Id,
SecondaryTarget = SecondaryPermissionType.AllModules,
SecondaryTargetName = "*",
State = action.Value
});
if (action.Value)
{
await ReplyConfirmLocalizedAsync(strs.arm_enable(
Format.Code(role.Name)));
}
await ReplyConfirmLocalizedAsync(strs.arm_enable(Format.Code(role.Name)));
else
{
await ReplyConfirmLocalizedAsync(strs.arm_disable(
Format.Code(role.Name)));
}
await ReplyConfirmLocalizedAsync(strs.arm_disable(Format.Code(role.Name)));
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
public async Task AllUsrMdls(PermissionAction action, [Leftover] IUser user)
{
await _service.AddPermissions(ctx.Guild.Id, new Permissionv2
{
PrimaryTarget = PrimaryPermissionType.User,
PrimaryTargetId = user.Id,
SecondaryTarget = SecondaryPermissionType.AllModules,
SecondaryTargetName = "*",
State = action.Value,
});
await _service.AddPermissions(ctx.Guild.Id,
new Permissionv2
{
PrimaryTarget = PrimaryPermissionType.User,
PrimaryTargetId = user.Id,
SecondaryTarget = SecondaryPermissionType.AllModules,
SecondaryTargetName = "*",
State = action.Value
});
if (action.Value)
{
await ReplyConfirmLocalizedAsync(strs.aum_enable(
Format.Code(user.ToString())));
}
await ReplyConfirmLocalizedAsync(strs.aum_enable(Format.Code(user.ToString())));
else
{
await ReplyConfirmLocalizedAsync(strs.aum_disable(
Format.Code(user.ToString())));
}
await ReplyConfirmLocalizedAsync(strs.aum_disable(Format.Code(user.ToString())));
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
public async Task AllSrvrMdls(PermissionAction action)
{
@@ -536,7 +485,7 @@ public partial class Permissions : NadekoModule<PermissionService>
PrimaryTargetId = 0,
SecondaryTarget = SecondaryPermissionType.AllModules,
SecondaryTargetName = "*",
State = action.Value,
State = action.Value
};
var allowUser = new Permissionv2
@@ -545,20 +494,14 @@ public partial class Permissions : NadekoModule<PermissionService>
PrimaryTargetId = ctx.User.Id,
SecondaryTarget = SecondaryPermissionType.AllModules,
SecondaryTargetName = "*",
State = true,
State = true
};
await _service.AddPermissions(ctx.Guild.Id,
newPerm,
allowUser);
await _service.AddPermissions(ctx.Guild.Id, newPerm, allowUser);
if (action.Value)
{
await ReplyConfirmLocalizedAsync(strs.asm_enable);
}
else
{
await ReplyConfirmLocalizedAsync(strs.asm_disable);
}
}
}
}

View File

@@ -17,7 +17,8 @@ public partial class Permissions
_perms = perms;
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
[UserPerm(GuildPerm.Administrator)]
public async Task ResetPerms()
@@ -26,7 +27,8 @@ public partial class Permissions
await ReplyConfirmLocalizedAsync(strs.perms_reset);
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[OwnerOnly]
public async Task ResetGlobalPerms()
{
@@ -34,4 +36,4 @@ public partial class Permissions
await ReplyConfirmLocalizedAsync(strs.global_perms_reset);
}
}
}
}

View File

@@ -1,20 +1,23 @@
#nullable disable
using NadekoBot.Common.ModuleBehaviors;
using NadekoBot.Services.Database.Models;
using Microsoft.EntityFrameworkCore;
using NadekoBot.Common.ModuleBehaviors;
using NadekoBot.Db;
using NadekoBot.Services.Database.Models;
namespace NadekoBot.Modules.Permissions.Services;
public sealed class BlacklistService : IEarlyBehavior
{
public int Priority
=> int.MaxValue;
private readonly DbService _db;
private readonly IPubSub _pubSub;
private readonly IBotCredentials _creds;
private IReadOnlyList<BlacklistEntry> _blacklist;
public int Priority => int.MaxValue;
private readonly TypedKey<BlacklistEntry[]> blPubKey = new("blacklist.reload");
public BlacklistService(DbService db, IPubSub pubSub, IBotCredentials creds)
{
_db = db;
@@ -37,10 +40,8 @@ public sealed class BlacklistService : IEarlyBehavior
{
if (guild != null && bl.Type == BlacklistType.Server && bl.ItemId == guild.Id)
{
Log.Information("Blocked input from blacklisted guild: {GuildName} [{GuildId}]",
guild.Name,
guild.Id);
Log.Information("Blocked input from blacklisted guild: {GuildName} [{GuildId}]", guild.Name, guild.Id);
return Task.FromResult(true);
}
@@ -49,16 +50,16 @@ public sealed class BlacklistService : IEarlyBehavior
Log.Information("Blocked input from blacklisted channel: {ChannelName} [{ChannelId}]",
usrMsg.Channel.Name,
usrMsg.Channel.Id);
return Task.FromResult(true);
}
if (bl.Type == BlacklistType.User && bl.ItemId == usrMsg.Author.Id)
{
Log.Information("Blocked input from blacklisted user: {UserName} [{UserId}]",
Log.Information("Blocked input from blacklisted user: {UserName} [{UserId}]",
usrMsg.Author.ToString(),
usrMsg.Author.Id);
return Task.FromResult(true);
}
}
@@ -74,57 +75,48 @@ public sealed class BlacklistService : IEarlyBehavior
using var uow = _db.GetDbContext();
var toPublish = uow.Blacklist.AsNoTracking().ToArray();
_blacklist = toPublish;
if (publish)
{
_pubSub.Pub(blPubKey, toPublish);
}
if (publish) _pubSub.Pub(blPubKey, toPublish);
}
public void Blacklist(BlacklistType type, ulong id)
{
if (_creds.OwnerIds.Contains(id))
return;
using var uow = _db.GetDbContext();
var item = new BlacklistEntry { ItemId = id, Type = type };
uow.Blacklist.Add(item);
uow.SaveChanges();
Reload(true);
Reload();
}
public void UnBlacklist(BlacklistType type, ulong id)
{
using var uow = _db.GetDbContext();
var toRemove = uow.Blacklist
.FirstOrDefault(bi => bi.ItemId == id && bi.Type == type);
var toRemove = uow.Blacklist.FirstOrDefault(bi => bi.ItemId == id && bi.Type == type);
if (toRemove is not null)
uow.Blacklist.Remove(toRemove);
uow.SaveChanges();
Reload(true);
Reload();
}
public void BlacklistUsers(IReadOnlyCollection<ulong> toBlacklist)
{
using (var uow = _db.GetDbContext())
using (var uow = _db.GetDbContext())
{
var bc = uow.Blacklist;
//blacklist the users
bc.AddRange(toBlacklist.Select(x =>
new BlacklistEntry
{
ItemId = x,
Type = BlacklistType.User,
}));
bc.AddRange(toBlacklist.Select(x => new BlacklistEntry { ItemId = x, Type = BlacklistType.User }));
//clear their currencies
uow.DiscordUser.RemoveFromMany(toBlacklist);
uow.SaveChanges();
}
Reload(true);
Reload();
}
}
}

View File

@@ -10,33 +10,26 @@ public class CmdCdService : ILateBlocker, INService
public ConcurrentDictionary<ulong, ConcurrentHashSet<ActiveCooldown>> ActiveCooldowns { get; } = new();
public int Priority { get; } = 0;
public CmdCdService(Bot bot)
=> CommandCooldowns = new(
bot.AllGuildConfigs.ToDictionary(k => k.GuildId,
v => new ConcurrentHashSet<CommandCooldown>(v.CommandCooldowns)));
=> CommandCooldowns = new(bot.AllGuildConfigs.ToDictionary(k => k.GuildId,
v => new ConcurrentHashSet<CommandCooldown>(v.CommandCooldowns)));
public Task<bool> TryBlock(IGuild guild, IUser user, string commandName)
{
if (guild is null)
return Task.FromResult(false);
var cmdcds = CommandCooldowns.GetOrAdd(guild.Id, new ConcurrentHashSet<CommandCooldown>());
CommandCooldown cdRule;
if ((cdRule = cmdcds.FirstOrDefault(cc => cc.CommandName == commandName)) != null)
{
var activeCdsForGuild = ActiveCooldowns.GetOrAdd(guild.Id, new ConcurrentHashSet<ActiveCooldown>());
if (activeCdsForGuild.FirstOrDefault(ac => ac.UserId == user.Id && ac.Command == commandName) != null)
{
return Task.FromResult(true);
}
activeCdsForGuild.Add(new()
{
UserId = user.Id,
Command = commandName,
});
activeCdsForGuild.Add(new() { UserId = user.Id, Command = commandName });
var _ = Task.Run(async () =>
{
try
@@ -53,7 +46,7 @@ public class CmdCdService : ILateBlocker, INService
return Task.FromResult(false);
}
public Task<bool> TryBlockLate(ICommandContext ctx, string moduleName, CommandInfo command)
{
var guild = ctx.Guild;
@@ -68,4 +61,4 @@ public class ActiveCooldown
{
public string Command { get; set; }
public ulong UserId { get; set; }
}
}

View File

@@ -1,15 +1,13 @@
#nullable disable
using NadekoBot.Common.ModuleBehaviors;
using Microsoft.EntityFrameworkCore;
using NadekoBot.Services.Database.Models;
using NadekoBot.Common.ModuleBehaviors;
using NadekoBot.Db;
using NadekoBot.Services.Database.Models;
namespace NadekoBot.Modules.Permissions.Services;
public sealed class FilterService : IEarlyBehavior
{
private readonly DbService _db;
public ConcurrentHashSet<ulong> InviteFilteringChannels { get; }
public ConcurrentHashSet<ulong> InviteFilteringServers { get; }
@@ -22,75 +20,44 @@ public sealed class FilterService : IEarlyBehavior
public ConcurrentHashSet<ulong> LinkFilteringChannels { get; }
public ConcurrentHashSet<ulong> LinkFilteringServers { get; }
public int Priority => int.MaxValue - 1;
public int Priority
=> int.MaxValue - 1;
public ConcurrentHashSet<string> FilteredWordsForChannel(ulong channelId, ulong guildId)
{
var words = new ConcurrentHashSet<string>();
if (WordFilteringChannels.Contains(channelId))
ServerFilteredWords.TryGetValue(guildId, out words);
return words;
}
public void ClearFilteredWords(ulong guildId)
{
using var uow = _db.GetDbContext();
var gc = uow.GuildConfigsForId(guildId,
set => set.Include(x => x.FilteredWords)
.Include(x => x.FilterWordsChannelIds));
WordFilteringServers.TryRemove(guildId);
ServerFilteredWords.TryRemove(guildId, out _);
foreach (var c in gc.FilterWordsChannelIds)
{
WordFilteringChannels.TryRemove(c.ChannelId);
}
gc.FilterWords = false;
gc.FilteredWords.Clear();
gc.FilterWordsChannelIds.Clear();
uow.SaveChanges();
}
public ConcurrentHashSet<string> FilteredWordsForServer(ulong guildId)
{
var words = new ConcurrentHashSet<string>();
if (WordFilteringServers.Contains(guildId))
ServerFilteredWords.TryGetValue(guildId, out words);
return words;
}
private readonly DbService _db;
public FilterService(DiscordSocketClient client, DbService db)
{
_db = db;
using(var uow = db.GetDbContext())
using (var uow = db.GetDbContext())
{
var ids = client.GetGuildIds();
var configs = uow.Set<GuildConfig>()
.AsQueryable()
.Include(x => x.FilteredWords)
.Include(x => x.FilterLinksChannelIds)
.Include(x => x.FilterWordsChannelIds)
.Include(x => x.FilterInvitesChannelIds)
.Where(gc => ids.Contains(gc.GuildId))
.ToList();
.AsQueryable()
.Include(x => x.FilteredWords)
.Include(x => x.FilterLinksChannelIds)
.Include(x => x.FilterWordsChannelIds)
.Include(x => x.FilterInvitesChannelIds)
.Where(gc => ids.Contains(gc.GuildId))
.ToList();
InviteFilteringServers = new(configs.Where(gc => gc.FilterInvites).Select(gc => gc.GuildId));
InviteFilteringChannels = new(configs.SelectMany(gc => gc.FilterInvitesChannelIds.Select(fci => fci.ChannelId)));
InviteFilteringChannels =
new(configs.SelectMany(gc => gc.FilterInvitesChannelIds.Select(fci => fci.ChannelId)));
LinkFilteringServers = new(configs.Where(gc => gc.FilterLinks).Select(gc => gc.GuildId));
LinkFilteringChannels = new(configs.SelectMany(gc => gc.FilterLinksChannelIds.Select(fci => fci.ChannelId)));
LinkFilteringChannels =
new(configs.SelectMany(gc => gc.FilterLinksChannelIds.Select(fci => fci.ChannelId)));
var dict = configs.ToDictionary(gc => gc.GuildId, gc => new ConcurrentHashSet<string>(gc.FilteredWords.Select(fw => fw.Word)));
var dict = configs.ToDictionary(gc => gc.GuildId,
gc => new ConcurrentHashSet<string>(gc.FilteredWords.Select(fw => fw.Word)));
ServerFilteredWords = new(dict);
var serverFiltering = configs.Where(gc => gc.FilterWords);
WordFilteringServers = new(serverFiltering.Select(gc => gc.GuildId));
WordFilteringChannels = new(configs.SelectMany(gc => gc.FilterWordsChannelIds.Select(fwci => fwci.ChannelId)));
WordFilteringChannels =
new(configs.SelectMany(gc => gc.FilterWordsChannelIds.Select(fwci => fwci.ChannelId)));
}
client.MessageUpdated += (oldData, newMsg, channel) =>
@@ -108,16 +75,47 @@ public sealed class FilterService : IEarlyBehavior
};
}
public ConcurrentHashSet<string> FilteredWordsForChannel(ulong channelId, ulong guildId)
{
var words = new ConcurrentHashSet<string>();
if (WordFilteringChannels.Contains(channelId))
ServerFilteredWords.TryGetValue(guildId, out words);
return words;
}
public void ClearFilteredWords(ulong guildId)
{
using var uow = _db.GetDbContext();
var gc = uow.GuildConfigsForId(guildId,
set => set.Include(x => x.FilteredWords).Include(x => x.FilterWordsChannelIds));
WordFilteringServers.TryRemove(guildId);
ServerFilteredWords.TryRemove(guildId, out _);
foreach (var c in gc.FilterWordsChannelIds) WordFilteringChannels.TryRemove(c.ChannelId);
gc.FilterWords = false;
gc.FilteredWords.Clear();
gc.FilterWordsChannelIds.Clear();
uow.SaveChanges();
}
public ConcurrentHashSet<string> FilteredWordsForServer(ulong guildId)
{
var words = new ConcurrentHashSet<string>();
if (WordFilteringServers.Contains(guildId))
ServerFilteredWords.TryGetValue(guildId, out words);
return words;
}
public async Task<bool> RunBehavior(IGuild guild, IUserMessage msg)
{
if (msg.Author is not IGuildUser gu || gu.GuildPermissions.Administrator)
return false;
var results = await Task.WhenAll(
FilterInvites(guild, msg),
FilterWords(guild, msg),
FilterLinks(guild, msg));
var results = await Task.WhenAll(FilterInvites(guild, msg), FilterWords(guild, msg), FilterLinks(guild, msg));
return results.Any(x => x);
}
@@ -128,33 +126,32 @@ public sealed class FilterService : IEarlyBehavior
if (usrMsg is null)
return false;
var filteredChannelWords = FilteredWordsForChannel(usrMsg.Channel.Id, guild.Id) ?? new ConcurrentHashSet<string>();
var filteredChannelWords =
FilteredWordsForChannel(usrMsg.Channel.Id, guild.Id) ?? new ConcurrentHashSet<string>();
var filteredServerWords = FilteredWordsForServer(guild.Id) ?? new ConcurrentHashSet<string>();
var wordsInMessage = usrMsg.Content.ToLowerInvariant().Split(' ');
if (filteredChannelWords.Count != 0 || filteredServerWords.Count != 0)
{
foreach (var word in wordsInMessage)
{
if (filteredChannelWords.Contains(word) ||
filteredServerWords.Contains(word))
if (filteredChannelWords.Contains(word) || filteredServerWords.Contains(word))
{
Log.Information("User {UserName} [{UserId}] used a filtered word in {ChannelId} channel",
usrMsg.Author.ToString(),
usrMsg.Author.Id,
usrMsg.Channel.Id);
try
{
await usrMsg.DeleteAsync();
}
catch (HttpException ex)
{
Log.Warning("I do not have permission to filter words in channel with id " + usrMsg.Channel.Id, ex);
Log.Warning("I do not have permission to filter words in channel with id " + usrMsg.Channel.Id,
ex);
}
return true;
}
}
}
return false;
}
@@ -165,15 +162,14 @@ public sealed class FilterService : IEarlyBehavior
if (usrMsg is null)
return false;
if ((InviteFilteringChannels.Contains(usrMsg.Channel.Id)
|| InviteFilteringServers.Contains(guild.Id))
if ((InviteFilteringChannels.Contains(usrMsg.Channel.Id) || InviteFilteringServers.Contains(guild.Id))
&& usrMsg.Content.IsDiscordInvite())
{
Log.Information("User {UserName} [{UserId}] sent a filtered invite to {ChannelId} channel",
usrMsg.Author.ToString(),
usrMsg.Author.Id,
usrMsg.Channel.Id);
try
{
await usrMsg.DeleteAsync();
@@ -185,6 +181,7 @@ public sealed class FilterService : IEarlyBehavior
return true;
}
}
return false;
}
@@ -195,15 +192,14 @@ public sealed class FilterService : IEarlyBehavior
if (usrMsg is null)
return false;
if ((LinkFilteringChannels.Contains(usrMsg.Channel.Id)
|| LinkFilteringServers.Contains(guild.Id))
if ((LinkFilteringChannels.Contains(usrMsg.Channel.Id) || LinkFilteringServers.Contains(guild.Id))
&& usrMsg.Content.TryGetUrlPath(out _))
{
Log.Information("User {UserName} [{UserId}] sent a filtered link to {ChannelId} channel",
usrMsg.Author.ToString(),
usrMsg.Author.Id,
usrMsg.Channel.Id);
try
{
await usrMsg.DeleteAsync();
@@ -215,6 +211,7 @@ public sealed class FilterService : IEarlyBehavior
return true;
}
}
return false;
}
}
}

View File

@@ -5,11 +5,15 @@ namespace NadekoBot.Modules.Permissions.Services;
public class GlobalPermissionService : ILateBlocker, INService
{
private readonly BotConfigService _bss;
public int Priority { get; } = 0;
public HashSet<string> BlockedCommands => _bss.Data.Blocked.Commands;
public HashSet<string> BlockedModules => _bss.Data.Blocked.Modules;
public HashSet<string> BlockedCommands
=> _bss.Data.Blocked.Commands;
public HashSet<string> BlockedModules
=> _bss.Data.Blocked.Modules;
private readonly BotConfigService _bss;
public GlobalPermissionService(BotConfigService bss)
=> _bss = bss;
@@ -17,21 +21,19 @@ public class GlobalPermissionService : ILateBlocker, INService
public Task<bool> TryBlockLate(ICommandContext ctx, string moduleName, CommandInfo command)
{
var settings = _bss.Data;
var settings = _bss.Data;
var commandName = command.Name.ToLowerInvariant();
if (commandName != "resetglobalperms" &&
(settings.Blocked.Commands.Contains(commandName) ||
settings.Blocked.Modules.Contains(moduleName.ToLowerInvariant())))
{
if (commandName != "resetglobalperms"
&& (settings.Blocked.Commands.Contains(commandName)
|| settings.Blocked.Modules.Contains(moduleName.ToLowerInvariant())))
return Task.FromResult(true);
}
return Task.FromResult(false);
}
/// <summary>
/// Toggles module blacklist
/// Toggles module blacklist
/// </summary>
/// <param name="moduleName">Lowercase module name</param>
/// <returns>Whether the module is added</returns>
@@ -53,9 +55,9 @@ public class GlobalPermissionService : ILateBlocker, INService
return added;
}
/// <summary>
/// Toggles command blacklist
/// Toggles command blacklist
/// </summary>
/// <param name="commandName">Lowercase command name</param>
/// <returns>Whether the command is added</returns>
@@ -79,7 +81,7 @@ public class GlobalPermissionService : ILateBlocker, INService
}
/// <summary>
/// Resets all global permissions
/// Resets all global permissions
/// </summary>
public Task Reset()
{
@@ -91,4 +93,4 @@ public class GlobalPermissionService : ILateBlocker, INService
return Task.CompletedTask;
}
}
}

View File

@@ -1,25 +1,26 @@
#nullable disable
using Microsoft.EntityFrameworkCore;
using NadekoBot.Common.ModuleBehaviors;
using NadekoBot.Db;
using NadekoBot.Modules.Permissions.Common;
using NadekoBot.Services.Database.Models;
using NadekoBot.Db;
namespace NadekoBot.Modules.Permissions.Services;
public class PermissionService : ILateBlocker, INService
{
public int Priority { get; } = 0;
//guildid, root permission
public ConcurrentDictionary<ulong, PermissionCache> Cache { get; } = new();
private readonly DbService _db;
private readonly CommandHandler _cmd;
private readonly IBotStrings _strings;
private readonly IEmbedBuilderService _eb;
//guildid, root permission
public ConcurrentDictionary<ulong, PermissionCache> Cache { get; } = new();
public PermissionService(DiscordSocketClient client,
public PermissionService(
DiscordSocketClient client,
DbService db,
CommandHandler cmd,
IBotStrings strings,
@@ -31,16 +32,12 @@ public class PermissionService : ILateBlocker, INService
_eb = eb;
using var uow = _db.GetDbContext();
foreach (var x in uow.GuildConfigs.Permissionsv2ForAll(client.Guilds.ToArray().Select(x => x.Id)
.ToList()))
{
Cache.TryAdd(x.GuildId, new()
{
Verbose = x.VerbosePermissions,
PermRole = x.PermissionRole,
Permissions = new(x.Permissions)
});
}
foreach (var x in uow.GuildConfigs.Permissionsv2ForAll(client.Guilds.ToArray().Select(x => x.Id).ToList()))
Cache.TryAdd(x.GuildId,
new()
{
Verbose = x.VerbosePermissions, PermRole = x.PermissionRole, Permissions = new(x.Permissions)
});
}
public PermissionCache GetCacheFor(ulong guildId)
@@ -49,14 +46,15 @@ public class PermissionService : ILateBlocker, INService
{
using (var uow = _db.GetDbContext())
{
var config = uow.GuildConfigsForId(guildId,
set => set.Include(x => x.Permissions));
var config = uow.GuildConfigsForId(guildId, set => set.Include(x => x.Permissions));
UpdateCache(config);
}
Cache.TryGetValue(guildId, out pc);
if (pc is null)
throw new("Cache is null.");
}
return pc;
}
@@ -71,23 +69,26 @@ public class PermissionService : ILateBlocker, INService
perm.Index = ++max;
config.Permissions.Add(perm);
}
await uow.SaveChangesAsync();
UpdateCache(config);
}
public void UpdateCache(GuildConfig config)
=> Cache.AddOrUpdate(config.GuildId, new PermissionCache()
{
Permissions = new(config.Permissions),
PermRole = config.PermissionRole,
Verbose = config.VerbosePermissions
}, (id, old) =>
{
old.Permissions = new(config.Permissions);
old.PermRole = config.PermissionRole;
old.Verbose = config.VerbosePermissions;
return old;
});
=> Cache.AddOrUpdate(config.GuildId,
new PermissionCache
{
Permissions = new(config.Permissions),
PermRole = config.PermissionRole,
Verbose = config.VerbosePermissions
},
(id, old) =>
{
old.Permissions = new(config.Permissions);
old.PermRole = config.PermissionRole;
old.Verbose = config.VerbosePermissions;
return old;
});
public async Task<bool> TryBlockLate(ICommandContext ctx, string moduleName, CommandInfo command)
{
@@ -96,68 +97,66 @@ public class PermissionService : ILateBlocker, INService
var user = ctx.User;
var channel = ctx.Channel;
var commandName = command.Name.ToLowerInvariant();
await Task.Yield();
if (guild is null)
{
return false;
}
else
{
var resetCommand = commandName == "resetperms";
var pc = GetCacheFor(guild.Id);
if (!resetCommand && !pc.Permissions.CheckPermissions(msg, commandName, moduleName, out var index))
{
if (pc.Verbose)
await Task.Yield();
if (guild is null) return false;
var resetCommand = commandName == "resetperms";
var pc = GetCacheFor(guild.Id);
if (!resetCommand && !pc.Permissions.CheckPermissions(msg, commandName, moduleName, out var index))
{
if (pc.Verbose)
try
{
try
{
await channel.SendErrorAsync(_eb,
_strings.GetText(strs.perm_prevent(index + 1,
await channel.SendErrorAsync(_eb,
_strings.GetText(strs.perm_prevent(index + 1,
Format.Bold(pc.Permissions[index]
.GetCommand(_cmd.GetPrefix(guild), (SocketGuild)guild))), guild.Id));
}
catch
{
}
.GetCommand(_cmd.GetPrefix(guild), (SocketGuild)guild))),
guild.Id));
}
catch
{
}
return true;
}
if (moduleName == nameof(Permissions))
{
if (user is not IGuildUser guildUser)
return true;
if (guildUser.GuildPermissions.Administrator)
return false;
var permRole = pc.PermRole;
if (!ulong.TryParse(permRole, out var rid))
rid = 0;
string returnMsg;
IRole role;
if (string.IsNullOrWhiteSpace(permRole) || (role = guild.GetRole(rid)) is null)
{
returnMsg = "You need Admin permissions in order to use permission commands.";
if (pc.Verbose)
try { await channel.SendErrorAsync(_eb, returnMsg); }
catch { }
return true;
}
if (moduleName == nameof(Permissions))
if (!guildUser.RoleIds.Contains(rid))
{
if (user is not IGuildUser guildUser)
return true;
returnMsg = $"You need the {Format.Bold(role.Name)} role in order to use permission commands.";
if (pc.Verbose)
try { await channel.SendErrorAsync(_eb, returnMsg); }
catch { }
if (guildUser.GuildPermissions.Administrator)
return false;
var permRole = pc.PermRole;
if (!ulong.TryParse(permRole, out var rid))
rid = 0;
string returnMsg;
IRole role;
if (string.IsNullOrWhiteSpace(permRole) || (role = guild.GetRole(rid)) is null)
{
returnMsg = $"You need Admin permissions in order to use permission commands.";
if (pc.Verbose)
try { await channel.SendErrorAsync(_eb, returnMsg); } catch { }
return true;
}
else if (!guildUser.RoleIds.Contains(rid))
{
returnMsg = $"You need the {Format.Bold(role.Name)} role in order to use permission commands.";
if (pc.Verbose)
try { await channel.SendErrorAsync(_eb, returnMsg); } catch { }
return true;
}
return false;
return true;
}
return false;
}
return false;
@@ -171,4 +170,4 @@ public class PermissionService : ILateBlocker, INService
await uow.SaveChangesAsync();
UpdateCache(config);
}
}
}