Work on permissions, added tests for permission linked list

This commit is contained in:
Kwoth 2016-09-27 15:26:37 +02:00
parent 597b73d38c
commit 210ca07cde
29 changed files with 13146 additions and 36 deletions

View File

@ -16,6 +16,8 @@ Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Discord.Net", "discord.net\
EndProject
Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Discord.Net.Commands", "discord.net\src\Discord.Net.Commands\Discord.Net.Commands.xproj", "{078DD7E6-943D-4D09-AFC2-D2BA58B76C9C}"
EndProject
Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "tests", "src\tests\tests.xproj", "{14CBADA0-971C-44E3-B331-C7D01DD74F0B}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -34,11 +36,16 @@ Global
{078DD7E6-943D-4D09-AFC2-D2BA58B76C9C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{078DD7E6-943D-4D09-AFC2-D2BA58B76C9C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{078DD7E6-943D-4D09-AFC2-D2BA58B76C9C}.Release|Any CPU.Build.0 = Release|Any CPU
{14CBADA0-971C-44E3-B331-C7D01DD74F0B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{14CBADA0-971C-44E3-B331-C7D01DD74F0B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{14CBADA0-971C-44E3-B331-C7D01DD74F0B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{14CBADA0-971C-44E3-B331-C7D01DD74F0B}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{45EC1473-C678-4857-A544-07DFE0D0B478} = {04929013-5BAB-42B0-B9B2-8F2BB8F16AF2}
{14CBADA0-971C-44E3-B331-C7D01DD74F0B} = {04929013-5BAB-42B0-B9B2-8F2BB8F16AF2}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,596 @@
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using NadekoBot.Services.Database.Impl;
namespace NadekoBot.Migrations
{
[DbContext(typeof(NadekoSqliteContext))]
[Migration("20160927023659_moar perms")]
partial class moarperms
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.0.0-rtm-21431");
modelBuilder.Entity("NadekoBot.Services.Database.Models.BlacklistItem", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("BotConfigId");
b.Property<ulong>("ItemId");
b.HasKey("Id");
b.HasIndex("BotConfigId");
b.ToTable("BlacklistItem");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.BotConfig", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<ulong>("BufferSize");
b.Property<float>("CurrencyGenerationChance");
b.Property<int>("CurrencyGenerationCooldown");
b.Property<string>("CurrencyName");
b.Property<string>("CurrencyPluralName");
b.Property<string>("CurrencySign");
b.Property<bool>("DontJoinServers");
b.Property<bool>("ForwardMessages");
b.Property<bool>("ForwardToAllOwners");
b.Property<string>("RemindMessageFormat");
b.Property<bool>("RotatingStatuses");
b.HasKey("Id");
b.ToTable("BotConfig");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.ClashCaller", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<bool>("BaseDestroyed");
b.Property<string>("CallUser");
b.Property<int>("ClashWarId");
b.Property<int>("Stars");
b.Property<DateTime>("TimeAdded");
b.HasKey("Id");
b.HasIndex("ClashWarId");
b.ToTable("ClashCallers");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.ClashWar", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<ulong>("ChannelId");
b.Property<string>("EnemyClan");
b.Property<ulong>("GuildId");
b.Property<int>("Size");
b.Property<DateTime>("StartedAt");
b.Property<int>("WarState");
b.HasKey("Id");
b.ToTable("ClashOfClans");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.ConvertUnit", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("InternalTrigger");
b.Property<decimal>("Modifier");
b.Property<string>("UnitType");
b.HasKey("Id");
b.ToTable("ConversionUnits");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.Currency", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<long>("Amount");
b.Property<ulong>("UserId");
b.HasKey("Id");
b.HasIndex("UserId")
.IsUnique();
b.ToTable("Currency");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.Donator", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("Amount");
b.Property<string>("Name");
b.Property<ulong>("UserId");
b.HasKey("Id");
b.HasIndex("UserId")
.IsUnique();
b.ToTable("Donators");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.EightBallResponse", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("BotConfigId");
b.Property<string>("Text");
b.HasKey("Id");
b.HasIndex("BotConfigId");
b.ToTable("EightBallResponses");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.FollowedStream", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<ulong>("ChannelId");
b.Property<int?>("GuildConfigId");
b.Property<ulong>("GuildId");
b.Property<bool>("LastStatus");
b.Property<int>("Type");
b.Property<string>("Username");
b.HasKey("Id");
b.HasIndex("GuildConfigId");
b.ToTable("FollowedStream");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.GuildConfig", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<ulong>("AutoAssignRoleId");
b.Property<bool>("AutoDeleteByeMessages");
b.Property<bool>("AutoDeleteGreetMessages");
b.Property<int>("AutoDeleteGreetMessagesTimer");
b.Property<bool>("AutoDeleteSelfAssignedRoleMessages");
b.Property<ulong>("ByeMessageChannelId");
b.Property<string>("ChannelByeMessageText");
b.Property<string>("ChannelGreetMessageText");
b.Property<float>("DefaultMusicVolume");
b.Property<bool>("DeleteMessageOnCommand");
b.Property<string>("DmGreetMessageText");
b.Property<bool>("ExclusiveSelfAssignedRoles");
b.Property<ulong?>("GenerateCurrencyChannelId");
b.Property<ulong>("GreetMessageChannelId");
b.Property<ulong>("GuildId");
b.Property<int?>("LogSettingId");
b.Property<int?>("RootPermissionId");
b.Property<bool>("SendChannelByeMessage");
b.Property<bool>("SendChannelGreetMessage");
b.Property<bool>("SendDmGreetMessage");
b.Property<bool>("VoicePlusTextEnabled");
b.HasKey("Id");
b.HasIndex("GuildId")
.IsUnique();
b.HasIndex("LogSettingId");
b.HasIndex("RootPermissionId");
b.ToTable("GuildConfigs");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.IgnoredLogChannel", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<ulong>("ChannelId");
b.Property<int?>("LogSettingId");
b.HasKey("Id");
b.HasIndex("LogSettingId");
b.ToTable("IgnoredLogChannels");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.IgnoredVoicePresenceChannel", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<ulong>("ChannelId");
b.Property<int?>("LogSettingId");
b.HasKey("Id");
b.HasIndex("LogSettingId");
b.ToTable("IgnoredVoicePresenceCHannels");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.LogSetting", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<bool>("ChannelCreated");
b.Property<bool>("ChannelDestroyed");
b.Property<ulong>("ChannelId");
b.Property<bool>("ChannelUpdated");
b.Property<bool>("IsLogging");
b.Property<bool>("LogUserPresence");
b.Property<bool>("LogVoicePresence");
b.Property<bool>("MessageDeleted");
b.Property<bool>("MessageReceived");
b.Property<bool>("MessageUpdated");
b.Property<bool>("UserBanned");
b.Property<bool>("UserJoined");
b.Property<bool>("UserLeft");
b.Property<ulong>("UserPresenceChannelId");
b.Property<bool>("UserUnbanned");
b.Property<bool>("UserUpdated");
b.Property<ulong>("VoicePresenceChannelId");
b.HasKey("Id");
b.ToTable("LogSettings");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.ModulePrefix", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("BotConfigId");
b.Property<string>("ModuleName");
b.Property<string>("Prefix");
b.HasKey("Id");
b.HasIndex("BotConfigId");
b.ToTable("ModulePrefixes");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.Permission", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("NextId");
b.Property<int>("PrimaryTarget");
b.Property<ulong>("PrimaryTargetId");
b.Property<int>("SecondaryTarget");
b.Property<string>("SecondaryTargetName");
b.Property<bool>("State");
b.HasKey("Id");
b.HasIndex("NextId")
.IsUnique();
b.ToTable("Permission");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.PlayingStatus", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("BotConfigId");
b.Property<string>("Status");
b.HasKey("Id");
b.HasIndex("BotConfigId");
b.ToTable("PlayingStatus");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.Quote", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<ulong>("AuthorId");
b.Property<string>("AuthorName")
.IsRequired();
b.Property<ulong>("GuildId");
b.Property<string>("Keyword")
.IsRequired();
b.Property<string>("Text")
.IsRequired();
b.HasKey("Id");
b.ToTable("Quotes");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.RaceAnimal", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("BotConfigId");
b.Property<string>("Icon");
b.Property<string>("Name");
b.HasKey("Id");
b.HasIndex("BotConfigId");
b.ToTable("RaceAnimals");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.Reminder", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<ulong>("ChannelId");
b.Property<bool>("IsPrivate");
b.Property<string>("Message");
b.Property<ulong>("ServerId");
b.Property<ulong>("UserId");
b.Property<DateTime>("When");
b.HasKey("Id");
b.ToTable("Reminders");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.Repeater", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<ulong>("ChannelId");
b.Property<ulong>("GuildId");
b.Property<TimeSpan>("Interval");
b.Property<string>("Message");
b.HasKey("Id");
b.HasIndex("ChannelId")
.IsUnique();
b.ToTable("Repeaters");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.SelfAssignedRole", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<ulong>("GuildId");
b.Property<ulong>("RoleId");
b.HasKey("Id");
b.HasIndex("GuildId", "RoleId")
.IsUnique();
b.ToTable("SelfAssignableRoles");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.TypingArticle", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Author");
b.Property<string>("Text");
b.HasKey("Id");
b.ToTable("TypingArticles");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.BlacklistItem", b =>
{
b.HasOne("NadekoBot.Services.Database.Models.BotConfig")
.WithMany("Blacklist")
.HasForeignKey("BotConfigId");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.ClashCaller", b =>
{
b.HasOne("NadekoBot.Services.Database.Models.ClashWar", "ClashWar")
.WithMany("Bases")
.HasForeignKey("ClashWarId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.EightBallResponse", b =>
{
b.HasOne("NadekoBot.Services.Database.Models.BotConfig")
.WithMany("EightBallResponses")
.HasForeignKey("BotConfigId");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.FollowedStream", b =>
{
b.HasOne("NadekoBot.Services.Database.Models.GuildConfig")
.WithMany("FollowedStreams")
.HasForeignKey("GuildConfigId");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.GuildConfig", b =>
{
b.HasOne("NadekoBot.Services.Database.Models.LogSetting", "LogSetting")
.WithMany()
.HasForeignKey("LogSettingId");
b.HasOne("NadekoBot.Services.Database.Models.Permission", "RootPermission")
.WithMany()
.HasForeignKey("RootPermissionId");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.IgnoredLogChannel", b =>
{
b.HasOne("NadekoBot.Services.Database.Models.LogSetting", "LogSetting")
.WithMany("IgnoredChannels")
.HasForeignKey("LogSettingId");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.IgnoredVoicePresenceChannel", b =>
{
b.HasOne("NadekoBot.Services.Database.Models.LogSetting", "LogSetting")
.WithMany("IgnoredVoicePresenceChannelIds")
.HasForeignKey("LogSettingId");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.ModulePrefix", b =>
{
b.HasOne("NadekoBot.Services.Database.Models.BotConfig", "BotConfig")
.WithMany("ModulePrefixes")
.HasForeignKey("BotConfigId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.Permission", b =>
{
b.HasOne("NadekoBot.Services.Database.Models.Permission", "Next")
.WithOne("Previous")
.HasForeignKey("NadekoBot.Services.Database.Models.Permission", "NextId");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.PlayingStatus", b =>
{
b.HasOne("NadekoBot.Services.Database.Models.BotConfig")
.WithMany("RotatingStatusMessages")
.HasForeignKey("BotConfigId");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.RaceAnimal", b =>
{
b.HasOne("NadekoBot.Services.Database.Models.BotConfig")
.WithMany("RaceAnimals")
.HasForeignKey("BotConfigId");
});
}
}
}

View File

@ -0,0 +1,106 @@
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Migrations;
namespace NadekoBot.Migrations
{
public partial class moarperms : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Permission_GuildConfigs_GuildConfigId",
table: "Permission");
migrationBuilder.DropIndex(
name: "IX_Permission_GuildConfigId",
table: "Permission");
migrationBuilder.DropColumn(
name: "GuildConfigId",
table: "Permission");
migrationBuilder.AddColumn<int>(
name: "NextId",
table: "Permission",
nullable: true);
migrationBuilder.AddColumn<int>(
name: "RootPermissionId",
table: "GuildConfigs",
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_Permission_NextId",
table: "Permission",
column: "NextId",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_GuildConfigs_RootPermissionId",
table: "GuildConfigs",
column: "RootPermissionId");
migrationBuilder.AddForeignKey(
name: "FK_GuildConfigs_Permission_RootPermissionId",
table: "GuildConfigs",
column: "RootPermissionId",
principalTable: "Permission",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Permission_Permission_NextId",
table: "Permission",
column: "NextId",
principalTable: "Permission",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_GuildConfigs_Permission_RootPermissionId",
table: "GuildConfigs");
migrationBuilder.DropForeignKey(
name: "FK_Permission_Permission_NextId",
table: "Permission");
migrationBuilder.DropIndex(
name: "IX_Permission_NextId",
table: "Permission");
migrationBuilder.DropIndex(
name: "IX_GuildConfigs_RootPermissionId",
table: "GuildConfigs");
migrationBuilder.DropColumn(
name: "NextId",
table: "Permission");
migrationBuilder.DropColumn(
name: "RootPermissionId",
table: "GuildConfigs");
migrationBuilder.AddColumn<int>(
name: "GuildConfigId",
table: "Permission",
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_Permission_GuildConfigId",
table: "Permission",
column: "GuildConfigId");
migrationBuilder.AddForeignKey(
name: "FK_Permission_GuildConfigs_GuildConfigId",
table: "Permission",
column: "GuildConfigId",
principalTable: "GuildConfigs",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
}
}

View File

@ -236,6 +236,8 @@ namespace NadekoBot.Migrations
b.Property<int?>("LogSettingId");
b.Property<int?>("RootPermissionId");
b.Property<bool>("SendChannelByeMessage");
b.Property<bool>("SendChannelGreetMessage");
@ -251,6 +253,8 @@ namespace NadekoBot.Migrations
b.HasIndex("LogSettingId");
b.HasIndex("RootPermissionId");
b.ToTable("GuildConfigs");
});
@ -353,7 +357,7 @@ namespace NadekoBot.Migrations
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("GuildConfigId");
b.Property<int?>("NextId");
b.Property<int>("PrimaryTarget");
@ -367,7 +371,8 @@ namespace NadekoBot.Migrations
b.HasKey("Id");
b.HasIndex("GuildConfigId");
b.HasIndex("NextId")
.IsUnique();
b.ToTable("Permission");
});
@ -537,6 +542,10 @@ namespace NadekoBot.Migrations
b.HasOne("NadekoBot.Services.Database.Models.LogSetting", "LogSetting")
.WithMany()
.HasForeignKey("LogSettingId");
b.HasOne("NadekoBot.Services.Database.Models.Permission", "RootPermission")
.WithMany()
.HasForeignKey("RootPermissionId");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.IgnoredLogChannel", b =>
@ -563,9 +572,9 @@ namespace NadekoBot.Migrations
modelBuilder.Entity("NadekoBot.Services.Database.Models.Permission", b =>
{
b.HasOne("NadekoBot.Services.Database.Models.GuildConfig")
.WithMany("Permissions")
.HasForeignKey("GuildConfigId");
b.HasOne("NadekoBot.Services.Database.Models.Permission", "Next")
.WithOne("Previous")
.HasForeignKey("NadekoBot.Services.Database.Models.Permission", "NextId");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.PlayingStatus", b =>

View File

@ -1,5 +1,6 @@
using Discord;
using Discord.Commands;
using NadekoBot.Services.Database;
using NadekoBot.Services.Database.Models;
using System;
using System.Collections.Generic;
@ -51,8 +52,8 @@ namespace NadekoBot.Modules.Permissions
if (!((perm.SecondaryTarget == SecondaryPermissionType.Command &&
perm.SecondaryTargetName == command.Text.ToLowerInvariant()) ||
((perm.SecondaryTarget == SecondaryPermissionType.Module || perm.SecondaryTarget == SecondaryPermissionType.AllCommands) &&
perm.SecondaryTargetName == command.Module.Name.ToLowerInvariant()) ||
perm.SecondaryTarget == SecondaryPermissionType.AllModules ||
perm.SecondaryTargetName == command.Module.Name.ToLowerInvariant()) ||
perm.SecondaryTarget == SecondaryPermissionType.AllModules ||
(perm.SecondaryTarget == SecondaryPermissionType.AllCommands && perm.SecondaryTargetName == command.Module.Name.ToLowerInvariant())))
return null;
@ -126,5 +127,109 @@ namespace NadekoBot.Modules.Permissions
return NadekoBot.ModulePrefixes[typeof(Permissions).Name] + com;
}
public static void Add(this Permission perm, Permission toAdd)
{
var last = perm;
while (last.Next != null)
{
last = last.Next;
}
toAdd.Previous = last;
last.Next = toAdd;
toAdd.Next = null;
}
public static void Insert(this Permission perm, int index, Permission toAdd)
{
if (index < 0)
throw new IndexOutOfRangeException();
if (index == 0)
{
perm.Previous = toAdd;
toAdd.Next = perm;
return;
}
var atIndex = perm;
var i = 0;
while (i != index)
{
atIndex = atIndex.Next;
i++;
if (atIndex == null)
throw new IndexOutOfRangeException();
}
var previous = atIndex.Previous;
//connect right side
atIndex.Previous = toAdd;
toAdd.Next = atIndex;
//connect left side
toAdd.Previous = previous;
previous.Next = toAdd;
}
public static Permission RemoveAt(this Permission perm, int index)
{
if (index < 0)
throw new IndexOutOfRangeException();
if (index == 0)
{
perm.Next.Previous = null;
perm.Next = null;
return perm;
}
var toRemove = perm;
var i = 0;
while (i != index)
{
toRemove = toRemove.Next;
i++;
if (toRemove == null)
throw new IndexOutOfRangeException();
}
toRemove.Previous.Next = toRemove.Next;
toRemove.Next.Previous = toRemove.Previous;
return toRemove;
}
public static Permission GetAt(this Permission perm, int index)
{
if (index < 0)
throw new IndexOutOfRangeException();
var temp = perm;
while (index > 0) { temp = temp?.Next; index--; }
if (temp == null)
throw new IndexOutOfRangeException();
return temp;
}
public static int Count(this Permission perm)
{
var i = 1;
var temp = perm;
while ((temp = temp.Next) != null) { i++; }
return i;
}
public static IEnumerable<Permission> AsEnumerable(this Permission perm)
{
do yield return perm;
while ((perm = perm.Next) != null);
}
public static Permission GetRoot(this Permission perm)
{
Permission toReturn;
do toReturn = perm;
while ((perm = perm.Previous) != null);
return toReturn;
}
}
}

View File

@ -30,7 +30,7 @@ namespace NadekoBot.Modules.Permissions
string toSend = "";
using (var uow = DbHandler.UnitOfWork())
{
var perms = uow.GuildConfigs.For(channel.Guild.Id).Permissions.AsEnumerable().Reverse();
var perms = uow.GuildConfigs.For(channel.Guild.Id).RootPermission.AsEnumerable().Reverse();
var i = 1;
toSend = String.Join("\n", perms.Select(p => $"`{(i++)}.` {p.GetCommand()}"));
@ -52,10 +52,8 @@ namespace NadekoBot.Modules.Permissions
Permission p;
using (var uow = DbHandler.UnitOfWork())
{
var perms = uow.GuildConfigs.For(channel.Guild.Id).Permissions.AsEnumerable().ToList();
p = perms[perms.Count - index];
perms.RemoveAt(perms.Count - index);
uow.GuildConfigs.For(channel.Guild.Id).Permissions = perms;
var perms = uow.GuildConfigs.For(channel.Guild.Id).RootPermission;
p = perms.RemoveAt(perms.Count() - index);
await uow.CompleteAsync().ConfigureAwait(false);
}
await channel.SendMessageAsync($"`Removed permission \"{p.GetCommand()}\" from position #{index}.`").ConfigureAwait(false);
@ -78,13 +76,13 @@ namespace NadekoBot.Modules.Permissions
Permission toInsert;
using (var uow = DbHandler.UnitOfWork())
{
var perms = uow.GuildConfigs.For(channel.Guild.Id).Permissions.AsEnumerable().ToList();
toInsert = perms[perms.Count - from];
perms.RemoveAt(perms.Count - from);
uow.GuildConfigs.For(channel.Guild.Id).Permissions = perms;
var perms = uow.GuildConfigs.For(channel.Guild.Id).RootPermission;
var count = perms.Count();
toInsert = perms.RemoveAt(count - from);
if (from < to)
to -= 1;
perms.Insert(perms.Count - to, toInsert);
perms.Insert(count - to, toInsert);
uow.GuildConfigs.For(channel.Guild.Id).RootPermission = perms;
await uow.CompleteAsync().ConfigureAwait(false);
}
await channel.SendMessageAsync($"`Moved permission \"{toInsert.GetCommand()}\" from #{from} to #{to}.`").ConfigureAwait(false);
@ -105,7 +103,7 @@ namespace NadekoBot.Modules.Permissions
using (var uow = DbHandler.UnitOfWork())
{
uow.GuildConfigs.For(channel.Guild.Id).Permissions.Add(new Permission
uow.GuildConfigs.For(channel.Guild.Id).RootPermission.Add(new Permission
{
PrimaryTarget = PrimaryPermissionType.User,
PrimaryTargetId = user.Id,
@ -126,7 +124,7 @@ namespace NadekoBot.Modules.Permissions
using (var uow = DbHandler.UnitOfWork())
{
uow.GuildConfigs.For(channel.Guild.Id).Permissions.Add(new Permission
uow.GuildConfigs.For(channel.Guild.Id).RootPermission.Add(new Permission
{
PrimaryTarget = PrimaryPermissionType.User,
PrimaryTargetId = user.Id,
@ -147,7 +145,7 @@ namespace NadekoBot.Modules.Permissions
using (var uow = DbHandler.UnitOfWork())
{
uow.GuildConfigs.For(channel.Guild.Id).Permissions.Add(new Permission
uow.GuildConfigs.For(channel.Guild.Id).RootPermission.Add(new Permission
{
PrimaryTarget = PrimaryPermissionType.Role,
PrimaryTargetId = role.Id,
@ -168,7 +166,7 @@ namespace NadekoBot.Modules.Permissions
using (var uow = DbHandler.UnitOfWork())
{
uow.GuildConfigs.For(channel.Guild.Id).Permissions.Add(new Permission
uow.GuildConfigs.For(channel.Guild.Id).RootPermission.Add(new Permission
{
PrimaryTarget = PrimaryPermissionType.Role,
PrimaryTargetId = role.Id,
@ -189,7 +187,7 @@ namespace NadekoBot.Modules.Permissions
using (var uow = DbHandler.UnitOfWork())
{
uow.GuildConfigs.For(channel.Guild.Id).Permissions.Add(new Permission
uow.GuildConfigs.For(channel.Guild.Id).RootPermission.Add(new Permission
{
PrimaryTarget = PrimaryPermissionType.Channel,
PrimaryTargetId = chnl.Id,
@ -210,7 +208,7 @@ namespace NadekoBot.Modules.Permissions
using (var uow = DbHandler.UnitOfWork())
{
uow.GuildConfigs.For(channel.Guild.Id).Permissions.Add(new Permission
uow.GuildConfigs.For(channel.Guild.Id).RootPermission.Add(new Permission
{
PrimaryTarget = PrimaryPermissionType.Channel,
PrimaryTargetId = chnl.Id,
@ -231,7 +229,7 @@ namespace NadekoBot.Modules.Permissions
using (var uow = DbHandler.UnitOfWork())
{
uow.GuildConfigs.For(channel.Guild.Id).Permissions.Add(new Permission
uow.GuildConfigs.For(channel.Guild.Id).RootPermission.Add(new Permission
{
PrimaryTarget = PrimaryPermissionType.Channel,
PrimaryTargetId = chnl.Id,
@ -252,7 +250,7 @@ namespace NadekoBot.Modules.Permissions
using (var uow = DbHandler.UnitOfWork())
{
uow.GuildConfigs.For(channel.Guild.Id).Permissions.Add(new Permission
uow.GuildConfigs.For(channel.Guild.Id).RootPermission.Add(new Permission
{
PrimaryTarget = PrimaryPermissionType.Role,
PrimaryTargetId = role.Id,
@ -273,7 +271,7 @@ namespace NadekoBot.Modules.Permissions
using (var uow = DbHandler.UnitOfWork())
{
uow.GuildConfigs.For(channel.Guild.Id).Permissions.Add(new Permission
uow.GuildConfigs.For(channel.Guild.Id).RootPermission.Add(new Permission
{
PrimaryTarget = PrimaryPermissionType.User,
PrimaryTargetId = user.Id,
@ -294,7 +292,7 @@ namespace NadekoBot.Modules.Permissions
using (var uow = DbHandler.UnitOfWork())
{
uow.GuildConfigs.For(channel.Guild.Id).Permissions.Add(new Permission
uow.GuildConfigs.For(channel.Guild.Id).RootPermission.Add(new Permission
{
PrimaryTarget = PrimaryPermissionType.Channel,
PrimaryTargetId = chnl.Id,
@ -315,7 +313,7 @@ namespace NadekoBot.Modules.Permissions
using (var uow = DbHandler.UnitOfWork())
{
uow.GuildConfigs.For(channel.Guild.Id).Permissions.Add(new Permission
uow.GuildConfigs.For(channel.Guild.Id).RootPermission.Add(new Permission
{
PrimaryTarget = PrimaryPermissionType.Role,
PrimaryTargetId = role.Id,
@ -336,7 +334,7 @@ namespace NadekoBot.Modules.Permissions
using (var uow = DbHandler.UnitOfWork())
{
uow.GuildConfigs.For(channel.Guild.Id).Permissions.Add(new Permission
uow.GuildConfigs.For(channel.Guild.Id).RootPermission.Add(new Permission
{
PrimaryTarget = PrimaryPermissionType.User,
PrimaryTargetId = user.Id,

View File

@ -127,17 +127,17 @@ namespace NadekoBot.Services
}
}
var cmd = commands[i];
List<Permission> perms;
Permission rootPerm;
//check permissions
if (guild != null)
{
using (var uow = DbHandler.UnitOfWork())
{
perms = uow.GuildConfigs.For(guild.Id).Permissions;
rootPerm = uow.GuildConfigs.For(guild.Id).RootPermission;
}
int index;
if (!perms.CheckPermissions(message, cmd, out index))
return new Tuple<Command, IResult>(null, SearchResult.FromError(CommandError.Exception, $"Permission error. Permission number {index} (`{(index != -1 ? perms[perms.Count - index].GetCommand() : "default")}`)"));
if (!rootPerm.AsEnumerable().CheckPermissions(message, cmd, out index))
return new Tuple<Command, IResult>(null, SearchResult.FromError(CommandError.Exception, $"Permission error. Permission number {index} (`{(index != -1 ? rootPerm.GetAt(rootPerm.Count() - index).GetCommand() : "default")}`)"));
}
return new Tuple<Command, IResult>(commands[i], await commands[i].Execute(message, parseResult));

View File

@ -43,6 +43,14 @@ namespace NadekoBot.Services.Database.Models
public ulong? GenerateCurrencyChannelId { get; set; }
//permissions
public List<Permission> Permissions { get; set; } = new List<Permission>();
public Permission RootPermission { get; set; } = new Permission()
{
Next = null,
Previous = null,
PrimaryTarget = PrimaryPermissionType.Role,
PrimaryTargetId = 0,
SecondaryTarget = SecondaryPermissionType.AllModules,
SecondaryTargetName = "*",
};
}
}

View File

@ -8,6 +8,9 @@ namespace NadekoBot.Services.Database.Models
{
public class Permission : DbEntity
{
public Permission Previous { get; set; } = null;
public Permission Next { get; set; } = null;
public PrimaryPermissionType PrimaryTarget { get; set; }
public ulong PrimaryTargetId { get; set; }

View File

@ -181,6 +181,13 @@ namespace NadekoBot.Services.Database
.IsUnique();
#endregion
#region Permission
var permissionEntity = modelBuilder.Entity<Permission>();
permissionEntity
.HasOne(p => p.Next)
.WithOne(p => p.Previous);
#endregion
#region LogSettings
//var logSettingEntity = modelBuilder.Entity<LogSetting>();

View File

@ -29,7 +29,7 @@ namespace NadekoBot.Services.Database.Repositories.Impl
public GuildConfig For(ulong guildId)
{
var config = _set.Include(gc => gc.FollowedStreams)
.Include(gc => gc.Permissions)
.Include(gc => gc.RootPermission)
.Include(gc => gc.LogSetting)
.ThenInclude(ls=>ls.IgnoredChannels)
.FirstOrDefault(c => c.GuildId == guildId);

View File

@ -10,7 +10,7 @@ namespace NadekoBot.Services.Database
{
public class UnitOfWork : IUnitOfWork
{
private NadekoContext _context;
public NadekoContext _context;
private IQuoteRepository _quotes;
public IQuoteRepository Quotes => _quotes ?? (_quotes = new QuoteRepository(_context));

111
src/tests/Tests.cs Normal file
View File

@ -0,0 +1,111 @@
using NadekoBot.Modules.Permissions;
using NadekoBot.Services.Database.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace Tests
{
public class Tests
{
private Permission GetRoot()
{
Permission root = new Permission();
root.SecondaryTargetName = "Root";
var cur = root;
for (var i = 1; i < 10; i++)
{
var p = new Permission();
p.SecondaryTargetName = i.ToString();
p.Previous = cur;
cur.Next = p;
cur = p;
}
return root;
}
[Fact]
public void CountTest()
{
var root = GetRoot();
Assert.Equal(10, root.Count());
}
[Fact]
public void AddTest()
{
var root = GetRoot();
root.Add(new Permission() { SecondaryTargetName = "Added" });
Assert.Equal(11, root.Count());
Assert.Equal("Added", root.AsEnumerable().Last().SecondaryTargetName);
}
[Fact]
public void GetAtTest()
{
var root = GetRoot();
Assert.Equal("Root", root.GetAt(0).SecondaryTargetName);
Assert.Equal("1", root.GetAt(1).SecondaryTargetName);
Assert.Equal("5", root.GetAt(5).SecondaryTargetName);
Assert.Equal("9", root.GetAt(9).SecondaryTargetName);
Assert.Throws(typeof(IndexOutOfRangeException), () => { root.GetAt(-5); });
Assert.Throws(typeof(IndexOutOfRangeException), () => { root.GetAt(10); });
}
[Fact]
public void InsertTest() {
var root = GetRoot();
root.Insert(5, new Permission() { SecondaryTargetName = "in2" });
Assert.Equal(11, root.Count());
Assert.Equal("in2", root.GetAt(5).SecondaryTargetName);
root.Insert(0, new Permission() { SecondaryTargetName = "Inserted" });
root = root.Previous;
Assert.Equal("Inserted", root.SecondaryTargetName);
Assert.Equal(12, root.Count());
Assert.Equal("Root", root.GetAt(1).SecondaryTargetName);
Assert.Throws(typeof(IndexOutOfRangeException), () => { root.GetAt(12); });
}
[Fact]
public void RemoveAtTest()
{
var root = GetRoot();
var removed = root.RemoveAt(3);
Assert.Equal("3", removed.SecondaryTargetName);
Assert.Equal(9, root.Count());
var temp = root.Next;
removed = root.RemoveAt(0);
Assert.Equal(8, temp.Count());
Assert.Equal(null, temp.Previous);
Assert.Throws(typeof(IndexOutOfRangeException), () => { temp.RemoveAt(8); });
Assert.Throws(typeof(IndexOutOfRangeException), () => { temp.RemoveAt(-1); });
}
[Fact]
public void TestGetRoot()
{
var root = GetRoot();
var random = root.GetAt(5).GetRoot();
Assert.Equal("Root", random.SecondaryTargetName);
}
}
}

View File

@ -0,0 +1,26 @@
<?xml version="1.0"?>
<doc>
<assembly>
<name>Discord.Net.Commands</name>
</assembly>
<members>
<member name="T:Discord.Commands.AliasAttribute">
<summary> Provides aliases for a command. </summary>
</member>
<member name="P:Discord.Commands.AliasAttribute.Aliases">
<summary> The aliases which have been defined for the command. </summary>
</member>
<member name="M:Discord.Commands.AliasAttribute.#ctor(System.String[])">
<summary> Creates a new <see cref="T:Discord.Commands.AliasAttribute"/> with the given aliases. </summary>
</member>
<member name="T:Discord.Commands.PriorityAttribute">
<summary> Sets priority of commands </summary>
</member>
<member name="P:Discord.Commands.PriorityAttribute.Priority">
<summary> The priority which has been set for the command </summary>
</member>
<member name="M:Discord.Commands.PriorityAttribute.#ctor(System.Int32)">
<summary> Creates a new <see cref="T:Discord.Commands.PriorityAttribute"/> with the given priority. </summary>
</member>
</members>
</doc>

Binary file not shown.

Binary file not shown.

File diff suppressed because it is too large Load Diff

Binary file not shown.

Binary file not shown.

File diff suppressed because it is too large Load Diff

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,7 @@
{
"runtimeOptions": {
"additionalProbingPaths": [
"C:\\Users\\Kwoth\\.nuget\\packages"
]
}
}

View File

@ -0,0 +1,8 @@
{
"runtimeOptions": {
"framework": {
"name": "Microsoft.NETCore.App",
"version": "1.0.0"
}
}
}

27
src/tests/project.json Normal file
View File

@ -0,0 +1,27 @@
{
"version": "1.0.0-*",
"buildOptions": {
"debugType": "portable"
},
"dependencies": {
"System.Runtime.Serialization.Primitives": "4.1.1",
"xunit": "2.1.0",
"dotnet-test-xunit": "1.0.0-rc2-192208-24",
"NadekoBot": "1.0.0-*"
},
"testRunner": "xunit",
"frameworks": {
"netcoreapp1.0": {
"dependencies": {
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.0.0"
}
},
"imports": [
"dotnet5.4",
"portable-net451+win8"
]
}
}
}

9841
src/tests/project.lock.json Normal file

File diff suppressed because it is too large Load Diff

21
src/tests/tests.xproj Normal file
View File

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0.25420" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">14.0.25420</VisualStudioVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
</PropertyGroup>
<Import Project="$(VSToolsPath)\DotNet\Microsoft.DotNet.Props" Condition="'$(VSToolsPath)' != ''" />
<PropertyGroup Label="Globals">
<ProjectGuid>14cbada0-971c-44e3-b331-c7d01dd74f0b</ProjectGuid>
<RootNamespace>tests</RootNamespace>
<BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">.\obj</BaseIntermediateOutputPath>
<OutputPath Condition="'$(OutputPath)'=='' ">.\bin\</OutputPath>
</PropertyGroup>
<PropertyGroup>
<SchemaVersion>2.0</SchemaVersion>
</PropertyGroup>
<ItemGroup>
<Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" />
</ItemGroup>
<Import Project="$(VSToolsPath)\DotNet\Microsoft.DotNet.targets" Condition="'$(VSToolsPath)' != ''" />
</Project>