refactor: add SqlKata for SQL generation, move connection handling into ModelRepository

This commit is contained in:
spiral 2021-09-29 21:51:38 -04:00
parent 6251d29abb
commit 92e45a07ff
No known key found for this signature in database
GPG key ID: A6059F0CA0E1BD31
60 changed files with 806 additions and 640 deletions

View file

@ -31,14 +31,14 @@ namespace PluralKit.Bot
if (!Regex.IsMatch(newHid, "^[a-z]{5}$"))
throw new PKError($"Invalid new system ID `{newHid}`.");
var existingSystem = await _db.Execute(c => _repo.GetSystemByHid(c, newHid));
var existingSystem = _repo.GetSystemByHid(newHid);
if (existingSystem != null)
throw new PKError($"Another system already exists with ID `{newHid}`.");
if (!await ctx.PromptYesNo($"Change system ID of `{target.Hid}` to `{newHid}`?", "Change"))
throw new PKError("ID change cancelled.");
await _db.Execute(c => _repo.UpdateSystem(c, target.Id, new SystemPatch { Hid = newHid }));
await _repo.UpdateSystem(target.Id, new() { Hid = newHid });
await ctx.Reply($"{Emojis.Success} System ID updated (`{target.Hid}` -> `{newHid}`).");
}
@ -54,14 +54,14 @@ namespace PluralKit.Bot
if (!Regex.IsMatch(newHid, "^[a-z]{5}$"))
throw new PKError($"Invalid new member ID `{newHid}`.");
var existingMember = await _db.Execute(c => _repo.GetMemberByHid(c, newHid));
var existingMember = await _repo.GetMemberByHid(newHid);
if (existingMember != null)
throw new PKError($"Another member already exists with ID `{newHid}`.");
if (!await ctx.PromptYesNo($"Change member ID of **{target.NameFor(LookupContext.ByNonOwner)}** (`{target.Hid}`) to `{newHid}`?", "Change"))
throw new PKError("ID change cancelled.");
await _db.Execute(c => _repo.UpdateMember(c, target.Id, new MemberPatch { Hid = newHid }));
await _repo.UpdateMember(target.Id, new() { Hid = newHid });
await ctx.Reply($"{Emojis.Success} Member ID updated (`{target.Hid}` -> `{newHid}`).");
}
@ -77,14 +77,14 @@ namespace PluralKit.Bot
if (!Regex.IsMatch(newHid, "^[a-z]{5}$"))
throw new PKError($"Invalid new group ID `{newHid}`.");
var existingGroup = await _db.Execute(c => _repo.GetGroupByHid(c, newHid));
var existingGroup = _repo.GetGroupByHid(newHid);
if (existingGroup != null)
throw new PKError($"Another group already exists with ID `{newHid}`.");
if (!await ctx.PromptYesNo($"Change group ID of **{target.Name}** (`{target.Hid}`) to `{newHid}`?", "Change"))
throw new PKError("ID change cancelled.");
await _db.Execute(c => _repo.UpdateGroup(c, target.Id, new GroupPatch { Hid = newHid }));
await _repo.UpdateGroup(target.Id, new() { Hid = newHid });
await ctx.Reply($"{Emojis.Success} Group ID updated (`{target.Hid}` -> `{newHid}`).");
}
@ -110,11 +110,7 @@ namespace PluralKit.Bot
if (!await ctx.PromptYesNo($"Update member limit from **{currentLimit}** to **{newLimit}**?", "Update"))
throw new PKError("Member limit change cancelled.");
await using var conn = await _db.Obtain();
await _repo.UpdateSystem(conn, target.Id, new SystemPatch
{
MemberLimitOverride = newLimit
});
await _repo.UpdateSystem(target.Id, new() { MemberLimitOverride = newLimit });
await ctx.Reply($"{Emojis.Success} Member limit updated.");
}
@ -140,11 +136,7 @@ namespace PluralKit.Bot
if (!await ctx.PromptYesNo($"Update group limit from **{currentLimit}** to **{newLimit}**?", "Update"))
throw new PKError("Group limit change cancelled.");
await using var conn = await _db.Obtain();
await _repo.UpdateSystem(conn, target.Id, new SystemPatch
{
GroupLimitOverride = newLimit
});
await _repo.UpdateSystem(target.Id, new() { GroupLimitOverride = newLimit });
await ctx.Reply($"{Emojis.Success} Group limit updated.");
}
}

View file

@ -94,8 +94,8 @@ namespace PluralKit.Bot
var fronters = ctx.MessageContext.LastSwitchMembers;
var relevantMember = ctx.MessageContext.AutoproxyMode switch
{
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)),
AutoproxyMode.Front => fronters.Length > 0 ? await _repo.GetMember(fronters[0]) : null,
AutoproxyMode.Member => await _repo.GetMember(ctx.MessageContext.AutoproxyMember.Value),
_ => null
};
@ -171,8 +171,7 @@ namespace PluralKit.Bot
else newTimeout = timeoutPeriod;
}
await _db.Execute(conn => _repo.UpdateSystem(conn, ctx.System.Id,
new SystemPatch { LatchTimeout = (int?)newTimeout?.TotalSeconds }));
await _repo.UpdateSystem(ctx.System.Id, new() { LatchTimeout = (int?)newTimeout?.TotalSeconds });
if (newTimeout == null)
await ctx.Reply($"{Emojis.Success} Latch timeout reset to default ({ProxyMatcher.DefaultLatchExpiryTime.ToTimeSpan().Humanize(4)}).");
@ -209,14 +208,16 @@ namespace PluralKit.Bot
return;
}
var patch = new AccountPatch { AllowAutoproxy = allow };
await _db.Execute(conn => _repo.UpdateAccount(conn, ctx.Author.Id, patch));
await _repo.UpdateAccount(ctx.Author.Id, patch);
await ctx.Reply($"{Emojis.Success} Autoproxy {statusString} for account <@{ctx.Author.Id}>.");
}
private Task UpdateAutoproxy(Context ctx, AutoproxyMode autoproxyMode, MemberId? autoproxyMember)
private async Task UpdateAutoproxy(Context ctx, AutoproxyMode autoproxyMode, MemberId? autoproxyMember)
{
await _repo.GetSystemGuild(ctx.Guild.Id, ctx.System.Id);
var patch = new SystemGuildPatch { AutoproxyMode = autoproxyMode, AutoproxyMember = autoproxyMember };
return _db.Execute(conn => _repo.UpsertSystemGuild(conn, ctx.System.Id, ctx.Guild.Id, patch));
await _repo.UpdateSystemGuild(ctx.System.Id, ctx.Guild.Id, patch);
}
}
}

View file

