Major database refactor (again)

This commit is contained in:
Ske
2020-08-29 13:46:27 +02:00
parent 3996cd48c7
commit c7612df37e
55 changed files with 1014 additions and 1100 deletions

View File

@@ -12,10 +12,12 @@ namespace PluralKit.Bot
public class Autoproxy
{
private readonly IDatabase _db;
private readonly ModelRepository _repo;
public Autoproxy(IDatabase db)
public Autoproxy(IDatabase db, ModelRepository repo)
{
_db = db;
_repo = repo;
}
public async Task AutoproxyRoot(Context ctx)
@@ -87,8 +89,8 @@ namespace PluralKit.Bot
var fronters = ctx.MessageContext.LastSwitchMembers;
var relevantMember = ctx.MessageContext.AutoproxyMode switch
{
AutoproxyMode.Front => fronters.Length > 0 ? await _db.Execute(c => c.QueryMember(fronters[0])) : null,
AutoproxyMode.Member => await _db.Execute(c => c.QueryMember(ctx.MessageContext.AutoproxyMember.Value)),
AutoproxyMode.Front => fronters.Length > 0 ? await _db.Execute(c => _repo.GetMember(c, fronters[0])) : null,
AutoproxyMode.Member => await _db.Execute(c => _repo.GetMember(c, ctx.MessageContext.AutoproxyMember.Value)),
_ => null
};
@@ -126,7 +128,7 @@ namespace PluralKit.Bot
private Task UpdateAutoproxy(Context ctx, AutoproxyMode autoproxyMode, MemberId? autoproxyMember)
{
var patch = new SystemGuildPatch {AutoproxyMode = autoproxyMode, AutoproxyMember = autoproxyMember};
return _db.Execute(conn => conn.UpsertSystemGuild(ctx.System.Id, ctx.Guild.Id, patch));
return _db.Execute(conn => _repo.UpsertSystemGuild(conn, ctx.System.Id, ctx.Guild.Id, patch));
}
}
}

View File

