feat: pk;config

This commit is contained in:
spiral
2021-11-29 21:35:21 -05:00
parent d195c80d92
commit 56d07e0f2d
41 changed files with 648 additions and 313 deletions

View File

@@ -97,7 +97,9 @@ public class Admin
if (target == null)
throw new PKError("Unknown system.");
var currentLimit = target.MemberLimitOverride ?? Limits.MaxMemberCount;
var config = await _repo.GetSystemConfig(target.Id);
var currentLimit = config.MemberLimitOverride ?? Limits.MaxMemberCount;
if (!ctx.HasNext())
{
await ctx.Reply($"Current member limit is **{currentLimit}** members.");
@@ -111,7 +113,7 @@ public class Admin
if (!await ctx.PromptYesNo($"Update member limit from **{currentLimit}** to **{newLimit}**?", "Update"))
throw new PKError("Member limit change cancelled.");
await _repo.UpdateSystem(target.Id, new SystemPatch { MemberLimitOverride = newLimit });
await _repo.UpdateSystemConfig(target.Id, new SystemConfigPatch { MemberLimitOverride = newLimit });
await ctx.Reply($"{Emojis.Success} Member limit updated.");
}
@@ -123,7 +125,9 @@ public class Admin
if (target == null)
throw new PKError("Unknown system.");
var currentLimit = target.GroupLimitOverride ?? Limits.MaxGroupCount;
var config = await _repo.GetSystemConfig(target.Id);
var currentLimit = config.GroupLimitOverride ?? Limits.MaxGroupCount;
if (!ctx.HasNext())
{
await ctx.Reply($"Current group limit is **{currentLimit}** groups.");
@@ -137,7 +141,7 @@ public class Admin
if (!await ctx.PromptYesNo($"Update group limit from **{currentLimit}** to **{newLimit}**?", "Update"))
throw new PKError("Group limit change cancelled.");
await _repo.UpdateSystem(target.Id, new SystemPatch { GroupLimitOverride = newLimit });
await _repo.UpdateSystemConfig(target.Id, new SystemConfigPatch { GroupLimitOverride = newLimit });
await ctx.Reply($"{Emojis.Success} Group limit updated.");
}
}

View File

