run dotnet format

This commit is contained in:
spiral
2021-08-27 11:03:47 -04:00
parent 05989242f9
commit ac2671452d
278 changed files with 1913 additions and 1808 deletions

View File

@@ -1,4 +1,4 @@
#nullable enable
#nullable enable
using PluralKit.Core;
namespace PluralKit.Bot
@@ -8,7 +8,7 @@ namespace PluralKit.Bot
public ProxyMember Member;
public string? Content;
public ProxyTag? ProxyTags;
public string? ProxyContent
{
get

View File

@@ -1,4 +1,4 @@
using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using NodaTime;
@@ -32,7 +32,7 @@ namespace PluralKit.Bot
private bool TryMatchTags(IReadOnlyCollection<ProxyMember> members, string messageContent, bool hasAttachments, out ProxyMatch match)
{
if (!_parser.TryMatch(members, messageContent, out match)) return false;
// Edge case: If we got a match with blank inner text, we'd normally just send w/ attachments
// However, if there are no attachments, the user probably intended something else, so we "un-match" and proceed to autoproxy
return hasAttachments || match.Content.Trim().Length > 0;
@@ -50,19 +50,19 @@ namespace PluralKit.Bot
// Find the member we should autoproxy (null if none)
var member = ctx.AutoproxyMode switch
{
AutoproxyMode.Member when ctx.AutoproxyMember != null =>
AutoproxyMode.Member when ctx.AutoproxyMember != null =>
members.FirstOrDefault(m => m.Id == ctx.AutoproxyMember),
AutoproxyMode.Front when ctx.LastSwitchMembers.Length > 0 =>
AutoproxyMode.Front when ctx.LastSwitchMembers.Length > 0 =>
members.FirstOrDefault(m => m.Id == ctx.LastSwitchMembers[0]),
AutoproxyMode.Latch when ctx.LastMessageMember != null =>
members.FirstOrDefault(m => m.Id == ctx.LastMessageMember.Value),
_ => null
};
// Throw an error if the member is null, message varies depending on autoproxy mode
if (member == null)
if (member == null)
{
if (ctx.AutoproxyMode == AutoproxyMode.Front)
throw new ProxyService.ProxyChecksFailedException("You are using autoproxy front, but no members are currently registered as fronting. Please use `pk;switch <member>` to log a new switch.");
@@ -78,13 +78,13 @@ namespace PluralKit.Bot
// Moved the IsLatchExpired() check to here, so that an expired latch and a latch without any previous messages throw different errors
if (ctx.AutoproxyMode == AutoproxyMode.Latch && IsLatchExpired(ctx))
throw new ProxyService.ProxyChecksFailedException("Latch-mode autoproxy has timed out. Please send a new message using proxy tags.");
throw new ProxyService.ProxyChecksFailedException("Latch-mode autoproxy has timed out. Please send a new message using proxy tags.");
match = new ProxyMatch
{
Content = messageContent,
Member = member,
// We're autoproxying, so not using any proxy tags here
// we just find the first pair of tags (if any), otherwise null
ProxyTags = member.ProxyTags.FirstOrDefault()
@@ -98,7 +98,7 @@ namespace PluralKit.Bot
if (ctx.LatchTimeout == 0) return false;
var timeout = ctx.LatchTimeout.HasValue
? Duration.FromSeconds(ctx.LatchTimeout.Value)
? Duration.FromSeconds(ctx.LatchTimeout.Value)
: DefaultLatchExpiryTime;
var timestamp = DiscordUtils.SnowflakeToInstant(ctx.LastMessage.Value);

View File

@@ -53,7 +53,7 @@ namespace PluralKit.Bot
public async Task<bool> HandleIncomingMessage(Shard shard, MessageCreateEvent message, MessageContext ctx, Guild guild, Channel channel, bool allowAutoproxy, PermissionSet botPermissions)
{
if (!ShouldProxy(channel, message, ctx))
if (!ShouldProxy(channel, message, ctx))
return false;
// Fetch members and try to match to a specific member
@@ -64,7 +64,7 @@ namespace PluralKit.Bot
List<ProxyMember> members;
using (_metrics.Measure.Timer.Time(BotMetrics.ProxyMembersQueryTime))
members = (await _repo.GetProxyMembers(conn, message.Author.Id, message.GuildId!.Value)).ToList();
if (!_matcher.TryMatch(ctx, members, out var match, message.Content, message.Attachments.Length > 0,
allowAutoproxy)) return false;
@@ -72,12 +72,12 @@ namespace PluralKit.Bot
if (message.Content != null && message.Content.Length > 2000) throw new PKError("PluralKit cannot proxy messages over 2000 characters in length.");
// Permission check after proxy match so we don't get spammed when not actually proxying
if (!await CheckBotPermissionsOrError(botPermissions, rootChannel.Id))
if (!await CheckBotPermissionsOrError(botPermissions, rootChannel.Id))
return false;
// this method throws, so no need to wrap it in an if statement
CheckProxyNameBoundsOrError(match.Member.ProxyName(ctx));
// Check if the sender account can mention everyone/here + embed links
// we need to "mirror" these permissions when proxying to prevent exploits
var senderPermissions = PermissionExtensions.PermissionsFor(guild, rootChannel, message);
@@ -94,17 +94,17 @@ namespace PluralKit.Bot
// Make sure author has a system
if (ctx.SystemId == null)
throw new ProxyChecksFailedException(Errors.NoSystemError.Message);
// Make sure channel is a guild text channel and this is a normal message
if (!DiscordUtils.IsValidGuildChannel(channel))
throw new ProxyChecksFailedException("This channel is not a text channel.");
if (msg.Type != Message.MessageType.Default && msg.Type != Message.MessageType.Reply)
throw new ProxyChecksFailedException("This message is not a normal message.");
// Make sure author is a normal user
if (msg.Author.System == true || msg.Author.Bot || msg.WebhookId != null)
throw new ProxyChecksFailedException("This message was not sent by a normal user.");
// Make sure proxying is enabled here
if (ctx.InBlacklist)
throw new ProxyChecksFailedException($"Proxying was disabled in this channel by a server administrator (via the proxy blacklist).");
@@ -112,12 +112,12 @@ namespace PluralKit.Bot
// Make sure the system has proxying enabled in the server
if (!ctx.ProxyEnabled)
throw new ProxyChecksFailedException("Your system has proxying disabled in this server. Type `pk;proxy on` to enable it.");
// Make sure we have either an attachment or message content
var isMessageBlank = msg.Content == null || msg.Content.Trim().Length == 0;
if (isMessageBlank && msg.Attachments.Length == 0)
throw new ProxyChecksFailedException("Message cannot be blank.");
// All good!
return true;
}
@@ -137,17 +137,17 @@ namespace PluralKit.Bot
if (embed != null)
embeds.Add(embed);
}
// TODO: have a clean error for when message can't be fetched instead of just being silent
}
// Send the webhook
var content = match.ProxyContent;
if (!allowEmbeds) content = content.BreakLinkEmbeds();
var messageChannel = _cache.GetChannel(trigger.ChannelId);
var rootChannel = _cache.GetRootChannel(trigger.ChannelId);
var threadId = messageChannel.IsThread() ? messageChannel.Id : (ulong?)null;
var threadId = messageChannel.IsThread() ? messageChannel.Id : (ulong?)null;
var proxyMessage = await _webhookExecutor.ExecuteWebhook(new ProxyRequest
{
@@ -186,7 +186,7 @@ namespace PluralKit.Bot
{
// repliedTo doesn't have a GuildId field :/
var jumpLink = $"https://discord.com/channels/{trigger.GuildId}/{repliedTo.ChannelId}/{repliedTo.Id}";
var content = new StringBuilder();
var hasContent = !string.IsNullOrWhiteSpace(repliedTo.Content);
@@ -211,7 +211,7 @@ namespace PluralKit.Bot
var urlTail = repliedTo.Content.Substring(100).Split(" ")[0];
msg += urlTail + " ";
}
var spoilersInOriginalString = Regex.Matches(repliedTo.Content, @"\|\|").Count;
var spoilersInTruncatedString = Regex.Matches(msg, @"\|\|").Count;
if (spoilersInTruncatedString % 2 == 1 && spoilersInOriginalString % 2 == 0)
@@ -219,7 +219,7 @@ namespace PluralKit.Bot
if (msg != repliedTo.Content)
msg += "…";
}
content.Append($"**[Reply to:]({jumpLink})** ");
content.Append(msg);
if (repliedTo.Attachments.Length > 0)
@@ -229,7 +229,7 @@ namespace PluralKit.Bot
{
content.Append($"*[(click to see attachment)]({jumpLink})*");
}
var username = nickname ?? repliedTo.Author.Username;
var avatarUrl = avatar != null
? $"https://cdn.discordapp.com/guilds/{trigger.GuildId}/users/{repliedTo.Author.Id}/{avatar}.png"
@@ -247,12 +247,12 @@ namespace PluralKit.Bot
private async Task<string> FixSameName(ulong channelId, MessageContext ctx, ProxyMember member)
{
var proxyName = member.ProxyName(ctx);
var lastMessage = _lastMessage.GetLastMessage(channelId)?.Previous;
if (lastMessage == null)
// cache is out of date or channel is empty.
return proxyName;
await using var conn = await _db.Obtain();
var pkMessage = await _repo.GetMessage(conn, lastMessage.Id);
@@ -294,9 +294,9 @@ namespace PluralKit.Bot
};
Task SaveMessageInDatabase() => _repo.AddMessage(conn, sentMessage);
Task LogMessageToChannel() => _logChannel.LogMessage(ctx, sentMessage, triggerMessage, proxyMessage).AsTask();
async Task DeleteProxyTriggerMessage()
{
// Wait a second or so before deleting the original message
@@ -307,13 +307,13 @@ namespace PluralKit.Bot
}
catch (NotFoundException)
{
_logger.Debug("Trigger message {TriggerMessageId} was already deleted when we attempted to; deleting proxy message {ProxyMessageId} also",
_logger.Debug("Trigger message {TriggerMessageId} was already deleted when we attempted to; deleting proxy message {ProxyMessageId} also",
triggerMessage.Id, proxyMessage.Id);
await HandleTriggerAlreadyDeleted(proxyMessage);
// Swallow the exception, we don't need it
}
}
// Run post-proxy actions (simultaneously; order doesn't matter)
// Note that only AddMessage is using our passed-in connection, careful not to pass it elsewhere and run into conflicts
await Task.WhenAll(
@@ -341,7 +341,7 @@ namespace PluralKit.Bot
{
// If we can't send messages at all, just bail immediately.
// 2020-04-22: Manage Messages does *not* override a lack of Send Messages.
if (!permissions.HasFlag(PermissionSet.SendMessages))
if (!permissions.HasFlag(PermissionSet.SendMessages))
return false;
if (!permissions.HasFlag(PermissionSet.ManageWebhooks))
@@ -370,9 +370,9 @@ namespace PluralKit.Bot
{
if (proxyName.Length > Limits.MaxProxyNameLength) throw Errors.ProxyNameTooLong(proxyName);
}
public class ProxyChecksFailedException : Exception
public class ProxyChecksFailedException: Exception
{
public ProxyChecksFailedException(string message) : base(message) {}
public ProxyChecksFailedException(string message) : base(message) { }
}
}
}
}

View File

@@ -1,4 +1,4 @@
#nullable enable
#nullable enable
using System.Collections.Generic;
using System.Linq;
@@ -11,10 +11,10 @@ namespace PluralKit.Bot
public bool TryMatch(IEnumerable<ProxyMember> members, string? input, out ProxyMatch result)
{
result = default;
// Null input is valid and is equivalent to empty string
if (input == null) return false;
// If the message starts with a @mention, and then proceeds to have proxy tags,
// extract the mention and place it inside the inner message
// eg. @Ske [text] => [@Ske text]
@@ -26,13 +26,13 @@ namespace PluralKit.Bot
var tags = members
.SelectMany(member => member.ProxyTags.Select(tag => (tag, member)))
.OrderByDescending(p => p.tag.ProxyString.Length);
// Iterate now-ordered list of tags and try matching each one
foreach (var (tag, member) in tags)
{
result.ProxyTags = tag;
result.Member = member;
// Skip blank tags (shouldn't ever happen in practice)
if (tag.Prefix == null && tag.Suffix == null) continue;
@@ -43,10 +43,10 @@ namespace PluralKit.Bot
if (leadingMention != null) result.Content = $"{leadingMention} {result.Content}";
return true;
}
// (if not, keep going)
}
// We couldn't match anything :(
return false;
}
@@ -54,25 +54,25 @@ namespace PluralKit.Bot
private bool TryMatchTagsInner(string input, ProxyTag tag, out string inner)
{
inner = "";
// Normalize null tags to empty strings
var prefix = tag.Prefix ?? "";
var suffix = tag.Suffix ?? "";
// Check if our input starts/ends with the tags
var isMatch = input.Length >= prefix.Length + suffix.Length
var isMatch = input.Length >= prefix.Length + suffix.Length
&& input.StartsWith(prefix) && input.EndsWith(suffix);
// Special case: image-only proxies + proxy tags with spaces
// Trim everything, then see if we have a "contentless tag pair" (normally disallowed, but OK if we have an attachment)
// Note `input` is still "", even if there are spaces between
if (!isMatch && input.Trim() == prefix.TrimEnd() + suffix.TrimStart())
return true;
if (!isMatch) return false;
if (!isMatch) return false;
// We got a match, extract inner text
inner = input.Substring(prefix.Length, input.Length - prefix.Length - suffix.Length);
// (see https://github.com/xSke/PluralKit/pull/181)
return inner.Trim() != "\U0000fe0f";
}
@@ -81,7 +81,7 @@ namespace PluralKit.Bot
{
var mentionPos = 0;
if (!DiscordUtils.HasMentionPrefix(input, ref mentionPos, out _)) return null;
var leadingMention = input.Substring(0, mentionPos);
input = input.Substring(mentionPos);
return leadingMention;