Add switch editing functionality

This commit is contained in:
BeautifulPixel 2021-09-26 20:08:38 -04:00 committed by spiral
parent e3fa0f3b32
commit 7d60b3e7cf
No known key found for this signature in database
GPG Key ID: A6059F0CA0E1BD31
5 changed files with 92 additions and 4 deletions

View File

@ -72,6 +72,8 @@ namespace PluralKit.Bot
public static Command Switch = new Command("switch", "switch <member> [member 2] [member 3...]", "Registers a switch"); public static Command Switch = new Command("switch", "switch <member> [member 2] [member 3...]", "Registers a switch");
public static Command SwitchOut = new Command("switch out", "switch out", "Registers a switch with no members"); public static Command SwitchOut = new Command("switch out", "switch out", "Registers a switch with no members");
public static Command SwitchMove = new Command("switch move", "switch move <date/time>", "Moves the latest switch in time"); public static Command SwitchMove = new Command("switch move", "switch move <date/time>", "Moves the latest switch in time");
public static Command SwitchEdit = new Command("switch edit", "switch edit <member> [member 2] [member 3...]", "Edits the members in the latest switch");
public static Command SwitchEditOut = new Command("switch edit out", "switch edit out", "Turns the latest switch into a switch-out");
public static Command SwitchDelete = new Command("switch delete", "switch delete", "Deletes the latest switch"); public static Command SwitchDelete = new Command("switch delete", "switch delete", "Deletes the latest switch");
public static Command SwitchDeleteAll = new Command("switch delete", "switch delete all", "Deletes all logged switches"); public static Command SwitchDeleteAll = new Command("switch delete", "switch delete all", "Deletes all logged switches");
public static Command Link = new Command("link", "link <account>", "Links your system to another account"); public static Command Link = new Command("link", "link <account>", "Links your system to another account");
@ -120,7 +122,7 @@ namespace PluralKit.Bot
GroupDelete, GroupMemberRandom, GroupFrontPercent GroupDelete, GroupMemberRandom, GroupFrontPercent
}; };
public static Command[] SwitchCommands = { Switch, SwitchOut, SwitchMove, SwitchDelete, SwitchDeleteAll }; public static Command[] SwitchCommands = { Switch, SwitchOut, SwitchMove, SwitchEdit, SwitchEditOut, SwitchDelete, SwitchDeleteAll };
public static Command[] AutoproxyCommands = { AutoproxySet, AutoproxyTimeout, AutoproxyAccount }; public static Command[] AutoproxyCommands = { AutoproxySet, AutoproxyTimeout, AutoproxyAccount };
@ -482,6 +484,11 @@ namespace PluralKit.Bot
await ctx.Execute<Switch>(SwitchOut, m => m.SwitchOut(ctx)); await ctx.Execute<Switch>(SwitchOut, m => m.SwitchOut(ctx));
else if (ctx.Match("move", "shift", "offset")) else if (ctx.Match("move", "shift", "offset"))
await ctx.Execute<Switch>(SwitchMove, m => m.SwitchMove(ctx)); await ctx.Execute<Switch>(SwitchMove, m => m.SwitchMove(ctx));
else if (ctx.Match("edit", "replace"))
if (ctx.Match("out"))
await ctx.Execute<Switch>(SwitchEditOut, m => m.SwitchEditOut(ctx));
else
await ctx.Execute<Switch>(SwitchEdit, m => m.SwitchEdit(ctx));
else if (ctx.Match("delete", "remove", "erase", "cancel", "yeet")) else if (ctx.Match("delete", "remove", "erase", "cancel", "yeet"))
await ctx.Execute<Switch>(SwitchDelete, m => m.SwitchDelete(ctx)); await ctx.Execute<Switch>(SwitchDelete, m => m.SwitchDelete(ctx));
else if (ctx.Match("commands", "help")) else if (ctx.Match("commands", "help"))
@ -489,7 +496,7 @@ namespace PluralKit.Bot
else if (ctx.HasNext()) // there are following arguments else if (ctx.HasNext()) // there are following arguments
await ctx.Execute<Switch>(Switch, m => m.SwitchDo(ctx)); await ctx.Execute<Switch>(Switch, m => m.SwitchDo(ctx));
else else
await PrintCommandNotFoundError(ctx, Switch, SwitchOut, SwitchMove, SwitchDelete, SystemFronter, SystemFrontHistory); await PrintCommandNotFoundError(ctx, Switch, SwitchOut, SwitchMove, SwitchEdit, SwitchEditOut, SwitchDelete, SystemFronter, SystemFrontHistory);
} }
private async Task CommandHelpRoot(Context ctx) private async Task CommandHelpRoot(Context ctx)