@@ -143,102 +143,6 @@ public class Autoproxy
return eb.Build();
}
public async Task AutoproxyTimeout(Context ctx)
{
if (!ctx.HasNext())
{
var timeout = ctx.System.LatchTimeout.HasValue
? Duration.FromSeconds(ctx.System.LatchTimeout.Value)
: (Duration?)null;
if (timeout == null)
await ctx.Reply(
$"You do not have a custom autoproxy timeout duration set. The default latch timeout duration is {ProxyMatcher.DefaultLatchExpiryTime.ToTimeSpan().Humanize(4)}.");
else if (timeout == Duration.Zero)
await ctx.Reply(
"Latch timeout is currently **disabled** for your system. Latch mode autoproxy will never time out.");
else
await ctx.Reply(
$"The current latch timeout duration for your system is {timeout.Value.ToTimeSpan().Humanize(4)}.");
return;
}
Duration? newTimeout;
var overflow = Duration.Zero;
if (ctx.Match("off", "stop", "cancel", "no", "disable", "remove"))
{
newTimeout = Duration.Zero;
}
else if (ctx.Match("reset", "default"))
{
newTimeout = null;
}
else
{
var timeoutStr = ctx.RemainderOrNull();
var timeoutPeriod = DateUtils.ParsePeriod(timeoutStr);
if (timeoutPeriod == null)
throw new PKError($"Could not parse '{timeoutStr}' as a valid duration. Try using a syntax such as \"3h5m\" (i.e. 3 hours and 5 minutes).");
if (timeoutPeriod.Value.TotalHours > 100000)
{
// sanity check to prevent seconds overflow if someone types in 999999999
overflow = timeoutPeriod.Value;
newTimeout = Duration.Zero;
}
else
{
newTimeout = timeoutPeriod;
}
}
await _repo.UpdateSystem(ctx.System.Id, new SystemPatch { LatchTimeout = (int?)newTimeout?.TotalSeconds });
if (newTimeout == null)
await ctx.Reply($"{Emojis.Success} Latch timeout reset to default ({ProxyMatcher.DefaultLatchExpiryTime.ToTimeSpan().Humanize(4)}).");
else if (newTimeout == Duration.Zero && overflow != Duration.Zero)
await ctx.Reply($"{Emojis.Success} Latch timeout disabled. Latch mode autoproxy will never time out. ({overflow.ToTimeSpan().Humanize(4)} is too long)");
else if (newTimeout == Duration.Zero)
await ctx.Reply($"{Emojis.Success} Latch timeout disabled. Latch mode autoproxy will never time out.");
else
await ctx.Reply($"{Emojis.Success} Latch timeout set to {newTimeout.Value!.ToTimeSpan().Humanize(4)}.");
}
public async Task AutoproxyAccount(Context ctx)
{
// todo: this might be useful elsewhere, consider moving it to ctx.MatchToggle
if (ctx.Match("enable", "on"))
{
await AutoproxyEnableDisable(ctx, true);
}
else if (ctx.Match("disable", "off"))
{
await AutoproxyEnableDisable(ctx, false);
}
else if (ctx.HasNext())
{
throw new PKSyntaxError("You must pass either \"on\" or \"off\".");
}
else
{
var statusString = ctx.MessageContext.AllowAutoproxy ? "enabled" : "disabled";
await ctx.Reply($"Autoproxy is currently **{statusString}** for account <@{ctx.Author.Id}>.");
}
}
private async Task AutoproxyEnableDisable(Context ctx, bool allow)
{
var statusString = allow ? "enabled" : "disabled";
if (ctx.MessageContext.AllowAutoproxy == allow)
{
await ctx.Reply($"{Emojis.Note} Autoproxy is already {statusString} for account <@{ctx.Author.Id}>.");
return;
}
var patch = new AccountPatch { AllowAutoproxy = allow };
await _repo.UpdateAccount(ctx.Author.Id, patch);
await ctx.Reply($"{Emojis.Success} Autoproxy {statusString} for account <@{ctx.Author.Id}>.");
}
private async Task UpdateAutoproxy(Context ctx, AutoproxyMode autoproxyMode, MemberId? autoproxyMember)
{
await _repo.GetSystemGuild(ctx.Guild.Id, ctx.System.Id);

View File

@@ -0,0 +1,301 @@
using System.Text;
using Humanizer;
using NodaTime;
using NodaTime.Text;
using NodaTime.TimeZones;
using PluralKit.Core;
namespace PluralKit.Bot;
public class Config
{
private readonly ModelRepository _repo;
public Config(ModelRepository repo)
{
_repo = repo;
}
private record PaginatedConfigItem(string Key, string Description, string? CurrentValue, string DefaultValue);
public async Task ShowConfig(Context ctx)
{
var items = new List<PaginatedConfigItem>();
items.Add(new(
"autoproxy account",
"Whether autoproxy is enabled for the current account",
EnabledDisabled(ctx.MessageContext.AllowAutoproxy),
"enabled"
));
items.Add(new(
"autoproxy timeout",
"If this is set, latch-mode autoproxy will not keep autoproxying after this amount of time has elapsed since the last message sent in the server",
ctx.Config.LatchTimeout.HasValue
? (
ctx.Config.LatchTimeout.Value != 0
? Duration.FromSeconds(ctx.Config.LatchTimeout.Value).ToTimeSpan().Humanize(4)
: "disabled"
)
: null,
ProxyMatcher.DefaultLatchExpiryTime.ToTimeSpan().Humanize(4)
));
items.Add(new(
"timezone",
"The system's time zone - shows timestamps in your local time",
ctx.Config.UiTz,
"UTC"
));
items.Add(new(
"ping",
$"Whether other users are able to mention you via a {Emojis.Bell} reaction",
EnabledDisabled(ctx.Config.PingsEnabled),
"enabled"
));
items.Add(new(
"Member limit",
"The maximum number of registered members for your system",
ctx.Config.MemberLimitOverride?.ToString(),
Limits.MaxMemberCount.ToString()
));
items.Add(new(
"Group limit",
"The maximum number of registered groups for your system",
ctx.Config.GroupLimitOverride?.ToString(),
Limits.MaxGroupCount.ToString()
));
await ctx.Paginate<PaginatedConfigItem>(
items.ToAsyncEnumerable(),
items.Count,
10,
"Current settings for your system",
ctx.System.Color,
(eb, l) =>
{
var description = new StringBuilder();
foreach (var item in l)
{
description.Append(item.Key.AsCode());
description.Append($" **({item.CurrentValue ?? item.DefaultValue})**");
if (item.CurrentValue != null && item.CurrentValue != item.DefaultValue)
description.Append("\ud83d\udd39");
description.AppendLine();
description.Append(item.Description);
description.AppendLine();
description.AppendLine();
}
eb.Description(description.ToString());
return Task.CompletedTask;
}
);
}
public async Task AutoproxyAccount(Context ctx)
{
// todo: this might be useful elsewhere, consider moving it to ctx.MatchToggle
if (ctx.Match("enable", "on"))
await AutoproxyEnableDisable(ctx, true);
else if (ctx.Match("disable", "off"))
await AutoproxyEnableDisable(ctx, false);
else if (ctx.HasNext())
throw new PKSyntaxError("You must pass either \"on\" or \"off\".");
else
{
var statusString = ctx.MessageContext.AllowAutoproxy ? "enabled" : "disabled";
await ctx.Reply($"Autoproxy is currently **{statusString}** for account <@{ctx.Author.Id}>.");
}
}
private string EnabledDisabled(bool value) => value ? "enabled" : "disabled";
private async Task AutoproxyEnableDisable(Context ctx, bool allow)
{
var statusString = EnabledDisabled(allow);
if (ctx.MessageContext.AllowAutoproxy == allow)
{
await ctx.Reply($"{Emojis.Note} Autoproxy is already {statusString} for account <@{ctx.Author.Id}>.");
return;
}
var patch = new AccountPatch { AllowAutoproxy = allow };
await _repo.UpdateAccount(ctx.Author.Id, patch);
await ctx.Reply($"{Emojis.Success} Autoproxy {statusString} for account <@{ctx.Author.Id}>.");
}
public async Task AutoproxyTimeout(Context ctx)
{
if (!ctx.HasNext())
{
var timeout = ctx.Config.LatchTimeout.HasValue
? Duration.FromSeconds(ctx.Config.LatchTimeout.Value)
: (Duration?)null;
if (timeout == null)
await ctx.Reply($"You do not have a custom autoproxy timeout duration set. The default latch timeout duration is {ProxyMatcher.DefaultLatchExpiryTime.ToTimeSpan().Humanize(4)}.");
else if (timeout == Duration.Zero)
await ctx.Reply("Latch timeout is currently **disabled** for your system. Latch mode autoproxy will never time out.");
else
await ctx.Reply($"The current latch timeout duration for your system is {timeout.Value.ToTimeSpan().Humanize(4)}.");
return;
}
Duration? newTimeout;
Duration overflow = Duration.Zero;
if (ctx.Match("off", "stop", "cancel", "no", "disable", "remove")) newTimeout = Duration.Zero;
else if (ctx.Match("reset", "default")) newTimeout = null;
else
{
var timeoutStr = ctx.RemainderOrNull();
var timeoutPeriod = DateUtils.ParsePeriod(timeoutStr);
if (timeoutPeriod == null) throw new PKError($"Could not parse '{timeoutStr}' as a valid duration. Try using a syntax such as \"3h5m\" (i.e. 3 hours and 5 minutes).");
if (timeoutPeriod.Value.TotalHours > 100000)
{
// sanity check to prevent seconds overflow if someone types in 999999999
overflow = timeoutPeriod.Value;
newTimeout = Duration.Zero;
}
else newTimeout = timeoutPeriod;
}
await _repo.UpdateSystemConfig(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)}).");
else if (newTimeout == Duration.Zero && overflow != Duration.Zero)
await ctx.Reply($"{Emojis.Success} Latch timeout disabled. Latch mode autoproxy will never time out. ({overflow.ToTimeSpan().Humanize(4)} is too long)");
else if (newTimeout == Duration.Zero)
await ctx.Reply($"{Emojis.Success} Latch timeout disabled. Latch mode autoproxy will never time out.");
else
await ctx.Reply($"{Emojis.Success} Latch timeout set to {newTimeout.Value!.ToTimeSpan().Humanize(4)}.");
}
public async Task SystemPing(Context ctx)
{
ctx.CheckSystem();
if (!ctx.HasNext())
{
if (ctx.Config.PingsEnabled) { await ctx.Reply("Reaction pings are currently **enabled** for your system. To disable reaction pings, type `pk;s ping disable`."); }
else { await ctx.Reply("Reaction pings are currently **disabled** for your system. To enable reaction pings, type `pk;s ping enable`."); }
}
else
{
if (ctx.Match("on", "enable"))
{
await _repo.UpdateSystemConfig(ctx.System.Id, new() { PingsEnabled = true });
await ctx.Reply("Reaction pings have now been enabled.");
}
if (ctx.Match("off", "disable"))
{
await _repo.UpdateSystemConfig(ctx.System.Id, new() { PingsEnabled = false });
await ctx.Reply("Reaction pings have now been disabled.");
}
}
}
public async Task SystemTimezone(Context ctx)
{
if (ctx.System == null) throw Errors.NoSystemError;
if (await ctx.MatchClear())
{
await _repo.UpdateSystemConfig(ctx.System.Id, new() { UiTz = "UTC" });
await ctx.Reply($"{Emojis.Success} System time zone cleared (set to UTC).");
return;
}
var zoneStr = ctx.RemainderOrNull();
if (zoneStr == null)
{
await ctx.Reply(
$"Your current system time zone is set to **{ctx.Config.UiTz}**. It is currently **{SystemClock.Instance.GetCurrentInstant().FormatZoned(ctx.Config.Zone)}** in that time zone. To change your system time zone, type `pk;s tz <zone>`.");
return;
}
var zone = await FindTimeZone(ctx, zoneStr);
if (zone == null) throw Errors.InvalidTimeZone(zoneStr);
var currentTime = SystemClock.Instance.GetCurrentInstant().InZone(zone);
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;
await _repo.UpdateSystemConfig(ctx.System.Id, new() { UiTz = zone.Id });
await ctx.Reply($"System time zone changed to **{zone.Id}**.");
}
private async Task<DateTimeZone> FindTimeZone(Context ctx, string zoneStr)
{
// First, if we're given a flag emoji, we extract the flag emoji code from it.
zoneStr = Core.StringUtils.ExtractCountryFlag(zoneStr) ?? zoneStr;
// Then, we find all *locations* matching either the given country code or the country name.
var locations = TzdbDateTimeZoneSource.Default.Zone1970Locations;
var matchingLocations = locations.Where(l => l.Countries.Any(c =>
string.Equals(c.Code, zoneStr, StringComparison.InvariantCultureIgnoreCase) ||
string.Equals(c.Name, zoneStr, StringComparison.InvariantCultureIgnoreCase)));
// Then, we find all (unique) time zone IDs that match.
var matchingZones = matchingLocations.Select(l => DateTimeZoneProviders.Tzdb.GetZoneOrNull(l.ZoneId))
.Distinct().ToList();
// If the set of matching zones is empty (ie. we didn't find anything), we try a few other things.
if (matchingZones.Count == 0)
{
// First, we try to just find the time zone given directly and return that.
var givenZone = DateTimeZoneProviders.Tzdb.GetZoneOrNull(zoneStr);
if (givenZone != null) return givenZone;
// If we didn't find anything there either, we try parsing the string as an offset, then
// find all possible zones that match that offset. For an offset like UTC+2, this doesn't *quite*
// work, since there are 57(!) matching zones (as of 2019-06-13) - but for less populated time zones
// this could work nicely.
var inputWithoutUtc = zoneStr.Replace("UTC", "").Replace("GMT", "");
var res = OffsetPattern.CreateWithInvariantCulture("+H").Parse(inputWithoutUtc);
if (!res.Success) res = OffsetPattern.CreateWithInvariantCulture("+H:mm").Parse(inputWithoutUtc);
// If *this* didn't parse correctly, fuck it, bail.
if (!res.Success) return null;
var offset = res.Value;
// To try to reduce the count, we go by locations from the 1970+ database instead of just the full database
// This elides regions that have been identical since 1970, omitting small distinctions due to Ancient History(tm).
var allZones = TzdbDateTimeZoneSource.Default.Zone1970Locations.Select(l => l.ZoneId).Distinct();
matchingZones = allZones.Select(z => DateTimeZoneProviders.Tzdb.GetZoneOrNull(z))
.Where(z => z.GetUtcOffset(SystemClock.Instance.GetCurrentInstant()) == offset).ToList();
}
// If we have a list of viable time zones, we ask the user which is correct.
// If we only have one, return that one.
if (matchingZones.Count == 1)
return matchingZones.First();
// Otherwise, prompt and return!
return await ctx.Choose("There were multiple matches for your time zone query. Please select the region that matches you the closest:", matchingZones,
z =>
{
if (TzdbDateTimeZoneSource.Default.Aliases.Contains(z.Id))
return $"**{z.Id}**, {string.Join(", ", TzdbDateTimeZoneSource.Default.Aliases[z.Id])}";
return $"**{z.Id}**";
});
}
}