@@ -17,10 +17,12 @@ namespace PluralKit.Bot
public class Groups
{
private readonly IDatabase _db;
private readonly ModelRepository _repo;
public Groups(IDatabase db)
public Groups(IDatabase db, ModelRepository repo)
{
_db = db;
_repo = repo;
}
public async Task CreateGroup(Context ctx)
@@ -40,14 +42,14 @@ namespace PluralKit.Bot
throw new PKError($"System has reached the maximum number of groups ({Limits.MaxGroupCount}). Please delete unused groups first in order to create new ones.");
// Warn if there's already a group by this name
var existingGroup = await conn.QueryGroupByName(ctx.System.Id, groupName);
var existingGroup = await _repo.GetGroupByName(conn, ctx.System.Id, groupName);
if (existingGroup != null) {
var msg = $"{Emojis.Warn} You already have a group in your system with the name \"{existingGroup.Name}\" (with ID `{existingGroup.Hid}`). Do you want to create another group with the same name?";
if (!await ctx.PromptYesNo(msg))
throw new PKError("Group creation cancelled.");
}
var newGroup = await conn.CreateGroup(ctx.System.Id, groupName);
var newGroup = await _repo.CreateGroup(conn, ctx.System.Id, groupName);
var eb = new DiscordEmbedBuilder()
.WithDescription($"Your new group, **{groupName}**, has been created, with the group ID **`{newGroup.Hid}`**.\nBelow are a couple of useful commands:")
@@ -70,14 +72,14 @@ namespace PluralKit.Bot
await using var conn = await _db.Obtain();
// Warn if there's already a group by this name
var existingGroup = await conn.QueryGroupByName(ctx.System.Id, newName);
var existingGroup = await _repo.GetGroupByName(conn, ctx.System.Id, newName);
if (existingGroup != null && existingGroup.Id != target.Id) {
var msg = $"{Emojis.Warn} You already have a group in your system with the name \"{existingGroup.Name}\" (with ID `{existingGroup.Hid}`). Do you want to rename this member to that name too?";
if (!await ctx.PromptYesNo(msg))
throw new PKError("Group creation cancelled.");
}
await conn.UpdateGroup(target.Id, new GroupPatch {Name = newName});
await _repo.UpdateGroup(conn, target.Id, new GroupPatch {Name = newName});
await ctx.Reply($"{Emojis.Success} Group name changed from **{target.Name}** to **{newName}**.");
}
@@ -89,7 +91,7 @@ namespace PluralKit.Bot
ctx.CheckOwnGroup(target);
var patch = new GroupPatch {DisplayName = Partial<string>.Null()};
await _db.Execute(conn => conn.UpdateGroup(target.Id, patch));
await _db.Execute(conn => _repo.UpdateGroup(conn, target.Id, patch));
await ctx.Reply($"{Emojis.Success} Group display name cleared.");
}
@@ -112,7 +114,7 @@ namespace PluralKit.Bot
var newDisplayName = ctx.RemainderOrNull();
var patch = new GroupPatch {DisplayName = Partial<string>.Present(newDisplayName)};
await _db.Execute(conn => conn.UpdateGroup(target.Id, patch));
await _db.Execute(conn => _repo.UpdateGroup(conn, target.Id, patch));
await ctx.Reply($"{Emojis.Success} Group display name changed.");
}
@@ -125,7 +127,7 @@ namespace PluralKit.Bot
ctx.CheckOwnGroup(target);
var patch = new GroupPatch {Description = Partial<string>.Null()};
await _db.Execute(conn => conn.UpdateGroup(target.Id, patch));
await _db.Execute(conn => _repo.UpdateGroup(conn, target.Id, patch));
await ctx.Reply($"{Emojis.Success} Group description cleared.");
}
else if (!ctx.HasNext())
@@ -154,7 +156,7 @@ namespace PluralKit.Bot
throw Errors.DescriptionTooLongError(description.Length);
var patch = new GroupPatch {Description = Partial<string>.Present(description)};
await _db.Execute(conn => conn.UpdateGroup(target.Id, patch));
await _db.Execute(conn => _repo.UpdateGroup(conn, target.Id, patch));
await ctx.Reply($"{Emojis.Success} Group description changed.");
}
@@ -166,7 +168,7 @@ namespace PluralKit.Bot
{
ctx.CheckOwnGroup(target);
await _db.Execute(c => c.UpdateGroup(target.Id, new GroupPatch {Icon = null}));
await _db.Execute(c => _repo.UpdateGroup(c, target.Id, new GroupPatch {Icon = null}));
await ctx.Reply($"{Emojis.Success} Group icon cleared.");
}
@@ -178,7 +180,7 @@ namespace PluralKit.Bot
throw Errors.InvalidUrl(img.Url);
await AvatarUtils.VerifyAvatarOrThrow(img.Url);
await _db.Execute(c => c.UpdateGroup(target.Id, new GroupPatch {Icon = img.Url}));
await _db.Execute(c => _repo.UpdateGroup(c, target.Id, new GroupPatch {Icon = img.Url}));
var msg = img.Source switch
{
@@ -282,7 +284,7 @@ namespace PluralKit.Bot
var system = await GetGroupSystem(ctx, target, conn);
var pctx = ctx.LookupContextFor(system);
var memberCount = await conn.QueryGroupMemberCount(target.Id, PrivacyLevel.Public);
var memberCount = await _repo.GetGroupMemberCount(conn, target.Id, PrivacyLevel.Public);
var nameField = target.Name;
if (system.Name != null)
@@ -333,7 +335,7 @@ namespace PluralKit.Bot
.Select(m => m.Id)
.Distinct()
.ToList();
await conn.AddMembersToGroup(target.Id, membersNotInGroup);
await _repo.AddMembersToGroup(conn, target.Id, membersNotInGroup);
if (membersNotInGroup.Count == members.Count)
await ctx.Reply($"{Emojis.Success} {"members".ToQuantity(membersNotInGroup.Count)} added to group.");
@@ -347,7 +349,7 @@ namespace PluralKit.Bot
.Select(m => m.Id)
.Distinct()
.ToList();
await conn.RemoveMembersFromGroup(target.Id, membersInGroup);
await _repo.RemoveMembersFromGroup(conn, target.Id, membersInGroup);
if (membersInGroup.Count == members.Count)
await ctx.Reply($"{Emojis.Success} {"members".ToQuantity(membersInGroup.Count)} removed from group.");
@@ -422,7 +424,7 @@ namespace PluralKit.Bot
async Task SetAll(PrivacyLevel level)
{
await _db.Execute(c => c.UpdateGroup(target.Id, new GroupPatch().WithAllPrivacy(level)));
await _db.Execute(c => _repo.UpdateGroup(c, target.Id, new GroupPatch().WithAllPrivacy(level)));
if (level == PrivacyLevel.Private)
await ctx.Reply($"{Emojis.Success} All {target.Name}'s privacy settings have been set to **{level.LevelName()}**. Other accounts will now see nothing on the group card.");
@@ -432,7 +434,7 @@ namespace PluralKit.Bot
async Task SetLevel(GroupPrivacySubject subject, PrivacyLevel level)
{
await _db.Execute(c => c.UpdateGroup(target.Id, new GroupPatch().WithPrivacy(subject, level)));
await _db.Execute(c => _repo.UpdateGroup(c, target.Id, new GroupPatch().WithPrivacy(subject, level)));
var subjectName = subject switch
{
@@ -475,17 +477,17 @@ namespace PluralKit.Bot
if (!await ctx.ConfirmWithReply(target.Hid))
throw new PKError($"Group deletion cancelled. Note that you must reply with your group ID (`{target.Hid}`) *verbatim*.");
await _db.Execute(conn => conn.DeleteGroup(target.Id));
await _db.Execute(conn => _repo.DeleteGroup(conn, target.Id));
await ctx.Reply($"{Emojis.Success} Group deleted.");
}
private static async Task<PKSystem> GetGroupSystem(Context ctx, PKGroup target, IPKConnection conn)
private async Task<PKSystem> GetGroupSystem(Context ctx, PKGroup target, IPKConnection conn)
{
var system = ctx.System;
if (system?.Id == target.System)
return system;
return await conn.QuerySystem(target.System)!;
return await _repo.GetSystem(conn, target.System)!;
}
}
}

View File

@@ -15,7 +15,7 @@ namespace PluralKit.Bot
{
public class ImportExport
{
private DataFileService _dataFiles;
private readonly DataFileService _dataFiles;
public ImportExport(DataFileService dataFiles)
{
_dataFiles = dataFiles;

View File

@@ -8,15 +8,15 @@ namespace PluralKit.Bot
{
public class Member
{
private IDataStore _data;
private IDatabase _db;
private EmbedService _embeds;
private readonly IDatabase _db;
private readonly ModelRepository _repo;
private readonly EmbedService _embeds;
public Member(IDataStore data, EmbedService embeds, IDatabase db)
public Member(EmbedService embeds, IDatabase db, ModelRepository repo)
{
_data = data;
_embeds = embeds;
_db = db;
_repo = repo;
}
public async Task NewMember(Context ctx) {
@@ -27,7 +27,7 @@ namespace PluralKit.Bot
if (memberName.Length > Limits.MaxMemberNameLength) throw Errors.MemberNameTooLongError(memberName.Length);
// Warn if there's already a member by this name
var existingMember = await _data.GetMemberByName(ctx.System, memberName);
var existingMember = await _db.Execute(c => _repo.GetMemberByName(c, ctx.System.Id, memberName));
if (existingMember != null) {
var msg = $"{Emojis.Warn} You already have a member in your system with the name \"{existingMember.NameFor(ctx)}\" (with ID `{existingMember.Hid}`). Do you want to create another member with the same name?";
if (!await ctx.PromptYesNo(msg)) throw new PKError("Member creation cancelled.");
@@ -36,12 +36,12 @@ namespace PluralKit.Bot
await using var conn = await _db.Obtain();
// Enforce per-system member limit
var memberCount = await conn.GetSystemMemberCount(ctx.System.Id);
var memberCount = await _repo.GetSystemMemberCount(conn, ctx.System.Id);
if (memberCount >= Limits.MaxMemberCount)
throw Errors.MemberLimitReachedError;
// Create the member
var member = await conn.CreateMember(ctx.System.Id, memberName);
var member = await _repo.CreateMember(conn, ctx.System.Id, memberName);
memberCount++;
// Send confirmation and space hint
@@ -62,10 +62,14 @@ namespace PluralKit.Bot
//Maybe move this somewhere else in the file structure since it doesn't need to get created at every command
// TODO: don't buffer these, find something else to do ig
List<PKMember> members;
if (ctx.MatchFlag("all", "a")) members = await _data.GetSystemMembers(ctx.System).ToListAsync();
else members = await _data.GetSystemMembers(ctx.System).Where(m => m.MemberVisibility == PrivacyLevel.Public).ToListAsync();
var members = await _db.Execute(c =>
{
if (ctx.MatchFlag("all", "a"))
return _repo.GetSystemMembers(c, ctx.System.Id);
return _repo.GetSystemMembers(c, ctx.System.Id)
.Where(m => m.MemberVisibility == PrivacyLevel.Public);
}).ToListAsync();
if (members == null || !members.Any())
throw Errors.NoMembersError;
@@ -75,8 +79,7 @@ namespace PluralKit.Bot
public async Task ViewMember(Context ctx, PKMember target)
{
var system = await _db.Execute(c => c.QuerySystem(target.System));
var system = await _db.Execute(c => _repo.GetSystem(c, target.System));
await ctx.Reply(embed: await _embeds.CreateMemberEmbed(system, target, ctx.Guild, ctx.LookupContextFor(system)));
}
}

View File

@@ -11,10 +11,12 @@ namespace PluralKit.Bot
public class MemberAvatar
{
private readonly IDatabase _db;
private readonly ModelRepository _repo;
public MemberAvatar(IDatabase db)
public MemberAvatar(IDatabase db, ModelRepository repo)
{
_db = db;
_repo = repo;
}
private async Task AvatarClear(AvatarLocation location, Context ctx, PKMember target, MemberGuildSettings? mgs)
@@ -67,14 +69,14 @@ namespace PluralKit.Bot
public async Task ServerAvatar(Context ctx, PKMember target)
{
ctx.CheckGuildContext();
var guildData = await _db.Execute(c => c.QueryOrInsertMemberGuildConfig(ctx.Guild.Id, target.Id));
var guildData = await _db.Execute(c => _repo.GetMemberGuild(c, ctx.Guild.Id, target.Id));
await AvatarCommandTree(AvatarLocation.Server, ctx, target, guildData);
}
public async Task Avatar(Context ctx, PKMember target)
{
var guildData = ctx.Guild != null ?
await _db.Execute(c => c.QueryOrInsertMemberGuildConfig(ctx.Guild.Id, target.Id))
await _db.Execute(c => _repo.GetMemberGuild(c, ctx.Guild.Id, target.Id))
: null;
await AvatarCommandTree(AvatarLocation.Member, ctx, target, guildData);
@@ -150,10 +152,10 @@ namespace PluralKit.Bot
{
case AvatarLocation.Server:
var serverPatch = new MemberGuildPatch { AvatarUrl = url };
return _db.Execute(c => c.UpsertMemberGuild(target.Id, ctx.Guild.Id, serverPatch));
return _db.Execute(c => _repo.UpsertMemberGuild(c, target.Id, ctx.Guild.Id, serverPatch));
case AvatarLocation.Member:
var memberPatch = new MemberPatch { AvatarUrl = url };
return _db.Execute(c => c.UpdateMember(target.Id, memberPatch));
return _db.Execute(c => _repo.UpdateMember(c, target.Id, memberPatch));
default:
throw new ArgumentOutOfRangeException($"Unknown avatar location {location}");
}

View File

@@ -15,13 +15,13 @@ namespace PluralKit.Bot
{
public class MemberEdit
{
private readonly IDataStore _data;
private readonly IDatabase _db;
private readonly ModelRepository _repo;
public MemberEdit(IDataStore data, IDatabase db)
public MemberEdit(IDatabase db, ModelRepository repo)
{
_data = data;
_db = db;
_repo = repo;
}
public async Task Name(Context ctx, PKMember target) {
@@ -35,7 +35,7 @@ namespace PluralKit.Bot
if (newName.Length > Limits.MaxMemberNameLength) throw Errors.MemberNameTooLongError(newName.Length);
// Warn if there's already a member by this name
var existingMember = await _data.GetMemberByName(ctx.System, newName);
var existingMember = await _db.Execute(conn => _repo.GetMemberByName(conn, ctx.System.Id, newName));
if (existingMember != null && existingMember.Id != target.Id)
{
var msg = $"{Emojis.Warn} You already have a member in your system with the name \"{existingMember.NameFor(ctx)}\" (`{existingMember.Hid}`). Do you want to rename this member to that name too?";
@@ -44,7 +44,7 @@ namespace PluralKit.Bot
// Rename the member
var patch = new MemberPatch {Name = Partial<string>.Present(newName)};
await _db.Execute(conn => conn.UpdateMember(target.Id, patch));
await _db.Execute(conn => _repo.UpdateMember(conn, target.Id, patch));
await ctx.Reply($"{Emojis.Success} Member renamed.");
if (newName.Contains(" ")) await ctx.Reply($"{Emojis.Note} Note that this member's name now contains spaces. You will need to surround it with \"double quotes\" when using commands referring to it.");
@@ -52,7 +52,7 @@ namespace PluralKit.Bot
if (ctx.Guild != null)
{
var memberGuildConfig = await _db.Execute(c => c.QueryOrInsertMemberGuildConfig(ctx.Guild.Id, target.Id));
var memberGuildConfig = await _db.Execute(c => _repo.GetMemberGuild(c, ctx.Guild.Id, target.Id));
if (memberGuildConfig.DisplayName != null)
await ctx.Reply($"{Emojis.Note} Note that this member has a server name set ({memberGuildConfig.DisplayName}) in this server ({ctx.Guild.Name}), and will be proxied using that name here.");
}
@@ -69,7 +69,7 @@ namespace PluralKit.Bot
CheckEditMemberPermission(ctx, target);
var patch = new MemberPatch {Description = Partial<string>.Null()};
await _db.Execute(conn => conn.UpdateMember(target.Id, patch));
await _db.Execute(conn => _repo.UpdateMember(conn, target.Id, patch));
await ctx.Reply($"{Emojis.Success} Member description cleared.");
}
else if (!ctx.HasNext())
@@ -100,7 +100,7 @@ namespace PluralKit.Bot
throw Errors.DescriptionTooLongError(description.Length);
var patch = new MemberPatch {Description = Partial<string>.Present(description)};
await _db.Execute(conn => conn.UpdateMember(target.Id, patch));
await _db.Execute(conn => _repo.UpdateMember(conn, target.Id, patch));
await ctx.Reply($"{Emojis.Success} Member description changed.");
}
@@ -111,7 +111,7 @@ namespace PluralKit.Bot
{
CheckEditMemberPermission(ctx, target);
var patch = new MemberPatch {Pronouns = Partial<string>.Null()};
await _db.Execute(conn => conn.UpdateMember(target.Id, patch));
await _db.Execute(conn => _repo.UpdateMember(conn, target.Id, patch));
await ctx.Reply($"{Emojis.Success} Member pronouns cleared.");
}
else if (!ctx.HasNext())
@@ -136,7 +136,7 @@ namespace PluralKit.Bot
throw Errors.MemberPronounsTooLongError(pronouns.Length);
var patch = new MemberPatch {Pronouns = Partial<string>.Present(pronouns)};
await _db.Execute(conn => conn.UpdateMember(target.Id, patch));
await _db.Execute(conn => _repo.UpdateMember(conn, target.Id, patch));
await ctx.Reply($"{Emojis.Success} Member pronouns changed.");
}
@@ -150,7 +150,7 @@ namespace PluralKit.Bot
CheckEditMemberPermission(ctx, target);
var patch = new MemberPatch {Color = Partial<string>.Null()};
await _db.Execute(conn => conn.UpdateMember(target.Id, patch));
await _db.Execute(conn => _repo.UpdateMember(conn, target.Id, patch));
await ctx.Reply($"{Emojis.Success} Member color cleared.");
}
@@ -182,7 +182,7 @@ namespace PluralKit.Bot
if (!Regex.IsMatch(color, "^[0-9a-fA-F]{6}$")) throw Errors.InvalidColorError(color);
var patch = new MemberPatch {Color = Partial<string>.Present(color.ToLowerInvariant())};
await _db.Execute(conn => conn.UpdateMember(target.Id, patch));
await _db.Execute(conn => _repo.UpdateMember(conn, target.Id, patch));
await ctx.Reply(embed: new DiscordEmbedBuilder()
.WithTitle($"{Emojis.Success} Member color changed.")
@@ -198,7 +198,7 @@ namespace PluralKit.Bot
CheckEditMemberPermission(ctx, target);
var patch = new MemberPatch {Birthday = Partial<LocalDate?>.Null()};
await _db.Execute(conn => conn.UpdateMember(target.Id, patch));
await _db.Execute(conn => _repo.UpdateMember(conn, target.Id, patch));
await ctx.Reply($"{Emojis.Success} Member birthdate cleared.");
}
@@ -223,7 +223,7 @@ namespace PluralKit.Bot
if (birthday == null) throw Errors.BirthdayParseError(birthdayStr);
var patch = new MemberPatch {Birthday = Partial<LocalDate?>.Present(birthday)};
await _db.Execute(conn => conn.UpdateMember(target.Id, patch));
await _db.Execute(conn => _repo.UpdateMember(conn, target.Id, patch));
await ctx.Reply($"{Emojis.Success} Member birthdate changed.");
}
@@ -235,7 +235,7 @@ namespace PluralKit.Bot
MemberGuildSettings memberGuildConfig = null;
if (ctx.Guild != null)
memberGuildConfig = await _db.Execute(c => c.QueryOrInsertMemberGuildConfig(ctx.Guild.Id, target.Id));
memberGuildConfig = await _db.Execute(c => _repo.GetMemberGuild(c, ctx.Guild.Id, target.Id));
var eb = new DiscordEmbedBuilder().WithTitle($"Member names")
.WithFooter($"Member ID: {target.Hid} | Active name in bold. Server name overrides display name, which overrides base name.");
@@ -271,7 +271,7 @@ namespace PluralKit.Bot
var successStr = text;
if (ctx.Guild != null)
{
var memberGuildConfig = await _db.Execute(c => c.QueryOrInsertMemberGuildConfig(ctx.Guild.Id, target.Id));
var memberGuildConfig = await _db.Execute(c => _repo.GetMemberGuild(c, ctx.Guild.Id, target.Id));
if (memberGuildConfig.DisplayName != null)
successStr += $" However, this member has a server name set in this server ({ctx.Guild.Name}), and will be proxied using that name, \"{memberGuildConfig.DisplayName}\", here.";
}
@@ -284,7 +284,7 @@ namespace PluralKit.Bot
CheckEditMemberPermission(ctx, target);
var patch = new MemberPatch {DisplayName = Partial<string>.Null()};
await _db.Execute(conn => conn.UpdateMember(target.Id, patch));
await _db.Execute(conn => _repo.UpdateMember(conn, target.Id, patch));
await PrintSuccess($"{Emojis.Success} Member display name cleared. This member will now be proxied using their member name \"{target.NameFor(ctx)}\".");
}
@@ -303,7 +303,7 @@ namespace PluralKit.Bot
var newDisplayName = ctx.RemainderOrNull();
var patch = new MemberPatch {DisplayName = Partial<string>.Present(newDisplayName)};
await _db.Execute(conn => conn.UpdateMember(target.Id, patch));
await _db.Execute(conn => _repo.UpdateMember(conn, target.Id, patch));
await PrintSuccess($"{Emojis.Success} Member display name changed. This member will now be proxied using the name \"{newDisplayName}\".");
}
@@ -318,7 +318,7 @@ namespace PluralKit.Bot
CheckEditMemberPermission(ctx, target);
var patch = new MemberGuildPatch {DisplayName = null};
await _db.Execute(conn => conn.UpsertMemberGuild(target.Id, ctx.Guild.Id, patch));
await _db.Execute(conn => _repo.UpsertMemberGuild(conn, target.Id, ctx.Guild.Id, patch));
if (target.DisplayName != null)
await ctx.Reply($"{Emojis.Success} Member server name cleared. This member will now be proxied using their global display name \"{target.DisplayName}\" in this server ({ctx.Guild.Name}).");
@@ -340,7 +340,7 @@ namespace PluralKit.Bot
var newServerName = ctx.RemainderOrNull();
var patch = new MemberGuildPatch {DisplayName = newServerName};
await _db.Execute(conn => conn.UpsertMemberGuild(target.Id, ctx.Guild.Id, patch));
await _db.Execute(conn => _repo.UpsertMemberGuild(conn, target.Id, ctx.Guild.Id, patch));
await ctx.Reply($"{Emojis.Success} Member server name changed. This member will now be proxied using the name \"{newServerName}\" in this server ({ctx.Guild.Name}).");
}
@@ -365,7 +365,7 @@ namespace PluralKit.Bot
};
var patch = new MemberPatch {KeepProxy = Partial<bool>.Present(newValue)};
await _db.Execute(conn => conn.UpdateMember(target.Id, patch));
await _db.Execute(conn => _repo.UpdateMember(conn, target.Id, patch));
if (newValue)
await ctx.Reply($"{Emojis.Success} Member proxy tags will now be included in the resulting message when proxying.");
@@ -398,11 +398,11 @@ namespace PluralKit.Bot
// Get guild settings (mostly for warnings and such)
MemberGuildSettings guildSettings = null;
if (ctx.Guild != null)
guildSettings = await _db.Execute(c => c.QueryOrInsertMemberGuildConfig(ctx.Guild.Id, target.Id));
guildSettings = await _db.Execute(c => _repo.GetMemberGuild(c, ctx.Guild.Id, target.Id));
async Task SetAll(PrivacyLevel level)
{
await _db.Execute(c => c.UpdateMember(target.Id, new MemberPatch().WithAllPrivacy(level)));
await _db.Execute(c => _repo.UpdateMember(c, target.Id, new MemberPatch().WithAllPrivacy(level)));
if (level == PrivacyLevel.Private)
await ctx.Reply($"{Emojis.Success} All {target.NameFor(ctx)}'s privacy settings have been set to **{level.LevelName()}**. Other accounts will now see nothing on the member card.");
@@ -412,7 +412,7 @@ namespace PluralKit.Bot
async Task SetLevel(MemberPrivacySubject subject, PrivacyLevel level)
{
await _db.Execute(c => c.UpdateMember(target.Id, new MemberPatch().WithPrivacy(subject, level)));
await _db.Execute(c => _repo.UpdateMember(c, target.Id, new MemberPatch().WithPrivacy(subject, level)));
var subjectName = subject switch
{
@@ -472,7 +472,7 @@ namespace PluralKit.Bot
await ctx.Reply($"{Emojis.Warn} Are you sure you want to delete \"{target.NameFor(ctx)}\"? If so, reply to this message with the member's ID (`{target.Hid}`). __***This cannot be undone!***__");
if (!await ctx.ConfirmWithReply(target.Hid)) throw Errors.MemberDeleteCancelled;
await _db.Execute(conn => conn.DeleteMember(target.Id));
await _db.Execute(conn => _repo.DeleteMember(conn, target.Id));
await ctx.Reply($"{Emojis.Success} Member deleted.");
}

View File

@@ -10,10 +10,12 @@ namespace PluralKit.Bot
public class MemberProxy
{
private readonly IDatabase _db;
private readonly ModelRepository _repo;
public MemberProxy(IDatabase db)
public MemberProxy(IDatabase db, ModelRepository repo)
{
_db = db;
_repo = repo;
}
public async Task Proxy(Context ctx, PKMember target)
@@ -55,7 +57,7 @@ namespace PluralKit.Bot
}
var patch = new MemberPatch {ProxyTags = Partial<ProxyTag[]>.Present(new ProxyTag[0])};
await _db.Execute(conn => conn.UpdateMember(target.Id, patch));
await _db.Execute(conn => _repo.UpdateMember(conn, target.Id, patch));
await ctx.Reply($"{Emojis.Success} Proxy tags cleared.");
}
@@ -83,7 +85,7 @@ namespace PluralKit.Bot
var newTags = target.ProxyTags.ToList();
newTags.Add(tagToAdd);
var patch = new MemberPatch {ProxyTags = Partial<ProxyTag[]>.Present(newTags.ToArray())};
await _db.Execute(conn => conn.UpdateMember(target.Id, patch));
await _db.Execute(conn => _repo.UpdateMember(conn, target.Id, patch));
await ctx.Reply($"{Emojis.Success} Added proxy tags {tagToAdd.ProxyString.AsCode()}.");
}
@@ -100,7 +102,7 @@ namespace PluralKit.Bot
var newTags = target.ProxyTags.ToList();
newTags.Remove(tagToRemove);
var patch = new MemberPatch {ProxyTags = Partial<ProxyTag[]>.Present(newTags.ToArray())};
await _db.Execute(conn => conn.UpdateMember(target.Id, patch));
await _db.Execute(conn => _repo.UpdateMember(conn, target.Id, patch));
await ctx.Reply($"{Emojis.Success} Removed proxy tags {tagToRemove.ProxyString.AsCode()}.");
}
@@ -124,7 +126,7 @@ namespace PluralKit.Bot
var newTags = new[] {requestedTag};
var patch = new MemberPatch {ProxyTags = Partial<ProxyTag[]>.Present(newTags)};
await _db.Execute(conn => conn.UpdateMember(target.Id, patch));
await _db.Execute(conn => _repo.UpdateMember(conn, target.Id, patch));
await ctx.Reply($"{Emojis.Success} Member proxy tags set to {requestedTag.ProxyString.AsCode()}.");
}

View File

@@ -18,21 +18,23 @@ using DSharpPlus.Entities;
namespace PluralKit.Bot {
public class Misc
{
private BotConfig _botConfig;
private IMetrics _metrics;
private CpuStatService _cpu;
private ShardInfoService _shards;
private IDataStore _data;
private EmbedService _embeds;
private readonly BotConfig _botConfig;
private readonly IMetrics _metrics;
private readonly CpuStatService _cpu;
private readonly ShardInfoService _shards;
private readonly EmbedService _embeds;
private readonly IDatabase _db;
private readonly ModelRepository _repo;
public Misc(BotConfig botConfig, IMetrics metrics, CpuStatService cpu, ShardInfoService shards, IDataStore data, EmbedService embeds)
public Misc(BotConfig botConfig, IMetrics metrics, CpuStatService cpu, ShardInfoService shards, EmbedService embeds, ModelRepository repo, IDatabase db)
{
_botConfig = botConfig;
_metrics = metrics;
_cpu = cpu;
_shards = shards;
_data = data;
_embeds = embeds;
_repo = repo;
_db = db;
}
public async Task Invite(Context ctx)
@@ -198,7 +200,7 @@ namespace PluralKit.Bot {
messageId = ulong.Parse(match.Groups[1].Value);
else throw new PKSyntaxError($"Could not parse {word.AsCode()} as a message ID or link.");
var message = await _data.GetMessage(messageId);
var message = await _db.Execute(c => _repo.GetMessage(c, messageId));
if (message == null) throw Errors.MessageNotFound(messageId);
await ctx.Reply(embed: await _embeds.CreateMessageInfoEmbed(ctx.Shard, message));

View File

@@ -12,12 +12,14 @@ namespace PluralKit.Bot
{
public class ServerConfig
{
private IDatabase _db;
private LoggerCleanService _cleanService;
public ServerConfig(LoggerCleanService cleanService, IDatabase db)
private readonly IDatabase _db;
private readonly ModelRepository _repo;
private readonly LoggerCleanService _cleanService;
public ServerConfig(LoggerCleanService cleanService, IDatabase db, ModelRepository repo)
{
_cleanService = cleanService;
_db = db;
_repo = repo;
}
public async Task SetLogChannel(Context ctx)
@@ -32,7 +34,7 @@ namespace PluralKit.Bot
if (channel == null || channel.GuildId != ctx.Guild.Id) throw Errors.ChannelNotFound(channelString);
var patch = new GuildPatch {LogChannel = channel?.Id};
await _db.Execute(conn => conn.UpsertGuild(ctx.Guild.Id, patch));
await _db.Execute(conn => _repo.UpsertGuild(conn, ctx.Guild.Id, patch));
if (channel != null)
await ctx.Reply($"{Emojis.Success} Proxy logging channel set to #{channel.Name}.");
@@ -59,7 +61,7 @@ namespace PluralKit.Bot
ulong? logChannel = null;
await using (var conn = await _db.Obtain())
{
var config = await conn.QueryOrInsertGuildConfig(ctx.Guild.Id);
var config = await _repo.GetGuild(conn, ctx.Guild.Id);
logChannel = config.LogChannel;
var blacklist = config.LogBlacklist.ToHashSet();
if (enable)
@@ -68,7 +70,7 @@ namespace PluralKit.Bot
blacklist.UnionWith(affectedChannels.Select(c => c.Id));
var patch = new GuildPatch {LogBlacklist = blacklist.ToArray()};
await conn.UpsertGuild(ctx.Guild.Id, patch);
await _repo.UpsertGuild(conn, ctx.Guild.Id, patch);
}
await ctx.Reply(
@@ -80,7 +82,7 @@ namespace PluralKit.Bot
{
ctx.CheckGuildContext().CheckAuthorPermission(Permissions.ManageGuild, "Manage Server");
var blacklist = await _db.Execute(c => c.QueryOrInsertGuildConfig(ctx.Guild.Id));
var blacklist = await _db.Execute(c => _repo.GetGuild(c, ctx.Guild.Id));
// Resolve all channels from the cache and order by position
var channels = blacklist.Blacklist
@@ -139,7 +141,7 @@ namespace PluralKit.Bot
await using (var conn = await _db.Obtain())
{
var guild = await conn.QueryOrInsertGuildConfig(ctx.Guild.Id);
var guild = await _repo.GetGuild(conn, ctx.Guild.Id);
var blacklist = guild.Blacklist.ToHashSet();
if (shouldAdd)
blacklist.UnionWith(affectedChannels.Select(c => c.Id));
@@ -147,7 +149,7 @@ namespace PluralKit.Bot
blacklist.ExceptWith(affectedChannels.Select(c => c.Id));
var patch = new GuildPatch {Blacklist = blacklist.ToArray()};
await conn.UpsertGuild(ctx.Guild.Id, patch);
await _repo.UpsertGuild(conn, ctx.Guild.Id, patch);
}
await ctx.Reply($"{Emojis.Success} Channels {(shouldAdd ? "added to" : "removed from")} the proxy blacklist.");
@@ -170,7 +172,7 @@ namespace PluralKit.Bot
.WithTitle("Log cleanup settings")
.AddField("Supported bots", botList);
var guildCfg = await _db.Execute(c => c.QueryOrInsertGuildConfig(ctx.Guild.Id));
var guildCfg = await _db.Execute(c => _repo.GetGuild(c, ctx.Guild.Id));
if (guildCfg.LogCleanupEnabled)
eb.WithDescription("Log cleanup is currently **on** for this server. To disable it, type `pk;logclean off`.");
else
@@ -180,7 +182,7 @@ namespace PluralKit.Bot
}
var patch = new GuildPatch {LogCleanupEnabled = newValue};
await _db.Execute(conn => conn.UpsertGuild(ctx.Guild.Id, patch));
await _db.Execute(conn => _repo.UpsertGuild(conn, ctx.Guild.Id, patch));
if (newValue)
await ctx.Reply($"{Emojis.Success} Log cleanup has been **enabled** for this server. Messages deleted by PluralKit will now be cleaned up from logging channels managed by the following bots:\n- **{botList}**\n\n{Emojis.Note} Make sure PluralKit has the **Manage Messages** permission in the channels in question.\n{Emojis.Note} Also, make sure to blacklist the logging channel itself from the bots in question to prevent conflicts.");

View File

@@ -13,11 +13,13 @@ namespace PluralKit.Bot
{
public class Switch
{
private IDataStore _data;
private readonly IDatabase _db;
private readonly ModelRepository _repo;
public Switch(IDataStore data)
public Switch(IDatabase db, ModelRepository repo)
{
_data = data;
_db = db;
_repo = repo;
}
public async Task SwitchDo(Context ctx)
@@ -42,16 +44,17 @@ namespace PluralKit.Bot
if (members.Select(m => m.Id).Distinct().Count() != members.Count) throw Errors.DuplicateSwitchMembers;
// Find the last switch and its members if applicable
var lastSwitch = await _data.GetLatestSwitch(ctx.System.Id);
await using var conn = await _db.Obtain();
var lastSwitch = await _repo.GetLatestSwitch(conn, ctx.System.Id);
if (lastSwitch != null)
{
var lastSwitchMembers = _data.GetSwitchMembers(lastSwitch);
var lastSwitchMembers = _repo.GetSwitchMembers(conn, lastSwitch.Id);
// Make sure the requested switch isn't identical to the last one
if (await lastSwitchMembers.Select(m => m.Id).SequenceEqualAsync(members.Select(m => m.Id).ToAsyncEnumerable()))
throw Errors.SameSwitch(members, ctx.LookupContextFor(ctx.System));
}
await _data.AddSwitch(ctx.System.Id, members);
await _repo.AddSwitch(conn, ctx.System.Id, members.Select(m => m.Id).ToList());
if (members.Count == 0)
await ctx.Reply($"{Emojis.Success} Switch-out registered.");
@@ -68,12 +71,14 @@ namespace PluralKit.Bot
var result = DateUtils.ParseDateTime(timeToMove, true, tz);
if (result == null) throw Errors.InvalidDateTime(timeToMove);
await using var conn = await _db.Obtain();
var time = result.Value;
if (time.ToInstant() > SystemClock.Instance.GetCurrentInstant()) throw Errors.SwitchTimeInFuture;
// Fetch the last two switches for the system to do bounds checking on
var lastTwoSwitches = await _data.GetSwitches(ctx.System.Id).Take(2).ToListAsync();
var lastTwoSwitches = await _repo.GetSwitches(conn, ctx.System.Id).Take(2).ToListAsync();
// If we don't have a switch to move, don't bother
if (lastTwoSwitches.Count == 0) throw Errors.NoRegisteredSwitches;
@@ -87,7 +92,7 @@ namespace PluralKit.Bot
// Now we can actually do the move, yay!
// But, we do a prompt to confirm.
var lastSwitchMembers = _data.GetSwitchMembers(lastTwoSwitches[0]);
var lastSwitchMembers = _repo.GetSwitchMembers(conn, lastTwoSwitches[0].Id);
var lastSwitchMemberStr = string.Join(", ", await lastSwitchMembers.Select(m => m.NameFor(ctx)).ToListAsync());
var lastSwitchTimeStr = lastTwoSwitches[0].Timestamp.FormatZoned(ctx.System);
var lastSwitchDeltaStr = (SystemClock.Instance.GetCurrentInstant() - lastTwoSwitches[0].Timestamp).FormatDuration();
@@ -99,7 +104,7 @@ namespace PluralKit.Bot
if (!await ctx.PromptYesNo(msg)) throw Errors.SwitchMoveCancelled;
// aaaand *now* we do the move
await _data.MoveSwitch(lastTwoSwitches[0], time.ToInstant());
await _repo.MoveSwitch(conn, lastTwoSwitches[0].Id, time.ToInstant());
await ctx.Reply($"{Emojis.Success} Switch moved.");
}
@@ -113,16 +118,18 @@ namespace PluralKit.Bot
var purgeMsg = $"{Emojis.Warn} This will delete *all registered switches* in your system. Are you sure you want to proceed?";
if (!await ctx.PromptYesNo(purgeMsg))
throw Errors.GenericCancelled();
await _data.DeleteAllSwitches(ctx.System);
await _db.Execute(c => _repo.DeleteAllSwitches(c, ctx.System.Id));
await ctx.Reply($"{Emojis.Success} Cleared system switches!");
return;
}
await using var conn = await _db.Obtain();
// Fetch the last two switches for the system to do bounds checking on
var lastTwoSwitches = await _data.GetSwitches(ctx.System.Id).Take(2).ToListAsync();
var lastTwoSwitches = await _repo.GetSwitches(conn, ctx.System.Id).Take(2).ToListAsync();
if (lastTwoSwitches.Count == 0) throw Errors.NoRegisteredSwitches;
var lastSwitchMembers = _data.GetSwitchMembers(lastTwoSwitches[0]);
var lastSwitchMembers = _repo.GetSwitchMembers(conn, lastTwoSwitches[0].Id);
var lastSwitchMemberStr = string.Join(", ", await lastSwitchMembers.Select(m => m.NameFor(ctx)).ToListAsync());
var lastSwitchDeltaStr = (SystemClock.Instance.GetCurrentInstant() - lastTwoSwitches[0].Timestamp).FormatDuration();
@@ -133,14 +140,14 @@ namespace PluralKit.Bot
}
else
{
var secondSwitchMembers = _data.GetSwitchMembers(lastTwoSwitches[1]);
var secondSwitchMembers = _repo.GetSwitchMembers(conn, lastTwoSwitches[1].Id);
var secondSwitchMemberStr = string.Join(", ", await secondSwitchMembers.Select(m => m.NameFor(ctx)).ToListAsync());
var secondSwitchDeltaStr = (SystemClock.Instance.GetCurrentInstant() - lastTwoSwitches[1].Timestamp).FormatDuration();
msg = $"{Emojis.Warn} This will delete the latest switch ({lastSwitchMemberStr}, {lastSwitchDeltaStr} ago). The next latest switch is {secondSwitchMemberStr} ({secondSwitchDeltaStr} ago). Is this okay?";
}
if (!await ctx.PromptYesNo(msg)) throw Errors.SwitchDeleteCancelled;
await _data.DeleteSwitch(lastTwoSwitches[0]);
await _repo.DeleteSwitch(conn, lastTwoSwitches[0].Id);
await ctx.Reply($"{Emojis.Success} Switch deleted.");
}

View File

@@ -6,13 +6,15 @@ namespace PluralKit.Bot
{
public class System
{
private IDataStore _data;
private EmbedService _embeds;
private readonly EmbedService _embeds;
private readonly IDatabase _db;
private readonly ModelRepository _repo;
public System(EmbedService embeds, IDataStore data)
public System(EmbedService embeds, IDatabase db, ModelRepository repo)
{
_embeds = embeds;
_data = data;
_db = db;
_repo = repo;
}
public async Task Query(Context ctx, PKSystem system) {
@@ -28,9 +30,15 @@ namespace PluralKit.Bot
var systemName = ctx.RemainderOrNull();
if (systemName != null && systemName.Length > Limits.MaxSystemNameLength)
throw Errors.SystemNameTooLongError(systemName.Length);
var system = _db.Execute(async c =>
{
var system = await _repo.CreateSystem(c, systemName);
await _repo.AddAccount(c, system.Id, ctx.Author.Id);
return system;
});
var system = await _data.CreateSystem(systemName);
await _data.AddAccount(system, ctx.Author.Id);
// TODO: better message, perhaps embed like in groups?
await ctx.Reply($"{Emojis.Success} Your system has been created. Type `pk;system` to view it, and type `pk;system help` for more information about commands you can use now. Now that you have that set up, check out the getting started guide on setting up members and proxies: <https://pluralkit.me/start>");
}
}

View File

@@ -19,15 +19,13 @@ namespace PluralKit.Bot
{
public class SystemEdit
{
private IDataStore _data;
private IDatabase _db;
private EmbedService _embeds;
private readonly IDatabase _db;
private readonly ModelRepository _repo;
public SystemEdit(IDataStore data, EmbedService embeds, IDatabase db)
public SystemEdit(IDatabase db, ModelRepository repo)
{
_data = data;
_embeds = embeds;
_db = db;
_repo = repo;
}
public async Task Name(Context ctx)
@@ -37,7 +35,7 @@ namespace PluralKit.Bot
if (ctx.MatchClear())
{
var clearPatch = new SystemPatch {Name = null};
await _db.Execute(conn => conn.UpdateSystem(ctx.System.Id, clearPatch));
await _db.Execute(conn => _repo.UpdateSystem(conn, ctx.System.Id, clearPatch));
await ctx.Reply($"{Emojis.Success} System name cleared.");
return;
@@ -57,7 +55,7 @@ namespace PluralKit.Bot
throw Errors.SystemNameTooLongError(newSystemName.Length);
var patch = new SystemPatch {Name = newSystemName};
await _db.Execute(conn => conn.UpdateSystem(ctx.System.Id, patch));
await _db.Execute(conn => _repo.UpdateSystem(conn, ctx.System.Id, patch));
await ctx.Reply($"{Emojis.Success} System name changed.");
}
@@ -68,7 +66,7 @@ namespace PluralKit.Bot
if (ctx.MatchClear())
{
var patch = new SystemPatch {Description = null};
await _db.Execute(conn => conn.UpdateSystem(ctx.System.Id, patch));
await _db.Execute(conn => _repo.UpdateSystem(conn, ctx.System.Id, patch));
await ctx.Reply($"{Emojis.Success} System description cleared.");
return;
@@ -93,7 +91,7 @@ namespace PluralKit.Bot
if (newDescription.Length > Limits.MaxDescriptionLength) throw Errors.DescriptionTooLongError(newDescription.Length);
var patch = new SystemPatch {Description = newDescription};
await _db.Execute(conn => conn.UpdateSystem(ctx.System.Id, patch));
await _db.Execute(conn => _repo.UpdateSystem(conn, ctx.System.Id, patch));
await ctx.Reply($"{Emojis.Success} System description changed.");
}
@@ -106,7 +104,7 @@ namespace PluralKit.Bot
if (ctx.MatchClear())
{
var patch = new SystemPatch {Tag = null};
await _db.Execute(conn => conn.UpdateSystem(ctx.System.Id, patch));
await _db.Execute(conn => _repo.UpdateSystem(conn, ctx.System.Id, patch));
await ctx.Reply($"{Emojis.Success} System tag cleared.");
} else if (!ctx.HasNext(skipFlags: false))
@@ -124,7 +122,7 @@ namespace PluralKit.Bot
throw Errors.SystemNameTooLongError(newTag.Length);
var patch = new SystemPatch {Tag = newTag};
await _db.Execute(conn => conn.UpdateSystem(ctx.System.Id, patch));
await _db.Execute(conn => _repo.UpdateSystem(conn, ctx.System.Id, patch));
await ctx.Reply($"{Emojis.Success} System tag changed. Member names will now end with {newTag.AsCode()} when proxied.");
}
@@ -136,7 +134,7 @@ namespace PluralKit.Bot
async Task ClearIcon()
{
await _db.Execute(c => c.UpdateSystem(ctx.System.Id, new SystemPatch {AvatarUrl = null}));
await _db.Execute(c => _repo.UpdateSystem(c, ctx.System.Id, new SystemPatch {AvatarUrl = null}));
await ctx.Reply($"{Emojis.Success} System icon cleared.");
}
@@ -146,7 +144,7 @@ namespace PluralKit.Bot
throw Errors.InvalidUrl(img.Url);
await AvatarUtils.VerifyAvatarOrThrow(img.Url);
await _db.Execute(c => c.UpdateSystem(ctx.System.Id, new SystemPatch {AvatarUrl = img.Url}));
await _db.Execute(c => _repo.UpdateSystem(c, ctx.System.Id, new SystemPatch {AvatarUrl = img.Url}));
var msg = img.Source switch
{
@@ -192,7 +190,7 @@ namespace PluralKit.Bot
if (!await ctx.ConfirmWithReply(ctx.System.Hid))
throw new PKError($"System deletion cancelled. Note that you must reply with your system ID (`{ctx.System.Hid}`) *verbatim*.");
await _db.Execute(conn => conn.DeleteSystem(ctx.System.Id));
await _db.Execute(conn => _repo.DeleteSystem(conn, ctx.System.Id));
await ctx.Reply($"{Emojis.Success} System deleted.");
}
@@ -200,7 +198,7 @@ namespace PluralKit.Bot
public async Task SystemProxy(Context ctx)
{
ctx.CheckSystem().CheckGuildContext();
var gs = await _db.Execute(c => c.QueryOrInsertSystemGuildConfig(ctx.Guild.Id, ctx.System.Id));
var gs = await _db.Execute(c => _repo.GetSystemGuild(c, ctx.Guild.Id, ctx.System.Id));
bool newValue;
if (ctx.Match("on", "enabled", "true", "yes")) newValue = true;
@@ -216,7 +214,7 @@ namespace PluralKit.Bot
}
var patch = new SystemGuildPatch {ProxyEnabled = newValue};
await _db.Execute(conn => conn.UpsertSystemGuild(ctx.System.Id, ctx.Guild.Id, patch));
await _db.Execute(conn => _repo.UpsertSystemGuild(conn, ctx.System.Id, ctx.Guild.Id, patch));
if (newValue)
await ctx.Reply($"Message proxying in this server ({ctx.Guild.Name.EscapeMarkdown()}) is now **enabled** for your system.");
@@ -231,7 +229,7 @@ namespace PluralKit.Bot
if (ctx.MatchClear())
{
var clearPatch = new SystemPatch {UiTz = "UTC"};
await _db.Execute(conn => conn.UpdateSystem(ctx.System.Id, clearPatch));
await _db.Execute(conn => _repo.UpdateSystem(conn, ctx.System.Id, clearPatch));
await ctx.Reply($"{Emojis.Success} System time zone cleared (set to UTC).");
return;
@@ -253,7 +251,7 @@ namespace PluralKit.Bot
if (!await ctx.PromptYesNo(msg)) throw Errors.TimezoneChangeCancelled;
var patch = new SystemPatch {UiTz = zone.Id};
await _db.Execute(conn => conn.UpdateSystem(ctx.System.Id, patch));
await _db.Execute(conn => _repo.UpdateSystem(conn, ctx.System.Id, patch));
await ctx.Reply($"System time zone changed to **{zone.Id}**.");
}
@@ -277,7 +275,7 @@ namespace PluralKit.Bot
async Task SetLevel(SystemPrivacySubject subject, PrivacyLevel level)
{
await _db.Execute(conn => conn.UpdateSystem(ctx.System.Id, new SystemPatch().WithPrivacy(subject, level)));
await _db.Execute(conn => _repo.UpdateSystem(conn, ctx.System.Id, new SystemPatch().WithPrivacy(subject, level)));
var levelExplanation = level switch
{
@@ -302,7 +300,7 @@ namespace PluralKit.Bot
async Task SetAll(PrivacyLevel level)
{
await _db.Execute(conn => conn.UpdateSystem(ctx.System.Id, new SystemPatch().WithAllPrivacy(level)));
await _db.Execute(conn => _repo.UpdateSystem(conn, ctx.System.Id, new SystemPatch().WithAllPrivacy(level)));
var msg = level switch
{
@@ -334,13 +332,13 @@ namespace PluralKit.Bot
else {
if (ctx.Match("on", "enable")) {
var patch = new SystemPatch {PingsEnabled = true};
await _db.Execute(conn => conn.UpdateSystem(ctx.System.Id, patch));
await _db.Execute(conn => _repo.UpdateSystem(conn, ctx.System.Id, patch));
await ctx.Reply("Reaction pings have now been enabled.");
}
if (ctx.Match("off", "disable")) {
var patch = new SystemPatch {PingsEnabled = false};
await _db.Execute(conn => conn.UpdateSystem(ctx.System.Id, patch));
await _db.Execute(conn => _repo.UpdateSystem(conn, ctx.System.Id, patch));
await ctx.Reply("Reaction pings have now been disabled.");
}

View File

@@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
@@ -10,19 +11,21 @@ namespace PluralKit.Bot
{
public class SystemFront
{
private IDataStore _data;
private EmbedService _embeds;
private readonly IDatabase _db;
private readonly ModelRepository _repo;
private readonly EmbedService _embeds;
public SystemFront(IDataStore data, EmbedService embeds)
public SystemFront(EmbedService embeds, IDatabase db, ModelRepository repo)
{
_data = data;
_embeds = embeds;
_db = db;
_repo = repo;
}
struct FrontHistoryEntry
{
public Instant? LastTime;
public PKSwitch ThisSwitch;
public readonly Instant? LastTime;
public readonly PKSwitch ThisSwitch;
public FrontHistoryEntry(Instant? lastTime, PKSwitch thisSwitch)
{
@@ -35,8 +38,10 @@ namespace PluralKit.Bot
{
if (system == null) throw Errors.NoSystemError;
ctx.CheckSystemPrivacy(system, system.FrontPrivacy);
await using var conn = await _db.Obtain();
var sw = await _data.GetLatestSwitch(system.Id);
var sw = await _repo.GetLatestSwitch(conn, system.Id);
if (sw == null) throw Errors.NoRegisteredSwitches;
await ctx.Reply(embed: await _embeds.CreateFronterEmbed(sw, system.Zone, ctx.LookupContextFor(system)));
@@ -47,11 +52,16 @@ namespace PluralKit.Bot
if (system == null) throw Errors.NoSystemError;
ctx.CheckSystemPrivacy(system, system.FrontHistoryPrivacy);
var sws = _data.GetSwitches(system.Id)
.Scan(new FrontHistoryEntry(null, null), (lastEntry, newSwitch) => new FrontHistoryEntry(lastEntry.ThisSwitch?.Timestamp, newSwitch));
var totalSwitches = await _data.GetSwitchCount(system);
if (totalSwitches == 0) throw Errors.NoRegisteredSwitches;
// Gotta be careful here: if we dispose of the connection while the IAE is alive, boom
await using var conn = await _db.Obtain();
var totalSwitches = await _repo.GetSwitchCount(conn, system.Id);
if (totalSwitches == 0) throw Errors.NoRegisteredSwitches;
var sws = _repo.GetSwitches(conn, system.Id)
.Scan(new FrontHistoryEntry(null, null),
(lastEntry, newSwitch) => new FrontHistoryEntry(lastEntry.ThisSwitch?.Timestamp, newSwitch));
var embedTitle = system.Name != null ? $"Front history of {system.Name} (`{system.Hid}`)" : $"Front history of `{system.Hid}`";
await ctx.Paginate(
@@ -66,8 +76,11 @@ namespace PluralKit.Bot
var lastSw = entry.LastTime;
var sw = entry.ThisSwitch;
// Fetch member list and format
var members = await _data.GetSwitchMembers(sw).ToListAsync();
await using var conn = await _db.Obtain();
var members = await _db.Execute(c => _repo.GetSwitchMembers(c, sw.Id)).ToListAsync();
var membersStr = members.Any() ? string.Join(", ", members.Select(m => m.NameFor(ctx))) : "no fronter";
var switchSince = SystemClock.Instance.GetCurrentInstant() - sw.Timestamp;
@@ -111,8 +124,8 @@ namespace PluralKit.Bot
var rangeStart = DateUtils.ParseDateTime(durationStr, true, system.Zone);
if (rangeStart == null) throw Errors.InvalidDateTime(durationStr);
if (rangeStart.Value.ToInstant() > now) throw Errors.FrontPercentTimeInFuture;
var frontpercent = await _data.GetFrontBreakdown(system, rangeStart.Value.ToInstant(), now);
var frontpercent = await _db.Execute(c => _repo.GetFrontBreakdown(c, system.Id, rangeStart.Value.ToInstant(), now));
await ctx.Reply(embed: await _embeds.CreateFrontPercentEmbed(frontpercent, system.Zone, ctx.LookupContextFor(system)));
}
}

View File

@@ -9,28 +9,34 @@ namespace PluralKit.Bot
{
public class SystemLink
{
private IDataStore _data;
private readonly IDatabase _db;
private readonly ModelRepository _repo;
public SystemLink(IDataStore data)
public SystemLink(IDatabase db, ModelRepository repo)
{
_data = data;
_db = db;
_repo = repo;
}
public async Task LinkSystem(Context ctx)
{
ctx.CheckSystem();
await using var conn = await _db.Obtain();
var account = await ctx.MatchUser() ?? throw new PKSyntaxError("You must pass an account to link with (either ID or @mention).");
var accountIds = await _data.GetSystemAccounts(ctx.System);
if (accountIds.Contains(account.Id)) throw Errors.AccountAlreadyLinked;
var accountIds = await _repo.GetSystemAccounts(conn, ctx.System.Id);
if (accountIds.Contains(account.Id))
throw Errors.AccountAlreadyLinked;
var existingAccount = await _data.GetSystemByAccount(account.Id);
if (existingAccount != null) throw Errors.AccountInOtherSystem(existingAccount);
var existingAccount = await _repo.GetSystemByAccount(conn, account.Id);
if (existingAccount != null)
throw Errors.AccountInOtherSystem(existingAccount);
var msg = $"{account.Mention}, please confirm the link by clicking the {Emojis.Success} reaction on this message.";
var mentions = new IMention[] { new UserMention(account) };
if (!await ctx.PromptYesNo(msg, user: account, mentions: mentions)) throw Errors.MemberLinkCancelled;
await _data.AddAccount(ctx.System, account.Id);
await _repo.AddAccount(conn, ctx.System.Id, account.Id);
await ctx.Reply($"{Emojis.Success} Account linked to system.");
}
@@ -38,20 +44,22 @@ namespace PluralKit.Bot
{
ctx.CheckSystem();
await using var conn = await _db.Obtain();
ulong id;
if (!ctx.HasNext())
id = ctx.Author.Id;
else if (!ctx.MatchUserRaw(out id))
throw new PKSyntaxError("You must pass an account to link with (either ID or @mention).");
var accountIds = (await _data.GetSystemAccounts(ctx.System)).ToList();
var accountIds = (await _repo.GetSystemAccounts(conn, ctx.System.Id)).ToList();
if (!accountIds.Contains(id)) throw Errors.AccountNotLinked;
if (accountIds.Count == 1) throw Errors.UnlinkingLastAccount;
var msg = $"Are you sure you want to unlink <@{id}> from your system?";
if (!await ctx.PromptYesNo(msg)) throw Errors.MemberUnlinkCancelled;
await _data.RemoveAccount(ctx.System, id);
await _repo.RemoveAccount(conn, ctx.System.Id, id);
await ctx.Reply($"{Emojis.Success} Account unlinked.");
}
}

View File

@@ -10,9 +10,11 @@ namespace PluralKit.Bot
public class Token
{
private readonly IDatabase _db;
public Token(IDatabase db)
private readonly ModelRepository _repo;
public Token(IDatabase db, ModelRepository repo)
{
_db = db;
_repo = repo;
}
public async Task GetToken(Context ctx)
@@ -45,7 +47,7 @@ namespace PluralKit.Bot
private async Task<string> MakeAndSetNewToken(PKSystem system)
{
var patch = new SystemPatch {Token = StringUtils.GenerateToken()};
system = await _db.Execute(conn => conn.UpdateSystem(system.Id, patch));
system = await _db.Execute(conn => _repo.UpdateSystem(conn, system.Id, patch));
return system.Token;
}