@ -237,9 +237,7 @@ namespace PluralKit.Bot
if (messageId == null || channelId == null)
throw new PKError(failedToGetMessage);
await using var conn = await _db.Obtain();
var proxiedMsg = await _repo.GetMessage(conn, messageId.Value);
var proxiedMsg = await _db.Execute(conn => _repo.GetMessage(conn, messageId.Value));
if (proxiedMsg != null)
{
await ctx.Reply($"{Emojis.Success} This message was proxied successfully.");
@ -276,8 +274,8 @@ namespace PluralKit.Bot
throw new PKError("Unable to get the channel associated with this message.");
// using channel.GuildId here since _rest.GetMessage() doesn't return the GuildId
var context = await _repo.GetMessageContext(conn, msg.Author.Id, channel.GuildId.Value, msg.ChannelId);
var members = (await _repo.GetProxyMembers(conn, msg.Author.Id, channel.GuildId.Value)).ToList();
var context = await _repo.GetMessageContext(msg.Author.Id, channel.GuildId.Value, msg.ChannelId);
var members = (await _repo.GetProxyMembers(msg.Author.Id, channel.GuildId.Value)).ToList();
// Run everything through the checks, catch the ProxyCheckFailedException, and reply with the error message.
try

View file

@ -42,16 +42,14 @@ namespace PluralKit.Bot
if (groupName.Length > Limits.MaxGroupNameLength)
throw new PKError($"Group name too long ({groupName.Length}/{Limits.MaxGroupNameLength} characters).");
await using var conn = await _db.Obtain();
// Check group cap
var existingGroupCount = await _repo.GetSystemGroupCount(conn, ctx.System.Id);
var existingGroupCount = await _repo.GetSystemGroupCount(ctx.System.Id);
var groupLimit = ctx.System.GroupLimitOverride ?? Limits.MaxGroupCount;
if (existingGroupCount >= groupLimit)
throw new PKError($"System has reached the maximum number of groups ({groupLimit}). Please delete unused groups first in order to create new ones.");
// Warn if there's already a group by this name
var existingGroup = await _repo.GetGroupByName(conn, ctx.System.Id, groupName);
var existingGroup = await _repo.GetGroupByName(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?";
@ -59,7 +57,7 @@ namespace PluralKit.Bot
throw new PKError("Group creation cancelled.");
}
var newGroup = await _repo.CreateGroup(conn, ctx.System.Id, groupName);
var newGroup = await _repo.CreateGroup(ctx.System.Id, groupName);
var eb = new EmbedBuilder()
.Description($"Your new group, **{groupName}**, has been created, with the group ID **`{newGroup.Hid}`**.\nBelow are a couple of useful commands:")
@ -82,10 +80,8 @@ namespace PluralKit.Bot
if (newName.Length > Limits.MaxGroupNameLength)
throw new PKError($"New group name too long ({newName.Length}/{Limits.MaxMemberNameLength} characters).");
await using var conn = await _db.Obtain();
// Warn if there's already a group by this name
var existingGroup = await _repo.GetGroupByName(conn, ctx.System.Id, newName);
var existingGroup = await _repo.GetGroupByName(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 group to that name too?";
@ -93,7 +89,7 @@ namespace PluralKit.Bot
throw new PKError("Group rename cancelled.");
}
await _repo.UpdateGroup(conn, target.Id, new GroupPatch { Name = newName });
await _repo.UpdateGroup(target.Id, new() { Name = newName });
await ctx.Reply($"{Emojis.Success} Group name changed from **{target.Name}** to **{newName}**.");
}
@ -139,7 +135,7 @@ namespace PluralKit.Bot
if (await ctx.MatchClear("this group's display name"))
{
var patch = new GroupPatch { DisplayName = Partial<string>.Null() };
await _db.Execute(conn => _repo.UpdateGroup(conn, target.Id, patch));
await _repo.UpdateGroup(target.Id, patch);
await ctx.Reply($"{Emojis.Success} Group display name cleared.");
}
@ -148,7 +144,7 @@ namespace PluralKit.Bot
var newDisplayName = ctx.RemainderOrNull(skipFlags: false).NormalizeLineEndSpacing();
var patch = new GroupPatch { DisplayName = Partial<string>.Present(newDisplayName) };
await _db.Execute(conn => _repo.UpdateGroup(conn, target.Id, patch));
await _repo.UpdateGroup(target.Id, patch);
await ctx.Reply($"{Emojis.Success} Group display name changed.");
}
@ -190,7 +186,7 @@ namespace PluralKit.Bot
if (await ctx.MatchClear("this group's description"))
{
var patch = new GroupPatch { Description = Partial<string>.Null() };
await _db.Execute(conn => _repo.UpdateGroup(conn, target.Id, patch));
await _repo.UpdateGroup(target.Id, patch);
await ctx.Reply($"{Emojis.Success} Group description cleared.");
}
else
@ -200,7 +196,7 @@ namespace PluralKit.Bot
throw Errors.StringTooLongError("Description", description.Length, Limits.MaxDescriptionLength);
var patch = new GroupPatch { Description = Partial<string>.Present(description) };
await _db.Execute(conn => _repo.UpdateGroup(conn, target.Id, patch));
await _repo.UpdateGroup(target.Id, patch);
await ctx.Reply($"{Emojis.Success} Group description changed.");
}
@ -212,7 +208,7 @@ namespace PluralKit.Bot
{
ctx.CheckOwnGroup(target);
await _db.Execute(c => _repo.UpdateGroup(c, target.Id, new GroupPatch { Icon = null }));
await _repo.UpdateGroup(target.Id, new() { Icon = null });
await ctx.Reply($"{Emojis.Success} Group icon cleared.");
}
@ -222,7 +218,7 @@ namespace PluralKit.Bot
await AvatarUtils.VerifyAvatarOrThrow(_client, img.Url);
await _db.Execute(c => _repo.UpdateGroup(c, target.Id, new GroupPatch { Icon = img.Url }));
await _repo.UpdateGroup(target.Id, new() { Icon = img.Url });
var msg = img.Source switch
{
@ -274,7 +270,7 @@ namespace PluralKit.Bot
{
ctx.CheckOwnGroup(target);
await _db.Execute(c => _repo.UpdateGroup(c, target.Id, new GroupPatch { BannerImage = null }));
await _repo.UpdateGroup(target.Id, new() { BannerImage = null });
await ctx.Reply($"{Emojis.Success} Group banner image cleared.");
}
@ -284,7 +280,7 @@ namespace PluralKit.Bot
await AvatarUtils.VerifyAvatarOrThrow(_client, img.Url, isFullSizeImage: true);
await _db.Execute(c => _repo.UpdateGroup(c, target.Id, new GroupPatch { BannerImage = img.Url }));
await _repo.UpdateGroup(target.Id, new() { BannerImage = img.Url });
var msg = img.Source switch
{
@ -338,7 +334,7 @@ namespace PluralKit.Bot
ctx.CheckOwnGroup(target);
var patch = new GroupPatch { Color = Partial<string>.Null() };
await _db.Execute(conn => _repo.UpdateGroup(conn, target.Id, patch));
await _repo.UpdateGroup(target.Id, patch);
await ctx.Reply($"{Emojis.Success} Group color cleared.");
}
@ -368,7 +364,7 @@ namespace PluralKit.Bot
if (!Regex.IsMatch(color, "^[0-9a-fA-F]{6}$")) throw Errors.InvalidColorError(color);
var patch = new GroupPatch { Color = Partial<string>.Present(color.ToLowerInvariant()) };
await _db.Execute(conn => _repo.UpdateGroup(conn, target.Id, patch));
await _repo.UpdateGroup(target.Id, patch);
await ctx.Reply(embed: new EmbedBuilder()
.Title($"{Emojis.Success} Group color changed.")
@ -389,7 +385,6 @@ namespace PluralKit.Bot
ctx.CheckSystemPrivacy(system, system.GroupListPrivacy);
// TODO: integrate with the normal "search" system
await using var conn = await _db.Obtain();
var pctx = LookupContext.ByNonOwner;
if (ctx.MatchFlag("a", "all"))
@ -400,7 +395,7 @@ namespace PluralKit.Bot
throw new PKError("You do not have permission to access this information.");
}
var groups = (await conn.QueryGroupList(system.Id))
var groups = (await _db.Execute(conn => conn.QueryGroupList(system.Id)))
.Where(g => g.Visibility.CanAccess(pctx))
.OrderBy(g => g.Name, StringComparer.InvariantCultureIgnoreCase)
.ToList();
@ -434,8 +429,7 @@ namespace PluralKit.Bot
public async Task ShowGroupCard(Context ctx, PKGroup target)
{
await using var conn = await _db.Obtain();
var system = await GetGroupSystem(ctx, target, conn);
var system = await GetGroupSystem(ctx, target);
await ctx.Reply(embed: await _embeds.CreateGroupEmbed(ctx, system, target));
}
@ -448,10 +442,8 @@ namespace PluralKit.Bot
.Distinct()
.ToList();
await using var conn = await _db.Obtain();
var existingMembersInGroup = (await conn.QueryMemberList(target.System,
new DatabaseViewsExt.MemberListQueryOptions { GroupFilter = target.Id }))
var existingMembersInGroup = (await _db.Execute(conn => conn.QueryMemberList(target.System,
new DatabaseViewsExt.MemberListQueryOptions { GroupFilter = target.Id })))
.Select(m => m.Id.Value)
.Distinct()
.ToHashSet();
@ -463,14 +455,14 @@ namespace PluralKit.Bot
toAction = members
.Where(m => !existingMembersInGroup.Contains(m.Value))
.ToList();
await _repo.AddMembersToGroup(conn, target.Id, toAction);
await _repo.AddMembersToGroup(target.Id, toAction);
}
else if (op == AddRemoveOperation.Remove)
{
toAction = members
.Where(m => existingMembersInGroup.Contains(m.Value))
.ToList();
await _repo.RemoveMembersFromGroup(conn, target.Id, toAction);
await _repo.RemoveMembersFromGroup(target.Id, toAction);
}
else return; // otherwise toAction "may be undefined"
@ -479,9 +471,7 @@ namespace PluralKit.Bot
public async Task ListGroupMembers(Context ctx, PKGroup target)
{
await using var conn = await _db.Obtain();
var targetSystem = await GetGroupSystem(ctx, target, conn);
var targetSystem = await GetGroupSystem(ctx, target);
ctx.CheckSystemPrivacy(targetSystem, target.ListPrivacy);
var opts = ctx.ParseMemberListOptions(ctx.LookupContextFor(target.System));
@ -523,7 +513,7 @@ namespace PluralKit.Bot
async Task SetAll(PrivacyLevel level)
{
await _db.Execute(c => _repo.UpdateGroup(c, target.Id, new GroupPatch().WithAllPrivacy(level)));
await _repo.UpdateGroup(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.");
@ -533,7 +523,7 @@ namespace PluralKit.Bot
async Task SetLevel(GroupPrivacySubject subject, PrivacyLevel level)
{
await _db.Execute(c => _repo.UpdateGroup(c, target.Id, new GroupPatch().WithPrivacy(subject, level)));
await _repo.UpdateGroup(target.Id, new GroupPatch().WithPrivacy(subject, level));
var subjectName = subject switch
{
@ -576,19 +566,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 => _repo.DeleteGroup(conn, target.Id));
await _repo.DeleteGroup(target.Id);
await ctx.Reply($"{Emojis.Success} Group deleted.");
}
public async Task GroupFrontPercent(Context ctx, PKGroup target)
{
await using var conn = await _db.Obtain();
var targetSystem = await GetGroupSystem(ctx, target, conn);
var targetSystem = await GetGroupSystem(ctx, target);
ctx.CheckSystemPrivacy(targetSystem, targetSystem.FrontHistoryPrivacy);
var totalSwitches = await _db.Execute(conn => _repo.GetSwitchCount(conn, targetSystem.Id));
var totalSwitches = await _repo.GetSwitchCount(targetSystem.Id);
if (totalSwitches == 0) throw Errors.NoRegisteredSwitches;
string durationStr = ctx.RemainderOrNull() ?? "30d";
@ -611,12 +599,12 @@ namespace PluralKit.Bot
await ctx.Reply(embed: await _embeds.CreateFrontPercentEmbed(frontpercent, targetSystem, target, targetSystem.Zone, ctx.LookupContextFor(targetSystem), title.ToString(), ignoreNoFronters, showFlat));
}
private async Task<PKSystem> GetGroupSystem(Context ctx, PKGroup target, IPKConnection conn)
private async Task<PKSystem> GetGroupSystem(Context ctx, PKGroup target)
{
var system = ctx.System;
if (system?.Id == target.System)
return system;
return await _repo.GetSystem(conn, target.System)!;
return await _repo.GetSystem(target.System)!;
}
}
}

View file

@ -40,7 +40,7 @@ namespace PluralKit.Bot
throw Errors.StringTooLongError("Member name", memberName.Length, Limits.MaxMemberNameLength);
// Warn if there's already a member by this name
var existingMember = await _db.Execute(c => _repo.GetMemberByName(c, ctx.System.Id, memberName));
var existingMember = await _repo.GetMemberByName(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?";
@ -50,13 +50,13 @@ namespace PluralKit.Bot
await using var conn = await _db.Obtain();
// Enforce per-system member limit
var memberCount = await _repo.GetSystemMemberCount(conn, ctx.System.Id);
var memberCount = await _repo.GetSystemMemberCount(ctx.System.Id);
var memberLimit = ctx.System.MemberLimitOverride ?? Limits.MaxMemberCount;
if (memberCount >= memberLimit)
throw Errors.MemberLimitReachedError(memberLimit);
// Create the member
var member = await _repo.CreateMember(conn, ctx.System.Id, memberName);
var member = await _repo.CreateMember(ctx.System.Id, memberName);
memberCount++;
// Try to match an image attached to the message
@ -67,7 +67,7 @@ namespace PluralKit.Bot
try
{
await AvatarUtils.VerifyAvatarOrThrow(_client, avatarArg.Url);
await _db.Execute(conn => _repo.UpdateMember(conn, member.Id, new MemberPatch { AvatarUrl = avatarArg.Url }));
await _repo.UpdateMember(member.Id, new MemberPatch { AvatarUrl = avatarArg.Url });
}
catch (Exception e)
{
@ -77,6 +77,7 @@ namespace PluralKit.Bot
// Send confirmation and space hint
await ctx.Reply($"{Emojis.Success} Member \"{memberName}\" (`{member.Hid}`) registered! Check out the getting started page for how to get a member up and running: https://pluralkit.me/start#create-a-member");
// todo: move this to ModelRepository
if (await _db.Execute(conn => conn.QuerySingleAsync<bool>("select has_private_members(@System)",
new { System = ctx.System.Id }))) //if has private members
await ctx.Reply($"{Emojis.Warn} This member is currently **public**. To change this, use `pk;member {member.Hid} private`.");
@ -95,7 +96,7 @@ namespace PluralKit.Bot
public async Task ViewMember(Context ctx, PKMember target)
{
var system = await _db.Execute(c => _repo.GetSystem(c, target.System));
var system = await _repo.GetSystem(target.System);
await ctx.Reply(embed: await _embeds.CreateMemberEmbed(system, target, ctx.Guild, ctx.LookupContextFor(system)));
}

View file

@ -72,14 +72,14 @@ namespace PluralKit.Bot
public async Task ServerAvatar(Context ctx, PKMember target)
{
ctx.CheckGuildContext();
var guildData = await _db.Execute(c => _repo.GetMemberGuild(c, ctx.Guild.Id, target.Id));
var guildData = await _repo.GetMemberGuild(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 => _repo.GetMemberGuild(c, ctx.Guild.Id, target.Id))
await _repo.GetMemberGuild(ctx.Guild.Id, target.Id)
: null;
await AvatarCommandTree(AvatarLocation.Member, ctx, target, guildData);
@ -147,11 +147,9 @@ namespace PluralKit.Bot
switch (location)
{
case AvatarLocation.Server:
var serverPatch = new MemberGuildPatch { AvatarUrl = url };
return _db.Execute(c => _repo.UpsertMemberGuild(c, target.Id, ctx.Guild.Id, serverPatch));
return _repo.UpdateMemberGuild(target.Id, ctx.Guild.Id, new() { AvatarUrl = url });
case AvatarLocation.Member:
var memberPatch = new MemberPatch { AvatarUrl = url };
return _db.Execute(c => _repo.UpdateMember(c, target.Id, memberPatch));
return _repo.UpdateMember(target.Id, new() { AvatarUrl = url });
default:
throw new ArgumentOutOfRangeException($"Unknown avatar location {location}");
}

View file

@ -35,7 +35,7 @@ namespace PluralKit.Bot
throw Errors.StringTooLongError("Member name", newName.Length, Limits.MaxMemberNameLength);
// Warn if there's already a member by this name
var existingMember = await _db.Execute(conn => _repo.GetMemberByName(conn, ctx.System.Id, newName));
var existingMember = await _repo.GetMemberByName(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 => _repo.UpdateMember(conn, target.Id, patch));
await _repo.UpdateMember(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 => _repo.GetMemberGuild(c, ctx.Guild.Id, target.Id));
var memberGuildConfig = await _repo.GetMemberGuild(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.");
}
@ -94,7 +94,7 @@ namespace PluralKit.Bot
if (await ctx.MatchClear("this member's description"))
{
var patch = new MemberPatch { Description = Partial<string>.Null() };
await _db.Execute(conn => _repo.UpdateMember(conn, target.Id, patch));
await _repo.UpdateMember(target.Id, patch);
await ctx.Reply($"{Emojis.Success} Member description cleared.");
}
else
@ -104,7 +104,7 @@ namespace PluralKit.Bot
throw Errors.StringTooLongError("Description", description.Length, Limits.MaxDescriptionLength);
var patch = new MemberPatch { Description = Partial<string>.Present(description) };
await _db.Execute(conn => _repo.UpdateMember(conn, target.Id, patch));
await _repo.UpdateMember(target.Id, patch);
await ctx.Reply($"{Emojis.Success} Member description changed.");
}
@ -142,7 +142,7 @@ namespace PluralKit.Bot
if (await ctx.MatchClear("this member's pronouns"))
{
var patch = new MemberPatch { Pronouns = Partial<string>.Null() };
await _db.Execute(conn => _repo.UpdateMember(conn, target.Id, patch));
await _repo.UpdateMember(target.Id, patch);
await ctx.Reply($"{Emojis.Success} Member pronouns cleared.");
}
else
@ -152,7 +152,7 @@ namespace PluralKit.Bot
throw Errors.StringTooLongError("Pronouns", pronouns.Length, Limits.MaxPronounsLength);
var patch = new MemberPatch { Pronouns = Partial<string>.Present(pronouns) };
await _db.Execute(conn => _repo.UpdateMember(conn, target.Id, patch));
await _repo.UpdateMember(target.Id, patch);
await ctx.Reply($"{Emojis.Success} Member pronouns changed.");
}
@ -164,7 +164,7 @@ namespace PluralKit.Bot
async Task ClearBannerImage()
{
await _db.Execute(c => _repo.UpdateMember(c, target.Id, new MemberPatch { BannerImage = null }));
await _repo.UpdateMember(target.Id, new() { BannerImage = null });
await ctx.Reply($"{Emojis.Success} Member banner image cleared.");
}
@ -172,7 +172,7 @@ namespace PluralKit.Bot
{
await AvatarUtils.VerifyAvatarOrThrow(_client, img.Url, isFullSizeImage: true);
await _db.Execute(c => _repo.UpdateMember(c, target.Id, new MemberPatch { BannerImage = img.Url }));
await _repo.UpdateMember(target.Id, new() { BannerImage = img.Url });
var msg = img.Source switch
{
@ -219,7 +219,7 @@ namespace PluralKit.Bot
ctx.CheckOwnMember(target);
var patch = new MemberPatch { Color = Partial<string>.Null() };
await _db.Execute(conn => _repo.UpdateMember(conn, target.Id, patch));
await _repo.UpdateMember(target.Id, patch);
await ctx.Reply($"{Emojis.Success} Member color cleared.");
}
@ -251,7 +251,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 => _repo.UpdateMember(conn, target.Id, patch));
await _repo.UpdateMember(target.Id, patch);
await ctx.Reply(embed: new EmbedBuilder()
.Title($"{Emojis.Success} Member color changed.")
@ -267,7 +267,7 @@ namespace PluralKit.Bot
ctx.CheckOwnMember(target);
var patch = new MemberPatch { Birthday = Partial<LocalDate?>.Null() };
await _db.Execute(conn => _repo.UpdateMember(conn, target.Id, patch));
await _repo.UpdateMember(target.Id, patch);
await ctx.Reply($"{Emojis.Success} Member birthdate cleared.");
}
@ -292,7 +292,7 @@ namespace PluralKit.Bot
if (birthday == null) throw Errors.BirthdayParseError(birthdayStr);
var patch = new MemberPatch { Birthday = Partial<LocalDate?>.Present(birthday) };
await _db.Execute(conn => _repo.UpdateMember(conn, target.Id, patch));
await _repo.UpdateMember(target.Id, patch);
await ctx.Reply($"{Emojis.Success} Member birthdate changed.");
}
@ -304,7 +304,7 @@ namespace PluralKit.Bot
MemberGuildSettings memberGuildConfig = null;
if (ctx.Guild != null)
memberGuildConfig = await _db.Execute(c => _repo.GetMemberGuild(c, ctx.Guild.Id, target.Id));
memberGuildConfig = await _repo.GetMemberGuild(ctx.Guild.Id, target.Id);
var eb = new EmbedBuilder()
.Title($"Member names")
@ -341,7 +341,7 @@ namespace PluralKit.Bot
var successStr = text;
if (ctx.Guild != null)
{
var memberGuildConfig = await _db.Execute(c => _repo.GetMemberGuild(c, ctx.Guild.Id, target.Id));
var memberGuildConfig = await _repo.GetMemberGuild(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.";
}
@ -379,7 +379,7 @@ namespace PluralKit.Bot
if (await ctx.MatchClear("this member's display name"))
{
var patch = new MemberPatch { DisplayName = Partial<string>.Null() };
await _db.Execute(conn => _repo.UpdateMember(conn, target.Id, patch));
await _repo.UpdateMember(target.Id, patch);
await PrintSuccess($"{Emojis.Success} Member display name cleared. This member will now be proxied using their member name \"{target.NameFor(ctx)}\".");
}
@ -388,7 +388,7 @@ namespace PluralKit.Bot
var newDisplayName = ctx.RemainderOrNull(skipFlags: false).NormalizeLineEndSpacing();
var patch = new MemberPatch { DisplayName = Partial<string>.Present(newDisplayName) };
await _db.Execute(conn => _repo.UpdateMember(conn, target.Id, patch));
await _repo.UpdateMember(target.Id, patch);
await PrintSuccess($"{Emojis.Success} Member display name changed. This member will now be proxied using the name \"{newDisplayName}\".");
}
@ -403,10 +403,10 @@ namespace PluralKit.Bot
noServerNameSetMessage += $" To set one, type `pk;member {target.Reference()} servername <server name>`.";
// No perms check, display name isn't covered by member privacy
var memberGuildConfig = await _repo.GetMemberGuild(ctx.Guild.Id, target.Id);
if (ctx.MatchRaw())
{
MemberGuildSettings memberGuildConfig = await _db.Execute(c => _repo.GetMemberGuild(c, ctx.Guild.Id, target.Id));
if (memberGuildConfig.DisplayName == null)
await ctx.Reply(noServerNameSetMessage);
@ -427,8 +427,7 @@ namespace PluralKit.Bot
if (await ctx.MatchClear("this member's server name"))
{
var patch = new MemberGuildPatch { DisplayName = null };
await _db.Execute(conn => _repo.UpsertMemberGuild(conn, target.Id, ctx.Guild.Id, patch));
await _repo.UpdateMemberGuild(target.Id, ctx.Guild.Id, new() { DisplayName = null });
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}).");
@ -439,8 +438,7 @@ namespace PluralKit.Bot
{
var newServerName = ctx.RemainderOrNull(skipFlags: false).NormalizeLineEndSpacing();
var patch = new MemberGuildPatch { DisplayName = newServerName };
await _db.Execute(conn => _repo.UpsertMemberGuild(conn, target.Id, ctx.Guild.Id, patch));
await _repo.UpdateMemberGuild(target.Id, ctx.Guild.Id, new() { DisplayName = newServerName });
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}).");
}
@ -464,7 +462,7 @@ namespace PluralKit.Bot
};
var patch = new MemberPatch { KeepProxy = Partial<bool>.Present(newValue) };
await _db.Execute(conn => _repo.UpdateMember(conn, target.Id, patch));
await _repo.UpdateMember(target.Id, patch);
if (newValue)
await ctx.Reply($"{Emojis.Success} Member proxy tags will now be included in the resulting message when proxying.");
@ -491,7 +489,7 @@ namespace PluralKit.Bot
};
var patch = new MemberPatch { AllowAutoproxy = Partial<bool>.Present(newValue) };
await _db.Execute(conn => _repo.UpdateMember(conn, target.Id, patch));
await _repo.UpdateMember(target.Id, patch);
if (newValue)
await ctx.Reply($"{Emojis.Success} Latch / front autoproxy have been **enabled** for this member.");
@ -523,11 +521,11 @@ namespace PluralKit.Bot
// Get guild settings (mostly for warnings and such)
MemberGuildSettings guildSettings = null;
if (ctx.Guild != null)
guildSettings = await _db.Execute(c => _repo.GetMemberGuild(c, ctx.Guild.Id, target.Id));
guildSettings = await _repo.GetMemberGuild(ctx.Guild.Id, target.Id);
async Task SetAll(PrivacyLevel level)
{
await _db.Execute(c => _repo.UpdateMember(c, target.Id, new MemberPatch().WithAllPrivacy(level)));
await _repo.UpdateMember(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.");
@ -537,7 +535,7 @@ namespace PluralKit.Bot
async Task SetLevel(MemberPrivacySubject subject, PrivacyLevel level)
{
await _db.Execute(c => _repo.UpdateMember(c, target.Id, new MemberPatch().WithPrivacy(subject, level)));
await _repo.UpdateMember(target.Id, new MemberPatch().WithPrivacy(subject, level));
var subjectName = subject switch
{
@ -596,7 +594,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 => _repo.DeleteMember(conn, target.Id));
await _repo.DeleteMember(target.Id);
await ctx.Reply($"{Emojis.Success} Member deleted.");
}

View file

@ -29,8 +29,7 @@ namespace PluralKit.Bot
.Distinct()
.ToList();
await using var conn = await _db.Obtain();
var existingGroups = (await _repo.GetMemberGroups(conn, target.Id).ToListAsync())
var existingGroups = (await _repo.GetMemberGroups(target.Id).ToListAsync())
.Select(g => g.Id)
.Distinct()
.ToList();
@ -43,7 +42,7 @@ namespace PluralKit.Bot
.Where(group => !existingGroups.Contains(group))
.ToList();
await _repo.AddGroupsToMember(conn, target.Id, toAction);
await _repo.AddGroupsToMember(target.Id, toAction);
}
else if (op == Groups.AddRemoveOperation.Remove)
{
@ -51,7 +50,7 @@ namespace PluralKit.Bot
.Where(group => existingGroups.Contains(group))
.ToList();
await _repo.RemoveGroupsFromMember(conn, target.Id, toAction);
await _repo.RemoveGroupsFromMember(target.Id, toAction);
}
else return; // otherwise toAction "may be unassigned"
@ -60,11 +59,9 @@ namespace PluralKit.Bot
public async Task List(Context ctx, PKMember target)
{
await using var conn = await _db.Obtain();
var pctx = ctx.LookupContextFor(target.System);
var groups = await _repo.GetMemberGroups(conn, target.Id)
var groups = await _repo.GetMemberGroups(target.Id)
.Where(g => g.Visibility.CanAccess(pctx))
.OrderBy(g => g.Name, StringComparer.InvariantCultureIgnoreCase)
.ToListAsync();

View file

@ -57,7 +57,7 @@ namespace PluralKit.Bot
}
var patch = new MemberPatch { ProxyTags = Partial<ProxyTag[]>.Present(new ProxyTag[0]) };
await _db.Execute(conn => _repo.UpdateMember(conn, target.Id, patch));
await _repo.UpdateMember(target.Id, patch);
await ctx.Reply($"{Emojis.Success} Proxy tags cleared.");
}
@ -87,7 +87,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 => _repo.UpdateMember(conn, target.Id, patch));
await _repo.UpdateMember(target.Id, patch);
await ctx.Reply($"{Emojis.Success} Added proxy tags {tagToAdd.ProxyString.AsCode()}.");
}
@ -104,7 +104,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 => _repo.UpdateMember(conn, target.Id, patch));
await _repo.UpdateMember(target.Id, patch);
await ctx.Reply($"{Emojis.Success} Removed proxy tags {tagToRemove.ProxyString.AsCode()}.");
}
@ -128,7 +128,7 @@ namespace PluralKit.Bot
var newTags = new[] { requestedTag };
var patch = new MemberPatch { ProxyTags = Partial<ProxyTag[]>.Present(newTags) };
await _db.Execute(conn => _repo.UpdateMember(conn, target.Id, patch));
await _repo.UpdateMember(target.Id, patch);
await ctx.Reply($"{Emojis.Success} Member proxy tags set to {requestedTag.ProxyString.AsCode()}.");
}