View File

@@ -49,7 +49,7 @@ public class Groups
// Check group cap
var existingGroupCount = await _repo.GetSystemGroupCount(ctx.System.Id);
var groupLimit = ctx.System.GroupLimitOverride ?? Limits.MaxGroupCount;
var groupLimit = ctx.Config.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.");
@@ -574,7 +574,7 @@ public class Groups
var now = SystemClock.Instance.GetCurrentInstant();
var rangeStart = DateUtils.ParseDateTime(durationStr, true, targetSystem.Zone);
var rangeStart = DateUtils.ParseDateTime(durationStr, true, ctx.Zone);
if (rangeStart == null) throw Errors.InvalidDateTime(durationStr);
if (rangeStart.Value.ToInstant() > now) throw Errors.FrontPercentTimeInFuture;
@@ -589,7 +589,7 @@ public class Groups
var frontpercent = await _db.Execute(c =>
_repo.GetFrontBreakdown(c, targetSystem.Id, target.Id, rangeStart.Value.ToInstant(), now));
await ctx.Reply(embed: await _embeds.CreateFrontPercentEmbed(frontpercent, targetSystem, target,
targetSystem.Zone, ctx.LookupContextFor(targetSystem), title.ToString(), ignoreNoFronters, showFlat));
ctx.Zone, ctx.LookupContextFor(targetSystem), title.ToString(), ignoreNoFronters, showFlat));
}
private async Task<PKSystem> GetGroupSystem(Context ctx, PKGroup target)