View File

@ -83,7 +83,7 @@ namespace PluralKit.Bot
// If we don't have a switch to move, don't bother // If we don't have a switch to move, don't bother
if (lastTwoSwitches.Count == 0) throw Errors.NoRegisteredSwitches; if (lastTwoSwitches.Count == 0) throw Errors.NoRegisteredSwitches;
// If there's a switch *behind* the one we move, we check to make srue we're not moving the time further back than that // If there's a switch *behind* the one we move, we check to make sure we're not moving the time further back than that
if (lastTwoSwitches.Count == 2) if (lastTwoSwitches.Count == 2)
{ {
if (lastTwoSwitches[1].Timestamp > time.ToInstant()) if (lastTwoSwitches[1].Timestamp > time.ToInstant())
@ -108,6 +108,58 @@ namespace PluralKit.Bot
await ctx.Reply($"{Emojis.Success} Switch moved to <t:{newSwitchTime}> ({newSwitchDeltaStr} ago)."); await ctx.Reply($"{Emojis.Success} Switch moved to <t:{newSwitchTime}> ({newSwitchDeltaStr} ago).");
} }
public async Task SwitchEdit(Context ctx)
{
ctx.CheckSystem();
var members = await ctx.ParseMemberList(ctx.System.Id);
await DoEditCommand(ctx, members);
}
public async Task SwitchEditOut(Context ctx)
{
ctx.CheckSystem();
await DoEditCommand(ctx, new PKMember[] { });
}
public async Task DoEditCommand(Context ctx, ICollection<PKMember> members)
{
// Make sure there are no dupes in the list
// We do this by checking if removing duplicate member IDs results in a list of different length
if (members.Select(m => m.Id).Distinct().Count() != members.Count) throw Errors.DuplicateSwitchMembers;
// Find the switch to edit
await using var conn = await _db.Obtain();
var lastSwitch = await _repo.GetLatestSwitch(conn, ctx.System.Id);
// Make sure there's at least one switch
if (lastSwitch == null) throw Errors.NoRegisteredSwitches;
var lastSwitchMembers = _repo.GetSwitchMembers(conn, lastSwitch.Id);
// Make sure switch isn't being edited to have the members it already does
if (await lastSwitchMembers.Select(m => m.Id).SequenceEqualAsync(members.Select(m => m.Id).ToAsyncEnumerable()))
throw Errors.SameSwitch(members, ctx.LookupContextFor(ctx.System));
// Send a prompt asking the user to confirm the switch
var lastSwitchDeltaStr = (SystemClock.Instance.GetCurrentInstant() - lastSwitch.Timestamp).FormatDuration();
var lastSwitchMemberStr = string.Join(", ", await lastSwitchMembers.Select(m => m.NameFor(ctx)).ToListAsync());
var newSwitchMemberStr = string.Join(", ", members.Select(m => m.NameFor(ctx)));
string msg;
if (members.Count == 0)
msg = $"{Emojis.Warn} This will turn the latest switch ({lastSwitchMemberStr}, {lastSwitchDeltaStr} ago) into a switch-out. Is this okay?";
else
msg = $"{Emojis.Warn} This will change the latest switch ({lastSwitchMemberStr}, {lastSwitchDeltaStr} ago) to {newSwitchMemberStr}. Is this okay?";
if (!await ctx.PromptYesNo(msg, "Edit")) throw Errors.SwitchEditCancelled;
// Actually edit the switch
await _repo.EditSwitch(conn, lastSwitch.Id, members.Select(m => m.Id).ToList());
// Tell the user the edit suceeded
if (members.Count == 0)
await ctx.Reply($"{Emojis.Success} Switch edited. The latest switch is now a switch-out.");
else
await ctx.Reply($"{Emojis.Success} Switch edited. Current fronter is now {newSwitchMemberStr}.");
}
public async Task SwitchDelete(Context ctx) public async Task SwitchDelete(Context ctx)
{ {
ctx.CheckSystem(); ctx.CheckSystem();

View File

@ -83,6 +83,7 @@ namespace PluralKit.Bot
public static PKError SwitchMoveBeforeSecondLast(ZonedDateTime time) => new PKError($"Can't move switch to before last switch time ({time.FormatZoned()}), as it would cause conflicts."); public static PKError SwitchMoveBeforeSecondLast(ZonedDateTime time) => new PKError($"Can't move switch to before last switch time ({time.FormatZoned()}), as it would cause conflicts.");
public static PKError SwitchMoveCancelled => new PKError("Switch move cancelled."); public static PKError SwitchMoveCancelled => new PKError("Switch move cancelled.");
public static PKError SwitchEditCancelled => new PKError("Switch edit cancelled.");
public static PKError SwitchDeleteCancelled => new PKError("Switch deletion cancelled."); public static PKError SwitchDeleteCancelled => new PKError("Switch deletion cancelled.");
public static PKError TimezoneParseError(string timezone) => new PKError($"Could not parse timezone offset {timezone}. Offset must be a value like 'UTC+5' or 'GMT-4:30'."); public static PKError TimezoneParseError(string timezone) => new PKError($"Could not parse timezone offset {timezone}. Offset must be a value like 'UTC+5' or 'GMT-4:30'.");

View File

@ -39,6 +39,33 @@ namespace PluralKit.Core
_logger.Information("Created {SwitchId} in {SystemId}: {Members}", sw.Id, system, members); _logger.Information("Created {SwitchId} in {SystemId}: {Members}", sw.Id, system, members);
} }
public async Task EditSwitch(IPKConnection conn, SwitchId switchId, IReadOnlyCollection<MemberId> members)
{
// Use a transaction here since we're doing multiple executed commands in one
await using var tx = await conn.BeginTransactionAsync();
// Remove the old members from the switch
await conn.ExecuteAsync("delete from switch_members where switch = @Switch",
new {Switch = switchId});
// Add the new members
await using (var w = conn.BeginBinaryImport("copy switch_members (switch, member) from stdin (format binary)"))
{
foreach (var member in members)
{
await w.StartRowAsync();
await w.WriteAsync(switchId.Value, NpgsqlDbType.Integer);
await w.WriteAsync(member.Value, NpgsqlDbType.Integer);
}
await w.CompleteAsync();
}
// Finally we commit the tx, since the using block will otherwise rollback it
await tx.CommitAsync();
_logger.Information("Updated {SwitchId} members: {Members}", switchId, members);
}
public async Task MoveSwitch(IPKConnection conn, SwitchId id, Instant time) public async Task MoveSwitch(IPKConnection conn, SwitchId id, Instant time)
{ {

View File

@ -99,10 +99,11 @@ Some arguments indicate the use of specific Discord features. These include:
## Switching commands ## Switching commands
- `pk;switch [member...]` - Registers a switch with the given members. - `pk;switch [member...]` - Registers a switch with the given members.
- `pk;switch out` - Registers a 'switch-out' - a switch with no associated members.
- `pk;switch edit <member...|out>` - Edits the members in the latest switch.
- `pk;switch move <time>` - Moves the latest switch backwards in time. - `pk;switch move <time>` - Moves the latest switch backwards in time.
- `pk;switch delete` - Deletes the latest switch. - `pk;switch delete` - Deletes the latest switch.
- `pk;switch delete all` - Deletes all logged switches. - `pk;switch delete all` - Deletes all logged switches.
- `pk;switch out` - Registers a 'switch-out' - a switch with no associated members.
## Autoproxy commands ## Autoproxy commands
- `pk;autoproxy [off|front|latch|<member>]` - Sets your system's autoproxy mode for the current server. - `pk;autoproxy [off|front|latch|<member>]` - Sets your system's autoproxy mode for the current server.