View file

@ -1,4 +1,5 @@
#nullable enable
using System;
using System.Threading.Tasks;
using Myriad.Builders;
@ -105,8 +106,7 @@ namespace PluralKit.Bot
private async Task<PKMessage?> FindRecentMessage(Context ctx)
{
await using var conn = await _db.Obtain();
var lastMessage = await _repo.GetLastMessage(conn, ctx.Guild.Id, ctx.Channel.Id, ctx.Author.Id);
var lastMessage = await _repo.GetLastMessage(ctx.Guild.Id, ctx.Channel.Id, ctx.Author.Id);
if (lastMessage == null)
return null;
@ -168,7 +168,7 @@ namespace PluralKit.Bot
private async Task DeleteCommandMessage(Context ctx, ulong messageId)
{
var message = await _db.Execute(conn => _repo.GetCommandMessage(conn, messageId));
var message = await _repo.GetCommandMessage(messageId);
if (message == null)
throw Errors.MessageNotFound(messageId);

View file

@ -1,3 +1,4 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
@ -26,13 +27,10 @@ namespace PluralKit.Bot
{
ctx.CheckSystem();
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();
var members = await _repo.GetSystemMembers(ctx.System.Id).ToListAsync();
if (!ctx.MatchFlag("all", "a"))
members = members.Where(m => m.MemberVisibility == PrivacyLevel.Public).ToList();
if (members == null || !members.Any())
throw new PKError("Your system has no members! Please create at least one member before using this command.");

View file

@ -29,10 +29,11 @@ namespace PluralKit.Bot
public async Task SetLogChannel(Context ctx)
{
ctx.CheckGuildContext().CheckAuthorPermission(PermissionSet.ManageGuild, "Manage Server");
await _repo.GetGuild(ctx.Guild.Id);
if (await ctx.MatchClear("the server log channel"))
{
await _db.Execute(conn => _repo.UpsertGuild(conn, ctx.Guild.Id, new GuildPatch { LogChannel = null }));
await _repo.UpdateGuild(ctx.Guild.Id, new() { LogChannel = null });
await ctx.Reply($"{Emojis.Success} Proxy logging channel cleared.");
return;
}
@ -45,8 +46,7 @@ namespace PluralKit.Bot
channel = await ctx.MatchChannel();
if (channel == null || channel.GuildId != ctx.Guild.Id) throw Errors.ChannelNotFound(channelString);
var patch = new GuildPatch { LogChannel = channel.Id };
await _db.Execute(conn => _repo.UpsertGuild(conn, ctx.Guild.Id, patch));
await _repo.UpdateGuild(ctx.Guild.Id, new() { LogChannel = channel.Id });
await ctx.Reply($"{Emojis.Success} Proxy logging channel set to #{channel.Name}.");
}
@ -67,19 +67,16 @@ namespace PluralKit.Bot
}
ulong? logChannel = null;
await using (var conn = await _db.Obtain())
{
var config = await _repo.GetGuild(conn, ctx.Guild.Id);
logChannel = config.LogChannel;
var blacklist = config.LogBlacklist.ToHashSet();
if (enable)
blacklist.ExceptWith(affectedChannels.Select(c => c.Id));
else
blacklist.UnionWith(affectedChannels.Select(c => c.Id));
var config = await _repo.GetGuild(ctx.Guild.Id);
logChannel = config.LogChannel;
var patch = new GuildPatch { LogBlacklist = blacklist.ToArray() };
await _repo.UpsertGuild(conn, ctx.Guild.Id, patch);
}
var blacklist = config.LogBlacklist.ToHashSet();
if (enable)
blacklist.ExceptWith(affectedChannels.Select(c => c.Id));
else
blacklist.UnionWith(affectedChannels.Select(c => c.Id));
await _repo.UpdateGuild(ctx.Guild.Id, new() { LogBlacklist = blacklist.ToArray() });
await ctx.Reply(
$"{Emojis.Success} Message logging for the given channels {(enable ? "enabled" : "disabled")}." +
@ -90,7 +87,7 @@ namespace PluralKit.Bot
{
ctx.CheckGuildContext().CheckAuthorPermission(PermissionSet.ManageGuild, "Manage Server");
var blacklist = await _db.Execute(c => _repo.GetGuild(c, ctx.Guild.Id));
var blacklist = await _repo.GetGuild(ctx.Guild.Id);
// Resolve all channels from the cache and order by position
var channels = blacklist.Blacklist
@ -151,18 +148,15 @@ namespace PluralKit.Bot
affectedChannels.Add(channel);
}
await using (var conn = await _db.Obtain())
{
var guild = await _repo.GetGuild(conn, ctx.Guild.Id);
var blacklist = guild.Blacklist.ToHashSet();
if (shouldAdd)
blacklist.UnionWith(affectedChannels.Select(c => c.Id));
else
blacklist.ExceptWith(affectedChannels.Select(c => c.Id));
var guild = await _repo.GetGuild(ctx.Guild.Id);
var patch = new GuildPatch { Blacklist = blacklist.ToArray() };
await _repo.UpsertGuild(conn, ctx.Guild.Id, patch);
}
var blacklist = guild.Blacklist.ToHashSet();
if (shouldAdd)
blacklist.UnionWith(affectedChannels.Select(c => c.Id));
else
blacklist.ExceptWith(affectedChannels.Select(c => c.Id));
await _repo.UpdateGuild(ctx.Guild.Id, new() { Blacklist = blacklist.ToArray() });
await ctx.Reply($"{Emojis.Success} Channels {(shouldAdd ? "added to" : "removed from")} the proxy blacklist.");
}
@ -184,7 +178,7 @@ namespace PluralKit.Bot
.Title("Log cleanup settings")
.Field(new("Supported bots", botList));
var guildCfg = await _db.Execute(c => _repo.GetGuild(c, ctx.Guild.Id));
var guildCfg = await _repo.GetGuild(ctx.Guild.Id);
if (guildCfg.LogCleanupEnabled)
eb.Description("Log cleanup is currently **on** for this server. To disable it, type `pk;logclean off`.");
else
@ -193,8 +187,7 @@ namespace PluralKit.Bot
return;
}
var patch = new GuildPatch { LogCleanupEnabled = newValue };
await _db.Execute(conn => _repo.UpsertGuild(conn, ctx.Guild.Id, patch));
await _repo.UpdateGuild(ctx.Guild.Id, new() { LogCleanupEnabled = newValue });
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

@ -45,7 +45,7 @@ namespace PluralKit.Bot
// Find the last switch and its members if applicable
await using var conn = await _db.Obtain();
var lastSwitch = await _repo.GetLatestSwitch(conn, ctx.System.Id);
var lastSwitch = await _repo.GetLatestSwitch(ctx.System.Id);
if (lastSwitch != null)
{
var lastSwitchMembers = _repo.GetSwitchMembers(conn, lastSwitch.Id);
@ -72,13 +72,12 @@ 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 _repo.GetSwitches(conn, ctx.System.Id).Take(2).ToListAsync();
var lastTwoSwitches = await _repo.GetSwitches(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;
@ -92,7 +91,7 @@ namespace PluralKit.Bot
// Now we can actually do the move, yay!
// But, we do a prompt to confirm.
var lastSwitchMembers = _repo.GetSwitchMembers(conn, lastTwoSwitches[0].Id);
var lastSwitchMembers = _db.Execute(conn => _repo.GetSwitchMembers(conn, lastTwoSwitches[0].Id));
var lastSwitchMemberStr = string.Join(", ", await lastSwitchMembers.Select(m => m.NameFor(ctx)).ToListAsync());
var lastSwitchTime = lastTwoSwitches[0].Timestamp.ToUnixTimeSeconds(); // .FormatZoned(ctx.System)
var lastSwitchDeltaStr = (SystemClock.Instance.GetCurrentInstant() - lastTwoSwitches[0].Timestamp).FormatDuration();
@ -104,7 +103,7 @@ namespace PluralKit.Bot
if (!await ctx.PromptYesNo(msg, "Move Switch")) throw Errors.SwitchMoveCancelled;
// aaaand *now* we do the move
await _repo.MoveSwitch(conn, lastTwoSwitches[0].Id, time.ToInstant());
await _repo.MoveSwitch(lastTwoSwitches[0].Id, time.ToInstant());
await ctx.Reply($"{Emojis.Success} Switch moved to <t:{newSwitchTime}> ({newSwitchDeltaStr} ago).");
}
@ -130,7 +129,7 @@ namespace PluralKit.Bot
// Find the switch to edit
await using var conn = await _db.Obtain();
var lastSwitch = await _repo.GetLatestSwitch(conn, ctx.System.Id);
var lastSwitch = await _repo.GetLatestSwitch(ctx.System.Id);
// Make sure there's at least one switch
if (lastSwitch == null) throw Errors.NoRegisteredSwitches;
var lastSwitchMembers = _repo.GetSwitchMembers(conn, lastSwitch.Id);
@ -170,18 +169,16 @@ 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, "Clear Switches"))
throw Errors.GenericCancelled();
await _db.Execute(c => _repo.DeleteAllSwitches(c, ctx.System.Id));
await _repo.DeleteAllSwitches(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 _repo.GetSwitches(conn, ctx.System.Id).Take(2).ToListAsync();
var lastTwoSwitches = await _repo.GetSwitches(ctx.System.Id).Take(2).ToListAsync();
if (lastTwoSwitches.Count == 0) throw Errors.NoRegisteredSwitches;
var lastSwitchMembers = _repo.GetSwitchMembers(conn, lastTwoSwitches[0].Id);
var lastSwitchMembers = _db.Execute(conn => _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();
@ -192,14 +189,14 @@ namespace PluralKit.Bot
}
else
{
var secondSwitchMembers = _repo.GetSwitchMembers(conn, lastTwoSwitches[1].Id);
var secondSwitchMembers = _db.Execute(conn => _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, "Delete Switch")) throw Errors.SwitchDeleteCancelled;
await _repo.DeleteSwitch(conn, lastTwoSwitches[0].Id);
await _repo.DeleteSwitch(lastTwoSwitches[0].Id);
await ctx.Reply($"{Emojis.Success} Switch deleted.");
}