View File

@@ -100,7 +100,7 @@ public class ImportExport
var json = await ctx.BusyIndicator(async () =>
{
// Make the actual data file
var data = await _dataFiles.ExportSystem(ctx.System);
var data = await _dataFiles.ExportSystem(ctx.System, ctx.Config.UiTz);
return JsonConvert.SerializeObject(data, Formatting.None);
});

View File

@@ -205,7 +205,6 @@ public static class ContextListExt
void LongRenderer(EmbedBuilder eb, IEnumerable<ListedMember> page)
{
var zone = ctx.System?.Zone ?? DateTimeZone.Utc;
foreach (var m in page)
{
var profile = new StringBuilder($"**ID**: {m.Hid}");
@@ -231,11 +230,11 @@ public static class ContextListExt
if ((opts.IncludeLastSwitch || opts.SortProperty == SortProperty.LastSwitch) &&
m.MetadataPrivacy.TryGet(lookupCtx, m.LastSwitchTime, out var lastSw))
profile.Append($"\n**Last switched in:** {lastSw.Value.FormatZoned(zone)}");
profile.Append($"\n**Last switched in:** {lastSw.Value.FormatZoned(ctx.Zone)}");
if ((opts.IncludeCreated || opts.SortProperty == SortProperty.CreationDate) &&
m.MetadataPrivacy.TryGet(lookupCtx, m.Created, out var created))
profile.Append($"\n**Created on:** {created.FormatZoned(zone)}");
profile.Append($"\n**Created on:** {created.FormatZoned(ctx.Zone)}");
if (opts.IncludeAvatar && m.AvatarFor(lookupCtx) is { } avatar)
profile.Append($"\n**Avatar URL:** {avatar.TryGetCleanCdnUrl()}");

View File

@@ -50,7 +50,7 @@ public class Member
// Enforce per-system member limit
var memberCount = await _repo.GetSystemMemberCount(ctx.System.Id);
var memberLimit = ctx.System.MemberLimitOverride ?? Limits.MaxMemberCount;
var memberLimit = ctx.Config.MemberLimitOverride ?? Limits.MaxMemberCount;
if (memberCount >= memberLimit)
throw Errors.MemberLimitReachedError(memberLimit);
@@ -117,7 +117,7 @@ public class Member
{
var system = await _repo.GetSystem(target.System);
await ctx.Reply(
embed: await _embeds.CreateMemberEmbed(system, target, ctx.Guild, ctx.LookupContextFor(system)));
embed: await _embeds.CreateMemberEmbed(system, target, ctx.Guild, ctx.LookupContextFor(system), ctx.Zone));
}
public async Task Soulscream(Context ctx, PKMember target)

View File

@@ -314,7 +314,7 @@ public class MemberEdit
LocalDate? birthday;
if (birthdayStr == "today" || birthdayStr == "now")
birthday = SystemClock.Instance.InZone(ctx.System.Zone).GetCurrentDate();
birthday = SystemClock.Instance.InZone(ctx.Zone).GetCurrentDate();
else
birthday = DateUtils.ParseDate(birthdayStr, true);

View File

@@ -34,7 +34,7 @@ public class Random
var randInt = randGen.Next(members.Count);
await ctx.Reply(embed: await _embeds.CreateMemberEmbed(ctx.System, members[randInt], ctx.Guild,
ctx.LookupContextFor(ctx.System)));
ctx.LookupContextFor(ctx.System), ctx.Zone));
}
public async Task Group(Context ctx)
@@ -72,6 +72,6 @@ public class Random
var randInt = randGen.Next(ms.Count);
await ctx.Reply(embed: await _embeds.CreateMemberEmbed(ctx.System, ms[randInt], ctx.Guild,
ctx.LookupContextFor(ctx.System)));
ctx.LookupContextFor(ctx.System), ctx.Zone));
}
}

