mirror of
https://gitlab.com/Kwoth/nadekobot.git
synced 2025-09-11 09:48:26 -04:00
Restructured folders and project names, ci should be fixed
This commit is contained in:
157
src/NadekoBot/Modules/Permissions/BlacklistCommands.cs
Normal file
157
src/NadekoBot/Modules/Permissions/BlacklistCommands.cs
Normal file
@@ -0,0 +1,157 @@
|
||||
using System;
|
||||
using Discord;
|
||||
using Discord.Commands;
|
||||
using NadekoBot.Common.Attributes;
|
||||
using NadekoBot.Common.TypeReaders;
|
||||
using NadekoBot.Core.Services.Database.Models;
|
||||
using NadekoBot.Modules.Permissions.Services;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Discord.WebSocket;
|
||||
using NadekoBot.Extensions;
|
||||
using Serilog;
|
||||
|
||||
namespace NadekoBot.Modules.Permissions
|
||||
{
|
||||
public partial class Permissions
|
||||
{
|
||||
[Group]
|
||||
public class BlacklistCommands : NadekoSubmodule<BlacklistService>
|
||||
{
|
||||
private readonly DiscordSocketClient _client;
|
||||
|
||||
public BlacklistCommands(DiscordSocketClient client)
|
||||
{
|
||||
_client = client;
|
||||
}
|
||||
|
||||
private async Task ListBlacklistInternal(string title, BlacklistType type, int page = 0)
|
||||
{
|
||||
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)
|
||||
{
|
||||
return new EmbedBuilder()
|
||||
.WithOkColor()
|
||||
.WithTitle(title)
|
||||
.WithDescription(GetText("empty_page"));
|
||||
}
|
||||
|
||||
return new EmbedBuilder()
|
||||
.WithTitle(title)
|
||||
.WithDescription(pageItems.JoinWith('\n'))
|
||||
.WithOkColor();
|
||||
}, items.Length, 10);
|
||||
}
|
||||
|
||||
[NadekoCommand, Usage, Description, Aliases]
|
||||
[OwnerOnly]
|
||||
public Task UserBlacklist(int page = 1)
|
||||
{
|
||||
if (--page < 0)
|
||||
return Task.CompletedTask;
|
||||
|
||||
return ListBlacklistInternal(GetText("blacklisted_users"), BlacklistType.User, page);
|
||||
}
|
||||
|
||||
[NadekoCommand, Usage, Description, Aliases]
|
||||
[OwnerOnly]
|
||||
public Task ChannelBlacklist(int page = 1)
|
||||
{
|
||||
if (--page < 0)
|
||||
return Task.CompletedTask;
|
||||
|
||||
return ListBlacklistInternal(GetText("blacklisted_channels"), BlacklistType.Channel, page);
|
||||
}
|
||||
|
||||
[NadekoCommand, Usage, Description, Aliases]
|
||||
[OwnerOnly]
|
||||
public Task ServerBlacklist(int page = 1)
|
||||
{
|
||||
if (--page < 0)
|
||||
return Task.CompletedTask;
|
||||
|
||||
return ListBlacklistInternal(GetText("blacklisted_servers"), BlacklistType.Server, page);
|
||||
}
|
||||
|
||||
[NadekoCommand, Usage, Description, Aliases]
|
||||
[OwnerOnly]
|
||||
public Task UserBlacklist(AddRemove action, ulong id)
|
||||
=> Blacklist(action, id, BlacklistType.User);
|
||||
|
||||
[NadekoCommand, Usage, Description, Aliases]
|
||||
[OwnerOnly]
|
||||
public Task UserBlacklist(AddRemove action, IUser usr)
|
||||
=> Blacklist(action, usr.Id, BlacklistType.User);
|
||||
|
||||
[NadekoCommand, Usage, Description, Aliases]
|
||||
[OwnerOnly]
|
||||
public Task ChannelBlacklist(AddRemove action, ulong id)
|
||||
=> Blacklist(action, id, BlacklistType.Channel);
|
||||
|
||||
[NadekoCommand, Usage, Description, Aliases]
|
||||
[OwnerOnly]
|
||||
public Task ServerBlacklist(AddRemove action, ulong id)
|
||||
=> Blacklist(action, id, BlacklistType.Server);
|
||||
|
||||
[NadekoCommand, Usage, Description, Aliases]
|
||||
[OwnerOnly]
|
||||
public Task ServerBlacklist(AddRemove action, IGuild guild)
|
||||
=> Blacklist(action, guild.Id, BlacklistType.Server);
|
||||
|
||||
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("blacklisted", Format.Code(type.ToString()),
|
||||
Format.Code(id.ToString())).ConfigureAwait(false);
|
||||
else
|
||||
await ReplyConfirmLocalizedAsync("unblacklisted", Format.Code(type.ToString()),
|
||||
Format.Code(id.ToString())).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
98
src/NadekoBot/Modules/Permissions/CmdCdsCommands.cs
Normal file
98
src/NadekoBot/Modules/Permissions/CmdCdsCommands.cs
Normal file
@@ -0,0 +1,98 @@
|
||||
using Discord;
|
||||
using Discord.Commands;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using NadekoBot.Extensions;
|
||||
using NadekoBot.Core.Services;
|
||||
using NadekoBot.Core.Services.Database.Models;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using NadekoBot.Common.Attributes;
|
||||
using NadekoBot.Common.Collections;
|
||||
using NadekoBot.Common.TypeReaders;
|
||||
using NadekoBot.Modules.Permissions.Services;
|
||||
|
||||
namespace NadekoBot.Modules.Permissions
|
||||
{
|
||||
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;
|
||||
|
||||
public CmdCdsCommands(CmdCdService service, DbService db)
|
||||
{
|
||||
_service = service;
|
||||
_db = db;
|
||||
}
|
||||
|
||||
[NadekoCommand, Usage, Description, Aliases]
|
||||
[RequireContext(ContextType.Guild)]
|
||||
public async Task CmdCooldown(CommandOrCrInfo command, int secs)
|
||||
{
|
||||
var channel = (ITextChannel)ctx.Channel;
|
||||
if (secs < 0 || secs > 3600)
|
||||
{
|
||||
await ReplyErrorLocalizedAsync("invalid_second_param_between", 0, 3600).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
var name = command.Name.ToLowerInvariant();
|
||||
using (var uow = _db.GetDbContext())
|
||||
{
|
||||
var config = uow.GuildConfigs.ForId(channel.Guild.Id, set => set.Include(gc => gc.CommandCooldowns));
|
||||
var localSet = CommandCooldowns.GetOrAdd(channel.Guild.Id, new ConcurrentHashSet<CommandCooldown>());
|
||||
|
||||
var toDelete = config.CommandCooldowns.FirstOrDefault(cc => cc.CommandName == name);
|
||||
if (toDelete != null)
|
||||
uow._context.Set<CommandCooldown>().Remove(toDelete);
|
||||
localSet.RemoveWhere(cc => cc.CommandName == name);
|
||||
if (secs != 0)
|
||||
{
|
||||
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>());
|
||||
activeCds.RemoveWhere(ac => ac.Command == name);
|
||||
await ReplyConfirmLocalizedAsync("cmdcd_cleared",
|
||||
Format.Bold(name)).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await ReplyConfirmLocalizedAsync("cmdcd_add",
|
||||
Format.Bold(name),
|
||||
Format.Bold(secs.ToString())).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
[NadekoCommand, Usage, Description, Aliases]
|
||||
[RequireContext(ContextType.Guild)]
|
||||
public async Task AllCmdCooldowns()
|
||||
{
|
||||
var channel = (ITextChannel)ctx.Channel;
|
||||
var localSet = CommandCooldowns.GetOrAdd(channel.Guild.Id, new ConcurrentHashSet<CommandCooldown>());
|
||||
|
||||
if (!localSet.Any())
|
||||
await ReplyConfirmLocalizedAsync("cmdcd_none").ConfigureAwait(false);
|
||||
else
|
||||
await channel.SendTableAsync("", localSet.Select(c => c.CommandName + ": " + c.Seconds + GetText("sec")), s => $"{s,-30}", 2).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
18
src/NadekoBot/Modules/Permissions/Common/PermissionCache.cs
Normal file
18
src/NadekoBot/Modules/Permissions/Common/PermissionCache.cs
Normal file
@@ -0,0 +1,18 @@
|
||||
using NadekoBot.Core.Services.Database.Models;
|
||||
|
||||
namespace NadekoBot.Modules.Permissions.Common
|
||||
{
|
||||
public class OldPermissionCache
|
||||
{
|
||||
public string PermRole { get; set; }
|
||||
public bool Verbose { get; set; } = true;
|
||||
public Permission RootPermission { get; set; }
|
||||
}
|
||||
|
||||
public class PermissionCache
|
||||
{
|
||||
public string PermRole { get; set; }
|
||||
public bool Verbose { get; set; } = true;
|
||||
public PermissionsCollection<Permissionv2> Permissions { get; set; }
|
||||
}
|
||||
}
|
131
src/NadekoBot/Modules/Permissions/Common/PermissionExtensions.cs
Normal file
131
src/NadekoBot/Modules/Permissions/Common/PermissionExtensions.cs
Normal file
@@ -0,0 +1,131 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Discord;
|
||||
using Discord.WebSocket;
|
||||
using NadekoBot.Core.Services.Database.Models;
|
||||
|
||||
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)
|
||||
{
|
||||
var perms = permsEnumerable as List<Permissionv2> ?? permsEnumerable.ToList();
|
||||
|
||||
for (int i = perms.Count - 1; i >= 0; i--)
|
||||
{
|
||||
var perm = perms[i];
|
||||
|
||||
var result = perm.CheckPermission(message, commandName, moduleName);
|
||||
|
||||
if (result == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
permIndex = i;
|
||||
return result.Value;
|
||||
}
|
||||
permIndex = -1; //defaut behaviour
|
||||
return true;
|
||||
}
|
||||
|
||||
//null = not applicable
|
||||
//true = applicable, allowed
|
||||
//false = applicable, not allowed
|
||||
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))
|
||||
return null;
|
||||
|
||||
var guildUser = message.Author as IGuildUser;
|
||||
|
||||
switch (perm.PrimaryTarget)
|
||||
{
|
||||
case PrimaryPermissionType.User:
|
||||
if (perm.PrimaryTargetId == message.Author.Id)
|
||||
return perm.State;
|
||||
break;
|
||||
case PrimaryPermissionType.Channel:
|
||||
if (perm.PrimaryTargetId == message.Channel.Id)
|
||||
return perm.State;
|
||||
break;
|
||||
case PrimaryPermissionType.Role:
|
||||
if (guildUser == null)
|
||||
break;
|
||||
if (guildUser.RoleIds.Contains(perm.PrimaryTargetId))
|
||||
return perm.State;
|
||||
break;
|
||||
case PrimaryPermissionType.Server:
|
||||
if (guildUser == null)
|
||||
break;
|
||||
return perm.State;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static string GetCommand(this Permissionv2 perm, string prefix, SocketGuild guild = null)
|
||||
{
|
||||
var com = "";
|
||||
switch (perm.PrimaryTarget)
|
||||
{
|
||||
case PrimaryPermissionType.User:
|
||||
com += "u";
|
||||
break;
|
||||
case PrimaryPermissionType.Channel:
|
||||
com += "c";
|
||||
break;
|
||||
case PrimaryPermissionType.Role:
|
||||
com += "r";
|
||||
break;
|
||||
case PrimaryPermissionType.Server:
|
||||
com += "s";
|
||||
break;
|
||||
}
|
||||
|
||||
switch (perm.SecondaryTarget)
|
||||
{
|
||||
case SecondaryPermissionType.Module:
|
||||
com += "m";
|
||||
break;
|
||||
case SecondaryPermissionType.Command:
|
||||
com += "c";
|
||||
break;
|
||||
case SecondaryPermissionType.AllModules:
|
||||
com = "a" + com + "m";
|
||||
break;
|
||||
}
|
||||
|
||||
var secName = perm.SecondaryTarget == SecondaryPermissionType.Command && !perm.IsCustomCommand ?
|
||||
prefix + perm.SecondaryTargetName : perm.SecondaryTargetName;
|
||||
com += " " + (perm.SecondaryTargetName != "*" ? secName + " " : "") + (perm.State ? "enable" : "disable") + " ";
|
||||
|
||||
switch (perm.PrimaryTarget)
|
||||
{
|
||||
case PrimaryPermissionType.User:
|
||||
com += guild?.GetUser(perm.PrimaryTargetId)?.ToString() ?? $"<@{perm.PrimaryTargetId}>";
|
||||
break;
|
||||
case PrimaryPermissionType.Channel:
|
||||
com += $"<#{perm.PrimaryTargetId}>";
|
||||
break;
|
||||
case PrimaryPermissionType.Role:
|
||||
com += guild?.GetRole(perm.PrimaryTargetId)?.ToString() ?? $"<@&{perm.PrimaryTargetId}>";
|
||||
break;
|
||||
case PrimaryPermissionType.Server:
|
||||
break;
|
||||
}
|
||||
|
||||
return prefix + com;
|
||||
}
|
||||
|
||||
public static IEnumerable<Permission> AsEnumerable(this Permission perm)
|
||||
{
|
||||
do yield return perm;
|
||||
while ((perm = perm.Next) != null);
|
||||
}
|
||||
}
|
||||
}
|
@@ -0,0 +1,74 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using NadekoBot.Common.Collections;
|
||||
using NadekoBot.Core.Services.Database.Models;
|
||||
|
||||
namespace NadekoBot.Modules.Permissions.Common
|
||||
{
|
||||
public class PermissionsCollection<T> : IndexedCollection<T> where T : class, IIndexed
|
||||
{
|
||||
private readonly object _localLocker = new object();
|
||||
public PermissionsCollection(IEnumerable<T> source) : base(source)
|
||||
{
|
||||
}
|
||||
|
||||
public static implicit operator List<T>(PermissionsCollection<T> x) =>
|
||||
x.Source;
|
||||
|
||||
public override void Clear()
|
||||
{
|
||||
lock (_localLocker)
|
||||
{
|
||||
var first = Source[0];
|
||||
base.Clear();
|
||||
Source[0] = first;
|
||||
}
|
||||
}
|
||||
|
||||
public override bool Remove(T item)
|
||||
{
|
||||
bool removed;
|
||||
lock (_localLocker)
|
||||
{
|
||||
if(Source.IndexOf(item) == 0)
|
||||
throw new ArgumentException("You can't remove first permsission (allow all)");
|
||||
removed = base.Remove(item);
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
|
||||
public override void Insert(int index, T item)
|
||||
{
|
||||
lock (_localLocker)
|
||||
{
|
||||
if(index == 0) // can't insert on first place. Last item is always allow all.
|
||||
throw new IndexOutOfRangeException(nameof(index));
|
||||
base.Insert(index, item);
|
||||
}
|
||||
}
|
||||
|
||||
public override void RemoveAt(int index)
|
||||
{
|
||||
lock (_localLocker)
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
296
src/NadekoBot/Modules/Permissions/FilterCommands.cs
Normal file
296
src/NadekoBot/Modules/Permissions/FilterCommands.cs
Normal file
@@ -0,0 +1,296 @@
|
||||
using Discord;
|
||||
using Discord.Commands;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using NadekoBot.Extensions;
|
||||
using NadekoBot.Core.Services;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using NadekoBot.Common.Attributes;
|
||||
using NadekoBot.Common.Collections;
|
||||
using NadekoBot.Modules.Permissions.Services;
|
||||
using NadekoBot.Core.Services.Database.Models;
|
||||
|
||||
namespace NadekoBot.Modules.Permissions
|
||||
{
|
||||
public partial class Permissions
|
||||
{
|
||||
[Group]
|
||||
public class FilterCommands : NadekoSubmodule<FilterService>
|
||||
{
|
||||
private readonly DbService _db;
|
||||
|
||||
public FilterCommands(DbService db)
|
||||
{
|
||||
_db = db;
|
||||
}
|
||||
|
||||
[NadekoCommand, Usage, Description, Aliases]
|
||||
[RequireContext(ContextType.Guild)]
|
||||
[UserPerm(GuildPerm.Administrator)]
|
||||
public async Task FwClear()
|
||||
{
|
||||
_service.ClearFilteredWords(ctx.Guild.Id);
|
||||
await ReplyConfirmLocalizedAsync("fw_cleared").ConfigureAwait(false);
|
||||
}
|
||||
|
||||
[NadekoCommand, Usage, Description, Aliases]
|
||||
[RequireContext(ContextType.Guild)]
|
||||
public async Task SrvrFilterInv()
|
||||
{
|
||||
var channel = (ITextChannel)ctx.Channel;
|
||||
|
||||
bool enabled;
|
||||
using (var uow = _db.GetDbContext())
|
||||
{
|
||||
var config = uow.GuildConfigs.ForId(channel.Guild.Id, set => set);
|
||||
enabled = config.FilterInvites = !config.FilterInvites;
|
||||
await uow.SaveChangesAsync();
|
||||
}
|
||||
|
||||
if (enabled)
|
||||
{
|
||||
_service.InviteFilteringServers.Add(channel.Guild.Id);
|
||||
await ReplyConfirmLocalizedAsync("invite_filter_server_on").ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
_service.InviteFilteringServers.TryRemove(channel.Guild.Id);
|
||||
await ReplyConfirmLocalizedAsync("invite_filter_server_off").ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
[NadekoCommand, Usage, Description, Aliases]
|
||||
[RequireContext(ContextType.Guild)]
|
||||
public async Task ChnlFilterInv()
|
||||
{
|
||||
var channel = (ITextChannel)ctx.Channel;
|
||||
|
||||
FilterChannelId removed;
|
||||
using (var uow = _db.GetDbContext())
|
||||
{
|
||||
var config = uow.GuildConfigs.ForId(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 == null)
|
||||
{
|
||||
config.FilterInvitesChannelIds.Add(match);
|
||||
}
|
||||
else
|
||||
{
|
||||
uow._context.Remove(removed);
|
||||
}
|
||||
await uow.SaveChangesAsync();
|
||||
}
|
||||
|
||||
if (removed == null)
|
||||
{
|
||||
_service.InviteFilteringChannels.Add(channel.Id);
|
||||
await ReplyConfirmLocalizedAsync("invite_filter_channel_on").ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
_service.InviteFilteringChannels.TryRemove(channel.Id);
|
||||
await ReplyConfirmLocalizedAsync("invite_filter_channel_off").ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
[NadekoCommand, Usage, Description, Aliases]
|
||||
[RequireContext(ContextType.Guild)]
|
||||
public async Task SrvrFilterLin()
|
||||
{
|
||||
var channel = (ITextChannel)ctx.Channel;
|
||||
|
||||
bool enabled;
|
||||
using (var uow = _db.GetDbContext())
|
||||
{
|
||||
var config = uow.GuildConfigs.ForId(channel.Guild.Id, set => set);
|
||||
enabled = config.FilterLinks = !config.FilterLinks;
|
||||
await uow.SaveChangesAsync();
|
||||
}
|
||||
|
||||
if (enabled)
|
||||
{
|
||||
_service.LinkFilteringServers.Add(channel.Guild.Id);
|
||||
await ReplyConfirmLocalizedAsync("link_filter_server_on").ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
_service.LinkFilteringServers.TryRemove(channel.Guild.Id);
|
||||
await ReplyConfirmLocalizedAsync("link_filter_server_off").ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
[NadekoCommand, Usage, Description, Aliases]
|
||||
[RequireContext(ContextType.Guild)]
|
||||
public async Task ChnlFilterLin()
|
||||
{
|
||||
var channel = (ITextChannel)ctx.Channel;
|
||||
|
||||
FilterLinksChannelId removed;
|
||||
using (var uow = _db.GetDbContext())
|
||||
{
|
||||
var config = uow.GuildConfigs.ForId(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 == null)
|
||||
{
|
||||
config.FilterLinksChannelIds.Add(match);
|
||||
}
|
||||
else
|
||||
{
|
||||
uow._context.Remove(removed);
|
||||
}
|
||||
await uow.SaveChangesAsync();
|
||||
}
|
||||
|
||||
if (removed == null)
|
||||
{
|
||||
_service.LinkFilteringChannels.Add(channel.Id);
|
||||
await ReplyConfirmLocalizedAsync("link_filter_channel_on").ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
_service.LinkFilteringChannels.TryRemove(channel.Id);
|
||||
await ReplyConfirmLocalizedAsync("link_filter_channel_off").ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
[NadekoCommand, Usage, Description, Aliases]
|
||||
[RequireContext(ContextType.Guild)]
|
||||
public async Task SrvrFilterWords()
|
||||
{
|
||||
var channel = (ITextChannel)ctx.Channel;
|
||||
|
||||
bool enabled;
|
||||
using (var uow = _db.GetDbContext())
|
||||
{
|
||||
var config = uow.GuildConfigs.ForId(channel.Guild.Id, set => set);
|
||||
enabled = config.FilterWords = !config.FilterWords;
|
||||
await uow.SaveChangesAsync();
|
||||
}
|
||||
|
||||
if (enabled)
|
||||
{
|
||||
_service.WordFilteringServers.Add(channel.Guild.Id);
|
||||
await ReplyConfirmLocalizedAsync("word_filter_server_on").ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
_service.WordFilteringServers.TryRemove(channel.Guild.Id);
|
||||
await ReplyConfirmLocalizedAsync("word_filter_server_off").ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
[NadekoCommand, Usage, Description, Aliases]
|
||||
[RequireContext(ContextType.Guild)]
|
||||
public async Task ChnlFilterWords()
|
||||
{
|
||||
var channel = (ITextChannel)ctx.Channel;
|
||||
|
||||
FilterChannelId removed;
|
||||
using (var uow = _db.GetDbContext())
|
||||
{
|
||||
var config = uow.GuildConfigs.ForId(channel.Guild.Id, set => set.Include(gc => gc.FilterWordsChannelIds));
|
||||
|
||||
var match = new FilterChannelId()
|
||||
{
|
||||
ChannelId = channel.Id
|
||||
};
|
||||
removed = config.FilterWordsChannelIds.FirstOrDefault(fc => fc.Equals(match));
|
||||
if (removed == null)
|
||||
{
|
||||
config.FilterWordsChannelIds.Add(match);
|
||||
}
|
||||
else
|
||||
{
|
||||
uow._context.Remove(removed);
|
||||
}
|
||||
await uow.SaveChangesAsync();
|
||||
}
|
||||
|
||||
if (removed == null)
|
||||
{
|
||||
_service.WordFilteringChannels.Add(channel.Id);
|
||||
await ReplyConfirmLocalizedAsync("word_filter_channel_on").ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
_service.WordFilteringChannels.TryRemove(channel.Id);
|
||||
await ReplyConfirmLocalizedAsync("word_filter_channel_off").ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
[NadekoCommand, Usage, Description, Aliases]
|
||||
[RequireContext(ContextType.Guild)]
|
||||
public async Task FilterWord([Leftover] string word)
|
||||
{
|
||||
var channel = (ITextChannel)ctx.Channel;
|
||||
|
||||
word = word?.Trim().ToLowerInvariant();
|
||||
|
||||
if (string.IsNullOrWhiteSpace(word))
|
||||
return;
|
||||
|
||||
FilteredWord removed;
|
||||
using (var uow = _db.GetDbContext())
|
||||
{
|
||||
var config = uow.GuildConfigs.ForId(channel.Guild.Id, set => set.Include(gc => gc.FilteredWords));
|
||||
|
||||
removed = config.FilteredWords.FirstOrDefault(fw => fw.Word.Trim().ToLowerInvariant() == word);
|
||||
|
||||
if (removed == null)
|
||||
config.FilteredWords.Add(new FilteredWord() { Word = word });
|
||||
else
|
||||
{
|
||||
uow._context.Remove(removed);
|
||||
}
|
||||
|
||||
await uow.SaveChangesAsync();
|
||||
}
|
||||
|
||||
var filteredWords = _service.ServerFilteredWords.GetOrAdd(channel.Guild.Id, new ConcurrentHashSet<string>());
|
||||
|
||||
if (removed == null)
|
||||
{
|
||||
filteredWords.Add(word);
|
||||
await ReplyConfirmLocalizedAsync("filter_word_add", Format.Code(word)).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
filteredWords.TryRemove(word);
|
||||
await ReplyConfirmLocalizedAsync("filter_word_remove", Format.Code(word)).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
[NadekoCommand, Usage, Description, Aliases]
|
||||
[RequireContext(ContextType.Guild)]
|
||||
public async Task LstFilterWords(int page = 1)
|
||||
{
|
||||
page--;
|
||||
if (page < 0)
|
||||
return;
|
||||
|
||||
var channel = (ITextChannel)ctx.Channel;
|
||||
|
||||
_service.ServerFilteredWords.TryGetValue(channel.Guild.Id, out var fwHash);
|
||||
|
||||
var fws = fwHash.ToArray();
|
||||
|
||||
await ctx.SendPaginatedConfirmAsync(page,
|
||||
(curPage) => new EmbedBuilder()
|
||||
.WithTitle(GetText("filter_word_list"))
|
||||
.WithDescription(string.Join("\n", fws.Skip(curPage * 10).Take(10)))
|
||||
.WithOkColor()
|
||||
, fws.Length, 10).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@@ -0,0 +1,90 @@
|
||||
using Discord;
|
||||
using Discord.Commands;
|
||||
using NadekoBot.Common.Attributes;
|
||||
using NadekoBot.Common.TypeReaders;
|
||||
using NadekoBot.Core.Services;
|
||||
using NadekoBot.Extensions;
|
||||
using NadekoBot.Modules.Permissions.Services;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace NadekoBot.Modules.Permissions
|
||||
{
|
||||
public partial class Permissions
|
||||
{
|
||||
[Group]
|
||||
public class GlobalPermissionCommands : NadekoSubmodule
|
||||
{
|
||||
private GlobalPermissionService _service;
|
||||
private readonly DbService _db;
|
||||
|
||||
public GlobalPermissionCommands(GlobalPermissionService service, DbService db)
|
||||
{
|
||||
_service = service;
|
||||
_db = db;
|
||||
}
|
||||
|
||||
[NadekoCommand, Usage, Description, Aliases]
|
||||
[OwnerOnly]
|
||||
public async Task GlobalPermList()
|
||||
{
|
||||
var blockedModule = _service.BlockedModules;
|
||||
var blockedCommands = _service.BlockedCommands;
|
||||
if (!blockedModule.Any() && !blockedCommands.Any())
|
||||
{
|
||||
await ReplyErrorLocalizedAsync("lgp_none").ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
var embed = new EmbedBuilder().WithOkColor();
|
||||
|
||||
if (blockedModule.Any())
|
||||
embed.AddField(efb => efb
|
||||
.WithName(GetText("blocked_modules"))
|
||||
.WithValue(string.Join("\n", _service.BlockedModules))
|
||||
.WithIsInline(false));
|
||||
|
||||
if (blockedCommands.Any())
|
||||
embed.AddField(efb => efb
|
||||
.WithName(GetText("blocked_commands"))
|
||||
.WithValue(string.Join("\n", _service.BlockedCommands))
|
||||
.WithIsInline(false));
|
||||
|
||||
await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
[NadekoCommand, Usage, Description, Aliases]
|
||||
[OwnerOnly]
|
||||
public async Task GlobalModule(ModuleOrCrInfo module)
|
||||
{
|
||||
var moduleName = module.Name.ToLowerInvariant();
|
||||
|
||||
var added = _service.ToggleModule(moduleName);
|
||||
|
||||
if (added)
|
||||
{
|
||||
await ReplyConfirmLocalizedAsync("gmod_add", Format.Bold(module.Name)).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
await ReplyConfirmLocalizedAsync("gmod_remove", Format.Bold(module.Name)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
[NadekoCommand, Usage, Description, Aliases]
|
||||
[OwnerOnly]
|
||||
public async Task GlobalCommand(CommandOrCrInfo cmd)
|
||||
{
|
||||
var commandName = cmd.Name.ToLowerInvariant();
|
||||
var added = _service.ToggleCommand(commandName);
|
||||
|
||||
if (added)
|
||||
{
|
||||
await ReplyConfirmLocalizedAsync("gcmd_add", Format.Bold(cmd.Name)).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
await ReplyConfirmLocalizedAsync("gcmd_remove", Format.Bold(cmd.Name)).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
572
src/NadekoBot/Modules/Permissions/Permissions.cs
Normal file
572
src/NadekoBot/Modules/Permissions/Permissions.cs
Normal file
@@ -0,0 +1,572 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Discord.Commands;
|
||||
using NadekoBot.Core.Services;
|
||||
using Discord;
|
||||
using NadekoBot.Core.Services.Database.Models;
|
||||
using System.Collections.Generic;
|
||||
using Discord.WebSocket;
|
||||
using NadekoBot.Common.Attributes;
|
||||
using NadekoBot.Common.TypeReaders;
|
||||
using NadekoBot.Common.TypeReaders.Models;
|
||||
using NadekoBot.Modules.Permissions.Common;
|
||||
using NadekoBot.Modules.Permissions.Services;
|
||||
|
||||
namespace NadekoBot.Modules.Permissions
|
||||
{
|
||||
public partial class Permissions : NadekoModule<PermissionService>
|
||||
{
|
||||
private readonly DbService _db;
|
||||
|
||||
public Permissions(DbService db)
|
||||
{
|
||||
_db = db;
|
||||
}
|
||||
|
||||
[NadekoCommand, Usage, Description, Aliases]
|
||||
[RequireContext(ContextType.Guild)]
|
||||
public async Task Verbose(PermissionAction action = null)
|
||||
{
|
||||
using (var uow = _db.GetDbContext())
|
||||
{
|
||||
var config = uow.GuildConfigs.GcWithPermissionsv2For(ctx.Guild.Id);
|
||||
if (action == null) action = new PermissionAction(!config.VerbosePermissions); // New behaviour, can toggle.
|
||||
config.VerbosePermissions = action.Value;
|
||||
await uow.SaveChangesAsync();
|
||||
_service.UpdateCache(config);
|
||||
}
|
||||
if (action.Value)
|
||||
{
|
||||
await ReplyConfirmLocalizedAsync("verbose_true").ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await ReplyConfirmLocalizedAsync("verbose_false").ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
[NadekoCommand, Usage, Description, Aliases]
|
||||
[RequireContext(ContextType.Guild)]
|
||||
[UserPerm(GuildPerm.Administrator)]
|
||||
[Priority(0)]
|
||||
public async Task PermRole([Leftover] IRole role = null)
|
||||
{
|
||||
if (role != null && role == role.Guild.EveryoneRole)
|
||||
return;
|
||||
|
||||
if (role == null)
|
||||
{
|
||||
var cache = _service.GetCacheFor(ctx.Guild.Id);
|
||||
if (!ulong.TryParse(cache.PermRole, out var roleId) ||
|
||||
(role = ((SocketGuild)ctx.Guild).GetRole(roleId)) == null)
|
||||
{
|
||||
await ReplyConfirmLocalizedAsync("permrole_not_set", Format.Bold(cache.PermRole)).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await ReplyConfirmLocalizedAsync("permrole", Format.Bold(role.ToString())).ConfigureAwait(false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
using (var uow = _db.GetDbContext())
|
||||
{
|
||||
var config = uow.GuildConfigs.GcWithPermissionsv2For(ctx.Guild.Id);
|
||||
config.PermissionRole = role.Id.ToString();
|
||||
uow.SaveChanges();
|
||||
_service.UpdateCache(config);
|
||||
}
|
||||
|
||||
await ReplyConfirmLocalizedAsync("permrole_changed", Format.Bold(role.Name)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public enum Reset { Reset };
|
||||
|
||||
[NadekoCommand, Usage, Description, Aliases]
|
||||
[RequireContext(ContextType.Guild)]
|
||||
[UserPerm(GuildPerm.Administrator)]
|
||||
[Priority(1)]
|
||||
public async Task PermRole(Reset _)
|
||||
{
|
||||
using (var uow = _db.GetDbContext())
|
||||
{
|
||||
var config = uow.GuildConfigs.GcWithPermissionsv2For(ctx.Guild.Id);
|
||||
config.PermissionRole = null;
|
||||
await uow.SaveChangesAsync();
|
||||
_service.UpdateCache(config);
|
||||
}
|
||||
|
||||
await ReplyConfirmLocalizedAsync("permrole_reset").ConfigureAwait(false);
|
||||
}
|
||||
|
||||
[NadekoCommand, Usage, Description, Aliases]
|
||||
[RequireContext(ContextType.Guild)]
|
||||
public async Task ListPerms(int page = 1)
|
||||
{
|
||||
if (page < 1)
|
||||
return;
|
||||
|
||||
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("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("uneditable")}]";
|
||||
return str;
|
||||
}));
|
||||
|
||||
await ctx.Channel.SendMessageAsync(toSend).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
[NadekoCommand, Usage, Description, Aliases]
|
||||
[RequireContext(ContextType.Guild)]
|
||||
public async Task RemovePerm(int index)
|
||||
{
|
||||
index -= 1;
|
||||
if (index < 0)
|
||||
return;
|
||||
try
|
||||
{
|
||||
Permissionv2 p;
|
||||
using (var uow = _db.GetDbContext())
|
||||
{
|
||||
var config = uow.GuildConfigs.GcWithPermissionsv2For(ctx.Guild.Id);
|
||||
var permsCol = new PermissionsCollection<Permissionv2>(config.Permissions);
|
||||
p = permsCol[index];
|
||||
permsCol.RemoveAt(index);
|
||||
uow._context.Remove(p);
|
||||
await uow.SaveChangesAsync();
|
||||
_service.UpdateCache(config);
|
||||
}
|
||||
await ReplyConfirmLocalizedAsync("removed",
|
||||
index + 1,
|
||||
Format.Code(p.GetCommand(Prefix, (SocketGuild)ctx.Guild))).ConfigureAwait(false);
|
||||
}
|
||||
catch (IndexOutOfRangeException)
|
||||
{
|
||||
await ReplyErrorLocalizedAsync("perm_out_of_range").ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
[NadekoCommand, Usage, Description, 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;
|
||||
using (var uow = _db.GetDbContext())
|
||||
{
|
||||
var config = uow.GuildConfigs.GcWithPermissionsv2For(ctx.Guild.Id);
|
||||
var permsCol = new PermissionsCollection<Permissionv2>(config.Permissions);
|
||||
|
||||
var fromFound = from < permsCol.Count;
|
||||
var toFound = to < permsCol.Count;
|
||||
|
||||
if (!fromFound)
|
||||
{
|
||||
await ReplyErrorLocalizedAsync("not_found", ++from);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!toFound)
|
||||
{
|
||||
await ReplyErrorLocalizedAsync("not_found", ++to);
|
||||
return;
|
||||
}
|
||||
fromPerm = permsCol[from];
|
||||
|
||||
permsCol.RemoveAt(from);
|
||||
permsCol.Insert(to, fromPerm);
|
||||
await uow.SaveChangesAsync();
|
||||
_service.UpdateCache(config);
|
||||
}
|
||||
await ReplyConfirmLocalizedAsync("moved_permission",
|
||||
Format.Code(fromPerm.GetCommand(Prefix, (SocketGuild)ctx.Guild)),
|
||||
++from,
|
||||
++to)
|
||||
.ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
catch (Exception e) when (e is ArgumentOutOfRangeException || e is IndexOutOfRangeException)
|
||||
{
|
||||
}
|
||||
}
|
||||
await ReplyErrorLocalizedAsync("perm_out_of_range").ConfigureAwait(false);
|
||||
}
|
||||
|
||||
[NadekoCommand, Usage, Description, 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,
|
||||
}).ConfigureAwait(false);
|
||||
|
||||
if (action.Value)
|
||||
{
|
||||
await ReplyConfirmLocalizedAsync("sx_enable",
|
||||
Format.Code(command.Name),
|
||||
GetText("of_command")).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await ReplyConfirmLocalizedAsync("sx_disable",
|
||||
Format.Code(command.Name),
|
||||
GetText("of_command")).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
[NadekoCommand, Usage, Description, 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,
|
||||
}).ConfigureAwait(false);
|
||||
|
||||
if (action.Value)
|
||||
{
|
||||
await ReplyConfirmLocalizedAsync("sx_enable",
|
||||
Format.Code(module.Name),
|
||||
GetText("of_module")).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await ReplyConfirmLocalizedAsync("sx_disable",
|
||||
Format.Code(module.Name),
|
||||
GetText("of_module")).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
[NadekoCommand, Usage, Description, 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,
|
||||
}).ConfigureAwait(false);
|
||||
|
||||
if (action.Value)
|
||||
{
|
||||
await ReplyConfirmLocalizedAsync("ux_enable",
|
||||
Format.Code(command.Name),
|
||||
GetText("of_command"),
|
||||
Format.Code(user.ToString())).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await ReplyConfirmLocalizedAsync("ux_disable",
|
||||
Format.Code(command.Name),
|
||||
GetText("of_command"),
|
||||
Format.Code(user.ToString())).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
[NadekoCommand, Usage, Description, 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,
|
||||
}).ConfigureAwait(false);
|
||||
|
||||
if (action.Value)
|
||||
{
|
||||
await ReplyConfirmLocalizedAsync("ux_enable",
|
||||
Format.Code(module.Name),
|
||||
GetText("of_module"),
|
||||
Format.Code(user.ToString())).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await ReplyConfirmLocalizedAsync("ux_disable",
|
||||
Format.Code(module.Name),
|
||||
GetText("of_module"),
|
||||
Format.Code(user.ToString())).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
[NadekoCommand, Usage, Description, 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,
|
||||
}).ConfigureAwait(false);
|
||||
|
||||
if (action.Value)
|
||||
{
|
||||
await ReplyConfirmLocalizedAsync("rx_enable",
|
||||
Format.Code(command.Name),
|
||||
GetText("of_command"),
|
||||
Format.Code(role.Name)).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await ReplyConfirmLocalizedAsync("rx_disable",
|
||||
Format.Code(command.Name),
|
||||
GetText("of_command"),
|
||||
Format.Code(role.Name)).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
[NadekoCommand, Usage, Description, 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,
|
||||
}).ConfigureAwait(false);
|
||||
|
||||
|
||||
if (action.Value)
|
||||
{
|
||||
await ReplyConfirmLocalizedAsync("rx_enable",
|
||||
Format.Code(module.Name),
|
||||
GetText("of_module"),
|
||||
Format.Code(role.Name)).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await ReplyConfirmLocalizedAsync("rx_disable",
|
||||
Format.Code(module.Name),
|
||||
GetText("of_module"),
|
||||
Format.Code(role.Name)).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
[NadekoCommand, Usage, Description, 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,
|
||||
}).ConfigureAwait(false);
|
||||
|
||||
if (action.Value)
|
||||
{
|
||||
await ReplyConfirmLocalizedAsync("cx_enable",
|
||||
Format.Code(command.Name),
|
||||
GetText("of_command"),
|
||||
Format.Code(chnl.Name)).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await ReplyConfirmLocalizedAsync("cx_disable",
|
||||
Format.Code(command.Name),
|
||||
GetText("of_command"),
|
||||
Format.Code(chnl.Name)).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
[NadekoCommand, Usage, Description, 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,
|
||||
}).ConfigureAwait(false);
|
||||
|
||||
if (action.Value)
|
||||
{
|
||||
await ReplyConfirmLocalizedAsync("cx_enable",
|
||||
Format.Code(module.Name),
|
||||
GetText("of_module"),
|
||||
Format.Code(chnl.Name)).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await ReplyConfirmLocalizedAsync("cx_disable",
|
||||
Format.Code(module.Name),
|
||||
GetText("of_module"),
|
||||
Format.Code(chnl.Name)).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
[NadekoCommand, Usage, Description, 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,
|
||||
}).ConfigureAwait(false);
|
||||
|
||||
if (action.Value)
|
||||
{
|
||||
await ReplyConfirmLocalizedAsync("acm_enable",
|
||||
Format.Code(chnl.Name)).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await ReplyConfirmLocalizedAsync("acm_disable",
|
||||
Format.Code(chnl.Name)).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
[NadekoCommand, Usage, Description, 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,
|
||||
}).ConfigureAwait(false);
|
||||
|
||||
if (action.Value)
|
||||
{
|
||||
await ReplyConfirmLocalizedAsync("arm_enable",
|
||||
Format.Code(role.Name)).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await ReplyConfirmLocalizedAsync("arm_disable",
|
||||
Format.Code(role.Name)).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
[NadekoCommand, Usage, Description, 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,
|
||||
}).ConfigureAwait(false);
|
||||
|
||||
if (action.Value)
|
||||
{
|
||||
await ReplyConfirmLocalizedAsync("aum_enable",
|
||||
Format.Code(user.ToString())).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await ReplyConfirmLocalizedAsync("aum_disable",
|
||||
Format.Code(user.ToString())).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
[NadekoCommand, Usage, Description, Aliases]
|
||||
[RequireContext(ContextType.Guild)]
|
||||
public async Task AllSrvrMdls(PermissionAction action)
|
||||
{
|
||||
var newPerm = new Permissionv2
|
||||
{
|
||||
PrimaryTarget = PrimaryPermissionType.Server,
|
||||
PrimaryTargetId = 0,
|
||||
SecondaryTarget = SecondaryPermissionType.AllModules,
|
||||
SecondaryTargetName = "*",
|
||||
State = action.Value,
|
||||
};
|
||||
|
||||
var allowUser = new Permissionv2
|
||||
{
|
||||
PrimaryTarget = PrimaryPermissionType.User,
|
||||
PrimaryTargetId = ctx.User.Id,
|
||||
SecondaryTarget = SecondaryPermissionType.AllModules,
|
||||
SecondaryTargetName = "*",
|
||||
State = true,
|
||||
};
|
||||
|
||||
await _service.AddPermissions(ctx.Guild.Id,
|
||||
newPerm,
|
||||
allowUser).ConfigureAwait(false);
|
||||
|
||||
if (action.Value)
|
||||
{
|
||||
await ReplyConfirmLocalizedAsync("asm_enable").ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await ReplyConfirmLocalizedAsync("asm_disable").ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@@ -0,0 +1,41 @@
|
||||
using Discord;
|
||||
using Discord.Commands;
|
||||
using System.Threading.Tasks;
|
||||
using NadekoBot.Common.Attributes;
|
||||
using NadekoBot.Modules.Permissions.Services;
|
||||
|
||||
namespace NadekoBot.Modules.Permissions
|
||||
{
|
||||
public partial class Permissions
|
||||
{
|
||||
[Group]
|
||||
public class ResetPermissionsCommands : NadekoSubmodule
|
||||
{
|
||||
private readonly GlobalPermissionService _gps;
|
||||
private readonly PermissionService _perms;
|
||||
|
||||
public ResetPermissionsCommands(GlobalPermissionService gps, PermissionService perms)
|
||||
{
|
||||
_gps = gps;
|
||||
_perms = perms;
|
||||
}
|
||||
|
||||
[NadekoCommand, Usage, Description, Aliases]
|
||||
[RequireContext(ContextType.Guild)]
|
||||
[UserPerm(GuildPerm.Administrator)]
|
||||
public async Task ResetPerms()
|
||||
{
|
||||
await _perms.Reset(ctx.Guild.Id).ConfigureAwait(false);
|
||||
await ReplyConfirmLocalizedAsync("perms_reset").ConfigureAwait(false);
|
||||
}
|
||||
|
||||
[NadekoCommand, Usage, Description, Aliases]
|
||||
[OwnerOnly]
|
||||
public async Task ResetGlobalPerms()
|
||||
{
|
||||
await _gps.Reset();
|
||||
await ReplyConfirmLocalizedAsync("global_perms_reset").ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
120
src/NadekoBot/Modules/Permissions/Services/BlacklistService.cs
Normal file
120
src/NadekoBot/Modules/Permissions/Services/BlacklistService.cs
Normal file
@@ -0,0 +1,120 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Discord;
|
||||
using Discord.WebSocket;
|
||||
using NadekoBot.Common.ModuleBehaviors;
|
||||
using NadekoBot.Core.Services;
|
||||
using NadekoBot.Core.Services.Database.Models;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using NadekoBot.Core.Common;
|
||||
|
||||
namespace NadekoBot.Modules.Permissions.Services
|
||||
{
|
||||
public sealed class BlacklistService : IEarlyBehavior, INService
|
||||
{
|
||||
private readonly DbService _db;
|
||||
private readonly IPubSub _pubSub;
|
||||
private readonly IBotCredentials _creds;
|
||||
private IReadOnlyList<BlacklistEntry> _blacklist;
|
||||
public int Priority => -100;
|
||||
|
||||
public ModuleBehaviorType BehaviorType => ModuleBehaviorType.Blocker;
|
||||
|
||||
private readonly TypedKey<BlacklistEntry[]> blPubKey = new TypedKey<BlacklistEntry[]>("blacklist.reload");
|
||||
public BlacklistService(DbService db, IPubSub pubSub, IBotCredentials creds)
|
||||
{
|
||||
_db = db;
|
||||
_pubSub = pubSub;
|
||||
_creds = creds;
|
||||
|
||||
Reload(false);
|
||||
_pubSub.Sub(blPubKey, OnReload);
|
||||
}
|
||||
|
||||
private ValueTask OnReload(BlacklistEntry[] blacklist)
|
||||
{
|
||||
_blacklist = blacklist;
|
||||
return default;
|
||||
}
|
||||
|
||||
public Task<bool> RunBehavior(DiscordSocketClient _, IGuild guild, IUserMessage usrMsg)
|
||||
{
|
||||
foreach (var bl in _blacklist)
|
||||
{
|
||||
if (guild != null && bl.Type == BlacklistType.Server && bl.ItemId == guild.Id)
|
||||
return Task.FromResult(true);
|
||||
|
||||
if (bl.Type == BlacklistType.Channel && bl.ItemId == usrMsg.Channel.Id)
|
||||
return Task.FromResult(true);
|
||||
|
||||
if (bl.Type == BlacklistType.User && bl.ItemId == usrMsg.Author.Id)
|
||||
return Task.FromResult(true);
|
||||
}
|
||||
|
||||
return Task.FromResult(false);
|
||||
}
|
||||
|
||||
public IReadOnlyList<BlacklistEntry> GetBlacklist()
|
||||
=> _blacklist;
|
||||
|
||||
public void Reload(bool publish = true)
|
||||
{
|
||||
using var uow = _db.GetDbContext();
|
||||
var toPublish = uow._context.Blacklist.AsNoTracking().ToArray();
|
||||
_blacklist = 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._context.Blacklist.Add(item);
|
||||
uow.SaveChanges();
|
||||
|
||||
Reload(true);
|
||||
}
|
||||
|
||||
public void UnBlacklist(BlacklistType type, ulong id)
|
||||
{
|
||||
using var uow = _db.GetDbContext();
|
||||
var toRemove = uow._context.Blacklist
|
||||
.FirstOrDefault(bi => bi.ItemId == id && bi.Type == type);
|
||||
|
||||
if (!(toRemove is null))
|
||||
uow._context.Blacklist.Remove(toRemove);
|
||||
|
||||
uow.SaveChanges();
|
||||
|
||||
Reload(true);
|
||||
}
|
||||
|
||||
public void BlacklistUsers(IReadOnlyCollection<ulong> toBlacklist)
|
||||
{
|
||||
using (var uow = _db.GetDbContext())
|
||||
{
|
||||
var bc = uow._context.Blacklist;
|
||||
//blacklist the users
|
||||
bc.AddRange(toBlacklist.Select(x =>
|
||||
new BlacklistEntry
|
||||
{
|
||||
ItemId = x,
|
||||
Type = BlacklistType.User,
|
||||
}));
|
||||
|
||||
//clear their currencies
|
||||
uow.DiscordUsers.RemoveFromMany(toBlacklist);
|
||||
uow.SaveChanges();
|
||||
}
|
||||
|
||||
Reload(true);
|
||||
}
|
||||
}
|
||||
}
|
81
src/NadekoBot/Modules/Permissions/Services/CmdCdService.cs
Normal file
81
src/NadekoBot/Modules/Permissions/Services/CmdCdService.cs
Normal file
@@ -0,0 +1,81 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Discord;
|
||||
using Discord.Commands;
|
||||
using Discord.WebSocket;
|
||||
using NadekoBot.Common.Collections;
|
||||
using NadekoBot.Common.ModuleBehaviors;
|
||||
using NadekoBot.Core.Services;
|
||||
using NadekoBot.Core.Services.Database.Models;
|
||||
|
||||
namespace NadekoBot.Modules.Permissions.Services
|
||||
{
|
||||
public class CmdCdService : ILateBlocker, INService
|
||||
{
|
||||
public ConcurrentDictionary<ulong, ConcurrentHashSet<CommandCooldown>> CommandCooldowns { get; }
|
||||
public ConcurrentDictionary<ulong, ConcurrentHashSet<ActiveCooldown>> ActiveCooldowns { get; } = new ConcurrentDictionary<ulong, ConcurrentHashSet<ActiveCooldown>>();
|
||||
|
||||
public int Priority { get; } = 0;
|
||||
|
||||
public CmdCdService(NadekoBot bot)
|
||||
{
|
||||
CommandCooldowns = new ConcurrentDictionary<ulong, ConcurrentHashSet<CommandCooldown>>(
|
||||
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 ActiveCooldown()
|
||||
{
|
||||
UserId = user.Id,
|
||||
Command = commandName,
|
||||
});
|
||||
|
||||
var _ = Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
await Task.Delay(cdRule.Seconds * 1000).ConfigureAwait(false);
|
||||
activeCdsForGuild.RemoveWhere(ac => ac.Command == commandName && ac.UserId == user.Id);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// ignored
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return Task.FromResult(false);
|
||||
}
|
||||
|
||||
public Task<bool> TryBlockLate(DiscordSocketClient client, ICommandContext ctx, string moduleName, CommandInfo command)
|
||||
{
|
||||
var guild = ctx.Guild;
|
||||
var user = ctx.User;
|
||||
var commandName = command.Name.ToLowerInvariant();
|
||||
|
||||
return TryBlock(guild, user, commandName);
|
||||
}
|
||||
}
|
||||
|
||||
public class ActiveCooldown
|
||||
{
|
||||
public string Command { get; set; }
|
||||
public ulong UserId { get; set; }
|
||||
}
|
||||
}
|
219
src/NadekoBot/Modules/Permissions/Services/FilterService.cs
Normal file
219
src/NadekoBot/Modules/Permissions/Services/FilterService.cs
Normal file
@@ -0,0 +1,219 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Discord;
|
||||
using Discord.Net;
|
||||
using Discord.WebSocket;
|
||||
using NadekoBot.Common.Collections;
|
||||
using NadekoBot.Common.ModuleBehaviors;
|
||||
using NadekoBot.Extensions;
|
||||
using NadekoBot.Core.Services;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Internal;
|
||||
using NadekoBot.Core.Services.Database.Models;
|
||||
using Serilog;
|
||||
|
||||
namespace NadekoBot.Modules.Permissions.Services
|
||||
{
|
||||
public class FilterService : IEarlyBehavior, INService
|
||||
{
|
||||
private readonly DbService _db;
|
||||
|
||||
public ConcurrentHashSet<ulong> InviteFilteringChannels { get; }
|
||||
public ConcurrentHashSet<ulong> InviteFilteringServers { get; }
|
||||
|
||||
//serverid, filteredwords
|
||||
public ConcurrentDictionary<ulong, ConcurrentHashSet<string>> ServerFilteredWords { get; }
|
||||
|
||||
public ConcurrentHashSet<ulong> WordFilteringChannels { get; }
|
||||
public ConcurrentHashSet<ulong> WordFilteringServers { get; }
|
||||
|
||||
public ConcurrentHashSet<ulong> LinkFilteringChannels { get; }
|
||||
public ConcurrentHashSet<ulong> LinkFilteringServers { get; }
|
||||
|
||||
public int Priority => -50;
|
||||
public ModuleBehaviorType BehaviorType => ModuleBehaviorType.Blocker;
|
||||
|
||||
public ConcurrentHashSet<string> FilteredWordsForChannel(ulong channelId, ulong guildId)
|
||||
{
|
||||
ConcurrentHashSet<string> 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.GuildConfigs.ForId(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 FilterService(DiscordSocketClient client, DbService db)
|
||||
{
|
||||
_db = db;
|
||||
|
||||
using(var uow = db.GetDbContext())
|
||||
{
|
||||
var ids = client.GetGuildIds();
|
||||
var configs = uow._context.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();
|
||||
|
||||
InviteFilteringServers = new ConcurrentHashSet<ulong>(configs.Where(gc => gc.FilterInvites).Select(gc => gc.GuildId));
|
||||
InviteFilteringChannels = new ConcurrentHashSet<ulong>(configs.SelectMany(gc => gc.FilterInvitesChannelIds.Select(fci => fci.ChannelId)));
|
||||
|
||||
LinkFilteringServers = new ConcurrentHashSet<ulong>(configs.Where(gc => gc.FilterLinks).Select(gc => gc.GuildId));
|
||||
LinkFilteringChannels = new ConcurrentHashSet<ulong>(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)));
|
||||
|
||||
ServerFilteredWords = new ConcurrentDictionary<ulong, ConcurrentHashSet<string>>(dict);
|
||||
|
||||
var serverFiltering = configs.Where(gc => gc.FilterWords);
|
||||
WordFilteringServers = new ConcurrentHashSet<ulong>(serverFiltering.Select(gc => gc.GuildId));
|
||||
WordFilteringChannels = new ConcurrentHashSet<ulong>(configs.SelectMany(gc => gc.FilterWordsChannelIds.Select(fwci => fwci.ChannelId)));
|
||||
}
|
||||
|
||||
client.MessageUpdated += (oldData, newMsg, channel) =>
|
||||
{
|
||||
var _ = Task.Run(() =>
|
||||
{
|
||||
var guild = (channel as ITextChannel)?.Guild;
|
||||
var usrMsg = newMsg as IUserMessage;
|
||||
|
||||
if (guild == null || usrMsg == null)
|
||||
return Task.CompletedTask;
|
||||
|
||||
return RunBehavior(null, guild, usrMsg);
|
||||
});
|
||||
return Task.CompletedTask;
|
||||
};
|
||||
}
|
||||
|
||||
public async Task<bool> RunBehavior(DiscordSocketClient _, IGuild guild, IUserMessage msg)
|
||||
{
|
||||
if (!(msg.Author is IGuildUser gu) || gu.GuildPermissions.Administrator)
|
||||
return false;
|
||||
|
||||
var results = await Task.WhenAll(
|
||||
FilterInvites(guild, msg),
|
||||
FilterWords(guild, msg),
|
||||
FilterLinks(guild, msg));
|
||||
|
||||
return results.Any(x => x);
|
||||
}
|
||||
|
||||
public async Task<bool> FilterWords(IGuild guild, IUserMessage usrMsg)
|
||||
{
|
||||
if (guild is null)
|
||||
return false;
|
||||
if (usrMsg is null)
|
||||
return false;
|
||||
|
||||
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))
|
||||
{
|
||||
try
|
||||
{
|
||||
await usrMsg.DeleteAsync().ConfigureAwait(false);
|
||||
}
|
||||
catch (HttpException ex)
|
||||
{
|
||||
Log.Warning("I do not have permission to filter words in channel with id " + usrMsg.Channel.Id, ex);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public async Task<bool> FilterInvites(IGuild guild, IUserMessage usrMsg)
|
||||
{
|
||||
if (guild is null)
|
||||
return false;
|
||||
if (usrMsg is null)
|
||||
return false;
|
||||
|
||||
if ((InviteFilteringChannels.Contains(usrMsg.Channel.Id)
|
||||
|| InviteFilteringServers.Contains(guild.Id))
|
||||
&& usrMsg.Content.IsDiscordInvite())
|
||||
{
|
||||
try
|
||||
{
|
||||
await usrMsg.DeleteAsync().ConfigureAwait(false);
|
||||
return true;
|
||||
}
|
||||
catch (HttpException ex)
|
||||
{
|
||||
Log.Warning("I do not have permission to filter invites in channel with id " + usrMsg.Channel.Id, ex);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public async Task<bool> FilterLinks(IGuild guild, IUserMessage usrMsg)
|
||||
{
|
||||
if (guild is null)
|
||||
return false;
|
||||
if (usrMsg is null)
|
||||
return false;
|
||||
|
||||
if ((LinkFilteringChannels.Contains(usrMsg.Channel.Id)
|
||||
|| LinkFilteringServers.Contains(guild.Id))
|
||||
&& usrMsg.Content.TryGetUrlPath(out _))
|
||||
{
|
||||
try
|
||||
{
|
||||
await usrMsg.DeleteAsync().ConfigureAwait(false);
|
||||
return true;
|
||||
}
|
||||
catch (HttpException ex)
|
||||
{
|
||||
Log.Warning("I do not have permission to filter links in channel with id " + usrMsg.Channel.Id, ex);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
@@ -0,0 +1,101 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using Discord.Commands;
|
||||
using Discord.WebSocket;
|
||||
using NadekoBot.Common.ModuleBehaviors;
|
||||
using NadekoBot.Core.Services;
|
||||
|
||||
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 GlobalPermissionService(BotConfigService bss)
|
||||
{
|
||||
_bss = bss;
|
||||
}
|
||||
|
||||
|
||||
public Task<bool> TryBlockLate(DiscordSocketClient client, ICommandContext ctx, string moduleName, CommandInfo command)
|
||||
{
|
||||
var settings = _bss.Data;
|
||||
var commandName = command.Name.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
|
||||
/// </summary>
|
||||
/// <param name="moduleName">Lowercase module name</param>
|
||||
/// <returns>Whether the module is added</returns>
|
||||
public bool ToggleModule(string moduleName)
|
||||
{
|
||||
var added = false;
|
||||
_bss.ModifyConfig(bs =>
|
||||
{
|
||||
if (bs.Blocked.Modules.Add(moduleName))
|
||||
{
|
||||
added = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
bs.Blocked.Modules.Remove(moduleName);
|
||||
added = false;
|
||||
}
|
||||
});
|
||||
|
||||
return added;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Toggles command blacklist
|
||||
/// </summary>
|
||||
/// <param name="commandName">Lowercase command name</param>
|
||||
/// <returns>Whether the command is added</returns>
|
||||
public bool ToggleCommand(string commandName)
|
||||
{
|
||||
var added = false;
|
||||
_bss.ModifyConfig(bs =>
|
||||
{
|
||||
if (bs.Blocked.Commands.Add(commandName))
|
||||
{
|
||||
added = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
bs.Blocked.Commands.Remove(commandName);
|
||||
added = false;
|
||||
}
|
||||
});
|
||||
|
||||
return added;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resets all global permissions
|
||||
/// </summary>
|
||||
public Task Reset()
|
||||
{
|
||||
_bss.ModifyConfig(bs =>
|
||||
{
|
||||
bs.Blocked.Commands.Clear();
|
||||
bs.Blocked.Modules.Clear();
|
||||
});
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
}
|
184
src/NadekoBot/Modules/Permissions/Services/PermissionsService.cs
Normal file
184
src/NadekoBot/Modules/Permissions/Services/PermissionsService.cs
Normal file
@@ -0,0 +1,184 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Discord;
|
||||
using Discord.Commands;
|
||||
using Discord.WebSocket;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using NadekoBot.Common.ModuleBehaviors;
|
||||
using NadekoBot.Extensions;
|
||||
using NadekoBot.Modules.Permissions.Common;
|
||||
using NadekoBot.Core.Services;
|
||||
using NadekoBot.Core.Services.Database.Models;
|
||||
|
||||
namespace NadekoBot.Modules.Permissions.Services
|
||||
{
|
||||
public class PermissionService : ILateBlocker, INService
|
||||
{
|
||||
public int Priority { get; } = 0;
|
||||
|
||||
private readonly DbService _db;
|
||||
private readonly CommandHandler _cmd;
|
||||
private readonly IBotStrings _strings;
|
||||
|
||||
//guildid, root permission
|
||||
public ConcurrentDictionary<ulong, PermissionCache> Cache { get; } =
|
||||
new ConcurrentDictionary<ulong, PermissionCache>();
|
||||
|
||||
public PermissionService(DiscordSocketClient client, DbService db, CommandHandler cmd, IBotStrings strings)
|
||||
{
|
||||
_db = db;
|
||||
_cmd = cmd;
|
||||
_strings = strings;
|
||||
|
||||
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 PermissionCache()
|
||||
{
|
||||
Verbose = x.VerbosePermissions,
|
||||
PermRole = x.PermissionRole,
|
||||
Permissions = new PermissionsCollection<Permissionv2>(x.Permissions)
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public PermissionCache GetCacheFor(ulong guildId)
|
||||
{
|
||||
if (!Cache.TryGetValue(guildId, out var pc))
|
||||
{
|
||||
using (var uow = _db.GetDbContext())
|
||||
{
|
||||
var config = uow.GuildConfigs.ForId(guildId,
|
||||
set => set.Include(x => x.Permissions));
|
||||
UpdateCache(config);
|
||||
}
|
||||
Cache.TryGetValue(guildId, out pc);
|
||||
if (pc == null)
|
||||
throw new Exception("Cache is null.");
|
||||
}
|
||||
return pc;
|
||||
}
|
||||
|
||||
public async Task AddPermissions(ulong guildId, params Permissionv2[] perms)
|
||||
{
|
||||
using (var uow = _db.GetDbContext())
|
||||
{
|
||||
var config = uow.GuildConfigs.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
|
||||
foreach (var perm in perms)
|
||||
{
|
||||
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 PermissionsCollection<Permissionv2>(config.Permissions),
|
||||
PermRole = config.PermissionRole,
|
||||
Verbose = config.VerbosePermissions
|
||||
}, (id, old) =>
|
||||
{
|
||||
old.Permissions = new PermissionsCollection<Permissionv2>(config.Permissions);
|
||||
old.PermRole = config.PermissionRole;
|
||||
old.Verbose = config.VerbosePermissions;
|
||||
return old;
|
||||
});
|
||||
}
|
||||
|
||||
public async Task<bool> TryBlockLate(DiscordSocketClient client, ICommandContext ctx, string moduleName,
|
||||
CommandInfo command)
|
||||
{
|
||||
var guild = ctx.Guild;
|
||||
var msg = ctx.Message;
|
||||
var user = ctx.User;
|
||||
var channel = ctx.Channel;
|
||||
var commandName = command.Name.ToLowerInvariant();
|
||||
|
||||
await Task.Yield();
|
||||
if (guild == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
var resetCommand = commandName == "resetperms";
|
||||
|
||||
PermissionCache pc = GetCacheFor(guild.Id);
|
||||
if (!resetCommand && !pc.Permissions.CheckPermissions(msg, commandName, moduleName, out int index))
|
||||
{
|
||||
if (pc.Verbose)
|
||||
{
|
||||
try
|
||||
{
|
||||
await channel.SendErrorAsync(_strings.GetText("perm_prevent", guild.Id, index + 1,
|
||||
Format.Bold(pc.Permissions[index].GetCommand(_cmd.GetPrefix(guild), (SocketGuild) guild))))
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
if (moduleName == nameof(Permissions))
|
||||
{
|
||||
if (!(user is 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)) == null)
|
||||
{
|
||||
returnMsg = $"You need Admin permissions in order to use permission commands.";
|
||||
if (pc.Verbose)
|
||||
try { await channel.SendErrorAsync(returnMsg).ConfigureAwait(false); } 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(returnMsg).ConfigureAwait(false); } catch { }
|
||||
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public async Task Reset(ulong guildId)
|
||||
{
|
||||
using (var uow = _db.GetDbContext())
|
||||
{
|
||||
var config = uow.GuildConfigs.GcWithPermissionsv2For(guildId);
|
||||
config.Permissions = Permissionv2.GetDefaultPermlist;
|
||||
await uow.SaveChangesAsync();
|
||||
UpdateCache(config);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user