View file

@ -32,12 +32,8 @@ namespace PluralKit.Bot
if (systemName != null && systemName.Length > Limits.MaxSystemNameLength)
throw Errors.StringTooLongError("System name", systemName.Length, Limits.MaxSystemNameLength);
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 _repo.CreateSystem(systemName);
await _repo.AddAccount(system.Id, 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

@ -52,8 +52,7 @@ namespace PluralKit.Bot
if (await ctx.MatchClear("your system's name"))
{
var clearPatch = new SystemPatch { Name = null };
await _db.Execute(conn => _repo.UpdateSystem(conn, ctx.System.Id, clearPatch));
await _repo.UpdateSystem(ctx.System.Id, new() { Name = null });
await ctx.Reply($"{Emojis.Success} System name cleared.");
}
@ -64,8 +63,7 @@ namespace PluralKit.Bot
if (newSystemName.Length > Limits.MaxSystemNameLength)
throw Errors.StringTooLongError("System name", newSystemName.Length, Limits.MaxSystemNameLength);
var patch = new SystemPatch { Name = newSystemName };
await _db.Execute(conn => _repo.UpdateSystem(conn, ctx.System.Id, patch));
await _repo.UpdateSystem(ctx.System.Id, new() { Name = newSystemName });
await ctx.Reply($"{Emojis.Success} System name changed.");
}
@ -100,11 +98,9 @@ namespace PluralKit.Bot
if (await ctx.MatchClear("your system's description"))
{
var patch = new SystemPatch { Description = null };
await _db.Execute(conn => _repo.UpdateSystem(conn, ctx.System.Id, patch));
await _repo.UpdateSystem(ctx.System.Id, new() { Description = null });
await ctx.Reply($"{Emojis.Success} System description cleared.");
return;
}
else
{
@ -112,8 +108,7 @@ namespace PluralKit.Bot
if (newDescription.Length > Limits.MaxDescriptionLength)
throw Errors.StringTooLongError("Description", newDescription.Length, Limits.MaxDescriptionLength);
var patch = new SystemPatch { Description = newDescription };
await _db.Execute(conn => _repo.UpdateSystem(conn, ctx.System.Id, patch));
await _repo.UpdateSystem(ctx.System.Id, new() { Description = newDescription });
await ctx.Reply($"{Emojis.Success} System description changed.");
}
@ -125,8 +120,7 @@ namespace PluralKit.Bot
if (await ctx.MatchClear())
{
var patch = new SystemPatch { Color = Partial<string>.Null() };
await _db.Execute(conn => _repo.UpdateSystem(conn, ctx.System.Id, patch));
await _repo.UpdateSystem(ctx.System.Id, new() { Color = Partial<string>.Null() });
await ctx.Reply($"{Emojis.Success} System color cleared.");
}
@ -150,8 +144,7 @@ namespace PluralKit.Bot
if (color.StartsWith("#")) color = color.Substring(1);
if (!Regex.IsMatch(color, "^[0-9a-fA-F]{6}$")) throw Errors.InvalidColorError(color);
var patch = new SystemPatch { Color = Partial<string>.Present(color.ToLowerInvariant()) };
await _db.Execute(conn => _repo.UpdateSystem(conn, ctx.System.Id, patch));
await _repo.UpdateSystem(ctx.System.Id, new() { Color = Partial<string>.Present(color.ToLowerInvariant()) });
await ctx.Reply(embed: new EmbedBuilder()
.Title($"{Emojis.Success} System color changed.")
@ -186,8 +179,7 @@ namespace PluralKit.Bot
if (await ctx.MatchClear("your system's tag"))
{
var patch = new SystemPatch { Tag = null };
await _db.Execute(conn => _repo.UpdateSystem(conn, ctx.System.Id, patch));
await _repo.UpdateSystem(ctx.System.Id, new() { Tag = null });
await ctx.Reply($"{Emojis.Success} System tag cleared.");
}
@ -198,8 +190,7 @@ namespace PluralKit.Bot
if (newTag.Length > Limits.MaxSystemTagLength)
throw Errors.StringTooLongError("System tag", newTag.Length, Limits.MaxSystemTagLength);
var patch = new SystemPatch { Tag = newTag };
await _db.Execute(conn => _repo.UpdateSystem(conn, ctx.System.Id, patch));
await _repo.UpdateSystem(ctx.System.Id, new() { Tag = newTag });
await ctx.Reply($"{Emojis.Success} System tag changed. Member names will now end with {newTag.AsCode()} when proxied.");
}
@ -211,18 +202,20 @@ namespace PluralKit.Bot
var setDisabledWarning = $"{Emojis.Warn} Your system tag is currently **disabled** in this server. No tag will be applied when proxying.\nTo re-enable the system tag in the current server, type `pk;s servertag -enable`.";
var settings = await _repo.GetSystemGuild(ctx.Guild.Id, ctx.System.Id);
async Task Show(bool raw = false)
{
if (ctx.MessageContext.SystemGuildTag != null)
if (settings.Tag != null)
{
if (raw)
{
await ctx.Reply($"```{ctx.MessageContext.SystemGuildTag}```");
await ctx.Reply($"```{settings.Tag}```");
return;
}
var msg = $"Your current system tag in '{ctx.Guild.Name}' is {ctx.MessageContext.SystemGuildTag.AsCode()}";
if (!ctx.MessageContext.TagEnabled)
var msg = $"Your current system tag in '{ctx.Guild.Name}' is {settings.Tag.AsCode()}";
if (!settings.TagEnabled)
msg += ", but it is currently **disabled**. To re-enable it, type `pk;s servertag -enable`.";
else
msg += ". To change it, type `pk;s servertag <tag>`. To clear it, type `pk;s servertag -clear`.";
@ -231,7 +224,7 @@ namespace PluralKit.Bot
return;
}
else if (!ctx.MessageContext.TagEnabled)
else if (!settings.TagEnabled)
await ctx.Reply($"Your global system tag is {ctx.System.Tag}, but it is **disabled** in this server. To re-enable it, type `pk;s servertag -enable`");
else
await ctx.Reply($"You currently have no system tag specific to the server '{ctx.Guild.Name}'. To set one, type `pk;s servertag <tag>`. To disable the system tag in the current server, type `pk;s servertag -disable`.");
@ -243,8 +236,7 @@ namespace PluralKit.Bot
if (newTag != null && newTag.Length > Limits.MaxSystemTagLength)
throw Errors.StringTooLongError("System server tag", newTag.Length, Limits.MaxSystemTagLength);
var patch = new SystemGuildPatch { Tag = newTag };
await _db.Execute(conn => _repo.UpsertSystemGuild(conn, ctx.System.Id, ctx.Guild.Id, patch));
await _repo.UpdateSystemGuild(ctx.System.Id, ctx.Guild.Id, new() { Tag = newTag });
await ctx.Reply($"{Emojis.Success} System server tag changed. Member names will now end with {newTag.AsCode()} when proxied in the current server '{ctx.Guild.Name}'.");
@ -254,8 +246,7 @@ namespace PluralKit.Bot
async Task Clear()
{
var patch = new SystemGuildPatch { Tag = null };
await _db.Execute(conn => _repo.UpsertSystemGuild(conn, ctx.System.Id, ctx.Guild.Id, patch));
await _repo.UpdateSystemGuild(ctx.System.Id, ctx.Guild.Id, new() { Tag = null });
await ctx.Reply($"{Emojis.Success} System server tag cleared. Member names will now end with the global system tag, if there is one set.");
@ -265,8 +256,7 @@ namespace PluralKit.Bot
async Task EnableDisable(bool newValue)
{
var patch = new SystemGuildPatch { TagEnabled = newValue };
await _db.Execute(conn => _repo.UpsertSystemGuild(conn, ctx.System.Id, ctx.Guild.Id, patch));
await _repo.UpdateSystemGuild(ctx.System.Id, ctx.Guild.Id, new() { TagEnabled = newValue });
await ctx.Reply(PrintEnableDisableResult(newValue, newValue != ctx.MessageContext.TagEnabled));
}
@ -320,7 +310,7 @@ namespace PluralKit.Bot
async Task ClearIcon()
{
await _db.Execute(c => _repo.UpdateSystem(c, ctx.System.Id, new SystemPatch { AvatarUrl = null }));
await _repo.UpdateSystem(ctx.System.Id, new() { AvatarUrl = null });
await ctx.Reply($"{Emojis.Success} System icon cleared.");
}
@ -328,7 +318,7 @@ namespace PluralKit.Bot
{
await AvatarUtils.VerifyAvatarOrThrow(_client, img.Url);
await _db.Execute(c => _repo.UpdateSystem(c, ctx.System.Id, new SystemPatch { AvatarUrl = img.Url }));
await _repo.UpdateSystem(ctx.System.Id, new() { AvatarUrl = img.Url });
var msg = img.Source switch
{
@ -373,7 +363,7 @@ namespace PluralKit.Bot
async Task ClearImage()
{
await _db.Execute(c => _repo.UpdateSystem(c, ctx.System.Id, new SystemPatch { BannerImage = null }));
await _repo.UpdateSystem(ctx.System.Id, new() { BannerImage = null });
await ctx.Reply($"{Emojis.Success} System banner image cleared.");
}
@ -381,7 +371,7 @@ namespace PluralKit.Bot
{
await AvatarUtils.VerifyAvatarOrThrow(_client, img.Url, isFullSizeImage: true);
await _db.Execute(c => _repo.UpdateSystem(c, ctx.System.Id, new SystemPatch { BannerImage = img.Url }));
await _repo.UpdateSystem(ctx.System.Id, new() { BannerImage = img.Url });
var msg = img.Source switch
{
@ -428,7 +418,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 => _repo.DeleteSystem(conn, ctx.System.Id));
await _repo.DeleteSystem(ctx.System.Id);
await ctx.Reply($"{Emojis.Success} System deleted.");
}
@ -440,7 +430,7 @@ namespace PluralKit.Bot
var guild = ctx.MatchGuild() ?? ctx.Guild ??
throw new PKError("You must run this command in a server or pass a server ID.");
var gs = await _db.Execute(c => _repo.GetSystemGuild(c, guild.Id, ctx.System.Id));
var gs = await _repo.GetSystemGuild(guild.Id, ctx.System.Id);
string serverText;
if (guild.Id == ctx.Guild?.Id)
@ -461,8 +451,7 @@ namespace PluralKit.Bot
return;
}
var patch = new SystemGuildPatch { ProxyEnabled = newValue };
await _db.Execute(conn => _repo.UpsertSystemGuild(conn, ctx.System.Id, guild.Id, patch));
await _repo.UpdateSystemGuild(ctx.System.Id, guild.Id, new() { ProxyEnabled = newValue });
if (newValue)
await ctx.Reply($"Message proxying in {serverText} is now **enabled** for your system.");
@ -476,8 +465,7 @@ namespace PluralKit.Bot
if (await ctx.MatchClear())
{
var clearPatch = new SystemPatch { UiTz = "UTC" };
await _db.Execute(conn => _repo.UpdateSystem(conn, ctx.System.Id, clearPatch));
await _repo.UpdateSystem(ctx.System.Id, new() { UiTz = "UTC" });
await ctx.Reply($"{Emojis.Success} System time zone cleared (set to UTC).");
return;
@ -498,8 +486,7 @@ namespace PluralKit.Bot
var msg = $"This will change the system time zone to **{zone.Id}**. The current time is **{currentTime.FormatZoned()}**. Is this correct?";
if (!await ctx.PromptYesNo(msg, "Change Timezone")) throw Errors.TimezoneChangeCancelled;
var patch = new SystemPatch { UiTz = zone.Id };
await _db.Execute(conn => _repo.UpdateSystem(conn, ctx.System.Id, patch));
await _repo.UpdateSystem(ctx.System.Id, new() { UiTz = zone.Id });
await ctx.Reply($"System time zone changed to **{zone.Id}**.");
}
@ -523,7 +510,7 @@ namespace PluralKit.Bot
async Task SetLevel(SystemPrivacySubject subject, PrivacyLevel level)
{
await _db.Execute(conn => _repo.UpdateSystem(conn, ctx.System.Id, new SystemPatch().WithPrivacy(subject, level)));
await _repo.UpdateSystem(ctx.System.Id, new SystemPatch().WithPrivacy(subject, level));
var levelExplanation = level switch
{
@ -548,7 +535,7 @@ namespace PluralKit.Bot
async Task SetAll(PrivacyLevel level)
{
await _db.Execute(conn => _repo.UpdateSystem(conn, ctx.System.Id, new SystemPatch().WithAllPrivacy(level)));
await _repo.UpdateSystem(ctx.System.Id, new SystemPatch().WithAllPrivacy(level));
var msg = level switch
{
@ -581,15 +568,13 @@ namespace PluralKit.Bot
{
if (ctx.Match("on", "enable"))
{
var patch = new SystemPatch { PingsEnabled = true };
await _db.Execute(conn => _repo.UpdateSystem(conn, ctx.System.Id, patch));
await _repo.UpdateSystem(ctx.System.Id, new() { PingsEnabled = true });
await ctx.Reply("Reaction pings have now been enabled.");
}
if (ctx.Match("off", "disable"))
{
var patch = new SystemPatch { PingsEnabled = false };
await _db.Execute(conn => _repo.UpdateSystem(conn, ctx.System.Id, patch));
await _repo.UpdateSystem(ctx.System.Id, new() { PingsEnabled = false });
await ctx.Reply("Reaction pings have now been disabled.");
}

View file

@ -39,9 +39,7 @@ namespace PluralKit.Bot
if (system == null) throw Errors.NoSystemError;
ctx.CheckSystemPrivacy(system, system.FrontPrivacy);
await using var conn = await _db.Obtain();
var sw = await _repo.GetLatestSwitch(conn, system.Id);
var sw = await _repo.GetLatestSwitch(system.Id);
if (sw == null) throw Errors.NoRegisteredSwitches;
await ctx.Reply(embed: await _embeds.CreateFronterEmbed(sw, system.Zone, ctx.LookupContextFor(system)));
@ -53,12 +51,13 @@ namespace PluralKit.Bot
ctx.CheckSystemPrivacy(system, system.FrontHistoryPrivacy);
// Gotta be careful here: if we dispose of the connection while the IAE is alive, boom
await using var conn = await _db.Obtain();
// todo: this comment was here, but we're not getting a connection here anymore
// hopefully nothing breaks?
var totalSwitches = await _repo.GetSwitchCount(conn, system.Id);
var totalSwitches = await _repo.GetSwitchCount(system.Id);
if (totalSwitches == 0) throw Errors.NoRegisteredSwitches;
var sws = _repo.GetSwitches(conn, system.Id)
var sws = _repo.GetSwitches(system.Id)
.Scan(new FrontHistoryEntry(null, null),
(lastEntry, newSwitch) => new FrontHistoryEntry(lastEntry.ThisSwitch?.Timestamp, newSwitch));
@ -80,7 +79,6 @@ namespace PluralKit.Bot
var sw = entry.ThisSwitch;
// Fetch member list and format
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";
@ -117,7 +115,7 @@ namespace PluralKit.Bot
if (system == null) throw Errors.NoSystemError;
ctx.CheckSystemPrivacy(system, system.FrontHistoryPrivacy);
var totalSwitches = await _db.Execute(conn => _repo.GetSwitchCount(conn, system.Id));
var totalSwitches = await _repo.GetSwitchCount(system.Id);
if (totalSwitches == 0) throw Errors.NoRegisteredSwitches;
string durationStr = ctx.RemainderOrNull() ?? "30d";

View file

@ -23,20 +23,18 @@ namespace PluralKit.Bot
{
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 _repo.GetSystemAccounts(conn, ctx.System.Id);
var accountIds = await _repo.GetSystemAccounts(ctx.System.Id);
if (accountIds.Contains(account.Id))
throw Errors.AccountAlreadyLinked;
var existingAccount = await _repo.GetSystemByAccount(conn, account.Id);
var existingAccount = await _repo.GetSystemByAccount(account.Id);
if (existingAccount != null)
throw Errors.AccountInOtherSystem(existingAccount);
var msg = $"{account.Mention()}, please confirm the link.";
if (!await ctx.PromptYesNo(msg, "Confirm", user: account, matchFlag: false)) throw Errors.MemberLinkCancelled;
await _repo.AddAccount(conn, ctx.System.Id, account.Id);
await _repo.AddAccount(ctx.System.Id, account.Id);
await ctx.Reply($"{Emojis.Success} Account linked to system.");
}
@ -44,20 +42,18 @@ namespace PluralKit.Bot
{
ctx.CheckSystem();
await using var conn = await _db.Obtain();
ulong id;
if (!ctx.MatchUserRaw(out id))
throw new PKSyntaxError("You must pass an account to link with (either ID or @mention).");
var accountIds = (await _repo.GetSystemAccounts(conn, ctx.System.Id)).ToList();
var accountIds = (await _repo.GetSystemAccounts(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, "Unlink")) throw Errors.MemberUnlinkCancelled;
await _repo.RemoveAccount(conn, ctx.System.Id, id);
await _repo.RemoveAccount(ctx.System.Id, id);
await ctx.Reply($"{Emojis.Success} Account unlinked.");
}
}

View file

@ -50,8 +50,7 @@ namespace PluralKit.Bot
private async Task<string> MakeAndSetNewToken(PKSystem system)
{
var patch = new SystemPatch { Token = StringUtils.GenerateToken() };
system = await _db.Execute(conn => _repo.UpdateSystem(conn, system.Id, patch));
system = await _repo.UpdateSystem(system.Id, new() { Token = StringUtils.GenerateToken() });
return system.Token;
}