View File

@@ -68,7 +68,7 @@ public class Switch
var timeToMove = ctx.RemainderOrNull() ??
throw new PKSyntaxError("Must pass a date or time to move the switch to.");
var tz = TzdbDateTimeZoneSource.Default.ForId(ctx.System.UiTz ?? "UTC");
var tz = TzdbDateTimeZoneSource.Default.ForId(ctx.Config?.UiTz ?? "UTC");
var result = DateUtils.ParseDateTime(timeToMove, true, tz);
if (result == null) throw Errors.InvalidDateTime(timeToMove);

View File

@@ -509,39 +509,6 @@ public class SystemEdit
await ctx.Reply($"Message proxying in {serverText} is now **disabled** for your system.");
}
public async Task SystemTimezone(Context ctx)
{
if (ctx.System == null) throw Errors.NoSystemError;
if (await ctx.MatchClear())
{
await _repo.UpdateSystem(ctx.System.Id, new SystemPatch { UiTz = "UTC" });
await ctx.Reply($"{Emojis.Success} System time zone cleared (set to UTC).");
return;
}
var zoneStr = ctx.RemainderOrNull();
if (zoneStr == null)
{
await ctx.Reply(
$"Your current system time zone is set to **{ctx.System.UiTz}**. It is currently **{SystemClock.Instance.GetCurrentInstant().FormatZoned(ctx.System)}** in that time zone. To change your system time zone, type `pk;s tz <zone>`.");
return;
}
var zone = await FindTimeZone(ctx, zoneStr);
if (zone == null) throw Errors.InvalidTimeZone(zoneStr);
var currentTime = SystemClock.Instance.GetCurrentInstant().InZone(zone);
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;
await _repo.UpdateSystem(ctx.System.Id, new SystemPatch { UiTz = zone.Id });
await ctx.Reply($"System time zone changed to **{zone.Id}**.");
}
public async Task SystemPrivacy(Context ctx)
{
ctx.CheckSystem();
@@ -609,96 +576,4 @@ public class SystemEdit
else
await SetLevel(ctx.PopSystemPrivacySubject(), ctx.PopPrivacyLevel());
}
public async Task SystemPing(Context ctx)
{
ctx.CheckSystem();
if (!ctx.HasNext())
{
if (ctx.System.PingsEnabled)
await ctx.Reply(
"Reaction pings are currently **enabled** for your system. To disable reaction pings, type `pk;s ping disable`.");
else
await ctx.Reply(
"Reaction pings are currently **disabled** for your system. To enable reaction pings, type `pk;s ping enable`.");
}
else
{
if (ctx.Match("on", "enable"))
{
await _repo.UpdateSystem(ctx.System.Id, new SystemPatch { PingsEnabled = true });
await ctx.Reply("Reaction pings have now been enabled.");
}
if (ctx.Match("off", "disable"))
{
await _repo.UpdateSystem(ctx.System.Id, new SystemPatch { PingsEnabled = false });
await ctx.Reply("Reaction pings have now been disabled.");
}
}
}
public async Task<DateTimeZone> FindTimeZone(Context ctx, string zoneStr)
{
// First, if we're given a flag emoji, we extract the flag emoji code from it.
zoneStr = StringUtils.ExtractCountryFlag(zoneStr) ?? zoneStr;
// Then, we find all *locations* matching either the given country code or the country name.
var locations = TzdbDateTimeZoneSource.Default.Zone1970Locations;
var matchingLocations = locations.Where(l => l.Countries.Any(c =>
string.Equals(c.Code, zoneStr, StringComparison.InvariantCultureIgnoreCase) ||
string.Equals(c.Name, zoneStr, StringComparison.InvariantCultureIgnoreCase)));
// Then, we find all (unique) time zone IDs that match.
var matchingZones = matchingLocations.Select(l => DateTimeZoneProviders.Tzdb.GetZoneOrNull(l.ZoneId))
.Distinct().ToList();
// If the set of matching zones is empty (ie. we didn't find anything), we try a few other things.
if (matchingZones.Count == 0)
{
// First, we try to just find the time zone given directly and return that.
var givenZone = DateTimeZoneProviders.Tzdb.GetZoneOrNull(zoneStr);
if (givenZone != null) return givenZone;
// If we didn't find anything there either, we try parsing the string as an offset, then
// find all possible zones that match that offset. For an offset like UTC+2, this doesn't *quite*
// work, since there are 57(!) matching zones (as of 2019-06-13) - but for less populated time zones
// this could work nicely.
var inputWithoutUtc = zoneStr.Replace("UTC", "").Replace("GMT", "");
var res = OffsetPattern.CreateWithInvariantCulture("+H").Parse(inputWithoutUtc);
if (!res.Success) res = OffsetPattern.CreateWithInvariantCulture("+H:mm").Parse(inputWithoutUtc);
// If *this* didn't parse correctly, fuck it, bail.
if (!res.Success) return null;
var offset = res.Value;
// To try to reduce the count, we go by locations from the 1970+ database instead of just the full database
// This elides regions that have been identical since 1970, omitting small distinctions due to Ancient History(tm).
var allZones = TzdbDateTimeZoneSource.Default.Zone1970Locations.Select(l => l.ZoneId).Distinct();
matchingZones = allZones.Select(z => DateTimeZoneProviders.Tzdb.GetZoneOrNull(z))
.Where(z => z.GetUtcOffset(SystemClock.Instance.GetCurrentInstant()) == offset).ToList();
}
// If we have a list of viable time zones, we ask the user which is correct.
// If we only have one, return that one.
if (matchingZones.Count == 1)
return matchingZones.First();
// Otherwise, prompt and return!
return await ctx.Choose(
"There were multiple matches for your time zone query. Please select the region that matches you the closest:",
matchingZones,
z =>
{
if (TzdbDateTimeZoneSource.Default.Aliases.Contains(z.Id))
return $"**{z.Id}**, {string.Join(", ", TzdbDateTimeZoneSource.Default.Aliases[z.Id])}";
return $"**{z.Id}**";
});
}
}

View File

@@ -27,7 +27,7 @@ public class SystemFront
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)));
await ctx.Reply(embed: await _embeds.CreateFronterEmbed(sw, ctx.Zone, ctx.LookupContextFor(system)));
}
public async Task SystemFrontHistory(Context ctx, PKSystem system)
@@ -77,12 +77,12 @@ public class SystemFront
// Calculate the time between the last switch (that we iterated - ie. the next one on the timeline) and the current one
var switchDuration = lastSw.Value - sw.Timestamp;
stringToAdd =
$"**{membersStr}** ({sw.Timestamp.FormatZoned(system.Zone)}, {switchSince.FormatDuration()} ago, for {switchDuration.FormatDuration()})\n";
$"**{membersStr}** ({sw.Timestamp.FormatZoned(ctx.Zone)}, {switchSince.FormatDuration()} ago, for {switchDuration.FormatDuration()})\n";
}
else
{
stringToAdd =
$"**{membersStr}** ({sw.Timestamp.FormatZoned(system.Zone)}, {switchSince.FormatDuration()} ago)\n";
$"**{membersStr}** ({sw.Timestamp.FormatZoned(ctx.Zone)}, {switchSince.FormatDuration()} ago)\n";
}
if (sb.Length + stringToAdd.Length >= 4096)
@@ -113,7 +113,7 @@ public class SystemFront
var now = SystemClock.Instance.GetCurrentInstant();
var rangeStart = DateUtils.ParseDateTime(durationStr, true, system.Zone);
var rangeStart = DateUtils.ParseDateTime(durationStr, true, ctx.Zone);
if (rangeStart == null) throw Errors.InvalidDateTime(durationStr);
if (rangeStart.Value.ToInstant() > now) throw Errors.FrontPercentTimeInFuture;
@@ -127,7 +127,7 @@ public class SystemFront
var showFlat = ctx.MatchFlag("flat");
var frontpercent = await _db.Execute(c =>
_repo.GetFrontBreakdown(c, system.Id, null, rangeStart.Value.ToInstant(), now));
await ctx.Reply(embed: await _embeds.CreateFrontPercentEmbed(frontpercent, system, null, system.Zone,
await ctx.Reply(embed: await _embeds.CreateFrontPercentEmbed(frontpercent, system, null, ctx.Zone,
ctx.LookupContextFor(system), title.ToString(), ignoreNoFronters, showFlat));
}